1 /*
2  * IRC - Internet Relay Chat, ircd/os_generic.c
3  * Copyright (C) 1999 Thomas Helvey
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 1, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /** @file
20  * @brief Implementation of OS-dependent operations.
21  * @version $Id$
22  */
23 #include "config.h"
24 
25 #ifdef IRCU_SOLARIS
26 /* Solaris requires C99 support for SUSv3, but C99 support breaks other
27  * parts of the build.  So fall back to SUSv2, but request IPv6 support
28  * by defining __EXTENSIONS__.
29  */
30 #define _XOPEN_SOURCE   500
31 #define __EXTENSIONS__  1
32 #elif (defined(__FreeBSD__) && __FreeBSD__ >= 5) || defined(__DragonFly__)
33 /* FreeBSD 6.0 requires SUSv3 to support IPv6 -- but if you ask for
34  * that specifically (by defining _XOPEN_SOURCE to anything at all),
35  * they cleverly hide IPPROTO_IPV6.  If you don't ask for anything,
36  * they give you everything.
37  */
38 #else
39 #define _XOPEN_SOURCE   600
40 #endif
41 
42 #include "ircd_osdep.h"
43 #include "msgq.h"
44 #include "ircd_log.h"
45 #include "res.h"
46 #include "s_bsd.h"
47 #include "sys.h"
48 
49 /* Include file dependency notes:
50  * FreeBSD requires struct timeval from sys/time.h before struct
51  * rusage in sys/resource.h.
52  * Solaris requires sys/time.h before struct rusage (indirectly) in
53  * netinet/in.h.
54  */
55 /* #include <assert.h> -- Now using assert in ircd_log.h */
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <stdio.h>
60 #include <string.h>
61 #include <sys/ioctl.h>
62 #include <sys/types.h>
63 #include <sys/time.h>
64 #include <netinet/in.h>
65 #include <sys/resource.h>
66 #include <sys/socket.h>
67 #include <sys/uio.h>
68 
69 #if HAVE_SYS_PARAM_H
70 #include <sys/param.h>
71 #endif
72 
73 #if HAVE_UNISTD_H
74 #include <unistd.h>
75 #endif
76 
77 #if defined(IPV6_BINDV6ONLY) &&!defined(IPV6_V6ONLY)
78 # define IPV6_V6ONLY IPV6_BINDV6ONLY
79 #endif
80 
81 #ifndef IOV_MAX
82 #define IOV_MAX 16	/**< minimum required length of an iovec array */
83 #endif
84 
85 #ifdef HPUX
86 #include <sys/syscall.h>
87 #define getrusage(a,b) syscall(SYS_GETRUSAGE, a, b)
88 #endif
89 
is_blocked(int error)90 static int is_blocked(int error)
91 {
92   return EWOULDBLOCK == error
93 #ifdef ENOMEM
94     || ENOMEM == error
95 #endif
96 #ifdef ENOBUFS
97     || ENOBUFS == error
98 #endif
99     || EAGAIN == error;
100 }
101 
sockaddr_in_to_irc(const struct sockaddr_in * v4,struct irc_sockaddr * irc)102 static void sockaddr_in_to_irc(const struct sockaddr_in *v4,
103                                struct irc_sockaddr *irc)
104 {
105     memset(&irc->addr, 0, 5*sizeof(int16_t));
106     irc->addr.in6_16[5] = 0xffff;
107     memcpy(&irc->addr.in6_16[6], &v4->sin_addr, sizeof(v4->sin_addr));
108     irc->port = ntohs(v4->sin_port);
109 }
110 
111 
112 #ifdef IPV6
113 /** Native socket address type. */
114 #define sockaddr_native sockaddr_in6
115 /** Field name inside sockaddr_native to find address family. */
116 #define sn_family sin6_family
117 
118 /** Convert native socket address to IRC format.
119  * @param[in] v6 Native socket address.
120  * @param[out] irc IRC format socket address.
121  */
sockaddr_to_irc(const struct sockaddr_in6 * v6,struct irc_sockaddr * irc)122 void sockaddr_to_irc(const struct sockaddr_in6 *v6, struct irc_sockaddr *irc)
123 {
124     if (v6->sin6_family == AF_INET6) {
125         memcpy(&irc->addr.in6_16[0], &v6->sin6_addr, sizeof(v6->sin6_addr));
126         irc->port = ntohs(v6->sin6_port);
127     }
128     else if (v6->sin6_family == AF_INET) {
129         sockaddr_in_to_irc((struct sockaddr_in *)v6, irc);
130     }
131     else assert(0 && "Unhandled native address family");
132 }
133 
134 /** Convert IRC socket address to native format.
135  * @param[out] v6 Native socket address.
136  * @param[in] irc IRC socket address.
137  * @param[in] compat_fd If non-negative, an FD specifying address family.
138  * @return Length of address written to \a v6.
139  */
sockaddr_from_irc(struct sockaddr_in6 * v6,const struct irc_sockaddr * irc,int compat_fd,int family)140 int sockaddr_from_irc(struct sockaddr_in6 *v6, const struct irc_sockaddr *irc, int compat_fd, int family)
141 {
142     struct sockaddr_in6 sin6;
143     socklen_t slen;
144 
145     assert(irc != 0);
146     slen = sizeof(sin6);
147     if (family) {
148         /* accept whatever user specified */
149     } else if ((0 <= compat_fd)
150         && (0 == getsockname(compat_fd, (struct sockaddr*)&sin6, &slen)))
151         family = sin6.sin6_family;
152     else if ((irc == &VirtualHost_v4) || irc_in_addr_is_ipv4(&irc->addr))
153         family = AF_INET;
154     else
155         family = AF_INET6;
156 
157     memset(v6, 0, sizeof(*v6));
158     if (family == AF_INET) {
159         struct sockaddr_in *v4 = (struct sockaddr_in*)v6;
160         v4->sin_family = AF_INET;
161         memcpy(&v4->sin_addr, &irc->addr.in6_16[6], sizeof(v4->sin_addr));
162         v4->sin_port = htons(irc->port);
163         return sizeof(*v4);
164     }
165     else {
166         v6->sin6_family = AF_INET6;
167         memcpy(&v6->sin6_addr, &irc->addr.in6_16[0], sizeof(v6->sin6_addr));
168         v6->sin6_port = htons(irc->port);
169         return sizeof(*v6);
170     }
171 }
172 
173 #else
174 #define sockaddr_native sockaddr_in
175 #define sn_family sin_family
176 #define sockaddr_to_irc sockaddr_in_to_irc
177 
sockaddr_from_irc(struct sockaddr_in * v4,const struct irc_sockaddr * irc,int compat_fd,int family)178 int sockaddr_from_irc(struct sockaddr_in *v4, const struct irc_sockaddr *irc, int compat_fd, int family)
179 {
180     assert(irc != 0);
181     memset(v4, 0, sizeof(*v4));
182     v4->sin_family = AF_INET;
183     if (irc) {
184         assert(!irc->addr.in6_16[0] && !irc->addr.in6_16[1] && !irc->addr.in6_16[2] && !irc->addr.in6_16[3] && !irc->addr.in6_16[4] && (!irc->addr.in6_16[5] || irc->addr.in6_16[5] == 0xffff));
185         memcpy(&v4->sin_addr, &irc->addr.in6_16[6], sizeof(v4->sin_addr));
186         v4->sin_port = htons(irc->port);
187     }
188     (void)compat_fd; (void)family;
189     return sizeof(*v4);
190 }
191 
192 #endif
193 
194 #ifdef DEBUGMODE
195 /** Send resource usage information to an enumerator function.
196  * @param[in] cptr Client requesting information.
197  * @param[in] uptime Wall time in seconds since the server started.
198  * @param[in] enumerator Function to call to send a line to \a cptr.
199  * @return Zero if some usage reports could not be sent, non-zero on success.
200  */
os_get_rusage(struct Client * cptr,int uptime,EnumFn enumerator)201 int os_get_rusage(struct Client *cptr, int uptime, EnumFn enumerator)
202 {
203 #ifdef HAVE_GETRUSAGE
204   char buf[256];
205   struct rusage rus;
206   time_t secs;
207 
208 #ifdef  hz
209 #  define hzz hz
210 #else
211 #  ifdef HZ
212 #    define hzz HZ
213 #  else
214   int hzz = 1;
215 #  ifdef HPUX
216   hzz = sysconf(_SC_CLK_TCK);
217 #  endif
218 #endif
219 #endif
220 
221   assert(0 != enumerator);
222   if (getrusage(RUSAGE_SELF, &rus) == -1)
223     return 0;
224 
225   secs = rus.ru_utime.tv_sec + rus.ru_stime.tv_sec;
226   if (secs == 0)
227     secs = 1;
228 
229   sprintf(buf, "CPU Secs %ld:%ld User %ld:%ld System %ld:%ld",
230           (long)(secs / 60), (long)(secs % 60),
231           rus.ru_utime.tv_sec / 60, rus.ru_utime.tv_sec % 60,
232           rus.ru_stime.tv_sec / 60, rus.ru_stime.tv_sec % 60);
233   (*enumerator)(cptr, buf);
234 
235   sprintf(buf, "RSS %ld ShMem %ld Data %ld Stack %ld",
236           rus.ru_maxrss,
237           rus.ru_ixrss / (uptime * hzz), rus.ru_idrss / (uptime * hzz),
238           rus.ru_isrss / (uptime * hzz));
239   (*enumerator)(cptr, buf);
240 
241   sprintf(buf, "Swaps %ld Reclaims %ld Faults %ld",
242           rus.ru_nswap, rus.ru_minflt, rus.ru_majflt);
243   (*enumerator)(cptr, buf);
244 
245   sprintf(buf, "Block in %ld out %ld", rus.ru_inblock, rus.ru_oublock);
246   (*enumerator)(cptr, buf);
247 
248   sprintf(buf, "Msg Rcv %ld Send %ld", rus.ru_msgrcv, rus.ru_msgsnd);
249   (*enumerator)(cptr, buf);
250 
251   sprintf(buf, "Signals %ld Context Vol. %ld Invol %ld",
252           rus.ru_nsignals, rus.ru_nvcsw, rus.ru_nivcsw);
253   (*enumerator)(cptr, buf);
254 
255 #elif HAVE_TIMES
256   char buf[256];
257   struct tms tmsbuf;
258   time_t secs, mins;
259   int hzz = 1, ticpermin;
260   int umin, smin, usec, ssec;
261 
262   assert(0 != enumerator);
263 #ifdef HPUX
264   hzz = sysconf(_SC_CLK_TCK);
265 #endif
266   ticpermin = hzz * 60;
267 
268   umin = tmsbuf.tms_utime / ticpermin;
269   usec = (tmsbuf.tms_utime % ticpermin) / (float)hzz;
270   smin = tmsbuf.tms_stime / ticpermin;
271   ssec = (tmsbuf.tms_stime % ticpermin) / (float)hzz;
272   secs = usec + ssec;
273   mins = (secs / 60) + umin + smin;
274   secs %= hzz;
275 
276   if (times(&tmsbuf) == -1)
277     return 0;
278   secs = tmsbuf.tms_utime + tmsbuf.tms_stime;
279 
280   sprintf(buf, "CPU Secs %d:%d User %d:%d System %d:%d",
281           mins, secs, umin, usec, smin, ssec);
282   (*enumerator)(cptr, buf);
283 #endif /* HAVE_GETRUSAGE, elif HAVE_TIMES */
284   return 1;
285 }
286 #endif
287 
288 /** Look up the most recent socket error for a socket file descriptor.
289  * @param[in] fd File descriptor to check.
290  * @return Error code from the socket, or 0 if the OS does not support this.
291  */
os_get_sockerr(int fd)292 int os_get_sockerr(int fd)
293 {
294   int    err = 0;
295 #if defined(SO_ERROR)
296   unsigned int len = sizeof(err);
297   getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
298 #endif
299   return err;
300 }
301 
302 /** Set a file descriptor to non-blocking mode.
303  * @param[in] fd %Socket file descriptor.
304  * @return Non-zero on success, or zero on failure.
305  */
os_set_nonblocking(int fd)306 int os_set_nonblocking(int fd)
307 {
308   int res;
309 #ifndef NBLOCK_SYSV
310   int nonb = 0;
311 #endif
312 
313   /*
314    * NOTE: consult ALL your relevant manual pages *BEFORE* changing
315    * these ioctl's. There are quite a few variations on them,
316    * as can be seen by the PCS one. They are *NOT* all the same.
317    * Heed this well. - Avalon.
318    */
319 #ifdef  NBLOCK_POSIX
320   nonb |= O_NONBLOCK;
321 #endif
322 #ifdef  NBLOCK_BSD
323   nonb |= O_NDELAY;
324 #endif
325 #ifdef  NBLOCK_SYSV
326   /* This portion of code might also apply to NeXT. -LynX */
327   res = 1;
328 
329   if (ioctl(fd, FIONBIO, &res) == -1)
330     return 0;
331 #else
332   if ((res = fcntl(fd, F_GETFL, 0)) == -1)
333     return 0;
334   else if (fcntl(fd, F_SETFL, res | nonb) == -1)
335     return 0;
336 #endif
337   return 1;
338 }
339 
340 /** Mark a socket's address as reusable.
341  * @param[in] fd %Socket file descriptor to manipulate.
342  * @return Non-zero on success, or zero on failure.
343  */
os_set_reuseaddr(int fd)344 int os_set_reuseaddr(int fd)
345 {
346   unsigned int opt = 1;
347   return (0 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
348                           (const char*) &opt, sizeof(opt)));
349 }
350 
351 /** Set a socket's send and receive buffer sizes.
352  * @param[in] fd %Socket file descriptor to manipulate.
353  * @param[in] ssize New send buffer size.
354  * @param[in] rsize New receive buffer size.
355  * @return Non-zero on success, or zero on failure.
356  */
os_set_sockbufs(int fd,unsigned int ssize,unsigned int rsize)357 int os_set_sockbufs(int fd, unsigned int ssize, unsigned int rsize)
358 {
359   unsigned int sopt = ssize;
360   unsigned int ropt = rsize;
361   return (0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
362                           (const char*) &ropt, sizeof(ropt)) &&
363           0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF,
364                           (const char*) &sopt, sizeof(sopt)));
365 }
366 
367 /** Set a socket's "type of service" value.
368  * @param[in] fd %Socket file descriptor to manipulate.
369  * @param[in] tos New type of service value to use.
370  * @param[in] family Address family of \a fd (AF_INET or AF_INET6).
371  * @return Non-zero on success, or zero on failure.
372  */
os_set_tos(int fd,int tos,int family)373 int os_set_tos(int fd, int tos, int family)
374 {
375   if (family == AF_INET) {
376 #if defined(IP_TOS) && defined(IPPROTO_IP)
377     return (0 == setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)));
378 #endif
379 #if defined(AF_INET6) && defined(IPV6_TCLASS) && defined(IPPROTO_IPV6)
380   } else if (family == AF_INET6) {
381     return (0 == setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)));
382 #endif
383   }
384 
385   return 1;
386 }
387 
388 /** Disable IP options on a socket.
389  * @param[in] fd %Socket file descriptor to manipulate.
390  * @return Non-zero on success, or zero on failure.
391  */
os_disable_options(int fd)392 int os_disable_options(int fd)
393 {
394 #if defined(IP_OPTIONS) && defined(IPPROTO_IP)
395   return (0 == setsockopt(fd, IPPROTO_IP, IP_OPTIONS, NULL, 0));
396 #else
397   return 1;
398 #endif
399 }
400 
401 /*
402  * Try and find the correct name to use with getrlimit() for setting the max.
403  * number of files allowed to be open by this process.
404  */
405 #ifdef RLIMIT_FDMAX
406 #define RLIMIT_FD_MAX   RLIMIT_FDMAX
407 #else
408 #ifdef RLIMIT_NOFILE
409 #define RLIMIT_FD_MAX RLIMIT_NOFILE
410 #else
411 #ifdef RLIMIT_OPEN_MAX
412 #define RLIMIT_FD_MAX RLIMIT_OPEN_MAX
413 #else
414 #undef RLIMIT_FD_MAX
415 #endif
416 #endif
417 #endif
418 
419 /** Set file descriptor limit for the process.
420  * @param[in] max_descriptors Ideal number of file descriptors.
421  * @return Zero on success; -1 on error; positive number of possible
422  * file descriptors if \a max_descriptors is too high.
423  */
os_set_fdlimit(unsigned int max_descriptors)424 int os_set_fdlimit(unsigned int max_descriptors)
425 {
426 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_FD_MAX)
427   struct rlimit limit;
428 
429   if (!getrlimit(RLIMIT_FD_MAX, &limit)) {
430     if (limit.rlim_max < max_descriptors)
431       return limit.rlim_max;
432     limit.rlim_cur = limit.rlim_max;    /* make soft limit the max */
433     return setrlimit(RLIMIT_FD_MAX, &limit);
434   }
435 #endif /* defined(HAVE_SETRLIMIT) && defined(RLIMIT_FD_MAX) */
436   return 0;
437 }
438 
439 /** Attempt to read from a non-blocking socket.
440  * @param[in] fd File descriptor to read from.
441  * @param[out] buf Output buffer to read into.
442  * @param[in] length Number of bytes to read.
443  * @param[out] count_out Receives number of bytes actually read.
444  * @return An IOResult value indicating status.
445  */
os_recv_nonb(int fd,char * buf,unsigned int length,unsigned int * count_out)446 IOResult os_recv_nonb(int fd, char* buf, unsigned int length,
447                  unsigned int* count_out)
448 {
449   int res;
450   assert(0 != buf);
451   assert(0 != count_out);
452 
453   if (0 < (res = recv(fd, buf, length, 0))) {
454     *count_out = (unsigned) res;
455     return IO_SUCCESS;
456   } else if (res == 0) {
457     *count_out = 0;
458     errno = 0; /* or ECONNRESET? */
459     return IO_FAILURE;
460   } else {
461     *count_out = 0;
462     return is_blocked(errno) ? IO_BLOCKED : IO_FAILURE;
463   }
464 }
465 
466 /** Attempt to read from a non-blocking UDP socket.
467  * @param[in] fd File descriptor to read from.
468  * @param[out] buf Output buffer to read into.
469  * @param[in] length Number of bytes to read.
470  * @param[out] length_out Receives number of bytes actually read.
471  * @param[out] addr_out Peer address that sent the message.
472  * @return An IOResult value indicating status.
473  */
os_recvfrom_nonb(int fd,char * buf,unsigned int length,unsigned int * length_out,struct irc_sockaddr * addr_out)474 IOResult os_recvfrom_nonb(int fd, char* buf, unsigned int length,
475                           unsigned int* length_out,
476                           struct irc_sockaddr* addr_out)
477 {
478   struct sockaddr_native addr;
479   unsigned int len = sizeof(addr);
480   int    res;
481   assert(0 != buf);
482   assert(0 != length_out);
483   assert(0 != addr_out);
484 
485   res = recvfrom(fd, buf, length, 0, (struct sockaddr*) &addr, &len);
486   if (-1 < res) {
487     sockaddr_to_irc(&addr, addr_out);
488     *length_out = res;
489     return IO_SUCCESS;
490   } else {
491     *length_out = 0;
492     return is_blocked(errno) ? IO_BLOCKED : IO_FAILURE;
493   }
494 }
495 
496 /** Attempt to write on a non-blocking UDP socket.
497  * @param[in] fd File descriptor to write to.
498  * @param[in] buf Output buffer to send from.
499  * @param[in] length Number of bytes to write.
500  * @param[out] count_out Receives number of bytes actually written.
501  * @param[in] flags Flags for call to sendto().
502  * @param[in] peer Destination address of the message.
503  * @return An IOResult value indicating status.
504  */
os_sendto_nonb(int fd,const char * buf,unsigned int length,unsigned int * count_out,unsigned int flags,const struct irc_sockaddr * peer)505 IOResult os_sendto_nonb(int fd, const char* buf, unsigned int length,
506                         unsigned int* count_out, unsigned int flags,
507                         const struct irc_sockaddr* peer)
508 {
509   struct sockaddr_native addr;
510   int res, size;
511   assert(0 != buf);
512 
513   size = sockaddr_from_irc(&addr, peer, fd, 0);
514   assert((addr.sn_family == AF_INET) == irc_in_addr_is_ipv4(&peer->addr));
515   if (-1 < (res = sendto(fd, buf, length, flags, (struct sockaddr*)&addr, size))) {
516     if (count_out)
517       *count_out = (unsigned) res;
518     return IO_SUCCESS;
519   } else {
520     if (count_out)
521       *count_out = 0;
522     return is_blocked(errno) ? IO_BLOCKED : IO_FAILURE;
523   }
524 }
525 
526 /** Attempt to write on a connected socket.
527  * @param[in] fd File descriptor to write to.
528  * @param[in] buf Output buffer to send from.
529  * @param[in] length Number of bytes to write.
530  * @param[out] count_out Receives number of bytes actually written.
531  * @return An IOResult value indicating status.
532  */
os_send_nonb(int fd,const char * buf,unsigned int length,unsigned int * count_out)533 IOResult os_send_nonb(int fd, const char* buf, unsigned int length,
534                  unsigned int* count_out)
535 {
536   int res;
537   assert(0 != buf);
538   assert(0 != count_out);
539 
540   if (-1 < (res = send(fd, buf, length, 0))) {
541     *count_out = (unsigned) res;
542     return IO_SUCCESS;
543   } else {
544     *count_out = 0;
545     return is_blocked(errno) ? IO_BLOCKED : IO_FAILURE;
546   }
547 }
548 
549 /** Attempt a vectored write on a connected socket.
550  * @param[in] fd File descriptor to write to.
551  * @param[in] buf Message queue to send from.
552  * @param[out] count_in Number of bytes mapped from \a buf.
553  * @param[out] count_out Receives number of bytes actually written.
554  * @return An IOResult value indicating status.
555  */
os_sendv_nonb(int fd,struct MsgQ * buf,unsigned int * count_in,unsigned int * count_out)556 IOResult os_sendv_nonb(int fd, struct MsgQ* buf, unsigned int* count_in,
557 		       unsigned int* count_out)
558 {
559   int res;
560   int count;
561   struct iovec iov[IOV_MAX];
562 
563   assert(0 != buf);
564   assert(0 != count_in);
565   assert(0 != count_out);
566 
567   *count_in = 0;
568   count = msgq_mapiov(buf, iov, IOV_MAX, count_in);
569 
570   if (-1 < (res = writev(fd, iov, count))) {
571     *count_out = (unsigned) res;
572     return IO_SUCCESS;
573   } else {
574     *count_out = 0;
575     return is_blocked(errno) ? IO_BLOCKED : IO_FAILURE;
576   }
577 }
578 
579 /** Open a TCP or UDP socket on a particular address.
580  * @param[in] local Local address to bind to.
581  * @param[in] type SOCK_STREAM or SOCK_DGRAM.
582  * @param[in] port_name Port name (used in error diagnostics).
583  * @param[in] family A specific address family to use, or 0 for automatic.
584  * @return Bound descriptor, or -1 on error.
585  */
os_socket(const struct irc_sockaddr * local,int type,const char * port_name,int family)586 int os_socket(const struct irc_sockaddr* local, int type, const char* port_name, int family)
587 {
588   struct sockaddr_native addr;
589   int size, fd;
590 
591   assert(local != 0);
592   size = sockaddr_from_irc(&addr, local, -1, family);
593   fd = socket(addr.sn_family, type, 0);
594   if (fd < 0) {
595     report_error(SOCKET_ERROR_MSG, port_name, errno);
596     return -1;
597   }
598   if (fd > MAXCLIENTS - 1) {
599     report_error(CONNLIMIT_ERROR_MSG, port_name, 0);
600     close(fd);
601     return -1;
602   }
603   if (!os_set_reuseaddr(fd)) {
604     report_error(REUSEADDR_ERROR_MSG, port_name, errno);
605     close(fd);
606     return -1;
607   }
608   if (!os_set_nonblocking(fd)) {
609     report_error(NONB_ERROR_MSG, port_name, errno);
610     close(fd);
611     return -1;
612   }
613   if (local) {
614 #if defined(IPV6_V6ONLY)
615     int on = 1;
616     if (family == AF_INET6 && irc_in_addr_unspec(&local->addr))
617       setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
618 #endif
619     if (bind(fd, (struct sockaddr*)&addr, size)) {
620       report_error(BIND_ERROR_MSG, port_name, errno);
621       close(fd);
622       return -1;
623     }
624   }
625   return fd;
626 }
627 
628 /** Accept a connection on a socket.
629  * @param[in] fd Listening file descriptor.
630  * @param[out] peer Peer address of connection.
631  * @return File descriptor for accepted connection.
632  */
os_accept(int fd,struct irc_sockaddr * peer)633 int os_accept(int fd, struct irc_sockaddr* peer)
634 {
635   struct sockaddr_native addr;
636   socklen_t addrlen;
637   int new_fd;
638 
639   addrlen = sizeof(addr);
640   new_fd = accept(fd, (struct sockaddr*)&addr, &addrlen);
641   if (new_fd < 0)
642     memset(peer, 0, sizeof(*peer));
643   else
644     sockaddr_to_irc(&addr, peer);
645   return new_fd;
646 }
647 
648 /** Start a non-blocking connection.
649  * @param[in] fd Disconnected file descriptor.
650  * @param[in] sin Target address for connection.
651  * @return IOResult code indicating status.
652  */
os_connect_nonb(int fd,const struct irc_sockaddr * sin)653 IOResult os_connect_nonb(int fd, const struct irc_sockaddr* sin)
654 {
655   struct sockaddr_native addr;
656   int size;
657 
658   size = sockaddr_from_irc(&addr, sin, fd, 0);
659   if (0 == connect(fd, (struct sockaddr*) &addr, size))
660     return IO_SUCCESS;
661   else if (errno == EINPROGRESS)
662     return IO_BLOCKED;
663   else
664     return IO_FAILURE;
665 }
666 
667 /** Get local address of a socket.
668  * @param[in] fd File descriptor to operate on.
669  * @param[out] sin_out Receives local socket address.
670  * @return Non-zero on success; zero on error.
671  */
os_get_sockname(int fd,struct irc_sockaddr * sin_out)672 int os_get_sockname(int fd, struct irc_sockaddr* sin_out)
673 {
674   struct sockaddr_native addr;
675   unsigned int len = sizeof(addr);
676 
677   assert(0 != sin_out);
678   if (getsockname(fd, (struct sockaddr*) &addr, &len))
679     return 0;
680   sockaddr_to_irc(&addr, sin_out);
681   return 1;
682 }
683 
684 /** Get remote address of a socket.
685  * @param[in] fd File descriptor to operate on.
686  * @param[out] sin_out Receives remote socket address.
687  * @return Non-zero on success; zero on error.
688  */
os_get_peername(int fd,struct irc_sockaddr * sin_out)689 int os_get_peername(int fd, struct irc_sockaddr* sin_out)
690 {
691   struct sockaddr_native addr;
692   unsigned int len = sizeof(addr);
693 
694   assert(0 != sin_out);
695   if (getpeername(fd, (struct sockaddr*) &addr, &len))
696     return 0;
697   sockaddr_to_irc(&addr, sin_out);
698   return 1;
699 }
700 
701 /** Start listening on a socket.
702  * @param[in] fd Disconnected file descriptor.
703  * @param[in] backlog Maximum number of un-accept()ed connections to keep.
704  * @return Non-zero on success; zero on error.
705  */
os_set_listen(int fd,int backlog)706 int os_set_listen(int fd, int backlog)
707 {
708   return (0 == listen(fd, backlog));
709 }
710 
711 /** Allocate a connected pair of local sockets.
712  * @param[out] sv Array of two file descriptors.
713  * @return Zero on success; non-zero number on error.
714  */
os_socketpair(int sv[2])715 int os_socketpair(int sv[2])
716 {
717     return socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
718 }
719