]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/bind9/lib/isc/unix/socket.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / bind9 / lib / isc / unix / socket.c
1 /*
2  * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 1998-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: socket.c,v 1.333.14.9 2011-07-29 02:19:20 marka Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <sys/param.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/uio.h>
30
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stddef.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37
38 #include <isc/buffer.h>
39 #include <isc/bufferlist.h>
40 #include <isc/condition.h>
41 #include <isc/formatcheck.h>
42 #include <isc/list.h>
43 #include <isc/log.h>
44 #include <isc/mem.h>
45 #include <isc/msgs.h>
46 #include <isc/mutex.h>
47 #include <isc/net.h>
48 #include <isc/once.h>
49 #include <isc/platform.h>
50 #include <isc/print.h>
51 #include <isc/region.h>
52 #include <isc/socket.h>
53 #include <isc/stats.h>
54 #include <isc/strerror.h>
55 #include <isc/task.h>
56 #include <isc/thread.h>
57 #include <isc/util.h>
58 #include <isc/xml.h>
59
60 #ifdef ISC_PLATFORM_HAVESYSUNH
61 #include <sys/un.h>
62 #endif
63 #ifdef ISC_PLATFORM_HAVEKQUEUE
64 #include <sys/event.h>
65 #endif
66 #ifdef ISC_PLATFORM_HAVEEPOLL
67 #include <sys/epoll.h>
68 #endif
69 #ifdef ISC_PLATFORM_HAVEDEVPOLL
70 #if defined(HAVE_SYS_DEVPOLL_H)
71 #include <sys/devpoll.h>
72 #elif defined(HAVE_DEVPOLL_H)
73 #include <devpoll.h>
74 #endif
75 #endif
76
77 #include "errno2result.h"
78
79 /* See task.c about the following definition: */
80 #ifdef BIND9
81 #ifdef ISC_PLATFORM_USETHREADS
82 #define USE_WATCHER_THREAD
83 #else
84 #define USE_SHARED_MANAGER
85 #endif  /* ISC_PLATFORM_USETHREADS */
86 #endif  /* BIND9 */
87
88 #ifndef USE_WATCHER_THREAD
89 #include "socket_p.h"
90 #include "../task_p.h"
91 #endif /* USE_WATCHER_THREAD */
92
93 #if defined(SO_BSDCOMPAT) && defined(__linux__)
94 #include <sys/utsname.h>
95 #endif
96
97 /*%
98  * Choose the most preferable multiplex method.
99  */
100 #ifdef ISC_PLATFORM_HAVEKQUEUE
101 #define USE_KQUEUE
102 #elif defined (ISC_PLATFORM_HAVEEPOLL)
103 #define USE_EPOLL
104 #elif defined (ISC_PLATFORM_HAVEDEVPOLL)
105 #define USE_DEVPOLL
106 typedef struct {
107         unsigned int want_read : 1,
108                 want_write : 1;
109 } pollinfo_t;
110 #else
111 #define USE_SELECT
112 #endif  /* ISC_PLATFORM_HAVEKQUEUE */
113
114 #ifndef USE_WATCHER_THREAD
115 #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL)
116 struct isc_socketwait {
117         int nevents;
118 };
119 #elif defined (USE_SELECT)
120 struct isc_socketwait {
121         fd_set *readset;
122         fd_set *writeset;
123         int nfds;
124         int maxfd;
125 };
126 #endif  /* USE_KQUEUE */
127 #endif /* !USE_WATCHER_THREAD */
128
129 /*%
130  * Maximum number of allowable open sockets.  This is also the maximum
131  * allowable socket file descriptor.
132  *
133  * Care should be taken before modifying this value for select():
134  * The API standard doesn't ensure select() accept more than (the system default
135  * of) FD_SETSIZE descriptors, and the default size should in fact be fine in
136  * the vast majority of cases.  This constant should therefore be increased only
137  * when absolutely necessary and possible, i.e., the server is exhausting all
138  * available file descriptors (up to FD_SETSIZE) and the select() function
139  * and FD_xxx macros support larger values than FD_SETSIZE (which may not
140  * always by true, but we keep using some of them to ensure as much
141  * portability as possible).  Note also that overall server performance
142  * may be rather worsened with a larger value of this constant due to
143  * inherent scalability problems of select().
144  *
145  * As a special note, this value shouldn't have to be touched if
146  * this is a build for an authoritative only DNS server.
147  */
148 #ifndef ISC_SOCKET_MAXSOCKETS
149 #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL)
150 #define ISC_SOCKET_MAXSOCKETS 4096
151 #elif defined(USE_SELECT)
152 #define ISC_SOCKET_MAXSOCKETS FD_SETSIZE
153 #endif  /* USE_KQUEUE... */
154 #endif  /* ISC_SOCKET_MAXSOCKETS */
155
156 #ifdef USE_SELECT
157 /*%
158  * Mac OS X needs a special definition to support larger values in select().
159  * We always define this because a larger value can be specified run-time.
160  */
161 #ifdef __APPLE__
162 #define _DARWIN_UNLIMITED_SELECT
163 #endif  /* __APPLE__ */
164 #endif  /* USE_SELECT */
165
166 #ifdef ISC_SOCKET_USE_POLLWATCH
167 /*%
168  * If this macro is defined, enable workaround for a Solaris /dev/poll kernel
169  * bug: DP_POLL ioctl could keep sleeping even if socket I/O is possible for
170  * some of the specified FD.  The idea is based on the observation that it's
171  * likely for a busy server to keep receiving packets.  It specifically works
172  * as follows: the socket watcher is first initialized with the state of
173  * "poll_idle".  While it's in the idle state it keeps sleeping until a socket
174  * event occurs.  When it wakes up for a socket I/O event, it moves to the
175  * poll_active state, and sets the poll timeout to a short period
176  * (ISC_SOCKET_POLLWATCH_TIMEOUT msec).  If timeout occurs in this state, the
177  * watcher goes to the poll_checking state with the same timeout period.
178  * In this state, the watcher tries to detect whether this is a break
179  * during intermittent events or the kernel bug is triggered.  If the next
180  * polling reports an event within the short period, the previous timeout is
181  * likely to be a kernel bug, and so the watcher goes back to the active state.
182  * Otherwise, it moves to the idle state again.
183  *
184  * It's not clear whether this is a thread-related bug, but since we've only
185  * seen this with threads, this workaround is used only when enabling threads.
186  */
187
188 typedef enum { poll_idle, poll_active, poll_checking } pollstate_t;
189
190 #ifndef ISC_SOCKET_POLLWATCH_TIMEOUT
191 #define ISC_SOCKET_POLLWATCH_TIMEOUT 10
192 #endif  /* ISC_SOCKET_POLLWATCH_TIMEOUT */
193 #endif  /* ISC_SOCKET_USE_POLLWATCH */
194
195 /*%
196  * Size of per-FD lock buckets.
197  */
198 #ifdef ISC_PLATFORM_USETHREADS
199 #define FDLOCK_COUNT            1024
200 #define FDLOCK_ID(fd)           ((fd) % FDLOCK_COUNT)
201 #else
202 #define FDLOCK_COUNT            1
203 #define FDLOCK_ID(fd)           0
204 #endif  /* ISC_PLATFORM_USETHREADS */
205
206 /*%
207  * Maximum number of events communicated with the kernel.  There should normally
208  * be no need for having a large number.
209  */
210 #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL)
211 #ifndef ISC_SOCKET_MAXEVENTS
212 #define ISC_SOCKET_MAXEVENTS    64
213 #endif
214 #endif
215
216 /*%
217  * Some systems define the socket length argument as an int, some as size_t,
218  * some as socklen_t.  This is here so it can be easily changed if needed.
219  */
220 #ifndef ISC_SOCKADDR_LEN_T
221 #define ISC_SOCKADDR_LEN_T unsigned int
222 #endif
223
224 /*%
225  * Define what the possible "soft" errors can be.  These are non-fatal returns
226  * of various network related functions, like recv() and so on.
227  *
228  * For some reason, BSDI (and perhaps others) will sometimes return <0
229  * from recv() but will have errno==0.  This is broken, but we have to
230  * work around it here.
231  */
232 #define SOFT_ERROR(e)   ((e) == EAGAIN || \
233                          (e) == EWOULDBLOCK || \
234                          (e) == EINTR || \
235                          (e) == 0)
236
237 #define DLVL(x) ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(x)
238
239 /*!<
240  * DLVL(90)  --  Function entry/exit and other tracing.
241  * DLVL(70)  --  Socket "correctness" -- including returning of events, etc.
242  * DLVL(60)  --  Socket data send/receive
243  * DLVL(50)  --  Event tracing, including receiving/sending completion events.
244  * DLVL(20)  --  Socket creation/destruction.
245  */
246 #define TRACE_LEVEL             90
247 #define CORRECTNESS_LEVEL       70
248 #define IOEVENT_LEVEL           60
249 #define EVENT_LEVEL             50
250 #define CREATION_LEVEL          20
251
252 #define TRACE           DLVL(TRACE_LEVEL)
253 #define CORRECTNESS     DLVL(CORRECTNESS_LEVEL)
254 #define IOEVENT         DLVL(IOEVENT_LEVEL)
255 #define EVENT           DLVL(EVENT_LEVEL)
256 #define CREATION        DLVL(CREATION_LEVEL)
257
258 typedef isc_event_t intev_t;
259
260 #define SOCKET_MAGIC            ISC_MAGIC('I', 'O', 'i', 'o')
261 #define VALID_SOCKET(s)         ISC_MAGIC_VALID(s, SOCKET_MAGIC)
262
263 /*!
264  * IPv6 control information.  If the socket is an IPv6 socket we want
265  * to collect the destination address and interface so the client can
266  * set them on outgoing packets.
267  */
268 #ifdef ISC_PLATFORM_HAVEIN6PKTINFO
269 #ifndef USE_CMSG
270 #define USE_CMSG        1
271 #endif
272 #endif
273
274 /*%
275  * NetBSD and FreeBSD can timestamp packets.  XXXMLG Should we have
276  * a setsockopt() like interface to request timestamps, and if the OS
277  * doesn't do it for us, call gettimeofday() on every UDP receive?
278  */
279 #ifdef SO_TIMESTAMP
280 #ifndef USE_CMSG
281 #define USE_CMSG        1
282 #endif
283 #endif
284
285 /*%
286  * The size to raise the receive buffer to (from BIND 8).
287  */
288 #define RCVBUFSIZE (32*1024)
289
290 /*%
291  * The number of times a send operation is repeated if the result is EINTR.
292  */
293 #define NRETRIES 10
294
295 typedef struct isc__socket isc__socket_t;
296 typedef struct isc__socketmgr isc__socketmgr_t;
297
298 #define NEWCONNSOCK(ev) ((isc__socket_t *)(ev)->newsocket)
299
300 struct isc__socket {
301         /* Not locked. */
302         isc_socket_t            common;
303         isc__socketmgr_t        *manager;
304         isc_mutex_t             lock;
305         isc_sockettype_t        type;
306         const isc_statscounter_t        *statsindex;
307
308         /* Locked by socket lock. */
309         ISC_LINK(isc__socket_t) link;
310         unsigned int            references;
311         int                     fd;
312         int                     pf;
313         char                            name[16];
314         void *                          tag;
315
316         ISC_LIST(isc_socketevent_t)             send_list;
317         ISC_LIST(isc_socketevent_t)             recv_list;
318         ISC_LIST(isc_socket_newconnev_t)        accept_list;
319         isc_socket_connev_t                    *connect_ev;
320
321         /*
322          * Internal events.  Posted when a descriptor is readable or
323          * writable.  These are statically allocated and never freed.
324          * They will be set to non-purgable before use.
325          */
326         intev_t                 readable_ev;
327         intev_t                 writable_ev;
328
329         isc_sockaddr_t          peer_address;  /* remote address */
330
331         unsigned int            pending_recv : 1,
332                                 pending_send : 1,
333                                 pending_accept : 1,
334                                 listener : 1, /* listener socket */
335                                 connected : 1,
336                                 connecting : 1, /* connect pending */
337                                 bound : 1; /* bound to local addr */
338
339 #ifdef ISC_NET_RECVOVERFLOW
340         unsigned char           overflow; /* used for MSG_TRUNC fake */
341 #endif
342
343         char                    *recvcmsgbuf;
344         ISC_SOCKADDR_LEN_T      recvcmsgbuflen;
345         char                    *sendcmsgbuf;
346         ISC_SOCKADDR_LEN_T      sendcmsgbuflen;
347
348         void                    *fdwatcharg;
349         isc_sockfdwatch_t       fdwatchcb;
350         int                     fdwatchflags;
351         isc_task_t              *fdwatchtask;
352 };
353
354 #define SOCKET_MANAGER_MAGIC    ISC_MAGIC('I', 'O', 'm', 'g')
355 #define VALID_MANAGER(m)        ISC_MAGIC_VALID(m, SOCKET_MANAGER_MAGIC)
356
357 struct isc__socketmgr {
358         /* Not locked. */
359         isc_socketmgr_t         common;
360         isc_mem_t              *mctx;
361         isc_mutex_t             lock;
362         isc_mutex_t             *fdlock;
363         isc_stats_t             *stats;
364 #ifdef USE_KQUEUE
365         int                     kqueue_fd;
366         int                     nevents;
367         struct kevent           *events;
368 #endif  /* USE_KQUEUE */
369 #ifdef USE_EPOLL
370         int                     epoll_fd;
371         int                     nevents;
372         struct epoll_event      *events;
373 #endif  /* USE_EPOLL */
374 #ifdef USE_DEVPOLL
375         int                     devpoll_fd;
376         int                     nevents;
377         struct pollfd           *events;
378 #endif  /* USE_DEVPOLL */
379 #ifdef USE_SELECT
380         int                     fd_bufsize;
381 #endif  /* USE_SELECT */
382         unsigned int            maxsocks;
383 #ifdef ISC_PLATFORM_USETHREADS
384         int                     pipe_fds[2];
385 #endif
386
387         /* Locked by fdlock. */
388         isc__socket_t          **fds;
389         int                     *fdstate;
390 #ifdef USE_DEVPOLL
391         pollinfo_t              *fdpollinfo;
392 #endif
393
394         /* Locked by manager lock. */
395         ISC_LIST(isc__socket_t) socklist;
396 #ifdef USE_SELECT
397         fd_set                  *read_fds;
398         fd_set                  *read_fds_copy;
399         fd_set                  *write_fds;
400         fd_set                  *write_fds_copy;
401         int                     maxfd;
402 #endif  /* USE_SELECT */
403         int                     reserved;       /* unlocked */
404 #ifdef USE_WATCHER_THREAD
405         isc_thread_t            watcher;
406         isc_condition_t         shutdown_ok;
407 #else /* USE_WATCHER_THREAD */
408         unsigned int            refs;
409 #endif /* USE_WATCHER_THREAD */
410         int                     maxudp;
411 };
412
413 #ifdef USE_SHARED_MANAGER
414 static isc__socketmgr_t *socketmgr = NULL;
415 #endif /* USE_SHARED_MANAGER */
416
417 #define CLOSED                  0       /* this one must be zero */
418 #define MANAGED                 1
419 #define CLOSE_PENDING           2
420
421 /*
422  * send() and recv() iovec counts
423  */
424 #define MAXSCATTERGATHER_SEND   (ISC_SOCKET_MAXSCATTERGATHER)
425 #ifdef ISC_NET_RECVOVERFLOW
426 # define MAXSCATTERGATHER_RECV  (ISC_SOCKET_MAXSCATTERGATHER + 1)
427 #else
428 # define MAXSCATTERGATHER_RECV  (ISC_SOCKET_MAXSCATTERGATHER)
429 #endif
430
431 static void send_recvdone_event(isc__socket_t *, isc_socketevent_t **);
432 static void send_senddone_event(isc__socket_t *, isc_socketevent_t **);
433 static void free_socket(isc__socket_t **);
434 static isc_result_t allocate_socket(isc__socketmgr_t *, isc_sockettype_t,
435                                     isc__socket_t **);
436 static void destroy(isc__socket_t **);
437 static void internal_accept(isc_task_t *, isc_event_t *);
438 static void internal_connect(isc_task_t *, isc_event_t *);
439 static void internal_recv(isc_task_t *, isc_event_t *);
440 static void internal_send(isc_task_t *, isc_event_t *);
441 static void internal_fdwatch_write(isc_task_t *, isc_event_t *);
442 static void internal_fdwatch_read(isc_task_t *, isc_event_t *);
443 static void process_cmsg(isc__socket_t *, struct msghdr *, isc_socketevent_t *);
444 static void build_msghdr_send(isc__socket_t *, isc_socketevent_t *,
445                               struct msghdr *, struct iovec *, size_t *);
446 static void build_msghdr_recv(isc__socket_t *, isc_socketevent_t *,
447                               struct msghdr *, struct iovec *, size_t *);
448 #ifdef USE_WATCHER_THREAD
449 static isc_boolean_t process_ctlfd(isc__socketmgr_t *manager);
450 #endif
451
452 /*%
453  * The following can be either static or public, depending on build environment.
454  */
455
456 #ifdef BIND9
457 #define ISC_SOCKETFUNC_SCOPE
458 #else
459 #define ISC_SOCKETFUNC_SCOPE static
460 #endif
461
462 ISC_SOCKETFUNC_SCOPE isc_result_t
463 isc__socket_create(isc_socketmgr_t *manager, int pf, isc_sockettype_t type,
464                    isc_socket_t **socketp);
465 ISC_SOCKETFUNC_SCOPE void
466 isc__socket_attach(isc_socket_t *sock, isc_socket_t **socketp);
467 ISC_SOCKETFUNC_SCOPE void
468 isc__socket_detach(isc_socket_t **socketp);
469 ISC_SOCKETFUNC_SCOPE isc_result_t
470 isc__socketmgr_create(isc_mem_t *mctx, isc_socketmgr_t **managerp);
471 ISC_SOCKETFUNC_SCOPE isc_result_t
472 isc__socketmgr_create2(isc_mem_t *mctx, isc_socketmgr_t **managerp,
473                        unsigned int maxsocks);
474 ISC_SOCKETFUNC_SCOPE void
475 isc__socketmgr_destroy(isc_socketmgr_t **managerp);
476 ISC_SOCKETFUNC_SCOPE isc_result_t
477 isc__socket_recvv(isc_socket_t *sock, isc_bufferlist_t *buflist,
478                  unsigned int minimum, isc_task_t *task,
479                   isc_taskaction_t action, const void *arg);
480 ISC_SOCKETFUNC_SCOPE isc_result_t
481 isc__socket_recv(isc_socket_t *sock, isc_region_t *region,
482                  unsigned int minimum, isc_task_t *task,
483                  isc_taskaction_t action, const void *arg);
484 ISC_SOCKETFUNC_SCOPE isc_result_t
485 isc__socket_recv2(isc_socket_t *sock, isc_region_t *region,
486                   unsigned int minimum, isc_task_t *task,
487                   isc_socketevent_t *event, unsigned int flags);
488 ISC_SOCKETFUNC_SCOPE isc_result_t
489 isc__socket_send(isc_socket_t *sock, isc_region_t *region,
490                  isc_task_t *task, isc_taskaction_t action, const void *arg);
491 ISC_SOCKETFUNC_SCOPE isc_result_t
492 isc__socket_sendto(isc_socket_t *sock, isc_region_t *region,
493                    isc_task_t *task, isc_taskaction_t action, const void *arg,
494                    isc_sockaddr_t *address, struct in6_pktinfo *pktinfo);
495 ISC_SOCKETFUNC_SCOPE isc_result_t
496 isc__socket_sendv(isc_socket_t *sock, isc_bufferlist_t *buflist,
497                   isc_task_t *task, isc_taskaction_t action, const void *arg);
498 ISC_SOCKETFUNC_SCOPE isc_result_t
499 isc__socket_sendtov(isc_socket_t *sock, isc_bufferlist_t *buflist,
500                     isc_task_t *task, isc_taskaction_t action, const void *arg,
501                     isc_sockaddr_t *address, struct in6_pktinfo *pktinfo);
502 ISC_SOCKETFUNC_SCOPE isc_result_t
503 isc__socket_sendto2(isc_socket_t *sock, isc_region_t *region,
504                     isc_task_t *task,
505                     isc_sockaddr_t *address, struct in6_pktinfo *pktinfo,
506                     isc_socketevent_t *event, unsigned int flags);
507 ISC_SOCKETFUNC_SCOPE void
508 isc__socket_cleanunix(isc_sockaddr_t *sockaddr, isc_boolean_t active);
509 ISC_SOCKETFUNC_SCOPE isc_result_t
510 isc__socket_permunix(isc_sockaddr_t *sockaddr, isc_uint32_t perm,
511                      isc_uint32_t owner, isc_uint32_t group);
512 ISC_SOCKETFUNC_SCOPE isc_result_t
513 isc__socket_bind(isc_socket_t *sock, isc_sockaddr_t *sockaddr,
514                  unsigned int options);
515 ISC_SOCKETFUNC_SCOPE isc_result_t
516 isc__socket_filter(isc_socket_t *sock, const char *filter);
517 ISC_SOCKETFUNC_SCOPE isc_result_t
518 isc__socket_listen(isc_socket_t *sock, unsigned int backlog);
519 ISC_SOCKETFUNC_SCOPE isc_result_t
520 isc__socket_accept(isc_socket_t *sock,
521                    isc_task_t *task, isc_taskaction_t action, const void *arg);
522 ISC_SOCKETFUNC_SCOPE isc_result_t
523 isc__socket_connect(isc_socket_t *sock, isc_sockaddr_t *addr,
524                     isc_task_t *task, isc_taskaction_t action,
525                     const void *arg);
526 ISC_SOCKETFUNC_SCOPE isc_result_t
527 isc__socket_getpeername(isc_socket_t *sock, isc_sockaddr_t *addressp);
528 ISC_SOCKETFUNC_SCOPE isc_result_t
529 isc__socket_getsockname(isc_socket_t *sock, isc_sockaddr_t *addressp);
530 ISC_SOCKETFUNC_SCOPE void
531 isc__socket_cancel(isc_socket_t *sock, isc_task_t *task, unsigned int how);
532 ISC_SOCKETFUNC_SCOPE isc_sockettype_t
533 isc__socket_gettype(isc_socket_t *sock);
534 ISC_SOCKETFUNC_SCOPE isc_boolean_t
535 isc__socket_isbound(isc_socket_t *sock);
536 ISC_SOCKETFUNC_SCOPE void
537 isc__socket_ipv6only(isc_socket_t *sock, isc_boolean_t yes);
538 #if defined(HAVE_LIBXML2) && defined(BIND9)
539 ISC_SOCKETFUNC_SCOPE void
540 isc__socketmgr_renderxml(isc_socketmgr_t *mgr0, xmlTextWriterPtr writer);
541 #endif
542
543 ISC_SOCKETFUNC_SCOPE isc_result_t
544 isc__socket_fdwatchcreate(isc_socketmgr_t *manager, int fd, int flags,
545                           isc_sockfdwatch_t callback, void *cbarg,
546                           isc_task_t *task, isc_socket_t **socketp);
547 ISC_SOCKETFUNC_SCOPE isc_result_t
548 isc__socket_fdwatchpoke(isc_socket_t *sock, int flags);
549
550 static struct {
551         isc_socketmethods_t methods;
552
553         /*%
554          * The following are defined just for avoiding unused static functions.
555          */
556 #ifndef BIND9
557         void *recvv, *send, *sendv, *sendto2, *cleanunix, *permunix, *filter,
558                 *listen, *accept, *getpeername, *isbound;
559 #endif
560 } socketmethods = {
561         {
562                 isc__socket_attach,
563                 isc__socket_detach,
564                 isc__socket_bind,
565                 isc__socket_sendto,
566                 isc__socket_connect,
567                 isc__socket_recv,
568                 isc__socket_cancel,
569                 isc__socket_getsockname,
570                 isc__socket_gettype,
571                 isc__socket_ipv6only,
572                 isc__socket_fdwatchpoke
573         }
574 #ifndef BIND9
575         ,
576         (void *)isc__socket_recvv, (void *)isc__socket_send,
577         (void *)isc__socket_sendv, (void *)isc__socket_sendto2,
578         (void *)isc__socket_cleanunix, (void *)isc__socket_permunix,
579         (void *)isc__socket_filter, (void *)isc__socket_listen,
580         (void *)isc__socket_accept, (void *)isc__socket_getpeername,
581         (void *)isc__socket_isbound
582 #endif
583 };
584
585 static isc_socketmgrmethods_t socketmgrmethods = {
586         isc__socketmgr_destroy,
587         isc__socket_create,
588         isc__socket_fdwatchcreate
589 };
590
591 #define SELECT_POKE_SHUTDOWN            (-1)
592 #define SELECT_POKE_NOTHING             (-2)
593 #define SELECT_POKE_READ                (-3)
594 #define SELECT_POKE_ACCEPT              (-3) /*%< Same as _READ */
595 #define SELECT_POKE_WRITE               (-4)
596 #define SELECT_POKE_CONNECT             (-4) /*%< Same as _WRITE */
597 #define SELECT_POKE_CLOSE               (-5)
598
599 #define SOCK_DEAD(s)                    ((s)->references == 0)
600
601 /*%
602  * Shortcut index arrays to get access to statistics counters.
603  */
604 enum {
605         STATID_OPEN = 0,
606         STATID_OPENFAIL = 1,
607         STATID_CLOSE = 2,
608         STATID_BINDFAIL = 3,
609         STATID_CONNECTFAIL = 4,
610         STATID_CONNECT = 5,
611         STATID_ACCEPTFAIL = 6,
612         STATID_ACCEPT = 7,
613         STATID_SENDFAIL = 8,
614         STATID_RECVFAIL = 9
615 };
616 static const isc_statscounter_t upd4statsindex[] = {
617         isc_sockstatscounter_udp4open,
618         isc_sockstatscounter_udp4openfail,
619         isc_sockstatscounter_udp4close,
620         isc_sockstatscounter_udp4bindfail,
621         isc_sockstatscounter_udp4connectfail,
622         isc_sockstatscounter_udp4connect,
623         -1,
624         -1,
625         isc_sockstatscounter_udp4sendfail,
626         isc_sockstatscounter_udp4recvfail
627 };
628 static const isc_statscounter_t upd6statsindex[] = {
629         isc_sockstatscounter_udp6open,
630         isc_sockstatscounter_udp6openfail,
631         isc_sockstatscounter_udp6close,
632         isc_sockstatscounter_udp6bindfail,
633         isc_sockstatscounter_udp6connectfail,
634         isc_sockstatscounter_udp6connect,
635         -1,
636         -1,
637         isc_sockstatscounter_udp6sendfail,
638         isc_sockstatscounter_udp6recvfail
639 };
640 static const isc_statscounter_t tcp4statsindex[] = {
641         isc_sockstatscounter_tcp4open,
642         isc_sockstatscounter_tcp4openfail,
643         isc_sockstatscounter_tcp4close,
644         isc_sockstatscounter_tcp4bindfail,
645         isc_sockstatscounter_tcp4connectfail,
646         isc_sockstatscounter_tcp4connect,
647         isc_sockstatscounter_tcp4acceptfail,
648         isc_sockstatscounter_tcp4accept,
649         isc_sockstatscounter_tcp4sendfail,
650         isc_sockstatscounter_tcp4recvfail
651 };
652 static const isc_statscounter_t tcp6statsindex[] = {
653         isc_sockstatscounter_tcp6open,
654         isc_sockstatscounter_tcp6openfail,
655         isc_sockstatscounter_tcp6close,
656         isc_sockstatscounter_tcp6bindfail,
657         isc_sockstatscounter_tcp6connectfail,
658         isc_sockstatscounter_tcp6connect,
659         isc_sockstatscounter_tcp6acceptfail,
660         isc_sockstatscounter_tcp6accept,
661         isc_sockstatscounter_tcp6sendfail,
662         isc_sockstatscounter_tcp6recvfail
663 };
664 static const isc_statscounter_t unixstatsindex[] = {
665         isc_sockstatscounter_unixopen,
666         isc_sockstatscounter_unixopenfail,
667         isc_sockstatscounter_unixclose,
668         isc_sockstatscounter_unixbindfail,
669         isc_sockstatscounter_unixconnectfail,
670         isc_sockstatscounter_unixconnect,
671         isc_sockstatscounter_unixacceptfail,
672         isc_sockstatscounter_unixaccept,
673         isc_sockstatscounter_unixsendfail,
674         isc_sockstatscounter_unixrecvfail
675 };
676 static const isc_statscounter_t fdwatchstatsindex[] = {
677         -1,
678         -1,
679         isc_sockstatscounter_fdwatchclose,
680         isc_sockstatscounter_fdwatchbindfail,
681         isc_sockstatscounter_fdwatchconnectfail,
682         isc_sockstatscounter_fdwatchconnect,
683         -1,
684         -1,
685         isc_sockstatscounter_fdwatchsendfail,
686         isc_sockstatscounter_fdwatchrecvfail
687 };
688
689 #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) || \
690     defined(USE_WATCHER_THREAD)
691 static void
692 manager_log(isc__socketmgr_t *sockmgr,
693             isc_logcategory_t *category, isc_logmodule_t *module, int level,
694             const char *fmt, ...) ISC_FORMAT_PRINTF(5, 6);
695 static void
696 manager_log(isc__socketmgr_t *sockmgr,
697             isc_logcategory_t *category, isc_logmodule_t *module, int level,
698             const char *fmt, ...)
699 {
700         char msgbuf[2048];
701         va_list ap;
702
703         if (! isc_log_wouldlog(isc_lctx, level))
704                 return;
705
706         va_start(ap, fmt);
707         vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
708         va_end(ap);
709
710         isc_log_write(isc_lctx, category, module, level,
711                       "sockmgr %p: %s", sockmgr, msgbuf);
712 }
713 #endif
714
715 static void
716 socket_log(isc__socket_t *sock, isc_sockaddr_t *address,
717            isc_logcategory_t *category, isc_logmodule_t *module, int level,
718            isc_msgcat_t *msgcat, int msgset, int message,
719            const char *fmt, ...) ISC_FORMAT_PRINTF(9, 10);
720 static void
721 socket_log(isc__socket_t *sock, isc_sockaddr_t *address,
722            isc_logcategory_t *category, isc_logmodule_t *module, int level,
723            isc_msgcat_t *msgcat, int msgset, int message,
724            const char *fmt, ...)
725 {
726         char msgbuf[2048];
727         char peerbuf[ISC_SOCKADDR_FORMATSIZE];
728         va_list ap;
729
730         if (! isc_log_wouldlog(isc_lctx, level))
731                 return;
732
733         va_start(ap, fmt);
734         vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
735         va_end(ap);
736
737         if (address == NULL) {
738                 isc_log_iwrite(isc_lctx, category, module, level,
739                                msgcat, msgset, message,
740                                "socket %p: %s", sock, msgbuf);
741         } else {
742                 isc_sockaddr_format(address, peerbuf, sizeof(peerbuf));
743                 isc_log_iwrite(isc_lctx, category, module, level,
744                                msgcat, msgset, message,
745                                "socket %p %s: %s", sock, peerbuf, msgbuf);
746         }
747 }
748
749 #if defined(_AIX) && defined(ISC_NET_BSD44MSGHDR) && \
750     defined(USE_CMSG) && defined(IPV6_RECVPKTINFO)
751 /*
752  * AIX has a kernel bug where IPV6_RECVPKTINFO gets cleared by
753  * setting IPV6_V6ONLY.
754  */
755 static void
756 FIX_IPV6_RECVPKTINFO(isc__socket_t *sock)
757 {
758         char strbuf[ISC_STRERRORSIZE];
759         int on = 1;
760
761         if (sock->pf != AF_INET6 || sock->type != isc_sockettype_udp)
762                 return;
763
764         if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
765                        (void *)&on, sizeof(on)) < 0) {
766
767                 isc__strerror(errno, strbuf, sizeof(strbuf));
768                 UNEXPECTED_ERROR(__FILE__, __LINE__,
769                                  "setsockopt(%d, IPV6_RECVPKTINFO) "
770                                  "%s: %s", sock->fd,
771                                  isc_msgcat_get(isc_msgcat,
772                                                 ISC_MSGSET_GENERAL,
773                                                 ISC_MSG_FAILED,
774                                                 "failed"),
775                                  strbuf);
776         }
777 }
778 #else
779 #define FIX_IPV6_RECVPKTINFO(sock) (void)0
780 #endif
781
782 /*%
783  * Increment socket-related statistics counters.
784  */
785 static inline void
786 inc_stats(isc_stats_t *stats, isc_statscounter_t counterid) {
787         REQUIRE(counterid != -1);
788
789         if (stats != NULL)
790                 isc_stats_increment(stats, counterid);
791 }
792
793 static inline isc_result_t
794 watch_fd(isc__socketmgr_t *manager, int fd, int msg) {
795         isc_result_t result = ISC_R_SUCCESS;
796
797 #ifdef USE_KQUEUE
798         struct kevent evchange;
799
800         memset(&evchange, 0, sizeof(evchange));
801         if (msg == SELECT_POKE_READ)
802                 evchange.filter = EVFILT_READ;
803         else
804                 evchange.filter = EVFILT_WRITE;
805         evchange.flags = EV_ADD;
806         evchange.ident = fd;
807         if (kevent(manager->kqueue_fd, &evchange, 1, NULL, 0, NULL) != 0)
808                 result = isc__errno2result(errno);
809
810         return (result);
811 #elif defined(USE_EPOLL)
812         struct epoll_event event;
813
814         if (msg == SELECT_POKE_READ)
815                 event.events = EPOLLIN;
816         else
817                 event.events = EPOLLOUT;
818         memset(&event.data, 0, sizeof(event.data));
819         event.data.fd = fd;
820         if (epoll_ctl(manager->epoll_fd, EPOLL_CTL_ADD, fd, &event) == -1 &&
821             errno != EEXIST) {
822                 result = isc__errno2result(errno);
823         }
824
825         return (result);
826 #elif defined(USE_DEVPOLL)
827         struct pollfd pfd;
828         int lockid = FDLOCK_ID(fd);
829
830         memset(&pfd, 0, sizeof(pfd));
831         if (msg == SELECT_POKE_READ)
832                 pfd.events = POLLIN;
833         else
834                 pfd.events = POLLOUT;
835         pfd.fd = fd;
836         pfd.revents = 0;
837         LOCK(&manager->fdlock[lockid]);
838         if (write(manager->devpoll_fd, &pfd, sizeof(pfd)) == -1)
839                 result = isc__errno2result(errno);
840         else {
841                 if (msg == SELECT_POKE_READ)
842                         manager->fdpollinfo[fd].want_read = 1;
843                 else
844                         manager->fdpollinfo[fd].want_write = 1;
845         }
846         UNLOCK(&manager->fdlock[lockid]);
847
848         return (result);
849 #elif defined(USE_SELECT)
850         LOCK(&manager->lock);
851         if (msg == SELECT_POKE_READ)
852                 FD_SET(fd, manager->read_fds);
853         if (msg == SELECT_POKE_WRITE)
854                 FD_SET(fd, manager->write_fds);
855         UNLOCK(&manager->lock);
856
857         return (result);
858 #endif
859 }
860
861 static inline isc_result_t
862 unwatch_fd(isc__socketmgr_t *manager, int fd, int msg) {
863         isc_result_t result = ISC_R_SUCCESS;
864
865 #ifdef USE_KQUEUE
866         struct kevent evchange;
867
868         memset(&evchange, 0, sizeof(evchange));
869         if (msg == SELECT_POKE_READ)
870                 evchange.filter = EVFILT_READ;
871         else
872                 evchange.filter = EVFILT_WRITE;
873         evchange.flags = EV_DELETE;
874         evchange.ident = fd;
875         if (kevent(manager->kqueue_fd, &evchange, 1, NULL, 0, NULL) != 0)
876                 result = isc__errno2result(errno);
877
878         return (result);
879 #elif defined(USE_EPOLL)
880         struct epoll_event event;
881
882         if (msg == SELECT_POKE_READ)
883                 event.events = EPOLLIN;
884         else
885                 event.events = EPOLLOUT;
886         memset(&event.data, 0, sizeof(event.data));
887         event.data.fd = fd;
888         if (epoll_ctl(manager->epoll_fd, EPOLL_CTL_DEL, fd, &event) == -1 &&
889             errno != ENOENT) {
890                 char strbuf[ISC_STRERRORSIZE];
891                 isc__strerror(errno, strbuf, sizeof(strbuf));
892                 UNEXPECTED_ERROR(__FILE__, __LINE__,
893                                  "epoll_ctl(DEL), %d: %s", fd, strbuf);
894                 result = ISC_R_UNEXPECTED;
895         }
896         return (result);
897 #elif defined(USE_DEVPOLL)
898         struct pollfd pfds[2];
899         size_t writelen = sizeof(pfds[0]);
900         int lockid = FDLOCK_ID(fd);
901
902         memset(pfds, 0, sizeof(pfds));
903         pfds[0].events = POLLREMOVE;
904         pfds[0].fd = fd;
905
906         /*
907          * Canceling read or write polling via /dev/poll is tricky.  Since it
908          * only provides a way of canceling per FD, we may need to re-poll the
909          * socket for the other operation.
910          */
911         LOCK(&manager->fdlock[lockid]);
912         if (msg == SELECT_POKE_READ &&
913             manager->fdpollinfo[fd].want_write == 1) {
914                 pfds[1].events = POLLOUT;
915                 pfds[1].fd = fd;
916                 writelen += sizeof(pfds[1]);
917         }
918         if (msg == SELECT_POKE_WRITE &&
919             manager->fdpollinfo[fd].want_read == 1) {
920                 pfds[1].events = POLLIN;
921                 pfds[1].fd = fd;
922                 writelen += sizeof(pfds[1]);
923         }
924
925         if (write(manager->devpoll_fd, pfds, writelen) == -1)
926                 result = isc__errno2result(errno);
927         else {
928                 if (msg == SELECT_POKE_READ)
929                         manager->fdpollinfo[fd].want_read = 0;
930                 else
931                         manager->fdpollinfo[fd].want_write = 0;
932         }
933         UNLOCK(&manager->fdlock[lockid]);
934
935         return (result);
936 #elif defined(USE_SELECT)
937         LOCK(&manager->lock);
938         if (msg == SELECT_POKE_READ)
939                 FD_CLR(fd, manager->read_fds);
940         else if (msg == SELECT_POKE_WRITE)
941                 FD_CLR(fd, manager->write_fds);
942         UNLOCK(&manager->lock);
943
944         return (result);
945 #endif
946 }
947
948 static void
949 wakeup_socket(isc__socketmgr_t *manager, int fd, int msg) {
950         isc_result_t result;
951         int lockid = FDLOCK_ID(fd);
952
953         /*
954          * This is a wakeup on a socket.  If the socket is not in the
955          * process of being closed, start watching it for either reads
956          * or writes.
957          */
958
959         INSIST(fd >= 0 && fd < (int)manager->maxsocks);
960
961         if (msg == SELECT_POKE_CLOSE) {
962                 /* No one should be updating fdstate, so no need to lock it */
963                 INSIST(manager->fdstate[fd] == CLOSE_PENDING);
964                 manager->fdstate[fd] = CLOSED;
965                 (void)unwatch_fd(manager, fd, SELECT_POKE_READ);
966                 (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE);
967                 (void)close(fd);
968                 return;
969         }
970
971         LOCK(&manager->fdlock[lockid]);
972         if (manager->fdstate[fd] == CLOSE_PENDING) {
973                 UNLOCK(&manager->fdlock[lockid]);
974
975                 /*
976                  * We accept (and ignore) any error from unwatch_fd() as we are
977                  * closing the socket, hoping it doesn't leave dangling state in
978                  * the kernel.
979                  * Note that unwatch_fd() must be called after releasing the
980                  * fdlock; otherwise it could cause deadlock due to a lock order
981                  * reversal.
982                  */
983                 (void)unwatch_fd(manager, fd, SELECT_POKE_READ);
984                 (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE);
985                 return;
986         }
987         if (manager->fdstate[fd] != MANAGED) {
988                 UNLOCK(&manager->fdlock[lockid]);
989                 return;
990         }
991         UNLOCK(&manager->fdlock[lockid]);
992
993         /*
994          * Set requested bit.
995          */
996         result = watch_fd(manager, fd, msg);
997         if (result != ISC_R_SUCCESS) {
998                 /*
999                  * XXXJT: what should we do?  Ignoring the failure of watching
1000                  * a socket will make the application dysfunctional, but there
1001                  * seems to be no reasonable recovery process.
1002                  */
1003                 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
1004                               ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
1005                               "failed to start watching FD (%d): %s",
1006                               fd, isc_result_totext(result));
1007         }
1008 }
1009
1010 #ifdef USE_WATCHER_THREAD
1011 /*
1012  * Poke the select loop when there is something for us to do.
1013  * The write is required (by POSIX) to complete.  That is, we
1014  * will not get partial writes.
1015  */
1016 static void
1017 select_poke(isc__socketmgr_t *mgr, int fd, int msg) {
1018         int cc;
1019         int buf[2];
1020         char strbuf[ISC_STRERRORSIZE];
1021
1022         buf[0] = fd;
1023         buf[1] = msg;
1024
1025         do {
1026                 cc = write(mgr->pipe_fds[1], buf, sizeof(buf));
1027 #ifdef ENOSR
1028                 /*
1029                  * Treat ENOSR as EAGAIN but loop slowly as it is
1030                  * unlikely to clear fast.
1031                  */
1032                 if (cc < 0 && errno == ENOSR) {
1033                         sleep(1);
1034                         errno = EAGAIN;
1035                 }
1036 #endif
1037         } while (cc < 0 && SOFT_ERROR(errno));
1038
1039         if (cc < 0) {
1040                 isc__strerror(errno, strbuf, sizeof(strbuf));
1041                 FATAL_ERROR(__FILE__, __LINE__,
1042                             isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
1043                                            ISC_MSG_WRITEFAILED,
1044                                            "write() failed "
1045                                            "during watcher poke: %s"),
1046                             strbuf);
1047         }
1048
1049         INSIST(cc == sizeof(buf));
1050 }
1051
1052 /*
1053  * Read a message on the internal fd.
1054  */
1055 static void
1056 select_readmsg(isc__socketmgr_t *mgr, int *fd, int *msg) {
1057         int buf[2];
1058         int cc;
1059         char strbuf[ISC_STRERRORSIZE];
1060
1061         cc = read(mgr->pipe_fds[0], buf, sizeof(buf));
1062         if (cc < 0) {
1063                 *msg = SELECT_POKE_NOTHING;
1064                 *fd = -1;       /* Silence compiler. */
1065                 if (SOFT_ERROR(errno))
1066                         return;
1067
1068                 isc__strerror(errno, strbuf, sizeof(strbuf));
1069                 FATAL_ERROR(__FILE__, __LINE__,
1070                             isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
1071                                            ISC_MSG_READFAILED,
1072                                            "read() failed "
1073                                            "during watcher poke: %s"),
1074                             strbuf);
1075
1076                 return;
1077         }
1078         INSIST(cc == sizeof(buf));
1079
1080         *fd = buf[0];
1081         *msg = buf[1];
1082 }
1083 #else /* USE_WATCHER_THREAD */
1084 /*
1085  * Update the state of the socketmgr when something changes.
1086  */
1087 static void
1088 select_poke(isc__socketmgr_t *manager, int fd, int msg) {
1089         if (msg == SELECT_POKE_SHUTDOWN)
1090                 return;
1091         else if (fd >= 0)
1092                 wakeup_socket(manager, fd, msg);
1093         return;
1094 }
1095 #endif /* USE_WATCHER_THREAD */
1096
1097 /*
1098  * Make a fd non-blocking.
1099  */
1100 static isc_result_t
1101 make_nonblock(int fd) {
1102         int ret;
1103         int flags;
1104         char strbuf[ISC_STRERRORSIZE];
1105 #ifdef USE_FIONBIO_IOCTL
1106         int on = 1;
1107
1108         ret = ioctl(fd, FIONBIO, (char *)&on);
1109 #else
1110         flags = fcntl(fd, F_GETFL, 0);
1111         flags |= PORT_NONBLOCK;
1112         ret = fcntl(fd, F_SETFL, flags);
1113 #endif
1114
1115         if (ret == -1) {
1116                 isc__strerror(errno, strbuf, sizeof(strbuf));
1117                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1118 #ifdef USE_FIONBIO_IOCTL
1119                                  "ioctl(%d, FIONBIO, &on): %s", fd,
1120 #else
1121                                  "fcntl(%d, F_SETFL, %d): %s", fd, flags,
1122 #endif
1123                                  strbuf);
1124
1125                 return (ISC_R_UNEXPECTED);
1126         }
1127
1128         return (ISC_R_SUCCESS);
1129 }
1130
1131 #ifdef USE_CMSG
1132 /*
1133  * Not all OSes support advanced CMSG macros: CMSG_LEN and CMSG_SPACE.
1134  * In order to ensure as much portability as possible, we provide wrapper
1135  * functions of these macros.
1136  * Note that cmsg_space() could run slow on OSes that do not have
1137  * CMSG_SPACE.
1138  */
1139 static inline ISC_SOCKADDR_LEN_T
1140 cmsg_len(ISC_SOCKADDR_LEN_T len) {
1141 #ifdef CMSG_LEN
1142         return (CMSG_LEN(len));
1143 #else
1144         ISC_SOCKADDR_LEN_T hdrlen;
1145
1146         /*
1147          * Cast NULL so that any pointer arithmetic performed by CMSG_DATA
1148          * is correct.
1149          */
1150         hdrlen = (ISC_SOCKADDR_LEN_T)CMSG_DATA(((struct cmsghdr *)NULL));
1151         return (hdrlen + len);
1152 #endif
1153 }
1154
1155 static inline ISC_SOCKADDR_LEN_T
1156 cmsg_space(ISC_SOCKADDR_LEN_T len) {
1157 #ifdef CMSG_SPACE
1158         return (CMSG_SPACE(len));
1159 #else
1160         struct msghdr msg;
1161         struct cmsghdr *cmsgp;
1162         /*
1163          * XXX: The buffer length is an ad-hoc value, but should be enough
1164          * in a practical sense.
1165          */
1166         char dummybuf[sizeof(struct cmsghdr) + 1024];
1167
1168         memset(&msg, 0, sizeof(msg));
1169         msg.msg_control = dummybuf;
1170         msg.msg_controllen = sizeof(dummybuf);
1171
1172         cmsgp = (struct cmsghdr *)dummybuf;
1173         cmsgp->cmsg_len = cmsg_len(len);
1174
1175         cmsgp = CMSG_NXTHDR(&msg, cmsgp);
1176         if (cmsgp != NULL)
1177                 return ((char *)cmsgp - (char *)msg.msg_control);
1178         else
1179                 return (0);
1180 #endif
1181 }
1182 #endif /* USE_CMSG */
1183
1184 /*
1185  * Process control messages received on a socket.
1186  */
1187 static void
1188 process_cmsg(isc__socket_t *sock, struct msghdr *msg, isc_socketevent_t *dev) {
1189 #ifdef USE_CMSG
1190         struct cmsghdr *cmsgp;
1191 #ifdef ISC_PLATFORM_HAVEIN6PKTINFO
1192         struct in6_pktinfo *pktinfop;
1193 #endif
1194 #ifdef SO_TIMESTAMP
1195         struct timeval *timevalp;
1196 #endif
1197 #endif
1198
1199         /*
1200          * sock is used only when ISC_NET_BSD44MSGHDR and USE_CMSG are defined.
1201          * msg and dev are used only when ISC_NET_BSD44MSGHDR is defined.
1202          * They are all here, outside of the CPP tests, because it is
1203          * more consistent with the usual ISC coding style.
1204          */
1205         UNUSED(sock);
1206         UNUSED(msg);
1207         UNUSED(dev);
1208
1209 #ifdef ISC_NET_BSD44MSGHDR
1210
1211 #ifdef MSG_TRUNC
1212         if ((msg->msg_flags & MSG_TRUNC) == MSG_TRUNC)
1213                 dev->attributes |= ISC_SOCKEVENTATTR_TRUNC;
1214 #endif
1215
1216 #ifdef MSG_CTRUNC
1217         if ((msg->msg_flags & MSG_CTRUNC) == MSG_CTRUNC)
1218                 dev->attributes |= ISC_SOCKEVENTATTR_CTRUNC;
1219 #endif
1220
1221 #ifndef USE_CMSG
1222         return;
1223 #else
1224         if (msg->msg_controllen == 0U || msg->msg_control == NULL)
1225                 return;
1226
1227 #ifdef SO_TIMESTAMP
1228         timevalp = NULL;
1229 #endif
1230 #ifdef ISC_PLATFORM_HAVEIN6PKTINFO
1231         pktinfop = NULL;
1232 #endif
1233
1234         cmsgp = CMSG_FIRSTHDR(msg);
1235         while (cmsgp != NULL) {
1236                 socket_log(sock, NULL, TRACE,
1237                            isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_PROCESSCMSG,
1238                            "processing cmsg %p", cmsgp);
1239
1240 #ifdef ISC_PLATFORM_HAVEIN6PKTINFO
1241                 if (cmsgp->cmsg_level == IPPROTO_IPV6
1242                     && cmsgp->cmsg_type == IPV6_PKTINFO) {
1243
1244                         pktinfop = (struct in6_pktinfo *)CMSG_DATA(cmsgp);
1245                         memcpy(&dev->pktinfo, pktinfop,
1246                                sizeof(struct in6_pktinfo));
1247                         dev->attributes |= ISC_SOCKEVENTATTR_PKTINFO;
1248                         socket_log(sock, NULL, TRACE,
1249                                    isc_msgcat, ISC_MSGSET_SOCKET,
1250                                    ISC_MSG_IFRECEIVED,
1251                                    "interface received on ifindex %u",
1252                                    dev->pktinfo.ipi6_ifindex);
1253                         if (IN6_IS_ADDR_MULTICAST(&pktinfop->ipi6_addr))
1254                                 dev->attributes |= ISC_SOCKEVENTATTR_MULTICAST;
1255                         goto next;
1256                 }
1257 #endif
1258
1259 #ifdef SO_TIMESTAMP
1260                 if (cmsgp->cmsg_level == SOL_SOCKET
1261                     && cmsgp->cmsg_type == SCM_TIMESTAMP) {
1262                         timevalp = (struct timeval *)CMSG_DATA(cmsgp);
1263                         dev->timestamp.seconds = timevalp->tv_sec;
1264                         dev->timestamp.nanoseconds = timevalp->tv_usec * 1000;
1265                         dev->attributes |= ISC_SOCKEVENTATTR_TIMESTAMP;
1266                         goto next;
1267                 }
1268 #endif
1269
1270         next:
1271                 cmsgp = CMSG_NXTHDR(msg, cmsgp);
1272         }
1273 #endif /* USE_CMSG */
1274
1275 #endif /* ISC_NET_BSD44MSGHDR */
1276 }
1277
1278 /*
1279  * Construct an iov array and attach it to the msghdr passed in.  This is
1280  * the SEND constructor, which will use the used region of the buffer
1281  * (if using a buffer list) or will use the internal region (if a single
1282  * buffer I/O is requested).
1283  *
1284  * Nothing can be NULL, and the done event must list at least one buffer
1285  * on the buffer linked list for this function to be meaningful.
1286  *
1287  * If write_countp != NULL, *write_countp will hold the number of bytes
1288  * this transaction can send.
1289  */
1290 static void
1291 build_msghdr_send(isc__socket_t *sock, isc_socketevent_t *dev,
1292                   struct msghdr *msg, struct iovec *iov, size_t *write_countp)
1293 {
1294         unsigned int iovcount;
1295         isc_buffer_t *buffer;
1296         isc_region_t used;
1297         size_t write_count;
1298         size_t skip_count;
1299
1300         memset(msg, 0, sizeof(*msg));
1301
1302         if (!sock->connected) {
1303                 msg->msg_name = (void *)&dev->address.type.sa;
1304                 msg->msg_namelen = dev->address.length;
1305         } else {
1306                 msg->msg_name = NULL;
1307                 msg->msg_namelen = 0;
1308         }
1309
1310         buffer = ISC_LIST_HEAD(dev->bufferlist);
1311         write_count = 0;
1312         iovcount = 0;
1313
1314         /*
1315          * Single buffer I/O?  Skip what we've done so far in this region.
1316          */
1317         if (buffer == NULL) {
1318                 write_count = dev->region.length - dev->n;
1319                 iov[0].iov_base = (void *)(dev->region.base + dev->n);
1320                 iov[0].iov_len = write_count;
1321                 iovcount = 1;
1322
1323                 goto config;
1324         }
1325
1326         /*
1327          * Multibuffer I/O.
1328          * Skip the data in the buffer list that we have already written.
1329          */
1330         skip_count = dev->n;
1331         while (buffer != NULL) {
1332                 REQUIRE(ISC_BUFFER_VALID(buffer));
1333                 if (skip_count < isc_buffer_usedlength(buffer))
1334                         break;
1335                 skip_count -= isc_buffer_usedlength(buffer);
1336                 buffer = ISC_LIST_NEXT(buffer, link);
1337         }
1338
1339         while (buffer != NULL) {
1340                 INSIST(iovcount < MAXSCATTERGATHER_SEND);
1341
1342                 isc_buffer_usedregion(buffer, &used);
1343
1344                 if (used.length > 0) {
1345                         iov[iovcount].iov_base = (void *)(used.base
1346                                                           + skip_count);
1347                         iov[iovcount].iov_len = used.length - skip_count;
1348                         write_count += (used.length - skip_count);
1349                         skip_count = 0;
1350                         iovcount++;
1351                 }
1352                 buffer = ISC_LIST_NEXT(buffer, link);
1353         }
1354
1355         INSIST(skip_count == 0U);
1356
1357  config:
1358         msg->msg_iov = iov;
1359         msg->msg_iovlen = iovcount;
1360
1361 #ifdef ISC_NET_BSD44MSGHDR
1362         msg->msg_control = NULL;
1363         msg->msg_controllen = 0;
1364         msg->msg_flags = 0;
1365 #if defined(USE_CMSG) && defined(ISC_PLATFORM_HAVEIN6PKTINFO)
1366         if ((sock->type == isc_sockettype_udp)
1367             && ((dev->attributes & ISC_SOCKEVENTATTR_PKTINFO) != 0)) {
1368 #if defined(IPV6_USE_MIN_MTU)
1369                 int use_min_mtu = 1;    /* -1, 0, 1 */
1370 #endif
1371                 struct cmsghdr *cmsgp;
1372                 struct in6_pktinfo *pktinfop;
1373
1374                 socket_log(sock, NULL, TRACE,
1375                            isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_SENDTODATA,
1376                            "sendto pktinfo data, ifindex %u",
1377                            dev->pktinfo.ipi6_ifindex);
1378
1379                 msg->msg_controllen = cmsg_space(sizeof(struct in6_pktinfo));
1380                 INSIST(msg->msg_controllen <= sock->sendcmsgbuflen);
1381                 msg->msg_control = (void *)sock->sendcmsgbuf;
1382
1383                 cmsgp = (struct cmsghdr *)sock->sendcmsgbuf;
1384                 cmsgp->cmsg_level = IPPROTO_IPV6;
1385                 cmsgp->cmsg_type = IPV6_PKTINFO;
1386                 cmsgp->cmsg_len = cmsg_len(sizeof(struct in6_pktinfo));
1387                 pktinfop = (struct in6_pktinfo *)CMSG_DATA(cmsgp);
1388                 memcpy(pktinfop, &dev->pktinfo, sizeof(struct in6_pktinfo));
1389 #if defined(IPV6_USE_MIN_MTU)
1390                 /*
1391                  * Set IPV6_USE_MIN_MTU as a per packet option as FreeBSD
1392                  * ignores setsockopt(IPV6_USE_MIN_MTU) when IPV6_PKTINFO
1393                  * is used.
1394                  */
1395                 cmsgp = (struct cmsghdr *)(sock->sendcmsgbuf +
1396                                            msg->msg_controllen);
1397                 msg->msg_controllen += cmsg_space(sizeof(use_min_mtu));
1398                 INSIST(msg->msg_controllen <= sock->sendcmsgbuflen);
1399
1400                 cmsgp->cmsg_level = IPPROTO_IPV6;
1401                 cmsgp->cmsg_type = IPV6_USE_MIN_MTU;
1402                 cmsgp->cmsg_len = cmsg_len(sizeof(use_min_mtu));
1403                 memcpy(CMSG_DATA(cmsgp), &use_min_mtu, sizeof(use_min_mtu));
1404 #endif
1405         }
1406 #endif /* USE_CMSG && ISC_PLATFORM_HAVEIPV6 */
1407 #else /* ISC_NET_BSD44MSGHDR */
1408         msg->msg_accrights = NULL;
1409         msg->msg_accrightslen = 0;
1410 #endif /* ISC_NET_BSD44MSGHDR */
1411
1412         if (write_countp != NULL)
1413                 *write_countp = write_count;
1414 }
1415
1416 /*
1417  * Construct an iov array and attach it to the msghdr passed in.  This is
1418  * the RECV constructor, which will use the available region of the buffer
1419  * (if using a buffer list) or will use the internal region (if a single
1420  * buffer I/O is requested).
1421  *
1422  * Nothing can be NULL, and the done event must list at least one buffer
1423  * on the buffer linked list for this function to be meaningful.
1424  *
1425  * If read_countp != NULL, *read_countp will hold the number of bytes
1426  * this transaction can receive.
1427  */
1428 static void
1429 build_msghdr_recv(isc__socket_t *sock, isc_socketevent_t *dev,
1430                   struct msghdr *msg, struct iovec *iov, size_t *read_countp)
1431 {
1432         unsigned int iovcount;
1433         isc_buffer_t *buffer;
1434         isc_region_t available;
1435         size_t read_count;
1436
1437         memset(msg, 0, sizeof(struct msghdr));
1438
1439         if (sock->type == isc_sockettype_udp) {
1440                 memset(&dev->address, 0, sizeof(dev->address));
1441 #ifdef BROKEN_RECVMSG
1442                 if (sock->pf == AF_INET) {
1443                         msg->msg_name = (void *)&dev->address.type.sin;
1444                         msg->msg_namelen = sizeof(dev->address.type.sin6);
1445                 } else if (sock->pf == AF_INET6) {
1446                         msg->msg_name = (void *)&dev->address.type.sin6;
1447                         msg->msg_namelen = sizeof(dev->address.type.sin6);
1448 #ifdef ISC_PLATFORM_HAVESYSUNH
1449                 } else if (sock->pf == AF_UNIX) {
1450                         msg->msg_name = (void *)&dev->address.type.sunix;
1451                         msg->msg_namelen = sizeof(dev->address.type.sunix);
1452 #endif
1453                 } else {
1454                         msg->msg_name = (void *)&dev->address.type.sa;
1455                         msg->msg_namelen = sizeof(dev->address.type);
1456                 }
1457 #else
1458                 msg->msg_name = (void *)&dev->address.type.sa;
1459                 msg->msg_namelen = sizeof(dev->address.type);
1460 #endif
1461 #ifdef ISC_NET_RECVOVERFLOW
1462                 /* If needed, steal one iovec for overflow detection. */
1463                 maxiov--;
1464 #endif
1465         } else { /* TCP */
1466                 msg->msg_name = NULL;
1467                 msg->msg_namelen = 0;
1468                 dev->address = sock->peer_address;
1469         }
1470
1471         buffer = ISC_LIST_HEAD(dev->bufferlist);
1472         read_count = 0;
1473
1474         /*
1475          * Single buffer I/O?  Skip what we've done so far in this region.
1476          */
1477         if (buffer == NULL) {
1478                 read_count = dev->region.length - dev->n;
1479                 iov[0].iov_base = (void *)(dev->region.base + dev->n);
1480                 iov[0].iov_len = read_count;
1481                 iovcount = 1;
1482
1483                 goto config;
1484         }
1485
1486         /*
1487          * Multibuffer I/O.
1488          * Skip empty buffers.
1489          */
1490         while (buffer != NULL) {
1491                 REQUIRE(ISC_BUFFER_VALID(buffer));
1492                 if (isc_buffer_availablelength(buffer) != 0)
1493                         break;
1494                 buffer = ISC_LIST_NEXT(buffer, link);
1495         }
1496
1497         iovcount = 0;
1498         while (buffer != NULL) {
1499                 INSIST(iovcount < MAXSCATTERGATHER_RECV);
1500
1501                 isc_buffer_availableregion(buffer, &available);
1502
1503                 if (available.length > 0) {
1504                         iov[iovcount].iov_base = (void *)(available.base);
1505                         iov[iovcount].iov_len = available.length;
1506                         read_count += available.length;
1507                         iovcount++;
1508                 }
1509                 buffer = ISC_LIST_NEXT(buffer, link);
1510         }
1511
1512  config:
1513
1514         /*
1515          * If needed, set up to receive that one extra byte.  Note that
1516          * we know there is at least one iov left, since we stole it
1517          * at the top of this function.
1518          */
1519 #ifdef ISC_NET_RECVOVERFLOW
1520         if (sock->type == isc_sockettype_udp) {
1521                 iov[iovcount].iov_base = (void *)(&sock->overflow);
1522                 iov[iovcount].iov_len = 1;
1523                 iovcount++;
1524         }
1525 #endif
1526
1527         msg->msg_iov = iov;
1528         msg->msg_iovlen = iovcount;
1529
1530 #ifdef ISC_NET_BSD44MSGHDR
1531         msg->msg_control = NULL;
1532         msg->msg_controllen = 0;
1533         msg->msg_flags = 0;
1534 #if defined(USE_CMSG)
1535         if (sock->type == isc_sockettype_udp) {
1536                 msg->msg_control = sock->recvcmsgbuf;
1537                 msg->msg_controllen = sock->recvcmsgbuflen;
1538         }
1539 #endif /* USE_CMSG */
1540 #else /* ISC_NET_BSD44MSGHDR */
1541         msg->msg_accrights = NULL;
1542         msg->msg_accrightslen = 0;
1543 #endif /* ISC_NET_BSD44MSGHDR */
1544
1545         if (read_countp != NULL)
1546                 *read_countp = read_count;
1547 }
1548
1549 static void
1550 set_dev_address(isc_sockaddr_t *address, isc__socket_t *sock,
1551                 isc_socketevent_t *dev)
1552 {
1553         if (sock->type == isc_sockettype_udp) {
1554                 if (address != NULL)
1555                         dev->address = *address;
1556                 else
1557                         dev->address = sock->peer_address;
1558         } else if (sock->type == isc_sockettype_tcp) {
1559                 INSIST(address == NULL);
1560                 dev->address = sock->peer_address;
1561         }
1562 }
1563
1564 static void
1565 destroy_socketevent(isc_event_t *event) {
1566         isc_socketevent_t *ev = (isc_socketevent_t *)event;
1567
1568         INSIST(ISC_LIST_EMPTY(ev->bufferlist));
1569
1570         (ev->destroy)(event);
1571 }
1572
1573 static isc_socketevent_t *
1574 allocate_socketevent(isc__socket_t *sock, isc_eventtype_t eventtype,
1575                      isc_taskaction_t action, const void *arg)
1576 {
1577         isc_socketevent_t *ev;
1578
1579         ev = (isc_socketevent_t *)isc_event_allocate(sock->manager->mctx,
1580                                                      sock, eventtype,
1581                                                      action, arg,
1582                                                      sizeof(*ev));
1583
1584         if (ev == NULL)
1585                 return (NULL);
1586
1587         ev->result = ISC_R_UNEXPECTED;
1588         ISC_LINK_INIT(ev, ev_link);
1589         ISC_LIST_INIT(ev->bufferlist);
1590         ev->region.base = NULL;
1591         ev->n = 0;
1592         ev->offset = 0;
1593         ev->attributes = 0;
1594         ev->destroy = ev->ev_destroy;
1595         ev->ev_destroy = destroy_socketevent;
1596
1597         return (ev);
1598 }
1599
1600 #if defined(ISC_SOCKET_DEBUG)
1601 static void
1602 dump_msg(struct msghdr *msg) {
1603         unsigned int i;
1604
1605         printf("MSGHDR %p\n", msg);
1606         printf("\tname %p, namelen %ld\n", msg->msg_name,
1607                (long) msg->msg_namelen);
1608         printf("\tiov %p, iovlen %ld\n", msg->msg_iov,
1609                (long) msg->msg_iovlen);
1610         for (i = 0; i < (unsigned int)msg->msg_iovlen; i++)
1611                 printf("\t\t%d\tbase %p, len %ld\n", i,
1612                        msg->msg_iov[i].iov_base,
1613                        (long) msg->msg_iov[i].iov_len);
1614 #ifdef ISC_NET_BSD44MSGHDR
1615         printf("\tcontrol %p, controllen %ld\n", msg->msg_control,
1616                (long) msg->msg_controllen);
1617 #endif
1618 }
1619 #endif
1620
1621 #define DOIO_SUCCESS            0       /* i/o ok, event sent */
1622 #define DOIO_SOFT               1       /* i/o ok, soft error, no event sent */
1623 #define DOIO_HARD               2       /* i/o error, event sent */
1624 #define DOIO_EOF                3       /* EOF, no event sent */
1625
1626 static int
1627 doio_recv(isc__socket_t *sock, isc_socketevent_t *dev) {
1628         int cc;
1629         struct iovec iov[MAXSCATTERGATHER_RECV];
1630         size_t read_count;
1631         size_t actual_count;
1632         struct msghdr msghdr;
1633         isc_buffer_t *buffer;
1634         int recv_errno;
1635         char strbuf[ISC_STRERRORSIZE];
1636
1637         build_msghdr_recv(sock, dev, &msghdr, iov, &read_count);
1638
1639 #if defined(ISC_SOCKET_DEBUG)
1640         dump_msg(&msghdr);
1641 #endif
1642
1643         cc = recvmsg(sock->fd, &msghdr, 0);
1644         recv_errno = errno;
1645
1646 #if defined(ISC_SOCKET_DEBUG)
1647         dump_msg(&msghdr);
1648 #endif
1649
1650         if (cc < 0) {
1651                 if (SOFT_ERROR(recv_errno))
1652                         return (DOIO_SOFT);
1653
1654                 if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) {
1655                         isc__strerror(recv_errno, strbuf, sizeof(strbuf));
1656                         socket_log(sock, NULL, IOEVENT,
1657                                    isc_msgcat, ISC_MSGSET_SOCKET,
1658                                    ISC_MSG_DOIORECV,
1659                                   "doio_recv: recvmsg(%d) %d bytes, err %d/%s",
1660                                    sock->fd, cc, recv_errno, strbuf);
1661                 }
1662
1663 #define SOFT_OR_HARD(_system, _isc) \
1664         if (recv_errno == _system) { \
1665                 if (sock->connected) { \
1666                         dev->result = _isc; \
1667                         inc_stats(sock->manager->stats, \
1668                                   sock->statsindex[STATID_RECVFAIL]); \
1669                         return (DOIO_HARD); \
1670                 } \
1671                 return (DOIO_SOFT); \
1672         }
1673 #define ALWAYS_HARD(_system, _isc) \
1674         if (recv_errno == _system) { \
1675                 dev->result = _isc; \
1676                 inc_stats(sock->manager->stats, \
1677                           sock->statsindex[STATID_RECVFAIL]); \
1678                 return (DOIO_HARD); \
1679         }
1680
1681                 SOFT_OR_HARD(ECONNREFUSED, ISC_R_CONNREFUSED);
1682                 SOFT_OR_HARD(ENETUNREACH, ISC_R_NETUNREACH);
1683                 SOFT_OR_HARD(EHOSTUNREACH, ISC_R_HOSTUNREACH);
1684                 SOFT_OR_HARD(EHOSTDOWN, ISC_R_HOSTDOWN);
1685                 /* HPUX 11.11 can return EADDRNOTAVAIL. */
1686                 SOFT_OR_HARD(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL);
1687                 ALWAYS_HARD(ENOBUFS, ISC_R_NORESOURCES);
1688                 /*
1689                  * HPUX returns EPROTO and EINVAL on receiving some ICMP/ICMPv6
1690                  * errors.
1691                  */
1692 #ifdef EPROTO
1693                 SOFT_OR_HARD(EPROTO, ISC_R_HOSTUNREACH);
1694 #endif
1695                 SOFT_OR_HARD(EINVAL, ISC_R_HOSTUNREACH);
1696
1697 #undef SOFT_OR_HARD
1698 #undef ALWAYS_HARD
1699
1700                 dev->result = isc__errno2result(recv_errno);
1701                 inc_stats(sock->manager->stats,
1702                           sock->statsindex[STATID_RECVFAIL]);
1703                 return (DOIO_HARD);
1704         }
1705
1706         /*
1707          * On TCP and UNIX sockets, zero length reads indicate EOF,
1708          * while on UDP sockets, zero length reads are perfectly valid,
1709          * although strange.
1710          */
1711         switch (sock->type) {
1712         case isc_sockettype_tcp:
1713         case isc_sockettype_unix:
1714                 if (cc == 0)
1715                         return (DOIO_EOF);
1716                 break;
1717         case isc_sockettype_udp:
1718                 break;
1719         case isc_sockettype_fdwatch:
1720         default:
1721                 INSIST(0);
1722         }
1723
1724         if (sock->type == isc_sockettype_udp) {
1725                 dev->address.length = msghdr.msg_namelen;
1726                 if (isc_sockaddr_getport(&dev->address) == 0) {
1727                         if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) {
1728                                 socket_log(sock, &dev->address, IOEVENT,
1729                                            isc_msgcat, ISC_MSGSET_SOCKET,
1730                                            ISC_MSG_ZEROPORT,
1731                                            "dropping source port zero packet");
1732                         }
1733                         return (DOIO_SOFT);
1734                 }
1735                 /*
1736                  * Simulate a firewall blocking UDP responses bigger than
1737                  * 512 bytes.
1738                  */
1739                 if (sock->manager->maxudp != 0 && cc > sock->manager->maxudp)
1740                         return (DOIO_SOFT);
1741         }
1742
1743         socket_log(sock, &dev->address, IOEVENT,
1744                    isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_PKTRECV,
1745                    "packet received correctly");
1746
1747         /*
1748          * Overflow bit detection.  If we received MORE bytes than we should,
1749          * this indicates an overflow situation.  Set the flag in the
1750          * dev entry and adjust how much we read by one.
1751          */
1752 #ifdef ISC_NET_RECVOVERFLOW
1753         if ((sock->type == isc_sockettype_udp) && ((size_t)cc > read_count)) {
1754                 dev->attributes |= ISC_SOCKEVENTATTR_TRUNC;
1755                 cc--;
1756         }
1757 #endif
1758
1759         /*
1760          * If there are control messages attached, run through them and pull
1761          * out the interesting bits.
1762          */
1763         if (sock->type == isc_sockettype_udp)
1764                 process_cmsg(sock, &msghdr, dev);
1765
1766         /*
1767          * update the buffers (if any) and the i/o count
1768          */
1769         dev->n += cc;
1770         actual_count = cc;
1771         buffer = ISC_LIST_HEAD(dev->bufferlist);
1772         while (buffer != NULL && actual_count > 0U) {
1773                 REQUIRE(ISC_BUFFER_VALID(buffer));
1774                 if (isc_buffer_availablelength(buffer) <= actual_count) {
1775                         actual_count -= isc_buffer_availablelength(buffer);
1776                         isc_buffer_add(buffer,
1777                                        isc_buffer_availablelength(buffer));
1778                 } else {
1779                         isc_buffer_add(buffer, actual_count);
1780                         actual_count = 0;
1781                         POST(actual_count);
1782                         break;
1783                 }
1784                 buffer = ISC_LIST_NEXT(buffer, link);
1785                 if (buffer == NULL) {
1786                         INSIST(actual_count == 0U);
1787                 }
1788         }
1789
1790         /*
1791          * If we read less than we expected, update counters,
1792          * and let the upper layer poke the descriptor.
1793          */
1794         if (((size_t)cc != read_count) && (dev->n < dev->minimum))
1795                 return (DOIO_SOFT);
1796
1797         /*
1798          * Full reads are posted, or partials if partials are ok.
1799          */
1800         dev->result = ISC_R_SUCCESS;
1801         return (DOIO_SUCCESS);
1802 }
1803
1804 /*
1805  * Returns:
1806  *      DOIO_SUCCESS    The operation succeeded.  dev->result contains
1807  *                      ISC_R_SUCCESS.
1808  *
1809  *      DOIO_HARD       A hard or unexpected I/O error was encountered.
1810  *                      dev->result contains the appropriate error.
1811  *
1812  *      DOIO_SOFT       A soft I/O error was encountered.  No senddone
1813  *                      event was sent.  The operation should be retried.
1814  *
1815  *      No other return values are possible.
1816  */
1817 static int
1818 doio_send(isc__socket_t *sock, isc_socketevent_t *dev) {
1819         int cc;
1820         struct iovec iov[MAXSCATTERGATHER_SEND];
1821         size_t write_count;
1822         struct msghdr msghdr;
1823         char addrbuf[ISC_SOCKADDR_FORMATSIZE];
1824         int attempts = 0;
1825         int send_errno;
1826         char strbuf[ISC_STRERRORSIZE];
1827
1828         build_msghdr_send(sock, dev, &msghdr, iov, &write_count);
1829
1830  resend:
1831         cc = sendmsg(sock->fd, &msghdr, 0);
1832         send_errno = errno;
1833
1834         /*
1835          * Check for error or block condition.
1836          */
1837         if (cc < 0) {
1838                 if (send_errno == EINTR && ++attempts < NRETRIES)
1839                         goto resend;
1840
1841                 if (SOFT_ERROR(send_errno))
1842                         return (DOIO_SOFT);
1843
1844 #define SOFT_OR_HARD(_system, _isc) \
1845         if (send_errno == _system) { \
1846                 if (sock->connected) { \
1847                         dev->result = _isc; \
1848                         inc_stats(sock->manager->stats, \
1849                                   sock->statsindex[STATID_SENDFAIL]); \
1850                         return (DOIO_HARD); \
1851                 } \
1852                 return (DOIO_SOFT); \
1853         }
1854 #define ALWAYS_HARD(_system, _isc) \
1855         if (send_errno == _system) { \
1856                 dev->result = _isc; \
1857                 inc_stats(sock->manager->stats, \
1858                           sock->statsindex[STATID_SENDFAIL]); \
1859                 return (DOIO_HARD); \
1860         }
1861
1862                 SOFT_OR_HARD(ECONNREFUSED, ISC_R_CONNREFUSED);
1863                 ALWAYS_HARD(EACCES, ISC_R_NOPERM);
1864                 ALWAYS_HARD(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL);
1865                 ALWAYS_HARD(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL);
1866                 ALWAYS_HARD(EHOSTUNREACH, ISC_R_HOSTUNREACH);
1867 #ifdef EHOSTDOWN
1868                 ALWAYS_HARD(EHOSTDOWN, ISC_R_HOSTUNREACH);
1869 #endif
1870                 ALWAYS_HARD(ENETUNREACH, ISC_R_NETUNREACH);
1871                 ALWAYS_HARD(ENOBUFS, ISC_R_NORESOURCES);
1872                 ALWAYS_HARD(EPERM, ISC_R_HOSTUNREACH);
1873                 ALWAYS_HARD(EPIPE, ISC_R_NOTCONNECTED);
1874                 ALWAYS_HARD(ECONNRESET, ISC_R_CONNECTIONRESET);
1875
1876 #undef SOFT_OR_HARD
1877 #undef ALWAYS_HARD
1878
1879                 /*
1880                  * The other error types depend on whether or not the
1881                  * socket is UDP or TCP.  If it is UDP, some errors
1882                  * that we expect to be fatal under TCP are merely
1883                  * annoying, and are really soft errors.
1884                  *
1885                  * However, these soft errors are still returned as
1886                  * a status.
1887                  */
1888                 isc_sockaddr_format(&dev->address, addrbuf, sizeof(addrbuf));
1889                 isc__strerror(send_errno, strbuf, sizeof(strbuf));
1890                 UNEXPECTED_ERROR(__FILE__, __LINE__, "internal_send: %s: %s",
1891                                  addrbuf, strbuf);
1892                 dev->result = isc__errno2result(send_errno);
1893                 inc_stats(sock->manager->stats,
1894                           sock->statsindex[STATID_SENDFAIL]);
1895                 return (DOIO_HARD);
1896         }
1897
1898         if (cc == 0) {
1899                 inc_stats(sock->manager->stats,
1900                           sock->statsindex[STATID_SENDFAIL]);
1901                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1902                                  "doio_send: send() %s 0",
1903                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
1904                                                 ISC_MSG_RETURNED, "returned"));
1905         }
1906
1907         /*
1908          * If we write less than we expected, update counters, poke.
1909          */
1910         dev->n += cc;
1911         if ((size_t)cc != write_count)
1912                 return (DOIO_SOFT);
1913
1914         /*
1915          * Exactly what we wanted to write.  We're done with this
1916          * entry.  Post its completion event.
1917          */
1918         dev->result = ISC_R_SUCCESS;
1919         return (DOIO_SUCCESS);
1920 }
1921
1922 /*
1923  * Kill.
1924  *
1925  * Caller must ensure that the socket is not locked and no external
1926  * references exist.
1927  */
1928 static void
1929 closesocket(isc__socketmgr_t *manager, isc__socket_t *sock, int fd) {
1930         isc_sockettype_t type = sock->type;
1931         int lockid = FDLOCK_ID(fd);
1932
1933         /*
1934          * No one has this socket open, so the watcher doesn't have to be
1935          * poked, and the socket doesn't have to be locked.
1936          */
1937         LOCK(&manager->fdlock[lockid]);
1938         manager->fds[fd] = NULL;
1939         if (type == isc_sockettype_fdwatch)
1940                 manager->fdstate[fd] = CLOSED;
1941         else
1942                 manager->fdstate[fd] = CLOSE_PENDING;
1943         UNLOCK(&manager->fdlock[lockid]);
1944         if (type == isc_sockettype_fdwatch) {
1945                 /*
1946                  * The caller may close the socket once this function returns,
1947                  * and `fd' may be reassigned for a new socket.  So we do
1948                  * unwatch_fd() here, rather than defer it via select_poke().
1949                  * Note: this may complicate data protection among threads and
1950                  * may reduce performance due to additional locks.  One way to
1951                  * solve this would be to dup() the watched descriptor, but we
1952                  * take a simpler approach at this moment.
1953                  */
1954                 (void)unwatch_fd(manager, fd, SELECT_POKE_READ);
1955                 (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE);
1956         } else
1957                 select_poke(manager, fd, SELECT_POKE_CLOSE);
1958
1959         inc_stats(manager->stats, sock->statsindex[STATID_CLOSE]);
1960
1961         /*
1962          * update manager->maxfd here (XXX: this should be implemented more
1963          * efficiently)
1964          */
1965 #ifdef USE_SELECT
1966         LOCK(&manager->lock);
1967         if (manager->maxfd == fd) {
1968                 int i;
1969
1970                 manager->maxfd = 0;
1971                 for (i = fd - 1; i >= 0; i--) {
1972                         lockid = FDLOCK_ID(i);
1973
1974                         LOCK(&manager->fdlock[lockid]);
1975                         if (manager->fdstate[i] == MANAGED) {
1976                                 manager->maxfd = i;
1977                                 UNLOCK(&manager->fdlock[lockid]);
1978                                 break;
1979                         }
1980                         UNLOCK(&manager->fdlock[lockid]);
1981                 }
1982 #ifdef ISC_PLATFORM_USETHREADS
1983                 if (manager->maxfd < manager->pipe_fds[0])
1984                         manager->maxfd = manager->pipe_fds[0];
1985 #endif
1986         }
1987         UNLOCK(&manager->lock);
1988 #endif  /* USE_SELECT */
1989 }
1990
1991 static void
1992 destroy(isc__socket_t **sockp) {
1993         int fd;
1994         isc__socket_t *sock = *sockp;
1995         isc__socketmgr_t *manager = sock->manager;
1996
1997         socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET,
1998                    ISC_MSG_DESTROYING, "destroying");
1999
2000         INSIST(ISC_LIST_EMPTY(sock->accept_list));
2001         INSIST(ISC_LIST_EMPTY(sock->recv_list));
2002         INSIST(ISC_LIST_EMPTY(sock->send_list));
2003         INSIST(sock->connect_ev == NULL);
2004         REQUIRE(sock->fd == -1 || sock->fd < (int)manager->maxsocks);
2005
2006         if (sock->fd >= 0) {
2007                 fd = sock->fd;
2008                 sock->fd = -1;
2009                 closesocket(manager, sock, fd);
2010         }
2011
2012         LOCK(&manager->lock);
2013
2014         ISC_LIST_UNLINK(manager->socklist, sock, link);
2015
2016 #ifdef USE_WATCHER_THREAD
2017         if (ISC_LIST_EMPTY(manager->socklist))
2018                 SIGNAL(&manager->shutdown_ok);
2019 #endif /* USE_WATCHER_THREAD */
2020
2021         /* can't unlock manager as its memory context is still used */
2022         free_socket(sockp);
2023
2024         UNLOCK(&manager->lock);
2025 }
2026
2027 static isc_result_t
2028 allocate_socket(isc__socketmgr_t *manager, isc_sockettype_t type,
2029                 isc__socket_t **socketp)
2030 {
2031         isc__socket_t *sock;
2032         isc_result_t result;
2033         ISC_SOCKADDR_LEN_T cmsgbuflen;
2034
2035         sock = isc_mem_get(manager->mctx, sizeof(*sock));
2036
2037         if (sock == NULL)
2038                 return (ISC_R_NOMEMORY);
2039
2040         result = ISC_R_UNEXPECTED;
2041
2042         sock->common.magic = 0;
2043         sock->common.impmagic = 0;
2044         sock->references = 0;
2045
2046         sock->manager = manager;
2047         sock->type = type;
2048         sock->fd = -1;
2049         sock->statsindex = NULL;
2050
2051         ISC_LINK_INIT(sock, link);
2052
2053         sock->recvcmsgbuf = NULL;
2054         sock->sendcmsgbuf = NULL;
2055
2056         /*
2057          * set up cmsg buffers
2058          */
2059         cmsgbuflen = 0;
2060 #if defined(USE_CMSG) && defined(ISC_PLATFORM_HAVEIN6PKTINFO)
2061         cmsgbuflen += cmsg_space(sizeof(struct in6_pktinfo));
2062 #endif
2063 #if defined(USE_CMSG) && defined(SO_TIMESTAMP)
2064         cmsgbuflen += cmsg_space(sizeof(struct timeval));
2065 #endif
2066         sock->recvcmsgbuflen = cmsgbuflen;
2067         if (sock->recvcmsgbuflen != 0U) {
2068                 sock->recvcmsgbuf = isc_mem_get(manager->mctx, cmsgbuflen);
2069                 if (sock->recvcmsgbuf == NULL)
2070                         goto error;
2071         }
2072
2073         cmsgbuflen = 0;
2074 #if defined(USE_CMSG) && defined(ISC_PLATFORM_HAVEIN6PKTINFO)
2075         cmsgbuflen += cmsg_space(sizeof(struct in6_pktinfo));
2076 #if defined(IPV6_USE_MIN_MTU)
2077         /*
2078          * Provide space for working around FreeBSD's broken IPV6_USE_MIN_MTU
2079          * support.
2080          */
2081         cmsgbuflen += cmsg_space(sizeof(int));
2082 #endif
2083 #endif
2084         sock->sendcmsgbuflen = cmsgbuflen;
2085         if (sock->sendcmsgbuflen != 0U) {
2086                 sock->sendcmsgbuf = isc_mem_get(manager->mctx, cmsgbuflen);
2087                 if (sock->sendcmsgbuf == NULL)
2088                         goto error;
2089         }
2090
2091         memset(sock->name, 0, sizeof(sock->name));
2092         sock->tag = NULL;
2093
2094         /*
2095          * set up list of readers and writers to be initially empty
2096          */
2097         ISC_LIST_INIT(sock->recv_list);
2098         ISC_LIST_INIT(sock->send_list);
2099         ISC_LIST_INIT(sock->accept_list);
2100         sock->connect_ev = NULL;
2101         sock->pending_recv = 0;
2102         sock->pending_send = 0;
2103         sock->pending_accept = 0;
2104         sock->listener = 0;
2105         sock->connected = 0;
2106         sock->connecting = 0;
2107         sock->bound = 0;
2108
2109         /*
2110          * initialize the lock
2111          */
2112         result = isc_mutex_init(&sock->lock);
2113         if (result != ISC_R_SUCCESS) {
2114                 sock->common.magic = 0;
2115                 sock->common.impmagic = 0;
2116                 goto error;
2117         }
2118
2119         /*
2120          * Initialize readable and writable events
2121          */
2122         ISC_EVENT_INIT(&sock->readable_ev, sizeof(intev_t),
2123                        ISC_EVENTATTR_NOPURGE, NULL, ISC_SOCKEVENT_INTR,
2124                        NULL, sock, sock, NULL, NULL);
2125         ISC_EVENT_INIT(&sock->writable_ev, sizeof(intev_t),
2126                        ISC_EVENTATTR_NOPURGE, NULL, ISC_SOCKEVENT_INTW,
2127                        NULL, sock, sock, NULL, NULL);
2128
2129         sock->common.magic = ISCAPI_SOCKET_MAGIC;
2130         sock->common.impmagic = SOCKET_MAGIC;
2131         *socketp = sock;
2132
2133         return (ISC_R_SUCCESS);
2134
2135  error:
2136         if (sock->recvcmsgbuf != NULL)
2137                 isc_mem_put(manager->mctx, sock->recvcmsgbuf,
2138                             sock->recvcmsgbuflen);
2139         if (sock->sendcmsgbuf != NULL)
2140                 isc_mem_put(manager->mctx, sock->sendcmsgbuf,
2141                             sock->sendcmsgbuflen);
2142         isc_mem_put(manager->mctx, sock, sizeof(*sock));
2143
2144         return (result);
2145 }
2146
2147 /*
2148  * This event requires that the various lists be empty, that the reference
2149  * count be 1, and that the magic number is valid.  The other socket bits,
2150  * like the lock, must be initialized as well.  The fd associated must be
2151  * marked as closed, by setting it to -1 on close, or this routine will
2152  * also close the socket.
2153  */
2154 static void
2155 free_socket(isc__socket_t **socketp) {
2156         isc__socket_t *sock = *socketp;
2157
2158         INSIST(sock->references == 0);
2159         INSIST(VALID_SOCKET(sock));
2160         INSIST(!sock->connecting);
2161         INSIST(!sock->pending_recv);
2162         INSIST(!sock->pending_send);
2163         INSIST(!sock->pending_accept);
2164         INSIST(ISC_LIST_EMPTY(sock->recv_list));
2165         INSIST(ISC_LIST_EMPTY(sock->send_list));
2166         INSIST(ISC_LIST_EMPTY(sock->accept_list));
2167         INSIST(!ISC_LINK_LINKED(sock, link));
2168
2169         if (sock->recvcmsgbuf != NULL)
2170                 isc_mem_put(sock->manager->mctx, sock->recvcmsgbuf,
2171                             sock->recvcmsgbuflen);
2172         if (sock->sendcmsgbuf != NULL)
2173                 isc_mem_put(sock->manager->mctx, sock->sendcmsgbuf,
2174                             sock->sendcmsgbuflen);
2175
2176         sock->common.magic = 0;
2177         sock->common.impmagic = 0;
2178
2179         DESTROYLOCK(&sock->lock);
2180
2181         isc_mem_put(sock->manager->mctx, sock, sizeof(*sock));
2182
2183         *socketp = NULL;
2184 }
2185
2186 #ifdef SO_BSDCOMPAT
2187 /*
2188  * This really should not be necessary to do.  Having to workout
2189  * which kernel version we are on at run time so that we don't cause
2190  * the kernel to issue a warning about us using a deprecated socket option.
2191  * Such warnings should *never* be on by default in production kernels.
2192  *
2193  * We can't do this a build time because executables are moved between
2194  * machines and hence kernels.
2195  *
2196  * We can't just not set SO_BSDCOMAT because some kernels require it.
2197  */
2198
2199 static isc_once_t         bsdcompat_once = ISC_ONCE_INIT;
2200 isc_boolean_t bsdcompat = ISC_TRUE;
2201
2202 static void
2203 clear_bsdcompat(void) {
2204 #ifdef __linux__
2205          struct utsname buf;
2206          char *endp;
2207          long int major;
2208          long int minor;
2209
2210          uname(&buf);    /* Can only fail if buf is bad in Linux. */
2211
2212          /* Paranoia in parsing can be increased, but we trust uname(). */
2213          major = strtol(buf.release, &endp, 10);
2214          if (*endp == '.') {
2215                 minor = strtol(endp+1, &endp, 10);
2216                 if ((major > 2) || ((major == 2) && (minor >= 4))) {
2217                         bsdcompat = ISC_FALSE;
2218                 }
2219          }
2220 #endif /* __linux __ */
2221 }
2222 #endif
2223
2224 static isc_result_t
2225 opensocket(isc__socketmgr_t *manager, isc__socket_t *sock) {
2226         char strbuf[ISC_STRERRORSIZE];
2227         const char *err = "socket";
2228         int tries = 0;
2229 #if defined(USE_CMSG) || defined(SO_BSDCOMPAT)
2230         int on = 1;
2231 #endif
2232 #if defined(SO_RCVBUF)
2233         ISC_SOCKADDR_LEN_T optlen;
2234         int size;
2235 #endif
2236
2237  again:
2238         switch (sock->type) {
2239         case isc_sockettype_udp:
2240                 sock->fd = socket(sock->pf, SOCK_DGRAM, IPPROTO_UDP);
2241                 break;
2242         case isc_sockettype_tcp:
2243                 sock->fd = socket(sock->pf, SOCK_STREAM, IPPROTO_TCP);
2244                 break;
2245         case isc_sockettype_unix:
2246                 sock->fd = socket(sock->pf, SOCK_STREAM, 0);
2247                 break;
2248         case isc_sockettype_fdwatch:
2249                 /*
2250                  * We should not be called for isc_sockettype_fdwatch sockets.
2251                  */
2252                 INSIST(0);
2253                 break;
2254         }
2255         if (sock->fd == -1 && errno == EINTR && tries++ < 42)
2256                 goto again;
2257
2258 #ifdef F_DUPFD
2259         /*
2260          * Leave a space for stdio and TCP to work in.
2261          */
2262         if (manager->reserved != 0 && sock->type == isc_sockettype_udp &&
2263             sock->fd >= 0 && sock->fd < manager->reserved) {
2264                 int new, tmp;
2265                 new = fcntl(sock->fd, F_DUPFD, manager->reserved);
2266                 tmp = errno;
2267                 (void)close(sock->fd);
2268                 errno = tmp;
2269                 sock->fd = new;
2270                 err = "isc_socket_create: fcntl/reserved";
2271         } else if (sock->fd >= 0 && sock->fd < 20) {
2272                 int new, tmp;
2273                 new = fcntl(sock->fd, F_DUPFD, 20);
2274                 tmp = errno;
2275                 (void)close(sock->fd);
2276                 errno = tmp;
2277                 sock->fd = new;
2278                 err = "isc_socket_create: fcntl";
2279         }
2280 #endif
2281
2282         if (sock->fd >= (int)manager->maxsocks) {
2283                 (void)close(sock->fd);
2284                 isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL,
2285                                ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
2286                                isc_msgcat, ISC_MSGSET_SOCKET,
2287                                ISC_MSG_TOOMANYFDS,
2288                                "socket: file descriptor exceeds limit (%d/%u)",
2289                                sock->fd, manager->maxsocks);
2290                 return (ISC_R_NORESOURCES);
2291         }
2292
2293         if (sock->fd < 0) {
2294                 switch (errno) {
2295                 case EMFILE:
2296                 case ENFILE:
2297                         isc__strerror(errno, strbuf, sizeof(strbuf));
2298                         isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL,
2299                                        ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
2300                                        isc_msgcat, ISC_MSGSET_SOCKET,
2301                                        ISC_MSG_TOOMANYFDS,
2302                                        "%s: %s", err, strbuf);
2303                         /* fallthrough */
2304                 case ENOBUFS:
2305                         return (ISC_R_NORESOURCES);
2306
2307                 case EPROTONOSUPPORT:
2308                 case EPFNOSUPPORT:
2309                 case EAFNOSUPPORT:
2310                 /*
2311                  * Linux 2.2 (and maybe others) return EINVAL instead of
2312                  * EAFNOSUPPORT.
2313                  */
2314                 case EINVAL:
2315                         return (ISC_R_FAMILYNOSUPPORT);
2316
2317                 default:
2318                         isc__strerror(errno, strbuf, sizeof(strbuf));
2319                         UNEXPECTED_ERROR(__FILE__, __LINE__,
2320                                          "%s() %s: %s", err,
2321                                          isc_msgcat_get(isc_msgcat,
2322                                                         ISC_MSGSET_GENERAL,
2323                                                         ISC_MSG_FAILED,
2324                                                         "failed"),
2325                                          strbuf);
2326                         return (ISC_R_UNEXPECTED);
2327                 }
2328         }
2329
2330         if (make_nonblock(sock->fd) != ISC_R_SUCCESS) {
2331                 (void)close(sock->fd);
2332                 return (ISC_R_UNEXPECTED);
2333         }
2334
2335 #ifdef SO_BSDCOMPAT
2336         RUNTIME_CHECK(isc_once_do(&bsdcompat_once,
2337                                   clear_bsdcompat) == ISC_R_SUCCESS);
2338         if (sock->type != isc_sockettype_unix && bsdcompat &&
2339             setsockopt(sock->fd, SOL_SOCKET, SO_BSDCOMPAT,
2340                        (void *)&on, sizeof(on)) < 0) {
2341                 isc__strerror(errno, strbuf, sizeof(strbuf));
2342                 UNEXPECTED_ERROR(__FILE__, __LINE__,
2343                                  "setsockopt(%d, SO_BSDCOMPAT) %s: %s",
2344                                  sock->fd,
2345                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
2346                                                 ISC_MSG_FAILED, "failed"),
2347                                  strbuf);
2348                 /* Press on... */
2349         }
2350 #endif
2351
2352 #ifdef SO_NOSIGPIPE
2353         if (setsockopt(sock->fd, SOL_SOCKET, SO_NOSIGPIPE,
2354                        (void *)&on, sizeof(on)) < 0) {
2355                 isc__strerror(errno, strbuf, sizeof(strbuf));
2356                 UNEXPECTED_ERROR(__FILE__, __LINE__,
2357                                  "setsockopt(%d, SO_NOSIGPIPE) %s: %s",
2358                                  sock->fd,
2359                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
2360                                                 ISC_MSG_FAILED, "failed"),
2361                                  strbuf);
2362                 /* Press on... */
2363         }
2364 #endif
2365
2366 #if defined(USE_CMSG) || defined(SO_RCVBUF)
2367         if (sock->type == isc_sockettype_udp) {
2368
2369 #if defined(USE_CMSG)
2370 #if defined(SO_TIMESTAMP)
2371                 if (setsockopt(sock->fd, SOL_SOCKET, SO_TIMESTAMP,
2372                                (void *)&on, sizeof(on)) < 0
2373                     && errno != ENOPROTOOPT) {
2374                         isc__strerror(errno, strbuf, sizeof(strbuf));
2375                         UNEXPECTED_ERROR(__FILE__, __LINE__,
2376                                          "setsockopt(%d, SO_TIMESTAMP) %s: %s",
2377                                          sock->fd,
2378                                          isc_msgcat_get(isc_msgcat,
2379                                                         ISC_MSGSET_GENERAL,
2380                                                         ISC_MSG_FAILED,
2381                                                         "failed"),
2382                                          strbuf);
2383                         /* Press on... */
2384                 }
2385 #endif /* SO_TIMESTAMP */
2386
2387 #if defined(ISC_PLATFORM_HAVEIPV6)
2388                 if (sock->pf == AF_INET6 && sock->recvcmsgbuflen == 0U) {
2389                         /*
2390                          * Warn explicitly because this anomaly can be hidden
2391                          * in usual operation (and unexpectedly appear later).
2392                          */
2393                         UNEXPECTED_ERROR(__FILE__, __LINE__,
2394                                          "No buffer available to receive "
2395                                          "IPv6 destination");
2396                 }
2397 #ifdef ISC_PLATFORM_HAVEIN6PKTINFO
2398 #ifdef IPV6_RECVPKTINFO
2399                 /* RFC 3542 */
2400                 if ((sock->pf == AF_INET6)
2401                     && (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
2402                                    (void *)&on, sizeof(on)) < 0)) {
2403                         isc__strerror(errno, strbuf, sizeof(strbuf));
2404                         UNEXPECTED_ERROR(__FILE__, __LINE__,
2405                                          "setsockopt(%d, IPV6_RECVPKTINFO) "
2406                                          "%s: %s", sock->fd,
2407                                          isc_msgcat_get(isc_msgcat,
2408                                                         ISC_MSGSET_GENERAL,
2409                                                         ISC_MSG_FAILED,
2410                                                         "failed"),
2411                                          strbuf);
2412                 }
2413 #else
2414                 /* RFC 2292 */
2415                 if ((sock->pf == AF_INET6)
2416                     && (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_PKTINFO,
2417                                    (void *)&on, sizeof(on)) < 0)) {
2418                         isc__strerror(errno, strbuf, sizeof(strbuf));
2419                         UNEXPECTED_ERROR(__FILE__, __LINE__,
2420                                          "setsockopt(%d, IPV6_PKTINFO) %s: %s",
2421                                          sock->fd,
2422                                          isc_msgcat_get(isc_msgcat,
2423                                                         ISC_MSGSET_GENERAL,
2424                                                         ISC_MSG_FAILED,
2425                                                         "failed"),
2426                                          strbuf);
2427                 }
2428 #endif /* IPV6_RECVPKTINFO */
2429 #endif /* ISC_PLATFORM_HAVEIN6PKTINFO */
2430 #ifdef IPV6_USE_MIN_MTU        /* RFC 3542, not too common yet*/
2431                 /* use minimum MTU */
2432                 if (sock->pf == AF_INET6 &&
2433                     setsockopt(sock->fd, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
2434                                (void *)&on, sizeof(on)) < 0) {
2435                         isc__strerror(errno, strbuf, sizeof(strbuf));
2436                         UNEXPECTED_ERROR(__FILE__, __LINE__,
2437                                          "setsockopt(%d, IPV6_USE_MIN_MTU) "
2438                                          "%s: %s", sock->fd,
2439                                          isc_msgcat_get(isc_msgcat,
2440                                                         ISC_MSGSET_GENERAL,
2441                                                         ISC_MSG_FAILED,
2442                                                         "failed"),
2443                                          strbuf);
2444                 }
2445 #endif
2446 #if defined(IPV6_MTU)
2447                 /*
2448                  * Use minimum MTU on IPv6 sockets.
2449                  */
2450                 if (sock->pf == AF_INET6) {
2451                         int mtu = 1280;
2452                         (void)setsockopt(sock->fd, IPPROTO_IPV6, IPV6_MTU,
2453                                          &mtu, sizeof(mtu));
2454                 }
2455 #endif
2456 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
2457                 /*
2458                  * Turn off Path MTU discovery on IPv6/UDP sockets.
2459                  */
2460                 if (sock->pf == AF_INET6) {
2461                         int action = IPV6_PMTUDISC_DONT;
2462                         (void)setsockopt(sock->fd, IPPROTO_IPV6,
2463                                          IPV6_MTU_DISCOVER, &action,
2464                                          sizeof(action));
2465                 }
2466 #endif
2467 #endif /* ISC_PLATFORM_HAVEIPV6 */
2468 #endif /* defined(USE_CMSG) */
2469
2470 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2471                 /*
2472                  * Turn off Path MTU discovery on IPv4/UDP sockets.
2473                  */
2474                 if (sock->pf == AF_INET) {
2475                         int action = IP_PMTUDISC_DONT;
2476                         (void)setsockopt(sock->fd, IPPROTO_IP, IP_MTU_DISCOVER,
2477                                          &action, sizeof(action));
2478                 }
2479 #endif
2480 #if defined(IP_DONTFRAG)
2481                 /*
2482                  * Turn off Path MTU discovery on IPv4/UDP sockets.
2483                  */
2484                 if (sock->pf == AF_INET) {
2485                         int off = 0;
2486                         (void)setsockopt(sock->fd, IPPROTO_IP, IP_DONTFRAG,
2487                                          &off, sizeof(off));
2488                 }
2489 #endif
2490
2491 #if defined(SO_RCVBUF)
2492                 optlen = sizeof(size);
2493                 if (getsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
2494                                (void *)&size, &optlen) >= 0 &&
2495                      size < RCVBUFSIZE) {
2496                         size = RCVBUFSIZE;
2497                         if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
2498                                        (void *)&size, sizeof(size)) == -1) {
2499                                 isc__strerror(errno, strbuf, sizeof(strbuf));
2500                                 UNEXPECTED_ERROR(__FILE__, __LINE__,
2501                                         "setsockopt(%d, SO_RCVBUF, %d) %s: %s",
2502                                         sock->fd, size,
2503                                         isc_msgcat_get(isc_msgcat,
2504                                                        ISC_MSGSET_GENERAL,
2505                                                        ISC_MSG_FAILED,
2506                                                        "failed"),
2507                                         strbuf);
2508                         }
2509                 }
2510 #endif
2511         }
2512 #endif /* defined(USE_CMSG) || defined(SO_RCVBUF) */
2513
2514         inc_stats(manager->stats, sock->statsindex[STATID_OPEN]);
2515
2516         return (ISC_R_SUCCESS);
2517 }
2518
2519 /*%
2520  * Create a new 'type' socket managed by 'manager'.  Events
2521  * will be posted to 'task' and when dispatched 'action' will be
2522  * called with 'arg' as the arg value.  The new socket is returned
2523  * in 'socketp'.
2524  */
2525 ISC_SOCKETFUNC_SCOPE isc_result_t
2526 isc__socket_create(isc_socketmgr_t *manager0, int pf, isc_sockettype_t type,
2527                    isc_socket_t **socketp)
2528 {
2529         isc__socket_t *sock = NULL;
2530         isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
2531         isc_result_t result;
2532         int lockid;
2533
2534         REQUIRE(VALID_MANAGER(manager));
2535         REQUIRE(socketp != NULL && *socketp == NULL);
2536         REQUIRE(type != isc_sockettype_fdwatch);
2537
2538         result = allocate_socket(manager, type, &sock);
2539         if (result != ISC_R_SUCCESS)
2540                 return (result);
2541
2542         switch (sock->type) {
2543         case isc_sockettype_udp:
2544                 sock->statsindex =
2545                         (pf == AF_INET) ? upd4statsindex : upd6statsindex;
2546                 break;
2547         case isc_sockettype_tcp:
2548                 sock->statsindex =
2549                         (pf == AF_INET) ? tcp4statsindex : tcp6statsindex;
2550                 break;
2551         case isc_sockettype_unix:
2552                 sock->statsindex = unixstatsindex;
2553                 break;
2554         default:
2555                 INSIST(0);
2556         }
2557
2558         sock->pf = pf;
2559         result = opensocket(manager, sock);
2560         if (result != ISC_R_SUCCESS) {
2561                 inc_stats(manager->stats, sock->statsindex[STATID_OPENFAIL]);
2562                 free_socket(&sock);
2563                 return (result);
2564         }
2565
2566         sock->common.methods = (isc_socketmethods_t *)&socketmethods;
2567         sock->references = 1;
2568         *socketp = (isc_socket_t *)sock;
2569
2570         /*
2571          * Note we don't have to lock the socket like we normally would because
2572          * there are no external references to it yet.
2573          */
2574
2575         lockid = FDLOCK_ID(sock->fd);
2576         LOCK(&manager->fdlock[lockid]);
2577         manager->fds[sock->fd] = sock;
2578         manager->fdstate[sock->fd] = MANAGED;
2579 #ifdef USE_DEVPOLL
2580         INSIST(sock->manager->fdpollinfo[sock->fd].want_read == 0 &&
2581                sock->manager->fdpollinfo[sock->fd].want_write == 0);
2582 #endif
2583         UNLOCK(&manager->fdlock[lockid]);
2584
2585         LOCK(&manager->lock);
2586         ISC_LIST_APPEND(manager->socklist, sock, link);
2587 #ifdef USE_SELECT
2588         if (manager->maxfd < sock->fd)
2589                 manager->maxfd = sock->fd;
2590 #endif
2591         UNLOCK(&manager->lock);
2592
2593         socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET,
2594                    ISC_MSG_CREATED, "created");
2595
2596         return (ISC_R_SUCCESS);
2597 }
2598
2599 #ifdef BIND9
2600 ISC_SOCKETFUNC_SCOPE isc_result_t
2601 isc__socket_open(isc_socket_t *sock0) {
2602         isc_result_t result;
2603         isc__socket_t *sock = (isc__socket_t *)sock0;
2604
2605         REQUIRE(VALID_SOCKET(sock));
2606
2607         LOCK(&sock->lock);
2608         REQUIRE(sock->references == 1);
2609         REQUIRE(sock->type != isc_sockettype_fdwatch);
2610         UNLOCK(&sock->lock);
2611         /*
2612          * We don't need to retain the lock hereafter, since no one else has
2613          * this socket.
2614          */
2615         REQUIRE(sock->fd == -1);
2616
2617         result = opensocket(sock->manager, sock);
2618         if (result != ISC_R_SUCCESS)
2619                 sock->fd = -1;
2620
2621         if (result == ISC_R_SUCCESS) {
2622                 int lockid = FDLOCK_ID(sock->fd);
2623
2624                 LOCK(&sock->manager->fdlock[lockid]);
2625                 sock->manager->fds[sock->fd] = sock;
2626                 sock->manager->fdstate[sock->fd] = MANAGED;
2627 #ifdef USE_DEVPOLL
2628                 INSIST(sock->manager->fdpollinfo[sock->fd].want_read == 0 &&
2629                        sock->manager->fdpollinfo[sock->fd].want_write == 0);
2630 #endif
2631                 UNLOCK(&sock->manager->fdlock[lockid]);
2632
2633 #ifdef USE_SELECT
2634                 LOCK(&sock->manager->lock);
2635                 if (sock->manager->maxfd < sock->fd)
2636                         sock->manager->maxfd = sock->fd;
2637                 UNLOCK(&sock->manager->lock);
2638 #endif
2639         }
2640
2641         return (result);
2642 }
2643 #endif  /* BIND9 */
2644
2645 /*
2646  * Create a new 'type' socket managed by 'manager'.  Events
2647  * will be posted to 'task' and when dispatched 'action' will be
2648  * called with 'arg' as the arg value.  The new socket is returned
2649  * in 'socketp'.
2650  */
2651 ISC_SOCKETFUNC_SCOPE isc_result_t
2652 isc__socket_fdwatchcreate(isc_socketmgr_t *manager0, int fd, int flags,
2653                           isc_sockfdwatch_t callback, void *cbarg,
2654                           isc_task_t *task, isc_socket_t **socketp)
2655 {
2656         isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
2657         isc__socket_t *sock = NULL;
2658         isc_result_t result;
2659         int lockid;
2660
2661         REQUIRE(VALID_MANAGER(manager));
2662         REQUIRE(socketp != NULL && *socketp == NULL);
2663
2664         result = allocate_socket(manager, isc_sockettype_fdwatch, &sock);
2665         if (result != ISC_R_SUCCESS)
2666                 return (result);
2667
2668         sock->fd = fd;
2669         sock->fdwatcharg = cbarg;
2670         sock->fdwatchcb = callback;
2671         sock->fdwatchflags = flags;
2672         sock->fdwatchtask = task;
2673         sock->statsindex = fdwatchstatsindex;
2674
2675         sock->common.methods = (isc_socketmethods_t *)&socketmethods;
2676         sock->references = 1;
2677         *socketp = (isc_socket_t *)sock;
2678
2679         /*
2680          * Note we don't have to lock the socket like we normally would because
2681          * there are no external references to it yet.
2682          */
2683
2684         lockid = FDLOCK_ID(sock->fd);
2685         LOCK(&manager->fdlock[lockid]);
2686         manager->fds[sock->fd] = sock;
2687         manager->fdstate[sock->fd] = MANAGED;
2688         UNLOCK(&manager->fdlock[lockid]);
2689
2690         LOCK(&manager->lock);
2691         ISC_LIST_APPEND(manager->socklist, sock, link);
2692 #ifdef USE_SELECT
2693         if (manager->maxfd < sock->fd)
2694                 manager->maxfd = sock->fd;
2695 #endif
2696         UNLOCK(&manager->lock);
2697
2698         if (flags & ISC_SOCKFDWATCH_READ)
2699                 select_poke(sock->manager, sock->fd, SELECT_POKE_READ);
2700         if (flags & ISC_SOCKFDWATCH_WRITE)
2701                 select_poke(sock->manager, sock->fd, SELECT_POKE_WRITE);
2702
2703         socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET,
2704                    ISC_MSG_CREATED, "fdwatch-created");
2705
2706         return (ISC_R_SUCCESS);
2707 }
2708
2709 /*
2710  * Indicate to the manager that it should watch the socket again.
2711  * This can be used to restart watching if the previous event handler
2712  * didn't indicate there was more data to be processed.  Primarily
2713  * it is for writing but could be used for reading if desired
2714  */
2715
2716 ISC_SOCKETFUNC_SCOPE isc_result_t
2717 isc__socket_fdwatchpoke(isc_socket_t *sock0, int flags)
2718 {
2719         isc__socket_t *sock = (isc__socket_t *)sock0;
2720
2721         REQUIRE(VALID_SOCKET(sock));
2722
2723         /*
2724          * We check both flags first to allow us to get the lock
2725          * once but only if we need it.
2726          */
2727
2728         if ((flags & (ISC_SOCKFDWATCH_READ | ISC_SOCKFDWATCH_WRITE)) != 0) {
2729                 LOCK(&sock->lock);
2730                 if (((flags & ISC_SOCKFDWATCH_READ) != 0) &&
2731                     !sock->pending_recv)
2732                         select_poke(sock->manager, sock->fd,
2733                                     SELECT_POKE_READ);
2734                 if (((flags & ISC_SOCKFDWATCH_WRITE) != 0) &&
2735                     !sock->pending_send)
2736                         select_poke(sock->manager, sock->fd,
2737                                     SELECT_POKE_WRITE);
2738                 UNLOCK(&sock->lock);
2739         }
2740
2741         socket_log(sock, NULL, TRACE, isc_msgcat, ISC_MSGSET_SOCKET,
2742                    ISC_MSG_POKED, "fdwatch-poked flags: %d", flags);
2743
2744         return (ISC_R_SUCCESS);
2745 }
2746
2747 /*
2748  * Attach to a socket.  Caller must explicitly detach when it is done.
2749  */
2750 ISC_SOCKETFUNC_SCOPE void
2751 isc__socket_attach(isc_socket_t *sock0, isc_socket_t **socketp) {
2752         isc__socket_t *sock = (isc__socket_t *)sock0;
2753
2754         REQUIRE(VALID_SOCKET(sock));
2755         REQUIRE(socketp != NULL && *socketp == NULL);
2756
2757         LOCK(&sock->lock);
2758         sock->references++;
2759         UNLOCK(&sock->lock);
2760
2761         *socketp = (isc_socket_t *)sock;
2762 }
2763
2764 /*
2765  * Dereference a socket.  If this is the last reference to it, clean things
2766  * up by destroying the socket.
2767  */
2768 ISC_SOCKETFUNC_SCOPE void
2769 isc__socket_detach(isc_socket_t **socketp) {
2770         isc__socket_t *sock;
2771         isc_boolean_t kill_socket = ISC_FALSE;
2772
2773         REQUIRE(socketp != NULL);
2774         sock = (isc__socket_t *)*socketp;
2775         REQUIRE(VALID_SOCKET(sock));
2776
2777         LOCK(&sock->lock);
2778         REQUIRE(sock->references > 0);
2779         sock->references--;
2780         if (sock->references == 0)
2781                 kill_socket = ISC_TRUE;
2782         UNLOCK(&sock->lock);
2783
2784         if (kill_socket)
2785                 destroy(&sock);
2786
2787         *socketp = NULL;
2788 }
2789
2790 #ifdef BIND9
2791 ISC_SOCKETFUNC_SCOPE isc_result_t
2792 isc__socket_close(isc_socket_t *sock0) {
2793         isc__socket_t *sock = (isc__socket_t *)sock0;
2794         int fd;
2795         isc__socketmgr_t *manager;
2796
2797         REQUIRE(VALID_SOCKET(sock));
2798
2799         LOCK(&sock->lock);
2800
2801         REQUIRE(sock->references == 1);
2802         REQUIRE(sock->type != isc_sockettype_fdwatch);
2803         REQUIRE(sock->fd >= 0 && sock->fd < (int)sock->manager->maxsocks);
2804
2805         INSIST(!sock->connecting);
2806         INSIST(!sock->pending_recv);
2807         INSIST(!sock->pending_send);
2808         INSIST(!sock->pending_accept);
2809         INSIST(ISC_LIST_EMPTY(sock->recv_list));
2810         INSIST(ISC_LIST_EMPTY(sock->send_list));
2811         INSIST(ISC_LIST_EMPTY(sock->accept_list));
2812         INSIST(sock->connect_ev == NULL);
2813
2814         manager = sock->manager;
2815         fd = sock->fd;
2816         sock->fd = -1;
2817         memset(sock->name, 0, sizeof(sock->name));
2818         sock->tag = NULL;
2819         sock->listener = 0;
2820         sock->connected = 0;
2821         sock->connecting = 0;
2822         sock->bound = 0;
2823         isc_sockaddr_any(&sock->peer_address);
2824
2825         UNLOCK(&sock->lock);
2826
2827         closesocket(manager, sock, fd);
2828
2829         return (ISC_R_SUCCESS);
2830 }
2831 #endif  /* BIND9 */
2832
2833 /*
2834  * I/O is possible on a given socket.  Schedule an event to this task that
2835  * will call an internal function to do the I/O.  This will charge the
2836  * task with the I/O operation and let our select loop handler get back
2837  * to doing something real as fast as possible.
2838  *
2839  * The socket and manager must be locked before calling this function.
2840  */
2841 static void
2842 dispatch_recv(isc__socket_t *sock) {
2843         intev_t *iev;
2844         isc_socketevent_t *ev;
2845         isc_task_t *sender;
2846
2847         INSIST(!sock->pending_recv);
2848
2849         if (sock->type != isc_sockettype_fdwatch) {
2850                 ev = ISC_LIST_HEAD(sock->recv_list);
2851                 if (ev == NULL)
2852                         return;
2853                 socket_log(sock, NULL, EVENT, NULL, 0, 0,
2854                            "dispatch_recv:  event %p -> task %p",
2855                            ev, ev->ev_sender);
2856                 sender = ev->ev_sender;
2857         } else {
2858                 sender = sock->fdwatchtask;
2859         }
2860
2861         sock->pending_recv = 1;
2862         iev = &sock->readable_ev;
2863
2864         sock->references++;
2865         iev->ev_sender = sock;
2866         if (sock->type == isc_sockettype_fdwatch)
2867                 iev->ev_action = internal_fdwatch_read;
2868         else
2869                 iev->ev_action = internal_recv;
2870         iev->ev_arg = sock;
2871
2872         isc_task_send(sender, (isc_event_t **)&iev);
2873 }
2874
2875 static void
2876 dispatch_send(isc__socket_t *sock) {
2877         intev_t *iev;
2878         isc_socketevent_t *ev;
2879         isc_task_t *sender;
2880
2881         INSIST(!sock->pending_send);
2882
2883         if (sock->type != isc_sockettype_fdwatch) {
2884                 ev = ISC_LIST_HEAD(sock->send_list);
2885                 if (ev == NULL)
2886                         return;
2887                 socket_log(sock, NULL, EVENT, NULL, 0, 0,
2888                            "dispatch_send:  event %p -> task %p",
2889                            ev, ev->ev_sender);
2890                 sender = ev->ev_sender;
2891         } else {
2892                 sender = sock->fdwatchtask;
2893         }
2894
2895         sock->pending_send = 1;
2896         iev = &sock->writable_ev;
2897
2898         sock->references++;
2899         iev->ev_sender = sock;
2900         if (sock->type == isc_sockettype_fdwatch)
2901                 iev->ev_action = internal_fdwatch_write;
2902         else
2903                 iev->ev_action = internal_send;
2904         iev->ev_arg = sock;
2905
2906         isc_task_send(sender, (isc_event_t **)&iev);
2907 }
2908
2909 /*
2910  * Dispatch an internal accept event.
2911  */
2912 static void
2913 dispatch_accept(isc__socket_t *sock) {
2914         intev_t *iev;
2915         isc_socket_newconnev_t *ev;
2916
2917         INSIST(!sock->pending_accept);
2918
2919         /*
2920          * Are there any done events left, or were they all canceled
2921          * before the manager got the socket lock?
2922          */
2923         ev = ISC_LIST_HEAD(sock->accept_list);
2924         if (ev == NULL)
2925                 return;
2926
2927         sock->pending_accept = 1;
2928         iev = &sock->readable_ev;
2929
2930         sock->references++;  /* keep socket around for this internal event */
2931         iev->ev_sender = sock;
2932         iev->ev_action = internal_accept;
2933         iev->ev_arg = sock;
2934
2935         isc_task_send(ev->ev_sender, (isc_event_t **)&iev);
2936 }
2937
2938 static void
2939 dispatch_connect(isc__socket_t *sock) {
2940         intev_t *iev;
2941         isc_socket_connev_t *ev;
2942
2943         iev = &sock->writable_ev;
2944
2945         ev = sock->connect_ev;
2946         INSIST(ev != NULL); /* XXX */
2947
2948         INSIST(sock->connecting);
2949
2950         sock->references++;  /* keep socket around for this internal event */
2951         iev->ev_sender = sock;
2952         iev->ev_action = internal_connect;
2953         iev->ev_arg = sock;
2954
2955         isc_task_send(ev->ev_sender, (isc_event_t **)&iev);
2956 }
2957
2958 /*
2959  * Dequeue an item off the given socket's read queue, set the result code
2960  * in the done event to the one provided, and send it to the task it was
2961  * destined for.
2962  *
2963  * If the event to be sent is on a list, remove it before sending.  If
2964  * asked to, send and detach from the socket as well.
2965  *
2966  * Caller must have the socket locked if the event is attached to the socket.
2967  */
2968 static void
2969 send_recvdone_event(isc__socket_t *sock, isc_socketevent_t **dev) {
2970         isc_task_t *task;
2971
2972         task = (*dev)->ev_sender;
2973
2974         (*dev)->ev_sender = sock;
2975
2976         if (ISC_LINK_LINKED(*dev, ev_link))
2977                 ISC_LIST_DEQUEUE(sock->recv_list, *dev, ev_link);
2978
2979         if (((*dev)->attributes & ISC_SOCKEVENTATTR_ATTACHED)
2980             == ISC_SOCKEVENTATTR_ATTACHED)
2981                 isc_task_sendanddetach(&task, (isc_event_t **)dev);
2982         else
2983                 isc_task_send(task, (isc_event_t **)dev);
2984 }
2985
2986 /*
2987  * See comments for send_recvdone_event() above.
2988  *
2989  * Caller must have the socket locked if the event is attached to the socket.
2990  */
2991 static void
2992 send_senddone_event(isc__socket_t *sock, isc_socketevent_t **dev) {
2993         isc_task_t *task;
2994
2995         INSIST(dev != NULL && *dev != NULL);
2996
2997         task = (*dev)->ev_sender;
2998         (*dev)->ev_sender = sock;
2999
3000         if (ISC_LINK_LINKED(*dev, ev_link))
3001                 ISC_LIST_DEQUEUE(sock->send_list, *dev, ev_link);
3002
3003         if (((*dev)->attributes & ISC_SOCKEVENTATTR_ATTACHED)
3004             == ISC_SOCKEVENTATTR_ATTACHED)
3005                 isc_task_sendanddetach(&task, (isc_event_t **)dev);
3006         else
3007                 isc_task_send(task, (isc_event_t **)dev);
3008 }
3009
3010 /*
3011  * Call accept() on a socket, to get the new file descriptor.  The listen
3012  * socket is used as a prototype to create a new isc_socket_t.  The new
3013  * socket has one outstanding reference.  The task receiving the event
3014  * will be detached from just after the event is delivered.
3015  *
3016  * On entry to this function, the event delivered is the internal
3017  * readable event, and the first item on the accept_list should be
3018  * the done event we want to send.  If the list is empty, this is a no-op,
3019  * so just unlock and return.
3020  */
3021 static void
3022 internal_accept(isc_task_t *me, isc_event_t *ev) {
3023         isc__socket_t *sock;
3024         isc__socketmgr_t *manager;
3025         isc_socket_newconnev_t *dev;
3026         isc_task_t *task;
3027         ISC_SOCKADDR_LEN_T addrlen;
3028         int fd;
3029         isc_result_t result = ISC_R_SUCCESS;
3030         char strbuf[ISC_STRERRORSIZE];
3031         const char *err = "accept";
3032
3033         UNUSED(me);
3034
3035         sock = ev->ev_sender;
3036         INSIST(VALID_SOCKET(sock));
3037
3038         LOCK(&sock->lock);
3039         socket_log(sock, NULL, TRACE,
3040                    isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_ACCEPTLOCK,
3041                    "internal_accept called, locked socket");
3042
3043         manager = sock->manager;
3044         INSIST(VALID_MANAGER(manager));
3045
3046         INSIST(sock->listener);
3047         INSIST(sock->pending_accept == 1);
3048         sock->pending_accept = 0;
3049
3050         INSIST(sock->references > 0);
3051         sock->references--;  /* the internal event is done with this socket */
3052         if (sock->references == 0) {
3053                 UNLOCK(&sock->lock);
3054                 destroy(&sock);
3055                 return;
3056         }
3057
3058         /*
3059          * Get the first item off the accept list.
3060          * If it is empty, unlock the socket and return.
3061          */
3062         dev = ISC_LIST_HEAD(sock->accept_list);
3063         if (dev == NULL) {
3064                 UNLOCK(&sock->lock);
3065                 return;
3066         }
3067
3068         /*
3069          * Try to accept the new connection.  If the accept fails with
3070          * EAGAIN or EINTR, simply poke the watcher to watch this socket
3071          * again.  Also ignore ECONNRESET, which has been reported to
3072          * be spuriously returned on Linux 2.2.19 although it is not
3073          * a documented error for accept().  ECONNABORTED has been
3074          * reported for Solaris 8.  The rest are thrown in not because
3075          * we have seen them but because they are ignored by other
3076          * daemons such as BIND 8 and Apache.
3077          */
3078
3079         addrlen = sizeof(NEWCONNSOCK(dev)->peer_address.type);
3080         memset(&NEWCONNSOCK(dev)->peer_address.type, 0, addrlen);
3081         fd = accept(sock->fd, &NEWCONNSOCK(dev)->peer_address.type.sa,
3082                     (void *)&addrlen);
3083
3084 #ifdef F_DUPFD
3085         /*
3086          * Leave a space for stdio to work in.
3087          */
3088         if (fd >= 0 && fd < 20) {
3089                 int new, tmp;
3090                 new = fcntl(fd, F_DUPFD, 20);
3091                 tmp = errno;
3092                 (void)close(fd);
3093                 errno = tmp;
3094                 fd = new;
3095                 err = "accept/fcntl";
3096         }
3097 #endif
3098
3099         if (fd < 0) {
3100                 if (SOFT_ERROR(errno))
3101                         goto soft_error;
3102                 switch (errno) {
3103                 case ENFILE:
3104                 case EMFILE:
3105                         isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL,
3106                                        ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
3107                                        isc_msgcat, ISC_MSGSET_SOCKET,
3108                                        ISC_MSG_TOOMANYFDS,
3109                                        "%s: too many open file descriptors",
3110                                        err);
3111                         goto soft_error;
3112
3113                 case ENOBUFS:
3114                 case ENOMEM:
3115                 case ECONNRESET:
3116                 case ECONNABORTED:
3117                 case EHOSTUNREACH:
3118                 case EHOSTDOWN:
3119                 case ENETUNREACH:
3120                 case ENETDOWN:
3121                 case ECONNREFUSED:
3122 #ifdef EPROTO
3123                 case EPROTO:
3124 #endif
3125 #ifdef ENONET
3126                 case ENONET:
3127 #endif
3128                         goto soft_error;
3129                 default:
3130                         break;
3131                 }
3132                 isc__strerror(errno, strbuf, sizeof(strbuf));
3133                 UNEXPECTED_ERROR(__FILE__, __LINE__,
3134                                  "internal_accept: %s() %s: %s", err,
3135                                  isc_msgcat_get(isc_msgcat,
3136                                                 ISC_MSGSET_GENERAL,
3137                                                 ISC_MSG_FAILED,
3138                                                 "failed"),
3139                                  strbuf);
3140                 fd = -1;
3141                 result = ISC_R_UNEXPECTED;
3142         } else {
3143                 if (addrlen == 0U) {
3144                         UNEXPECTED_ERROR(__FILE__, __LINE__,
3145                                          "internal_accept(): "
3146                                          "accept() failed to return "
3147                                          "remote address");
3148
3149                         (void)close(fd);
3150                         goto soft_error;
3151                 } else if (NEWCONNSOCK(dev)->peer_address.type.sa.sa_family !=
3152                            sock->pf)
3153                 {
3154                         UNEXPECTED_ERROR(__FILE__, __LINE__,
3155                                          "internal_accept(): "
3156                                          "accept() returned peer address "
3157                                          "family %u (expected %u)",
3158                                          NEWCONNSOCK(dev)->peer_address.
3159                                          type.sa.sa_family,
3160                                          sock->pf);
3161                         (void)close(fd);
3162                         goto soft_error;
3163                 } else if (fd >= (int)manager->maxsocks) {
3164                         isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL,
3165                                        ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
3166                                        isc_msgcat, ISC_MSGSET_SOCKET,
3167                                        ISC_MSG_TOOMANYFDS,
3168                                        "accept: "
3169                                        "file descriptor exceeds limit (%d/%u)",
3170                                        fd, manager->maxsocks);
3171                         (void)close(fd);
3172                         goto soft_error;
3173                 }
3174         }
3175
3176         if (fd != -1) {
3177                 NEWCONNSOCK(dev)->peer_address.length = addrlen;
3178                 NEWCONNSOCK(dev)->pf = sock->pf;
3179         }
3180
3181         /*
3182          * Pull off the done event.
3183          */
3184         ISC_LIST_UNLINK(sock->accept_list, dev, ev_link);
3185
3186         /*
3187          * Poke watcher if there are more pending accepts.
3188          */
3189         if (!ISC_LIST_EMPTY(sock->accept_list))
3190                 select_poke(sock->manager, sock->fd, SELECT_POKE_ACCEPT);
3191
3192         UNLOCK(&sock->lock);
3193
3194         if (fd != -1 && (make_nonblock(fd) != ISC_R_SUCCESS)) {
3195                 (void)close(fd);
3196                 fd = -1;
3197                 result = ISC_R_UNEXPECTED;
3198         }
3199
3200         /*
3201          * -1 means the new socket didn't happen.
3202          */
3203         if (fd != -1) {
3204                 int lockid = FDLOCK_ID(fd);
3205
3206                 LOCK(&manager->fdlock[lockid]);
3207                 manager->fds[fd] = NEWCONNSOCK(dev);
3208                 manager->fdstate[fd] = MANAGED;
3209                 UNLOCK(&manager->fdlock[lockid]);
3210
3211                 LOCK(&manager->lock);
3212                 ISC_LIST_APPEND(manager->socklist, NEWCONNSOCK(dev), link);
3213
3214                 NEWCONNSOCK(dev)->fd = fd;
3215                 NEWCONNSOCK(dev)->bound = 1;
3216                 NEWCONNSOCK(dev)->connected = 1;
3217
3218                 /*
3219                  * Save away the remote address
3220                  */
3221                 dev->address = NEWCONNSOCK(dev)->peer_address;
3222
3223 #ifdef USE_SELECT
3224                 if (manager->maxfd < fd)
3225                         manager->maxfd = fd;
3226 #endif
3227
3228                 socket_log(sock, &NEWCONNSOCK(dev)->peer_address, CREATION,
3229                            isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_ACCEPTEDCXN,
3230                            "accepted connection, new socket %p",
3231                            dev->newsocket);
3232
3233                 UNLOCK(&manager->lock);
3234
3235                 inc_stats(manager->stats, sock->statsindex[STATID_ACCEPT]);
3236         } else {
3237                 inc_stats(manager->stats, sock->statsindex[STATID_ACCEPTFAIL]);
3238                 NEWCONNSOCK(dev)->references--;
3239                 free_socket((isc__socket_t **)&dev->newsocket);
3240         }
3241
3242         /*
3243          * Fill in the done event details and send it off.
3244          */
3245         dev->result = result;
3246         task = dev->ev_sender;
3247         dev->ev_sender = sock;
3248
3249         isc_task_sendanddetach(&task, ISC_EVENT_PTR(&dev));
3250         return;
3251
3252  soft_error:
3253         select_poke(sock->manager, sock->fd, SELECT_POKE_ACCEPT);
3254         UNLOCK(&sock->lock);
3255
3256         inc_stats(manager->stats, sock->statsindex[STATID_ACCEPTFAIL]);
3257         return;
3258 }
3259
3260 static void
3261 internal_recv(isc_task_t *me, isc_event_t *ev) {
3262         isc_socketevent_t *dev;
3263         isc__socket_t *sock;
3264
3265         INSIST(ev->ev_type == ISC_SOCKEVENT_INTR);
3266
3267         sock = ev->ev_sender;
3268         INSIST(VALID_SOCKET(sock));
3269
3270         LOCK(&sock->lock);
3271         socket_log(sock, NULL, IOEVENT,
3272                    isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_INTERNALRECV,
3273                    "internal_recv: task %p got event %p", me, ev);
3274
3275         INSIST(sock->pending_recv == 1);
3276         sock->pending_recv = 0;
3277
3278         INSIST(sock->references > 0);
3279         sock->references--;  /* the internal event is done with this socket */
3280         if (sock->references == 0) {
3281                 UNLOCK(&sock->lock);
3282                 destroy(&sock);
3283                 return;
3284         }
3285
3286         /*
3287          * Try to do as much I/O as possible on this socket.  There are no
3288          * limits here, currently.
3289          */
3290         dev = ISC_LIST_HEAD(sock->recv_list);
3291         while (dev != NULL) {
3292                 switch (doio_recv(sock, dev)) {
3293                 case DOIO_SOFT:
3294                         goto poke;
3295
3296                 case DOIO_EOF:
3297                         /*
3298                          * read of 0 means the remote end was closed.
3299                          * Run through the event queue and dispatch all
3300                          * the events with an EOF result code.
3301                          */
3302                         do {
3303                                 dev->result = ISC_R_EOF;
3304                                 send_recvdone_event(sock, &dev);
3305                                 dev = ISC_LIST_HEAD(sock->recv_list);
3306                         } while (dev != NULL);
3307                         goto poke;
3308
3309                 case DOIO_SUCCESS:
3310                 case DOIO_HARD:
3311                         send_recvdone_event(sock, &dev);
3312                         break;
3313                 }
3314
3315                 dev = ISC_LIST_HEAD(sock->recv_list);
3316         }
3317
3318  poke:
3319         if (!ISC_LIST_EMPTY(sock->recv_list))
3320                 select_poke(sock->manager, sock->fd, SELECT_POKE_READ);
3321
3322         UNLOCK(&sock->lock);
3323 }
3324
3325 static void
3326 internal_send(isc_task_t *me, isc_event_t *ev) {
3327         isc_socketevent_t *dev;
3328         isc__socket_t *sock;
3329
3330         INSIST(ev->ev_type == ISC_SOCKEVENT_INTW);
3331
3332         /*
3333          * Find out what socket this is and lock it.
3334          */
3335         sock = (isc__socket_t *)ev->ev_sender;
3336         INSIST(VALID_SOCKET(sock));
3337
3338         LOCK(&sock->lock);
3339         socket_log(sock, NULL, IOEVENT,
3340                    isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_INTERNALSEND,
3341                    "internal_send: task %p got event %p", me, ev);
3342
3343         INSIST(sock->pending_send == 1);
3344         sock->pending_send = 0;
3345
3346         INSIST(sock->references > 0);
3347         sock->references--;  /* the internal event is done with this socket */
3348         if (sock->references == 0) {
3349                 UNLOCK(&sock->lock);
3350                 destroy(&sock);
3351                 return;
3352         }
3353
3354         /*
3355          * Try to do as much I/O as possible on this socket.  There are no
3356          * limits here, currently.
3357          */
3358         dev = ISC_LIST_HEAD(sock->send_list);
3359         while (dev != NULL) {
3360                 switch (doio_send(sock, dev)) {
3361                 case DOIO_SOFT:
3362                         goto poke;
3363
3364                 case DOIO_HARD:
3365                 case DOIO_SUCCESS:
3366                         send_senddone_event(sock, &dev);
3367                         break;
3368                 }
3369
3370                 dev = ISC_LIST_HEAD(sock->send_list);
3371         }
3372
3373  poke:
3374         if (!ISC_LIST_EMPTY(sock->send_list))
3375                 select_poke(sock->manager, sock->fd, SELECT_POKE_WRITE);
3376
3377         UNLOCK(&sock->lock);
3378 }
3379
3380 static void
3381 internal_fdwatch_write(isc_task_t *me, isc_event_t *ev) {
3382         isc__socket_t *sock;
3383         int more_data;
3384
3385         INSIST(ev->ev_type == ISC_SOCKEVENT_INTW);
3386
3387         /*
3388          * Find out what socket this is and lock it.
3389          */
3390         sock = (isc__socket_t *)ev->ev_sender;
3391         INSIST(VALID_SOCKET(sock));
3392
3393         LOCK(&sock->lock);
3394         socket_log(sock, NULL, IOEVENT,
3395                    isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_INTERNALSEND,
3396                    "internal_fdwatch_write: task %p got event %p", me, ev);
3397
3398         INSIST(sock->pending_send == 1);
3399
3400         UNLOCK(&sock->lock);
3401         more_data = (sock->fdwatchcb)(me, (isc_socket_t *)sock,
3402                                       sock->fdwatcharg, ISC_SOCKFDWATCH_WRITE);
3403         LOCK(&sock->lock);
3404
3405         sock->pending_send = 0;
3406
3407         INSIST(sock->references > 0);
3408         sock->references--;  /* the internal event is done with this socket */
3409         if (sock->references == 0) {
3410                 UNLOCK(&sock->lock);
3411                 destroy(&sock);
3412                 return;
3413         }
3414
3415         if (more_data)
3416                 select_poke(sock->manager, sock->fd, SELECT_POKE_WRITE);
3417
3418         UNLOCK(&sock->lock);
3419 }
3420
3421 static void
3422 internal_fdwatch_read(isc_task_t *me, isc_event_t *ev) {
3423         isc__socket_t *sock;
3424         int more_data;
3425
3426         INSIST(ev->ev_type == ISC_SOCKEVENT_INTR);
3427
3428         /*
3429          * Find out what socket this is and lock it.
3430          */
3431         sock = (isc__socket_t *)ev->ev_sender;
3432         INSIST(VALID_SOCKET(sock));
3433
3434         LOCK(&sock->lock);
3435         socket_log(sock, NULL, IOEVENT,
3436                    isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_INTERNALRECV,
3437                    "internal_fdwatch_read: task %p got event %p", me, ev);
3438
3439         INSIST(sock->pending_recv == 1);
3440
3441         UNLOCK(&sock->lock);
3442         more_data = (sock->fdwatchcb)(me, (isc_socket_t *)sock,
3443                                       sock->fdwatcharg, ISC_SOCKFDWATCH_READ);
3444         LOCK(&sock->lock);
3445
3446         sock->pending_recv = 0;
3447
3448         INSIST(sock->references > 0);
3449         sock->references--;  /* the internal event is done with this socket */
3450         if (sock->references == 0) {
3451                 UNLOCK(&sock->lock);
3452                 destroy(&sock);
3453                 return;
3454         }
3455
3456         if (more_data)
3457                 select_poke(sock->manager, sock->fd, SELECT_POKE_READ);
3458
3459         UNLOCK(&sock->lock);
3460 }
3461
3462 /*
3463  * Process read/writes on each fd here.  Avoid locking
3464  * and unlocking twice if both reads and writes are possible.
3465  */
3466 static void
3467 process_fd(isc__socketmgr_t *manager, int fd, isc_boolean_t readable,
3468            isc_boolean_t writeable)
3469 {
3470         isc__socket_t *sock;
3471         isc_boolean_t unlock_sock;
3472         isc_boolean_t unwatch_read = ISC_FALSE, unwatch_write = ISC_FALSE;
3473         int lockid = FDLOCK_ID(fd);
3474
3475         /*
3476          * If the socket is going to be closed, don't do more I/O.
3477          */
3478         LOCK(&manager->fdlock[lockid]);
3479         if (manager->fdstate[fd] == CLOSE_PENDING) {
3480                 UNLOCK(&manager->fdlock[lockid]);
3481
3482                 (void)unwatch_fd(manager, fd, SELECT_POKE_READ);
3483                 (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE);
3484                 return;
3485         }
3486
3487         sock = manager->fds[fd];
3488         unlock_sock = ISC_FALSE;
3489         if (readable) {
3490                 if (sock == NULL) {
3491                         unwatch_read = ISC_TRUE;
3492                         goto check_write;
3493                 }
3494                 unlock_sock = ISC_TRUE;
3495                 LOCK(&sock->lock);
3496                 if (!SOCK_DEAD(sock)) {
3497                         if (sock->listener)
3498                                 dispatch_accept(sock);
3499                         else
3500                                 dispatch_recv(sock);
3501                 }
3502                 unwatch_read = ISC_TRUE;
3503         }
3504 check_write:
3505         if (writeable) {
3506                 if (sock == NULL) {
3507                         unwatch_write = ISC_TRUE;
3508                         goto unlock_fd;
3509                 }
3510                 if (!unlock_sock) {
3511                         unlock_sock = ISC_TRUE;
3512                         LOCK(&sock->lock);
3513                 }
3514                 if (!SOCK_DEAD(sock)) {
3515                         if (sock->connecting)
3516                                 dispatch_connect(sock);
3517                         else
3518                                 dispatch_send(sock);
3519                 }
3520                 unwatch_write = ISC_TRUE;
3521         }
3522         if (unlock_sock)
3523                 UNLOCK(&sock->lock);
3524
3525  unlock_fd:
3526         UNLOCK(&manager->fdlock[lockid]);
3527         if (unwatch_read)
3528                 (void)unwatch_fd(manager, fd, SELECT_POKE_READ);
3529         if (unwatch_write)
3530                 (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE);
3531
3532 }
3533
3534 #ifdef USE_KQUEUE
3535 static isc_boolean_t
3536 process_fds(isc__socketmgr_t *manager, struct kevent *events, int nevents) {
3537         int i;
3538         isc_boolean_t readable, writable;
3539         isc_boolean_t done = ISC_FALSE;
3540 #ifdef USE_WATCHER_THREAD
3541         isc_boolean_t have_ctlevent = ISC_FALSE;
3542 #endif
3543
3544         if (nevents == manager->nevents) {
3545                 /*
3546                  * This is not an error, but something unexpected.  If this
3547                  * happens, it may indicate the need for increasing
3548                  * ISC_SOCKET_MAXEVENTS.
3549                  */
3550                 manager_log(manager, ISC_LOGCATEGORY_GENERAL,
3551                             ISC_LOGMODULE_SOCKET, ISC_LOG_INFO,
3552                             "maximum number of FD events (%d) received",
3553                             nevents);
3554         }
3555
3556         for (i = 0; i < nevents; i++) {
3557                 REQUIRE(events[i].ident < manager->maxsocks);
3558 #ifdef USE_WATCHER_THREAD
3559                 if (events[i].ident == (uintptr_t)manager->pipe_fds[0]) {
3560                         have_ctlevent = ISC_TRUE;
3561                         continue;
3562                 }
3563 #endif
3564                 readable = ISC_TF(events[i].filter == EVFILT_READ);
3565                 writable = ISC_TF(events[i].filter == EVFILT_WRITE);
3566                 process_fd(manager, events[i].ident, readable, writable);
3567         }
3568
3569 #ifdef USE_WATCHER_THREAD
3570         if (have_ctlevent)
3571                 done = process_ctlfd(manager);
3572 #endif
3573
3574         return (done);
3575 }
3576 #elif defined(USE_EPOLL)
3577 static isc_boolean_t
3578 process_fds(isc__socketmgr_t *manager, struct epoll_event *events, int nevents)
3579 {
3580         int i;
3581         isc_boolean_t done = ISC_FALSE;
3582 #ifdef USE_WATCHER_THREAD
3583         isc_boolean_t have_ctlevent = ISC_FALSE;
3584 #endif
3585
3586         if (nevents == manager->nevents) {
3587                 manager_log(manager, ISC_LOGCATEGORY_GENERAL,
3588                             ISC_LOGMODULE_SOCKET, ISC_LOG_INFO,
3589                             "maximum number of FD events (%d) received",
3590                             nevents);
3591         }
3592
3593         for (i = 0; i < nevents; i++) {
3594                 REQUIRE(events[i].data.fd < (int)manager->maxsocks);
3595 #ifdef USE_WATCHER_THREAD
3596                 if (events[i].data.fd == manager->pipe_fds[0]) {
3597                         have_ctlevent = ISC_TRUE;
3598                         continue;
3599                 }
3600 #endif
3601                 if ((events[i].events & EPOLLERR) != 0 ||
3602                     (events[i].events & EPOLLHUP) != 0) {
3603                         /*
3604                          * epoll does not set IN/OUT bits on an erroneous
3605                          * condition, so we need to try both anyway.  This is a
3606                          * bit inefficient, but should be okay for such rare
3607                          * events.  Note also that the read or write attempt
3608                          * won't block because we use non-blocking sockets.
3609                          */
3610                         events[i].events |= (EPOLLIN | EPOLLOUT);
3611                 }
3612                 process_fd(manager, events[i].data.fd,
3613                            (events[i].events & EPOLLIN) != 0,
3614                            (events[i].events & EPOLLOUT) != 0);
3615         }
3616
3617 #ifdef USE_WATCHER_THREAD
3618         if (have_ctlevent)
3619                 done = process_ctlfd(manager);
3620 #endif
3621
3622         return (done);
3623 }
3624 #elif defined(USE_DEVPOLL)
3625 static isc_boolean_t
3626 process_fds(isc__socketmgr_t *manager, struct pollfd *events, int nevents) {
3627         int i;
3628         isc_boolean_t done = ISC_FALSE;
3629 #ifdef USE_WATCHER_THREAD
3630         isc_boolean_t have_ctlevent = ISC_FALSE;
3631 #endif
3632
3633         if (nevents == manager->nevents) {
3634                 manager_log(manager, ISC_LOGCATEGORY_GENERAL,
3635                             ISC_LOGMODULE_SOCKET, ISC_LOG_INFO,
3636                             "maximum number of FD events (%d) received",
3637                             nevents);
3638         }
3639
3640         for (i = 0; i < nevents; i++) {
3641                 REQUIRE(events[i].fd < (int)manager->maxsocks);
3642 #ifdef USE_WATCHER_THREAD
3643                 if (events[i].fd == manager->pipe_fds[0]) {
3644                         have_ctlevent = ISC_TRUE;
3645                         continue;
3646                 }
3647 #endif
3648                 process_fd(manager, events[i].fd,
3649                            (events[i].events & POLLIN) != 0,
3650                            (events[i].events & POLLOUT) != 0);
3651         }
3652
3653 #ifdef USE_WATCHER_THREAD
3654         if (have_ctlevent)
3655                 done = process_ctlfd(manager);
3656 #endif
3657
3658         return (done);
3659 }
3660 #elif defined(USE_SELECT)
3661 static void
3662 process_fds(isc__socketmgr_t *manager, int maxfd, fd_set *readfds,
3663             fd_set *writefds)
3664 {
3665         int i;
3666
3667         REQUIRE(maxfd <= (int)manager->maxsocks);
3668
3669         for (i = 0; i < maxfd; i++) {
3670 #ifdef USE_WATCHER_THREAD
3671                 if (i == manager->pipe_fds[0] || i == manager->pipe_fds[1])
3672                         continue;
3673 #endif /* USE_WATCHER_THREAD */
3674                 process_fd(manager, i, FD_ISSET(i, readfds),
3675                            FD_ISSET(i, writefds));
3676         }
3677 }
3678 #endif
3679
3680 #ifdef USE_WATCHER_THREAD
3681 static isc_boolean_t
3682 process_ctlfd(isc__socketmgr_t *manager) {
3683         int msg, fd;
3684
3685         for (;;) {
3686                 select_readmsg(manager, &fd, &msg);
3687
3688                 manager_log(manager, IOEVENT,
3689                             isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
3690                                            ISC_MSG_WATCHERMSG,
3691                                            "watcher got message %d "
3692                                            "for socket %d"), msg, fd);
3693
3694                 /*
3695                  * Nothing to read?
3696                  */
3697                 if (msg == SELECT_POKE_NOTHING)
3698                         break;
3699
3700                 /*
3701                  * Handle shutdown message.  We really should
3702                  * jump out of this loop right away, but
3703                  * it doesn't matter if we have to do a little
3704                  * more work first.
3705                  */
3706                 if (msg == SELECT_POKE_SHUTDOWN)
3707                         return (ISC_TRUE);
3708
3709                 /*
3710                  * This is a wakeup on a socket.  Look
3711                  * at the event queue for both read and write,
3712                  * and decide if we need to watch on it now
3713                  * or not.
3714                  */
3715                 wakeup_socket(manager, fd, msg);
3716         }
3717
3718         return (ISC_FALSE);
3719 }
3720
3721 /*
3722  * This is the thread that will loop forever, always in a select or poll
3723  * call.
3724  *
3725  * When select returns something to do, track down what thread gets to do
3726  * this I/O and post the event to it.
3727  */
3728 static isc_threadresult_t
3729 watcher(void *uap) {
3730         isc__socketmgr_t *manager = uap;
3731         isc_boolean_t done;
3732         int ctlfd;
3733         int cc;
3734 #ifdef USE_KQUEUE
3735         const char *fnname = "kevent()";
3736 #elif defined (USE_EPOLL)
3737         const char *fnname = "epoll_wait()";
3738 #elif defined(USE_DEVPOLL)
3739         const char *fnname = "ioctl(DP_POLL)";
3740         struct dvpoll dvp;
3741 #elif defined (USE_SELECT)
3742         const char *fnname = "select()";
3743         int maxfd;
3744 #endif
3745         char strbuf[ISC_STRERRORSIZE];
3746 #ifdef ISC_SOCKET_USE_POLLWATCH
3747         pollstate_t pollstate = poll_idle;
3748 #endif
3749
3750         /*
3751          * Get the control fd here.  This will never change.
3752          */
3753         ctlfd = manager->pipe_fds[0];
3754         done = ISC_FALSE;
3755         while (!done) {
3756                 do {
3757 #ifdef USE_KQUEUE
3758                         cc = kevent(manager->kqueue_fd, NULL, 0,
3759                                     manager->events, manager->nevents, NULL);
3760 #elif defined(USE_EPOLL)
3761                         cc = epoll_wait(manager->epoll_fd, manager->events,
3762                                         manager->nevents, -1);
3763 #elif defined(USE_DEVPOLL)
3764                         dvp.dp_fds = manager->events;
3765                         dvp.dp_nfds = manager->nevents;
3766 #ifndef ISC_SOCKET_USE_POLLWATCH
3767                         dvp.dp_timeout = -1;
3768 #else
3769                         if (pollstate == poll_idle)
3770                                 dvp.dp_timeout = -1;
3771                         else
3772                                 dvp.dp_timeout = ISC_SOCKET_POLLWATCH_TIMEOUT;
3773 #endif  /* ISC_SOCKET_USE_POLLWATCH */
3774                         cc = ioctl(manager->devpoll_fd, DP_POLL, &dvp);
3775 #elif defined(USE_SELECT)
3776                         LOCK(&manager->lock);
3777                         memcpy(manager->read_fds_copy, manager->read_fds,
3778                                manager->fd_bufsize);
3779                         memcpy(manager->write_fds_copy, manager->write_fds,
3780                                manager->fd_bufsize);
3781                         maxfd = manager->maxfd + 1;
3782                         UNLOCK(&manager->lock);
3783
3784                         cc = select(maxfd, manager->read_fds_copy,
3785                                     manager->write_fds_copy, NULL, NULL);
3786 #endif  /* USE_KQUEUE */
3787
3788                         if (cc < 0 && !SOFT_ERROR(errno)) {
3789                                 isc__strerror(errno, strbuf, sizeof(strbuf));
3790                                 FATAL_ERROR(__FILE__, __LINE__,
3791                                             "%s %s: %s", fnname,
3792                                             isc_msgcat_get(isc_msgcat,
3793                                                            ISC_MSGSET_GENERAL,
3794                                                            ISC_MSG_FAILED,
3795                                                            "failed"), strbuf);
3796                         }
3797
3798 #if defined(USE_DEVPOLL) && defined(ISC_SOCKET_USE_POLLWATCH)
3799                         if (cc == 0) {
3800                                 if (pollstate == poll_active)
3801                                         pollstate = poll_checking;
3802                                 else if (pollstate == poll_checking)
3803                                         pollstate = poll_idle;
3804                         } else if (cc > 0) {
3805                                 if (pollstate == poll_checking) {
3806                                         /*
3807                                          * XXX: We'd like to use a more
3808                                          * verbose log level as it's actually an
3809                                          * unexpected event, but the kernel bug
3810                                          * reportedly happens pretty frequently
3811                                          * (and it can also be a false positive)
3812                                          * so it would be just too noisy.
3813                                          */
3814                                         manager_log(manager,
3815                                                     ISC_LOGCATEGORY_GENERAL,
3816                                                     ISC_LOGMODULE_SOCKET,
3817                                                     ISC_LOG_DEBUG(1),
3818                                                     "unexpected POLL timeout");
3819                                 }
3820                                 pollstate = poll_active;
3821                         }
3822 #endif
3823                 } while (cc < 0);
3824
3825 #if defined(USE_KQUEUE) || defined (USE_EPOLL) || defined (USE_DEVPOLL)
3826                 done = process_fds(manager, manager->events, cc);
3827 #elif defined(USE_SELECT)
3828                 process_fds(manager, maxfd, manager->read_fds_copy,
3829                             manager->write_fds_copy);
3830
3831                 /*
3832                  * Process reads on internal, control fd.
3833                  */
3834                 if (FD_ISSET(ctlfd, manager->read_fds_copy))
3835                         done = process_ctlfd(manager);
3836 #endif
3837         }
3838
3839         manager_log(manager, TRACE, "%s",
3840                     isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
3841                                    ISC_MSG_EXITING, "watcher exiting"));
3842
3843         return ((isc_threadresult_t)0);
3844 }
3845 #endif /* USE_WATCHER_THREAD */
3846
3847 #ifdef BIND9
3848 ISC_SOCKETFUNC_SCOPE void
3849 isc__socketmgr_setreserved(isc_socketmgr_t *manager0, isc_uint32_t reserved) {
3850         isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
3851
3852         REQUIRE(VALID_MANAGER(manager));
3853
3854         manager->reserved = reserved;
3855 }
3856
3857 ISC_SOCKETFUNC_SCOPE void
3858 isc___socketmgr_maxudp(isc_socketmgr_t *manager0, int maxudp) {
3859         isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
3860
3861         REQUIRE(VALID_MANAGER(manager));
3862
3863         manager->maxudp = maxudp;
3864 }
3865 #endif  /* BIND9 */
3866
3867 /*
3868  * Create a new socket manager.
3869  */
3870
3871 static isc_result_t
3872 setup_watcher(isc_mem_t *mctx, isc__socketmgr_t *manager) {
3873         isc_result_t result;
3874 #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL)
3875         char strbuf[ISC_STRERRORSIZE];
3876 #endif
3877
3878 #ifdef USE_KQUEUE
3879         manager->nevents = ISC_SOCKET_MAXEVENTS;
3880         manager->events = isc_mem_get(mctx, sizeof(struct kevent) *
3881                                       manager->nevents);
3882         if (manager->events == NULL)
3883                 return (ISC_R_NOMEMORY);
3884         manager->kqueue_fd = kqueue();
3885         if (manager->kqueue_fd == -1) {
3886                 result = isc__errno2result(errno);
3887                 isc__strerror(errno, strbuf, sizeof(strbuf));
3888                 UNEXPECTED_ERROR(__FILE__, __LINE__,
3889                                  "kqueue %s: %s",
3890                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
3891                                                 ISC_MSG_FAILED, "failed"),
3892                                  strbuf);
3893                 isc_mem_put(mctx, manager->events,
3894                             sizeof(struct kevent) * manager->nevents);
3895                 return (result);
3896         }
3897
3898 #ifdef USE_WATCHER_THREAD
3899         result = watch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ);
3900         if (result != ISC_R_SUCCESS) {
3901                 close(manager->kqueue_fd);
3902                 isc_mem_put(mctx, manager->events,
3903                             sizeof(struct kevent) * manager->nevents);
3904                 return (result);
3905         }
3906 #endif  /* USE_WATCHER_THREAD */
3907 #elif defined(USE_EPOLL)
3908         manager->nevents = ISC_SOCKET_MAXEVENTS;
3909         manager->events = isc_mem_get(mctx, sizeof(struct epoll_event) *
3910                                       manager->nevents);
3911         if (manager->events == NULL)
3912                 return (ISC_R_NOMEMORY);
3913         manager->epoll_fd = epoll_create(manager->nevents);
3914         if (manager->epoll_fd == -1) {
3915                 result = isc__errno2result(errno);
3916                 isc__strerror(errno, strbuf, sizeof(strbuf));
3917                 UNEXPECTED_ERROR(__FILE__, __LINE__,
3918                                  "epoll_create %s: %s",
3919                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
3920                                                 ISC_MSG_FAILED, "failed"),
3921                                  strbuf);
3922                 isc_mem_put(mctx, manager->events,
3923                             sizeof(struct epoll_event) * manager->nevents);
3924                 return (result);
3925         }
3926 #ifdef USE_WATCHER_THREAD
3927         result = watch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ);
3928         if (result != ISC_R_SUCCESS) {
3929                 close(manager->epoll_fd);
3930                 isc_mem_put(mctx, manager->events,
3931                             sizeof(struct epoll_event) * manager->nevents);
3932                 return (result);
3933         }
3934 #endif  /* USE_WATCHER_THREAD */
3935 #elif defined(USE_DEVPOLL)
3936         /*
3937          * XXXJT: /dev/poll seems to reject large numbers of events,
3938          * so we should be careful about redefining ISC_SOCKET_MAXEVENTS.
3939          */
3940         manager->nevents = ISC_SOCKET_MAXEVENTS;
3941         manager->events = isc_mem_get(mctx, sizeof(struct pollfd) *
3942                                       manager->nevents);
3943         if (manager->events == NULL)
3944                 return (ISC_R_NOMEMORY);
3945         /*
3946          * Note: fdpollinfo should be able to support all possible FDs, so
3947          * it must have maxsocks entries (not nevents).
3948          */
3949         manager->fdpollinfo = isc_mem_get(mctx, sizeof(pollinfo_t) *
3950                                           manager->maxsocks);
3951         if (manager->fdpollinfo == NULL) {
3952                 isc_mem_put(mctx, manager->events,
3953                             sizeof(struct pollfd) * manager->nevents);
3954                 return (ISC_R_NOMEMORY);
3955         }
3956         memset(manager->fdpollinfo, 0, sizeof(pollinfo_t) * manager->maxsocks);
3957         manager->devpoll_fd = open("/dev/poll", O_RDWR);
3958         if (manager->devpoll_fd == -1) {
3959                 result = isc__errno2result(errno);
3960                 isc__strerror(errno, strbuf, sizeof(strbuf));
3961                 UNEXPECTED_ERROR(__FILE__, __LINE__,
3962                                  "open(/dev/poll) %s: %s",
3963                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
3964                                                 ISC_MSG_FAILED, "failed"),
3965                                  strbuf);
3966                 isc_mem_put(mctx, manager->events,
3967                             sizeof(struct pollfd) * manager->nevents);
3968                 isc_mem_put(mctx, manager->fdpollinfo,
3969                             sizeof(pollinfo_t) * manager->maxsocks);
3970                 return (result);
3971         }
3972 #ifdef USE_WATCHER_THREAD
3973         result = watch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ);
3974         if (result != ISC_R_SUCCESS) {
3975                 close(manager->devpoll_fd);
3976                 isc_mem_put(mctx, manager->events,
3977                             sizeof(struct pollfd) * manager->nevents);
3978                 isc_mem_put(mctx, manager->fdpollinfo,
3979                             sizeof(pollinfo_t) * manager->maxsocks);
3980                 return (result);
3981         }
3982 #endif  /* USE_WATCHER_THREAD */
3983 #elif defined(USE_SELECT)
3984         UNUSED(result);
3985
3986 #if ISC_SOCKET_MAXSOCKETS > FD_SETSIZE
3987         /*
3988          * Note: this code should also cover the case of MAXSOCKETS <=
3989          * FD_SETSIZE, but we separate the cases to avoid possible portability
3990          * issues regarding howmany() and the actual representation of fd_set.
3991          */
3992         manager->fd_bufsize = howmany(manager->maxsocks, NFDBITS) *
3993                 sizeof(fd_mask);
3994 #else
3995         manager->fd_bufsize = sizeof(fd_set);
3996 #endif
3997
3998         manager->read_fds = NULL;
3999         manager->read_fds_copy = NULL;
4000         manager->write_fds = NULL;
4001         manager->write_fds_copy = NULL;
4002
4003         manager->read_fds = isc_mem_get(mctx, manager->fd_bufsize);
4004         if (manager->read_fds != NULL)
4005                 manager->read_fds_copy = isc_mem_get(mctx, manager->fd_bufsize);
4006         if (manager->read_fds_copy != NULL)
4007                 manager->write_fds = isc_mem_get(mctx, manager->fd_bufsize);
4008         if (manager->write_fds != NULL) {
4009                 manager->write_fds_copy = isc_mem_get(mctx,
4010                                                       manager->fd_bufsize);
4011         }
4012         if (manager->write_fds_copy == NULL) {
4013                 if (manager->write_fds != NULL) {
4014                         isc_mem_put(mctx, manager->write_fds,
4015                                     manager->fd_bufsize);
4016                 }
4017                 if (manager->read_fds_copy != NULL) {
4018                         isc_mem_put(mctx, manager->read_fds_copy,
4019                                     manager->fd_bufsize);
4020                 }
4021                 if (manager->read_fds != NULL) {
4022                         isc_mem_put(mctx, manager->read_fds,
4023                                     manager->fd_bufsize);
4024                 }
4025                 return (ISC_R_NOMEMORY);
4026         }
4027         memset(manager->read_fds, 0, manager->fd_bufsize);
4028         memset(manager->write_fds, 0, manager->fd_bufsize);
4029
4030 #ifdef USE_WATCHER_THREAD
4031         (void)watch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ);
4032         manager->maxfd = manager->pipe_fds[0];
4033 #else /* USE_WATCHER_THREAD */
4034         manager->maxfd = 0;
4035 #endif /* USE_WATCHER_THREAD */
4036 #endif  /* USE_KQUEUE */
4037
4038         return (ISC_R_SUCCESS);
4039 }
4040
4041 static void
4042 cleanup_watcher(isc_mem_t *mctx, isc__socketmgr_t *manager) {
4043 #ifdef USE_WATCHER_THREAD
4044         isc_result_t result;
4045
4046         result = unwatch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ);
4047         if (result != ISC_R_SUCCESS) {
4048                 UNEXPECTED_ERROR(__FILE__, __LINE__,
4049                                  "epoll_ctl(DEL) %s",
4050                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
4051                                                 ISC_MSG_FAILED, "failed"));
4052         }
4053 #endif  /* USE_WATCHER_THREAD */
4054
4055 #ifdef USE_KQUEUE
4056         close(manager->kqueue_fd);
4057         isc_mem_put(mctx, manager->events,
4058                     sizeof(struct kevent) * manager->nevents);
4059 #elif defined(USE_EPOLL)
4060         close(manager->epoll_fd);
4061         isc_mem_put(mctx, manager->events,
4062                     sizeof(struct epoll_event) * manager->nevents);
4063 #elif defined(USE_DEVPOLL)
4064         close(manager->devpoll_fd);
4065         isc_mem_put(mctx, manager->events,
4066                     sizeof(struct pollfd) * manager->nevents);
4067         isc_mem_put(mctx, manager->fdpollinfo,
4068                     sizeof(pollinfo_t) * manager->maxsocks);
4069 #elif defined(USE_SELECT)
4070         if (manager->read_fds != NULL)
4071                 isc_mem_put(mctx, manager->read_fds, manager->fd_bufsize);
4072         if (manager->read_fds_copy != NULL)
4073                 isc_mem_put(mctx, manager->read_fds_copy, manager->fd_bufsize);
4074         if (manager->write_fds != NULL)
4075                 isc_mem_put(mctx, manager->write_fds, manager->fd_bufsize);
4076         if (manager->write_fds_copy != NULL)
4077                 isc_mem_put(mctx, manager->write_fds_copy, manager->fd_bufsize);
4078 #endif  /* USE_KQUEUE */
4079 }
4080
4081 ISC_SOCKETFUNC_SCOPE isc_result_t
4082 isc__socketmgr_create(isc_mem_t *mctx, isc_socketmgr_t **managerp) {
4083         return (isc__socketmgr_create2(mctx, managerp, 0));
4084 }
4085
4086 ISC_SOCKETFUNC_SCOPE isc_result_t
4087 isc__socketmgr_create2(isc_mem_t *mctx, isc_socketmgr_t **managerp,
4088                        unsigned int maxsocks)
4089 {
4090         int i;
4091         isc__socketmgr_t *manager;
4092 #ifdef USE_WATCHER_THREAD
4093         char strbuf[ISC_STRERRORSIZE];
4094 #endif
4095         isc_result_t result;
4096
4097         REQUIRE(managerp != NULL && *managerp == NULL);
4098
4099 #ifdef USE_SHARED_MANAGER
4100         if (socketmgr != NULL) {
4101                 /* Don't allow maxsocks to be updated */
4102                 if (maxsocks > 0 && socketmgr->maxsocks != maxsocks)
4103                         return (ISC_R_EXISTS);
4104
4105                 socketmgr->refs++;
4106                 *managerp = (isc_socketmgr_t *)socketmgr;
4107                 return (ISC_R_SUCCESS);
4108         }
4109 #endif /* USE_SHARED_MANAGER */
4110
4111         if (maxsocks == 0)
4112                 maxsocks = ISC_SOCKET_MAXSOCKETS;
4113
4114         manager = isc_mem_get(mctx, sizeof(*manager));
4115         if (manager == NULL)
4116                 return (ISC_R_NOMEMORY);
4117
4118         /* zero-clear so that necessary cleanup on failure will be easy */
4119         memset(manager, 0, sizeof(*manager));
4120         manager->maxsocks = maxsocks;
4121         manager->reserved = 0;
4122         manager->maxudp = 0;
4123         manager->fds = isc_mem_get(mctx,
4124                                    manager->maxsocks * sizeof(isc__socket_t *));
4125         if (manager->fds == NULL) {
4126                 result = ISC_R_NOMEMORY;
4127                 goto free_manager;
4128         }
4129         manager->fdstate = isc_mem_get(mctx, manager->maxsocks * sizeof(int));
4130         if (manager->fdstate == NULL) {
4131                 result = ISC_R_NOMEMORY;
4132                 goto free_manager;
4133         }
4134         manager->stats = NULL;
4135
4136         manager->common.methods = &socketmgrmethods;
4137         manager->common.magic = ISCAPI_SOCKETMGR_MAGIC;
4138         manager->common.impmagic = SOCKET_MANAGER_MAGIC;
4139         manager->mctx = NULL;
4140         memset(manager->fds, 0, manager->maxsocks * sizeof(isc_socket_t *));
4141         ISC_LIST_INIT(manager->socklist);
4142         result = isc_mutex_init(&manager->lock);
4143         if (result != ISC_R_SUCCESS)
4144                 goto free_manager;
4145         manager->fdlock = isc_mem_get(mctx, FDLOCK_COUNT * sizeof(isc_mutex_t));
4146         if (manager->fdlock == NULL) {
4147                 result = ISC_R_NOMEMORY;
4148                 goto cleanup_lock;
4149         }
4150         for (i = 0; i < FDLOCK_COUNT; i++) {
4151                 result = isc_mutex_init(&manager->fdlock[i]);
4152                 if (result != ISC_R_SUCCESS) {
4153                         while (--i >= 0)
4154                                 DESTROYLOCK(&manager->fdlock[i]);
4155                         isc_mem_put(mctx, manager->fdlock,
4156                                     FDLOCK_COUNT * sizeof(isc_mutex_t));
4157                         manager->fdlock = NULL;
4158                         goto cleanup_lock;
4159                 }
4160         }
4161
4162 #ifdef USE_WATCHER_THREAD
4163         if (isc_condition_init(&manager->shutdown_ok) != ISC_R_SUCCESS) {
4164                 UNEXPECTED_ERROR(__FILE__, __LINE__,
4165                                  "isc_condition_init() %s",
4166                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
4167                                                 ISC_MSG_FAILED, "failed"));
4168                 result = ISC_R_UNEXPECTED;
4169                 goto cleanup_lock;
4170         }
4171
4172         /*
4173          * Create the special fds that will be used to wake up the
4174          * select/poll loop when something internal needs to be done.
4175          */
4176         if (pipe(manager->pipe_fds) != 0) {
4177                 isc__strerror(errno, strbuf, sizeof(strbuf));
4178                 UNEXPECTED_ERROR(__FILE__, __LINE__,
4179                                  "pipe() %s: %s",
4180                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
4181                                                 ISC_MSG_FAILED, "failed"),
4182                                  strbuf);
4183                 result = ISC_R_UNEXPECTED;
4184                 goto cleanup_condition;
4185         }
4186
4187         RUNTIME_CHECK(make_nonblock(manager->pipe_fds[0]) == ISC_R_SUCCESS);
4188 #if 0
4189         RUNTIME_CHECK(make_nonblock(manager->pipe_fds[1]) == ISC_R_SUCCESS);
4190 #endif
4191 #endif  /* USE_WATCHER_THREAD */
4192
4193 #ifdef USE_SHARED_MANAGER
4194         manager->refs = 1;
4195 #endif /* USE_SHARED_MANAGER */
4196
4197         /*
4198          * Set up initial state for the select loop
4199          */
4200         result = setup_watcher(mctx, manager);
4201         if (result != ISC_R_SUCCESS)
4202                 goto cleanup;
4203         memset(manager->fdstate, 0, manager->maxsocks * sizeof(int));
4204 #ifdef USE_WATCHER_THREAD
4205         /*
4206          * Start up the select/poll thread.
4207          */
4208         if (isc_thread_create(watcher, manager, &manager->watcher) !=
4209             ISC_R_SUCCESS) {
4210                 UNEXPECTED_ERROR(__FILE__, __LINE__,
4211                                  "isc_thread_create() %s",
4212                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
4213                                                 ISC_MSG_FAILED, "failed"));
4214                 cleanup_watcher(mctx, manager);
4215                 result = ISC_R_UNEXPECTED;
4216                 goto cleanup;
4217         }
4218 #endif /* USE_WATCHER_THREAD */
4219         isc_mem_attach(mctx, &manager->mctx);
4220
4221 #ifdef USE_SHARED_MANAGER
4222         socketmgr = manager;
4223 #endif /* USE_SHARED_MANAGER */
4224         *managerp = (isc_socketmgr_t *)manager;
4225
4226         return (ISC_R_SUCCESS);
4227
4228 cleanup:
4229 #ifdef USE_WATCHER_THREAD
4230         (void)close(manager->pipe_fds[0]);
4231         (void)close(manager->pipe_fds[1]);
4232 #endif  /* USE_WATCHER_THREAD */
4233
4234 #ifdef USE_WATCHER_THREAD
4235 cleanup_condition:
4236         (void)isc_condition_destroy(&manager->shutdown_ok);
4237 #endif  /* USE_WATCHER_THREAD */
4238
4239
4240 cleanup_lock:
4241         if (manager->fdlock != NULL) {
4242                 for (i = 0; i < FDLOCK_COUNT; i++)
4243                         DESTROYLOCK(&manager->fdlock[i]);
4244         }
4245         DESTROYLOCK(&manager->lock);
4246
4247 free_manager:
4248         if (manager->fdlock != NULL) {
4249                 isc_mem_put(mctx, manager->fdlock,
4250                             FDLOCK_COUNT * sizeof(isc_mutex_t));
4251         }
4252         if (manager->fdstate != NULL) {
4253                 isc_mem_put(mctx, manager->fdstate,
4254                             manager->maxsocks * sizeof(int));
4255         }
4256         if (manager->fds != NULL) {
4257                 isc_mem_put(mctx, manager->fds,
4258                             manager->maxsocks * sizeof(isc_socket_t *));
4259         }
4260         isc_mem_put(mctx, manager, sizeof(*manager));
4261
4262         return (result);
4263 }
4264
4265 #ifdef BIND9
4266 isc_result_t
4267 isc__socketmgr_getmaxsockets(isc_socketmgr_t *manager0, unsigned int *nsockp) {
4268         isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
4269         REQUIRE(VALID_MANAGER(manager));
4270         REQUIRE(nsockp != NULL);
4271
4272         *nsockp = manager->maxsocks;
4273
4274         return (ISC_R_SUCCESS);
4275 }
4276
4277 void
4278 isc__socketmgr_setstats(isc_socketmgr_t *manager0, isc_stats_t *stats) {
4279         isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
4280
4281         REQUIRE(VALID_MANAGER(manager));
4282         REQUIRE(ISC_LIST_EMPTY(manager->socklist));
4283         REQUIRE(manager->stats == NULL);
4284         REQUIRE(isc_stats_ncounters(stats) == isc_sockstatscounter_max);
4285
4286         isc_stats_attach(stats, &manager->stats);
4287 }
4288 #endif
4289
4290 ISC_SOCKETFUNC_SCOPE void
4291 isc__socketmgr_destroy(isc_socketmgr_t **managerp) {
4292         isc__socketmgr_t *manager;
4293         int i;
4294         isc_mem_t *mctx;
4295
4296         /*
4297          * Destroy a socket manager.
4298          */
4299
4300         REQUIRE(managerp != NULL);
4301         manager = (isc__socketmgr_t *)*managerp;
4302         REQUIRE(VALID_MANAGER(manager));
4303
4304 #ifdef USE_SHARED_MANAGER
4305         manager->refs--;
4306         if (manager->refs > 0) {
4307                 *managerp = NULL;
4308                 return;
4309         }
4310         socketmgr = NULL;
4311 #endif /* USE_SHARED_MANAGER */
4312
4313         LOCK(&manager->lock);
4314
4315         /*
4316          * Wait for all sockets to be destroyed.
4317          */
4318         while (!ISC_LIST_EMPTY(manager->socklist)) {
4319 #ifdef USE_WATCHER_THREAD
4320                 manager_log(manager, CREATION, "%s",
4321                             isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
4322                                            ISC_MSG_SOCKETSREMAIN,
4323                                            "sockets exist"));
4324                 WAIT(&manager->shutdown_ok, &manager->lock);
4325 #else /* USE_WATCHER_THREAD */
4326                 UNLOCK(&manager->lock);
4327                 isc__taskmgr_dispatch(NULL);
4328                 LOCK(&manager->lock);
4329 #endif /* USE_WATCHER_THREAD */
4330         }
4331
4332         UNLOCK(&manager->lock);
4333
4334         /*
4335          * Here, poke our select/poll thread.  Do this by closing the write
4336          * half of the pipe, which will send EOF to the read half.
4337          * This is currently a no-op in the non-threaded case.
4338          */
4339         select_poke(manager, 0, SELECT_POKE_SHUTDOWN);
4340
4341 #ifdef USE_WATCHER_THREAD
4342         /*
4343          * Wait for thread to exit.
4344          */
4345         if (isc_thread_join(manager->watcher, NULL) != ISC_R_SUCCESS)
4346                 UNEXPECTED_ERROR(__FILE__, __LINE__,
4347                                  "isc_thread_join() %s",
4348                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
4349                                                 ISC_MSG_FAILED, "failed"));
4350 #endif /* USE_WATCHER_THREAD */
4351
4352         /*
4353          * Clean up.
4354          */
4355         cleanup_watcher(manager->mctx, manager);
4356
4357 #ifdef USE_WATCHER_THREAD
4358         (void)close(manager->pipe_fds[0]);
4359         (void)close(manager->pipe_fds[1]);
4360         (void)isc_condition_destroy(&manager->shutdown_ok);
4361 #endif /* USE_WATCHER_THREAD */
4362
4363         for (i = 0; i < (int)manager->maxsocks; i++)
4364                 if (manager->fdstate[i] == CLOSE_PENDING) /* no need to lock */
4365                         (void)close(i);
4366
4367         isc_mem_put(manager->mctx, manager->fds,
4368                     manager->maxsocks * sizeof(isc__socket_t *));
4369         isc_mem_put(manager->mctx, manager->fdstate,
4370                     manager->maxsocks * sizeof(int));
4371
4372         if (manager->stats != NULL)
4373                 isc_stats_detach(&manager->stats);
4374
4375         if (manager->fdlock != NULL) {
4376                 for (i = 0; i < FDLOCK_COUNT; i++)
4377                         DESTROYLOCK(&manager->fdlock[i]);
4378                 isc_mem_put(manager->mctx, manager->fdlock,
4379                             FDLOCK_COUNT * sizeof(isc_mutex_t));
4380         }
4381         DESTROYLOCK(&manager->lock);
4382         manager->common.magic = 0;
4383         manager->common.impmagic = 0;
4384         mctx= manager->mctx;
4385         isc_mem_put(mctx, manager, sizeof(*manager));
4386
4387         isc_mem_detach(&mctx);
4388
4389         *managerp = NULL;
4390
4391 #ifdef USE_SHARED_MANAGER
4392         socketmgr = NULL;
4393 #endif
4394 }
4395
4396 static isc_result_t
4397 socket_recv(isc__socket_t *sock, isc_socketevent_t *dev, isc_task_t *task,
4398             unsigned int flags)
4399 {
4400         int io_state;
4401         isc_boolean_t have_lock = ISC_FALSE;
4402         isc_task_t *ntask = NULL;
4403         isc_result_t result = ISC_R_SUCCESS;
4404
4405         dev->ev_sender = task;
4406
4407         if (sock->type == isc_sockettype_udp) {
4408                 io_state = doio_recv(sock, dev);
4409         } else {
4410                 LOCK(&sock->lock);
4411                 have_lock = ISC_TRUE;
4412
4413                 if (ISC_LIST_EMPTY(sock->recv_list))
4414                         io_state = doio_recv(sock, dev);
4415                 else
4416                         io_state = DOIO_SOFT;
4417         }
4418
4419         switch (io_state) {
4420         case DOIO_SOFT:
4421                 /*
4422                  * We couldn't read all or part of the request right now, so
4423                  * queue it.
4424                  *
4425                  * Attach to socket and to task
4426                  */
4427                 isc_task_attach(task, &ntask);
4428                 dev->attributes |= ISC_SOCKEVENTATTR_ATTACHED;
4429
4430                 if (!have_lock) {
4431                         LOCK(&sock->lock);
4432                         have_lock = ISC_TRUE;
4433                 }
4434
4435                 /*
4436                  * Enqueue the request.  If the socket was previously not being
4437                  * watched, poke the watcher to start paying attention to it.
4438                  */
4439                 if (ISC_LIST_EMPTY(sock->recv_list) && !sock->pending_recv)
4440                         select_poke(sock->manager, sock->fd, SELECT_POKE_READ);
4441                 ISC_LIST_ENQUEUE(sock->recv_list, dev, ev_link);
4442
4443                 socket_log(sock, NULL, EVENT, NULL, 0, 0,
4444                            "socket_recv: event %p -> task %p",
4445                            dev, ntask);
4446
4447                 if ((flags & ISC_SOCKFLAG_IMMEDIATE) != 0)
4448                         result = ISC_R_INPROGRESS;
4449                 break;
4450
4451         case DOIO_EOF:
4452                 dev->result = ISC_R_EOF;
4453                 /* fallthrough */
4454
4455         case DOIO_HARD:
4456         case DOIO_SUCCESS:
4457                 if ((flags & ISC_SOCKFLAG_IMMEDIATE) == 0)
4458                         send_recvdone_event(sock, &dev);
4459                 break;
4460         }
4461
4462         if (have_lock)
4463                 UNLOCK(&sock->lock);
4464
4465         return (result);
4466 }
4467
4468 ISC_SOCKETFUNC_SCOPE isc_result_t
4469 isc__socket_recvv(isc_socket_t *sock0, isc_bufferlist_t *buflist,
4470                   unsigned int minimum, isc_task_t *task,
4471                   isc_taskaction_t action, const void *arg)
4472 {
4473         isc__socket_t *sock = (isc__socket_t *)sock0;
4474         isc_socketevent_t *dev;
4475         isc__socketmgr_t *manager;
4476         unsigned int iocount;
4477         isc_buffer_t *buffer;
4478
4479         REQUIRE(VALID_SOCKET(sock));
4480         REQUIRE(buflist != NULL);
4481         REQUIRE(!ISC_LIST_EMPTY(*buflist));
4482         REQUIRE(task != NULL);
4483         REQUIRE(action != NULL);
4484
4485         manager = sock->manager;
4486         REQUIRE(VALID_MANAGER(manager));
4487
4488         iocount = isc_bufferlist_availablecount(buflist);
4489         REQUIRE(iocount > 0);
4490
4491         INSIST(sock->bound);
4492
4493         dev = allocate_socketevent(sock, ISC_SOCKEVENT_RECVDONE, action, arg);
4494         if (dev == NULL)
4495                 return (ISC_R_NOMEMORY);
4496
4497         /*
4498          * UDP sockets are always partial read
4499          */
4500         if (sock->type == isc_sockettype_udp)
4501                 dev->minimum = 1;
4502         else {
4503                 if (minimum == 0)
4504                         dev->minimum = iocount;
4505                 else
4506                         dev->minimum = minimum;
4507         }
4508
4509         /*
4510          * Move each buffer from the passed in list to our internal one.
4511          */
4512         buffer = ISC_LIST_HEAD(*buflist);
4513         while (buffer != NULL) {
4514                 ISC_LIST_DEQUEUE(*buflist, buffer, link);
4515                 ISC_LIST_ENQUEUE(dev->bufferlist, buffer, link);
4516                 buffer = ISC_LIST_HEAD(*buflist);
4517         }
4518
4519         return (socket_recv(sock, dev, task, 0));
4520 }
4521
4522 ISC_SOCKETFUNC_SCOPE isc_result_t
4523 isc__socket_recv(isc_socket_t *sock0, isc_region_t *region,
4524                  unsigned int minimum, isc_task_t *task,
4525                  isc_taskaction_t action, const void *arg)
4526 {
4527         isc__socket_t *sock = (isc__socket_t *)sock0;
4528         isc_socketevent_t *dev;
4529         isc__socketmgr_t *manager;
4530
4531         REQUIRE(VALID_SOCKET(sock));
4532         REQUIRE(action != NULL);
4533
4534         manager = sock->manager;
4535         REQUIRE(VALID_MANAGER(manager));
4536
4537         INSIST(sock->bound);
4538
4539         dev = allocate_socketevent(sock, ISC_SOCKEVENT_RECVDONE, action, arg);
4540         if (dev == NULL)
4541                 return (ISC_R_NOMEMORY);
4542
4543         return (isc__socket_recv2(sock0, region, minimum, task, dev, 0));
4544 }
4545
4546 ISC_SOCKETFUNC_SCOPE isc_result_t
4547 isc__socket_recv2(isc_socket_t *sock0, isc_region_t *region,
4548                   unsigned int minimum, isc_task_t *task,
4549                   isc_socketevent_t *event, unsigned int flags)
4550 {
4551         isc__socket_t *sock = (isc__socket_t *)sock0;
4552
4553         event->ev_sender = sock;
4554         event->result = ISC_R_UNEXPECTED;
4555         ISC_LIST_INIT(event->bufferlist);
4556         event->region = *region;
4557         event->n = 0;
4558         event->offset = 0;
4559         event->attributes = 0;
4560
4561         /*
4562          * UDP sockets are always partial read.
4563          */
4564         if (sock->type == isc_sockettype_udp)
4565                 event->minimum = 1;
4566         else {
4567                 if (minimum == 0)
4568                         event->minimum = region->length;
4569                 else
4570                         event->minimum = minimum;
4571         }
4572
4573         return (socket_recv(sock, event, task, flags));
4574 }
4575
4576 static isc_result_t
4577 socket_send(isc__socket_t *sock, isc_socketevent_t *dev, isc_task_t *task,
4578             isc_sockaddr_t *address, struct in6_pktinfo *pktinfo,
4579             unsigned int flags)
4580 {
4581         int io_state;
4582         isc_boolean_t have_lock = ISC_FALSE;
4583         isc_task_t *ntask = NULL;
4584         isc_result_t result = ISC_R_SUCCESS;
4585
4586         dev->ev_sender = task;
4587
4588         set_dev_address(address, sock, dev);
4589         if (pktinfo != NULL) {
4590                 dev->attributes |= ISC_SOCKEVENTATTR_PKTINFO;
4591                 dev->pktinfo = *pktinfo;
4592
4593                 if (!isc_sockaddr_issitelocal(&dev->address) &&
4594                     !isc_sockaddr_islinklocal(&dev->address)) {
4595                         socket_log(sock, NULL, TRACE, isc_msgcat,
4596                                    ISC_MSGSET_SOCKET, ISC_MSG_PKTINFOPROVIDED,
4597                                    "pktinfo structure provided, ifindex %u "
4598                                    "(set to 0)", pktinfo->ipi6_ifindex);
4599
4600                         /*
4601                          * Set the pktinfo index to 0 here, to let the
4602                          * kernel decide what interface it should send on.
4603                          */
4604                         dev->pktinfo.ipi6_ifindex = 0;
4605                 }
4606         }
4607
4608         if (sock->type == isc_sockettype_udp)
4609                 io_state = doio_send(sock, dev);
4610         else {
4611                 LOCK(&sock->lock);
4612                 have_lock = ISC_TRUE;
4613
4614                 if (ISC_LIST_EMPTY(sock->send_list))
4615                         io_state = doio_send(sock, dev);
4616                 else
4617                         io_state = DOIO_SOFT;
4618         }
4619
4620         switch (io_state) {
4621         case DOIO_SOFT:
4622                 /*
4623                  * We couldn't send all or part of the request right now, so
4624                  * queue it unless ISC_SOCKFLAG_NORETRY is set.
4625                  */
4626                 if ((flags & ISC_SOCKFLAG_NORETRY) == 0) {
4627                         isc_task_attach(task, &ntask);
4628                         dev->attributes |= ISC_SOCKEVENTATTR_ATTACHED;
4629
4630                         if (!have_lock) {
4631                                 LOCK(&sock->lock);
4632                                 have_lock = ISC_TRUE;
4633                         }
4634
4635                         /*
4636                          * Enqueue the request.  If the socket was previously
4637                          * not being watched, poke the watcher to start
4638                          * paying attention to it.
4639                          */
4640                         if (ISC_LIST_EMPTY(sock->send_list) &&
4641                             !sock->pending_send)
4642                                 select_poke(sock->manager, sock->fd,
4643                                             SELECT_POKE_WRITE);
4644                         ISC_LIST_ENQUEUE(sock->send_list, dev, ev_link);
4645
4646                         socket_log(sock, NULL, EVENT, NULL, 0, 0,
4647                                    "socket_send: event %p -> task %p",
4648                                    dev, ntask);
4649
4650                         if ((flags & ISC_SOCKFLAG_IMMEDIATE) != 0)
4651                                 result = ISC_R_INPROGRESS;
4652                         break;
4653                 }
4654
4655         case DOIO_HARD:
4656         case DOIO_SUCCESS:
4657                 if ((flags & ISC_SOCKFLAG_IMMEDIATE) == 0)
4658                         send_senddone_event(sock, &dev);
4659                 break;
4660         }
4661
4662         if (have_lock)
4663                 UNLOCK(&sock->lock);
4664
4665         return (result);
4666 }
4667
4668 ISC_SOCKETFUNC_SCOPE isc_result_t
4669 isc__socket_send(isc_socket_t *sock, isc_region_t *region,
4670                  isc_task_t *task, isc_taskaction_t action, const void *arg)
4671 {
4672         /*
4673          * REQUIRE() checking is performed in isc_socket_sendto().
4674          */
4675         return (isc__socket_sendto(sock, region, task, action, arg, NULL,
4676                                    NULL));
4677 }
4678
4679 ISC_SOCKETFUNC_SCOPE isc_result_t
4680 isc__socket_sendto(isc_socket_t *sock0, isc_region_t *region,
4681                    isc_task_t *task, isc_taskaction_t action, const void *arg,
4682                    isc_sockaddr_t *address, struct in6_pktinfo *pktinfo)
4683 {
4684         isc__socket_t *sock = (isc__socket_t *)sock0;
4685         isc_socketevent_t *dev;
4686         isc__socketmgr_t *manager;
4687
4688         REQUIRE(VALID_SOCKET(sock));
4689         REQUIRE(region != NULL);
4690         REQUIRE(task != NULL);
4691         REQUIRE(action != NULL);
4692
4693         manager = sock->manager;
4694         REQUIRE(VALID_MANAGER(manager));
4695
4696         INSIST(sock->bound);
4697
4698         dev = allocate_socketevent(sock, ISC_SOCKEVENT_SENDDONE, action, arg);
4699         if (dev == NULL)
4700                 return (ISC_R_NOMEMORY);
4701
4702         dev->region = *region;
4703
4704         return (socket_send(sock, dev, task, address, pktinfo, 0));
4705 }
4706
4707 ISC_SOCKETFUNC_SCOPE isc_result_t
4708 isc__socket_sendv(isc_socket_t *sock, isc_bufferlist_t *buflist,
4709                   isc_task_t *task, isc_taskaction_t action, const void *arg)
4710 {
4711         return (isc__socket_sendtov(sock, buflist, task, action, arg, NULL,
4712                                     NULL));
4713 }
4714
4715 ISC_SOCKETFUNC_SCOPE isc_result_t
4716 isc__socket_sendtov(isc_socket_t *sock0, isc_bufferlist_t *buflist,
4717                     isc_task_t *task, isc_taskaction_t action, const void *arg,
4718                     isc_sockaddr_t *address, struct in6_pktinfo *pktinfo)
4719 {
4720         isc__socket_t *sock = (isc__socket_t *)sock0;
4721         isc_socketevent_t *dev;
4722         isc__socketmgr_t *manager;
4723         unsigned int iocount;
4724         isc_buffer_t *buffer;
4725
4726         REQUIRE(VALID_SOCKET(sock));
4727         REQUIRE(buflist != NULL);
4728         REQUIRE(!ISC_LIST_EMPTY(*buflist));
4729         REQUIRE(task != NULL);
4730         REQUIRE(action != NULL);
4731
4732         manager = sock->manager;
4733         REQUIRE(VALID_MANAGER(manager));
4734
4735         iocount = isc_bufferlist_usedcount(buflist);
4736         REQUIRE(iocount > 0);
4737
4738         dev = allocate_socketevent(sock, ISC_SOCKEVENT_SENDDONE, action, arg);
4739         if (dev == NULL)
4740                 return (ISC_R_NOMEMORY);
4741
4742         /*
4743          * Move each buffer from the passed in list to our internal one.
4744          */
4745         buffer = ISC_LIST_HEAD(*buflist);
4746         while (buffer != NULL) {
4747                 ISC_LIST_DEQUEUE(*buflist, buffer, link);
4748                 ISC_LIST_ENQUEUE(dev->bufferlist, buffer, link);
4749                 buffer = ISC_LIST_HEAD(*buflist);
4750         }
4751
4752         return (socket_send(sock, dev, task, address, pktinfo, 0));
4753 }
4754
4755 ISC_SOCKETFUNC_SCOPE isc_result_t
4756 isc__socket_sendto2(isc_socket_t *sock0, isc_region_t *region,
4757                     isc_task_t *task,
4758                     isc_sockaddr_t *address, struct in6_pktinfo *pktinfo,
4759                     isc_socketevent_t *event, unsigned int flags)
4760 {
4761         isc__socket_t *sock = (isc__socket_t *)sock0;
4762
4763         REQUIRE(VALID_SOCKET(sock));
4764         REQUIRE((flags & ~(ISC_SOCKFLAG_IMMEDIATE|ISC_SOCKFLAG_NORETRY)) == 0);
4765         if ((flags & ISC_SOCKFLAG_NORETRY) != 0)
4766                 REQUIRE(sock->type == isc_sockettype_udp);
4767         event->ev_sender = sock;
4768         event->result = ISC_R_UNEXPECTED;
4769         ISC_LIST_INIT(event->bufferlist);
4770         event->region = *region;
4771         event->n = 0;
4772         event->offset = 0;
4773         event->attributes = 0;
4774
4775         return (socket_send(sock, event, task, address, pktinfo, flags));
4776 }
4777
4778 ISC_SOCKETFUNC_SCOPE void
4779 isc__socket_cleanunix(isc_sockaddr_t *sockaddr, isc_boolean_t active) {
4780 #ifdef ISC_PLATFORM_HAVESYSUNH
4781         int s;
4782         struct stat sb;
4783         char strbuf[ISC_STRERRORSIZE];
4784
4785         if (sockaddr->type.sa.sa_family != AF_UNIX)
4786                 return;
4787
4788 #ifndef S_ISSOCK
4789 #if defined(S_IFMT) && defined(S_IFSOCK)
4790 #define S_ISSOCK(mode) ((mode & S_IFMT)==S_IFSOCK)
4791 #elif defined(_S_IFMT) && defined(S_IFSOCK)
4792 #define S_ISSOCK(mode) ((mode & _S_IFMT)==S_IFSOCK)
4793 #endif
4794 #endif
4795
4796 #ifndef S_ISFIFO
4797 #if defined(S_IFMT) && defined(S_IFIFO)
4798 #define S_ISFIFO(mode) ((mode & S_IFMT)==S_IFIFO)
4799 #elif defined(_S_IFMT) && defined(S_IFIFO)
4800 #define S_ISFIFO(mode) ((mode & _S_IFMT)==S_IFIFO)
4801 #endif
4802 #endif
4803
4804 #if !defined(S_ISFIFO) && !defined(S_ISSOCK)
4805 #error You need to define S_ISFIFO and S_ISSOCK as appropriate for your platform.  See <sys/stat.h>.
4806 #endif
4807
4808 #ifndef S_ISFIFO
4809 #define S_ISFIFO(mode) 0
4810 #endif
4811
4812 #ifndef S_ISSOCK
4813 #define S_ISSOCK(mode) 0
4814 #endif
4815
4816         if (active) {
4817                 if (stat(sockaddr->type.sunix.sun_path, &sb) < 0) {
4818                         isc__strerror(errno, strbuf, sizeof(strbuf));
4819                         isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4820                                       ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
4821                                       "isc_socket_cleanunix: stat(%s): %s",
4822                                       sockaddr->type.sunix.sun_path, strbuf);
4823                         return;
4824                 }
4825                 if (!(S_ISSOCK(sb.st_mode) || S_ISFIFO(sb.st_mode))) {
4826                         isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4827                                       ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
4828                                       "isc_socket_cleanunix: %s: not a socket",
4829                                       sockaddr->type.sunix.sun_path);
4830                         return;
4831                 }
4832                 if (unlink(sockaddr->type.sunix.sun_path) < 0) {
4833                         isc__strerror(errno, strbuf, sizeof(strbuf));
4834                         isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4835                                       ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
4836                                       "isc_socket_cleanunix: unlink(%s): %s",
4837                                       sockaddr->type.sunix.sun_path, strbuf);
4838                 }
4839                 return;
4840         }
4841
4842         s = socket(AF_UNIX, SOCK_STREAM, 0);
4843         if (s < 0) {
4844                 isc__strerror(errno, strbuf, sizeof(strbuf));
4845                 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4846                               ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING,
4847                               "isc_socket_cleanunix: socket(%s): %s",
4848                               sockaddr->type.sunix.sun_path, strbuf);
4849                 return;
4850         }
4851
4852         if (stat(sockaddr->type.sunix.sun_path, &sb) < 0) {
4853                 switch (errno) {
4854                 case ENOENT:    /* We exited cleanly last time */
4855                         break;
4856                 default:
4857                         isc__strerror(errno, strbuf, sizeof(strbuf));
4858                         isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4859                                       ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING,
4860                                       "isc_socket_cleanunix: stat(%s): %s",
4861                                       sockaddr->type.sunix.sun_path, strbuf);
4862                         break;
4863                 }
4864                 goto cleanup;
4865         }
4866
4867         if (!(S_ISSOCK(sb.st_mode) || S_ISFIFO(sb.st_mode))) {
4868                 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4869                               ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING,
4870                               "isc_socket_cleanunix: %s: not a socket",
4871                               sockaddr->type.sunix.sun_path);
4872                 goto cleanup;
4873         }
4874
4875         if (connect(s, (struct sockaddr *)&sockaddr->type.sunix,
4876                     sizeof(sockaddr->type.sunix)) < 0) {
4877                 switch (errno) {
4878                 case ECONNREFUSED:
4879                 case ECONNRESET:
4880                         if (unlink(sockaddr->type.sunix.sun_path) < 0) {
4881                                 isc__strerror(errno, strbuf, sizeof(strbuf));
4882                                 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4883                                               ISC_LOGMODULE_SOCKET,
4884                                               ISC_LOG_WARNING,
4885                                               "isc_socket_cleanunix: "
4886                                               "unlink(%s): %s",
4887                                               sockaddr->type.sunix.sun_path,
4888                                               strbuf);
4889                         }
4890                         break;
4891                 default:
4892                         isc__strerror(errno, strbuf, sizeof(strbuf));
4893                         isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4894                                       ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING,
4895                                       "isc_socket_cleanunix: connect(%s): %s",
4896                                       sockaddr->type.sunix.sun_path, strbuf);
4897                         break;
4898                 }
4899         }
4900  cleanup:
4901         close(s);
4902 #else
4903         UNUSED(sockaddr);
4904         UNUSED(active);
4905 #endif
4906 }
4907
4908 ISC_SOCKETFUNC_SCOPE isc_result_t
4909 isc__socket_permunix(isc_sockaddr_t *sockaddr, isc_uint32_t perm,
4910                     isc_uint32_t owner, isc_uint32_t group)
4911 {
4912 #ifdef ISC_PLATFORM_HAVESYSUNH
4913         isc_result_t result = ISC_R_SUCCESS;
4914         char strbuf[ISC_STRERRORSIZE];
4915         char path[sizeof(sockaddr->type.sunix.sun_path)];
4916 #ifdef NEED_SECURE_DIRECTORY
4917         char *slash;
4918 #endif
4919
4920         REQUIRE(sockaddr->type.sa.sa_family == AF_UNIX);
4921         INSIST(strlen(sockaddr->type.sunix.sun_path) < sizeof(path));
4922         strcpy(path, sockaddr->type.sunix.sun_path);
4923
4924 #ifdef NEED_SECURE_DIRECTORY
4925         slash = strrchr(path, '/');
4926         if (slash != NULL) {
4927                 if (slash != path)
4928                         *slash = '\0';
4929                 else
4930                         strcpy(path, "/");
4931         } else
4932                 strcpy(path, ".");
4933 #endif
4934
4935         if (chmod(path, perm) < 0) {
4936                 isc__strerror(errno, strbuf, sizeof(strbuf));
4937                 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4938                               ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
4939                               "isc_socket_permunix: chmod(%s, %d): %s",
4940                               path, perm, strbuf);
4941                 result = ISC_R_FAILURE;
4942         }
4943         if (chown(path, owner, group) < 0) {
4944                 isc__strerror(errno, strbuf, sizeof(strbuf));
4945                 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
4946                               ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
4947                               "isc_socket_permunix: chown(%s, %d, %d): %s",
4948                               path, owner, group,
4949                               strbuf);
4950                 result = ISC_R_FAILURE;
4951         }
4952         return (result);
4953 #else
4954         UNUSED(sockaddr);
4955         UNUSED(perm);
4956         UNUSED(owner);
4957         UNUSED(group);
4958         return (ISC_R_NOTIMPLEMENTED);
4959 #endif
4960 }
4961
4962 ISC_SOCKETFUNC_SCOPE isc_result_t
4963 isc__socket_bind(isc_socket_t *sock0, isc_sockaddr_t *sockaddr,
4964                  unsigned int options) {
4965         isc__socket_t *sock = (isc__socket_t *)sock0;
4966         char strbuf[ISC_STRERRORSIZE];
4967         int on = 1;
4968
4969         REQUIRE(VALID_SOCKET(sock));
4970
4971         LOCK(&sock->lock);
4972
4973         INSIST(!sock->bound);
4974
4975         if (sock->pf != sockaddr->type.sa.sa_family) {
4976                 UNLOCK(&sock->lock);
4977                 return (ISC_R_FAMILYMISMATCH);
4978         }
4979         /*
4980          * Only set SO_REUSEADDR when we want a specific port.
4981          */
4982 #ifdef AF_UNIX
4983         if (sock->pf == AF_UNIX)
4984                 goto bind_socket;
4985 #endif
4986         if ((options & ISC_SOCKET_REUSEADDRESS) != 0 &&
4987             isc_sockaddr_getport(sockaddr) != (in_port_t)0 &&
4988             setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
4989                        sizeof(on)) < 0) {
4990                 UNEXPECTED_ERROR(__FILE__, __LINE__,
4991                                  "setsockopt(%d) %s", sock->fd,
4992                                  isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
4993                                                 ISC_MSG_FAILED, "failed"));
4994                 /* Press on... */
4995         }
4996 #ifdef AF_UNIX
4997  bind_socket:
4998 #endif
4999         if (bind(sock->fd, &sockaddr->type.sa, sockaddr->length) < 0) {
5000                 inc_stats(sock->manager->stats,
5001                           sock->statsindex[STATID_BINDFAIL]);
5002
5003                 UNLOCK(&sock->lock);
5004                 switch (errno) {
5005                 case EACCES:
5006                         return (ISC_R_NOPERM);
5007                 case EADDRNOTAVAIL:
5008                         return (ISC_R_ADDRNOTAVAIL);
5009                 case EADDRINUSE:
5010                         return (ISC_R_ADDRINUSE);
5011                 case EINVAL:
5012                         return (ISC_R_BOUND);
5013                 default:
5014                         isc__strerror(errno, strbuf, sizeof(strbuf));
5015                         UNEXPECTED_ERROR(__FILE__, __LINE__, "bind: %s",
5016                                          strbuf);
5017                         return (ISC_R_UNEXPECTED);
5018                 }
5019         }
5020
5021         socket_log(sock, sockaddr, TRACE,
5022                    isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_BOUND, "bound");
5023         sock->bound = 1;
5024
5025         UNLOCK(&sock->lock);
5026         return (ISC_R_SUCCESS);
5027 }
5028
5029 /*
5030  * Enable this only for specific OS versions, and only when they have repaired
5031  * their problems with it.  Until then, this is is broken and needs to be
5032  * diabled by default.  See RT22589 for details.
5033  */
5034 #undef ENABLE_ACCEPTFILTER
5035
5036 ISC_SOCKETFUNC_SCOPE isc_result_t
5037 isc__socket_filter(isc_socket_t *sock0, const char *filter) {
5038         isc__socket_t *sock = (isc__socket_t *)sock0;
5039 #if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER)
5040         char strbuf[ISC_STRERRORSIZE];
5041         struct accept_filter_arg afa;
5042 #else
5043         UNUSED(sock);
5044         UNUSED(filter);
5045 #endif
5046
5047         REQUIRE(VALID_SOCKET(sock));
5048
5049 #if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER)
5050         bzero(&afa, sizeof(afa));
5051         strncpy(afa.af_name, filter, sizeof(afa.af_name));
5052         if (setsockopt(sock->fd, SOL_SOCKET, SO_ACCEPTFILTER,
5053                          &afa, sizeof(afa)) == -1) {
5054                 isc__strerror(errno, strbuf, sizeof(strbuf));
5055                 socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET,
5056                            ISC_MSG_FILTER, "setsockopt(SO_ACCEPTFILTER): %s",
5057                            strbuf);
5058                 return (ISC_R_FAILURE);
5059         }
5060         return (ISC_R_SUCCESS);
5061 #else
5062         return (ISC_R_NOTIMPLEMENTED);
5063 #endif
5064 }
5065
5066 /*
5067  * Set up to listen on a given socket.  We do this by creating an internal
5068  * event that will be dispatched when the socket has read activity.  The
5069  * watcher will send the internal event to the task when there is a new
5070  * connection.
5071  *
5072  * Unlike in read, we don't preallocate a done event here.  Every time there
5073  * is a new connection we'll have to allocate a new one anyway, so we might
5074  * as well keep things simple rather than having to track them.
5075  */
5076 ISC_SOCKETFUNC_SCOPE isc_result_t
5077 isc__socket_listen(isc_socket_t *sock0, unsigned int backlog) {
5078         isc__socket_t *sock = (isc__socket_t *)sock0;
5079         char strbuf[ISC_STRERRORSIZE];
5080
5081         REQUIRE(VALID_SOCKET(sock));
5082
5083         LOCK(&sock->lock);
5084
5085         REQUIRE(!sock->listener);
5086         REQUIRE(sock->bound);
5087         REQUIRE(sock->type == isc_sockettype_tcp ||
5088                 sock->type == isc_sockettype_unix);
5089
5090         if (backlog == 0)
5091                 backlog = SOMAXCONN;
5092
5093         if (listen(sock->fd, (int)backlog) < 0) {
5094                 UNLOCK(&sock->lock);
5095                 isc__strerror(errno, strbuf, sizeof(strbuf));
5096
5097                 UNEXPECTED_ERROR(__FILE__, __LINE__, "listen: %s", strbuf);
5098
5099                 return (ISC_R_UNEXPECTED);
5100         }
5101
5102         sock->listener = 1;
5103
5104         UNLOCK(&sock->lock);
5105         return (ISC_R_SUCCESS);
5106 }
5107
5108 /*
5109  * This should try to do aggressive accept() XXXMLG
5110  */
5111 ISC_SOCKETFUNC_SCOPE isc_result_t
5112 isc__socket_accept(isc_socket_t *sock0,
5113                   isc_task_t *task, isc_taskaction_t action, const void *arg)
5114 {
5115         isc__socket_t *sock = (isc__socket_t *)sock0;
5116         isc_socket_newconnev_t *dev;
5117         isc__socketmgr_t *manager;
5118         isc_task_t *ntask = NULL;
5119         isc__socket_t *nsock;
5120         isc_result_t result;
5121         isc_boolean_t do_poke = ISC_FALSE;
5122
5123         REQUIRE(VALID_SOCKET(sock));
5124         manager = sock->manager;
5125         REQUIRE(VALID_MANAGER(manager));
5126
5127         LOCK(&sock->lock);
5128
5129         REQUIRE(sock->listener);
5130
5131         /*
5132          * Sender field is overloaded here with the task we will be sending
5133          * this event to.  Just before the actual event is delivered the
5134          * actual ev_sender will be touched up to be the socket.
5135          */
5136         dev = (isc_socket_newconnev_t *)
5137                 isc_event_allocate(manager->mctx, task, ISC_SOCKEVENT_NEWCONN,
5138                                    action, arg, sizeof(*dev));
5139         if (dev == NULL) {
5140                 UNLOCK(&sock->lock);
5141                 return (ISC_R_NOMEMORY);
5142         }
5143         ISC_LINK_INIT(dev, ev_link);
5144
5145         result = allocate_socket(manager, sock->type, &nsock);
5146         if (result != ISC_R_SUCCESS) {
5147                 isc_event_free(ISC_EVENT_PTR(&dev));
5148                 UNLOCK(&sock->lock);
5149                 return (result);
5150         }
5151
5152         /*
5153          * Attach to socket and to task.
5154          */
5155         isc_task_attach(task, &ntask);
5156         if (isc_task_exiting(ntask)) {
5157                 free_socket(&nsock);
5158                 isc_task_detach(&ntask);
5159                 isc_event_free(ISC_EVENT_PTR(&dev));
5160                 UNLOCK(&sock->lock);
5161                 return (ISC_R_SHUTTINGDOWN);
5162         }
5163         nsock->references++;
5164         nsock->statsindex = sock->statsindex;
5165
5166         dev->ev_sender = ntask;
5167         dev->newsocket = (isc_socket_t *)nsock;
5168
5169         /*
5170          * Poke watcher here.  We still have the socket locked, so there
5171          * is no race condition.  We will keep the lock for such a short
5172          * bit of time waking it up now or later won't matter all that much.
5173          */
5174         if (ISC_LIST_EMPTY(sock->accept_list))
5175                 do_poke = ISC_TRUE;
5176
5177         ISC_LIST_ENQUEUE(sock->accept_list, dev, ev_link);
5178
5179         if (do_poke)
5180                 select_poke(manager, sock->fd, SELECT_POKE_ACCEPT);
5181
5182         UNLOCK(&sock->lock);
5183         return (ISC_R_SUCCESS);
5184 }
5185
5186 ISC_SOCKETFUNC_SCOPE isc_result_t
5187 isc__socket_connect(isc_socket_t *sock0, isc_sockaddr_t *addr,
5188                    isc_task_t *task, isc_taskaction_t action, const void *arg)
5189 {
5190         isc__socket_t *sock = (isc__socket_t *)sock0;
5191         isc_socket_connev_t *dev;
5192         isc_task_t *ntask = NULL;
5193         isc__socketmgr_t *manager;
5194         int cc;
5195         char strbuf[ISC_STRERRORSIZE];
5196         char addrbuf[ISC_SOCKADDR_FORMATSIZE];
5197
5198         REQUIRE(VALID_SOCKET(sock));
5199         REQUIRE(addr != NULL);
5200         REQUIRE(task != NULL);
5201         REQUIRE(action != NULL);
5202
5203         manager = sock->manager;
5204         REQUIRE(VALID_MANAGER(manager));
5205         REQUIRE(addr != NULL);
5206
5207         if (isc_sockaddr_ismulticast(addr))
5208                 return (ISC_R_MULTICAST);
5209
5210         LOCK(&sock->lock);
5211
5212         REQUIRE(!sock->connecting);
5213
5214         dev = (isc_socket_connev_t *)isc_event_allocate(manager->mctx, sock,
5215                                                         ISC_SOCKEVENT_CONNECT,
5216                                                         action, arg,
5217                                                         sizeof(*dev));
5218         if (dev == NULL) {
5219                 UNLOCK(&sock->lock);
5220                 return (ISC_R_NOMEMORY);
5221         }
5222         ISC_LINK_INIT(dev, ev_link);
5223
5224         /*
5225          * Try to do the connect right away, as there can be only one
5226          * outstanding, and it might happen to complete.
5227          */
5228         sock->peer_address = *addr;
5229         cc = connect(sock->fd, &addr->type.sa, addr->length);
5230         if (cc < 0) {
5231                 /*
5232                  * HP-UX "fails" to connect a UDP socket and sets errno to
5233                  * EINPROGRESS if it's non-blocking.  We'd rather regard this as
5234                  * a success and let the user detect it if it's really an error
5235                  * at the time of sending a packet on the socket.
5236                  */
5237                 if (sock->type == isc_sockettype_udp && errno == EINPROGRESS) {
5238                         cc = 0;
5239                         goto success;
5240                 }
5241                 if (SOFT_ERROR(errno) || errno == EINPROGRESS)
5242                         goto queue;
5243
5244                 switch (errno) {
5245 #define ERROR_MATCH(a, b) case a: dev->result = b; goto err_exit;
5246                         ERROR_MATCH(EACCES, ISC_R_NOPERM);
5247                         ERROR_MATCH(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL);
5248                         ERROR_MATCH(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL);
5249                         ERROR_MATCH(ECONNREFUSED, ISC_R_CONNREFUSED);
5250                         ERROR_MATCH(EHOSTUNREACH, ISC_R_HOSTUNREACH);
5251 #ifdef EHOSTDOWN
5252                         ERROR_MATCH(EHOSTDOWN, ISC_R_HOSTUNREACH);
5253 #endif
5254                         ERROR_MATCH(ENETUNREACH, ISC_R_NETUNREACH);
5255                         ERROR_MATCH(ENOBUFS, ISC_R_NORESOURCES);
5256                         ERROR_MATCH(EPERM, ISC_R_HOSTUNREACH);
5257                         ERROR_MATCH(EPIPE, ISC_R_NOTCONNECTED);
5258                         ERROR_MATCH(ECONNRESET, ISC_R_CONNECTIONRESET);
5259 #undef ERROR_MATCH
5260                 }
5261
5262                 sock->connected = 0;
5263
5264                 isc__strerror(errno, strbuf, sizeof(strbuf));
5265                 isc_sockaddr_format(addr, addrbuf, sizeof(addrbuf));
5266                 UNEXPECTED_ERROR(__FILE__, __LINE__, "connect(%s) %d/%s",
5267                                  addrbuf, errno, strbuf);
5268
5269                 UNLOCK(&sock->lock);
5270                 inc_stats(sock->manager->stats,
5271                           sock->statsindex[STATID_CONNECTFAIL]);
5272                 isc_event_free(ISC_EVENT_PTR(&dev));
5273                 return (ISC_R_UNEXPECTED);
5274
5275         err_exit:
5276                 sock->connected = 0;
5277                 isc_task_send(task, ISC_EVENT_PTR(&dev));
5278
5279                 UNLOCK(&sock->lock);
5280                 inc_stats(sock->manager->stats,
5281                           sock->statsindex[STATID_CONNECTFAIL]);
5282                 return (ISC_R_SUCCESS);
5283         }
5284
5285         /*
5286          * If connect completed, fire off the done event.
5287          */
5288  success:
5289         if (cc == 0) {
5290                 sock->connected = 1;
5291                 sock->bound = 1;
5292                 dev->result = ISC_R_SUCCESS;
5293                 isc_task_send(task, ISC_EVENT_PTR(&dev));
5294
5295                 UNLOCK(&sock->lock);
5296
5297                 inc_stats(sock->manager->stats,
5298                           sock->statsindex[STATID_CONNECT]);
5299
5300                 return (ISC_R_SUCCESS);
5301         }
5302
5303  queue:
5304
5305         /*
5306          * Attach to task.
5307          */
5308         isc_task_attach(task, &ntask);
5309
5310         sock->connecting = 1;
5311
5312         dev->ev_sender = ntask;
5313
5314         /*
5315          * Poke watcher here.  We still have the socket locked, so there
5316          * is no race condition.  We will keep the lock for such a short
5317          * bit of time waking it up now or later won't matter all that much.
5318          */
5319         if (sock->connect_ev == NULL)
5320                 select_poke(manager, sock->fd, SELECT_POKE_CONNECT);
5321
5322         sock->connect_ev = dev;
5323
5324         UNLOCK(&sock->lock);
5325         return (ISC_R_SUCCESS);
5326 }
5327
5328 /*
5329  * Called when a socket with a pending connect() finishes.
5330  */
5331 static void
5332 internal_connect(isc_task_t *me, isc_event_t *ev) {
5333         isc__socket_t *sock;
5334         isc_socket_connev_t *dev;
5335         isc_task_t *task;
5336         int cc;
5337         ISC_SOCKADDR_LEN_T optlen;
5338         char strbuf[ISC_STRERRORSIZE];
5339         char peerbuf[ISC_SOCKADDR_FORMATSIZE];
5340
5341         UNUSED(me);
5342         INSIST(ev->ev_type == ISC_SOCKEVENT_INTW);
5343
5344         sock = ev->ev_sender;
5345         INSIST(VALID_SOCKET(sock));
5346
5347         LOCK(&sock->lock);
5348
5349         /*
5350          * When the internal event was sent the reference count was bumped
5351          * to keep the socket around for us.  Decrement the count here.
5352          */
5353         INSIST(sock->references > 0);
5354         sock->references--;
5355         if (sock->references == 0) {
5356                 UNLOCK(&sock->lock);
5357                 destroy(&sock);
5358                 return;
5359         }
5360
5361         /*
5362          * Has this event been canceled?
5363          */
5364         dev = sock->connect_ev;
5365         if (dev == NULL) {
5366                 INSIST(!sock->connecting);
5367                 UNLOCK(&sock->lock);
5368                 return;
5369         }
5370
5371         INSIST(sock->connecting);
5372         sock->connecting = 0;
5373
5374         /*
5375          * Get any possible error status here.
5376          */
5377         optlen = sizeof(cc);
5378         if (getsockopt(sock->fd, SOL_SOCKET, SO_ERROR,
5379                        (void *)&cc, (void *)&optlen) < 0)
5380                 cc = errno;
5381         else
5382                 errno = cc;
5383
5384         if (errno != 0) {
5385                 /*
5386                  * If the error is EAGAIN, just re-select on this
5387                  * fd and pretend nothing strange happened.
5388                  */
5389                 if (SOFT_ERROR(errno) || errno == EINPROGRESS) {
5390                         sock->connecting = 1;
5391                         select_poke(sock->manager, sock->fd,
5392                                     SELECT_POKE_CONNECT);
5393                         UNLOCK(&sock->lock);
5394
5395                         return;
5396                 }
5397
5398                 inc_stats(sock->manager->stats,
5399                           sock->statsindex[STATID_CONNECTFAIL]);
5400
5401                 /*
5402                  * Translate other errors into ISC_R_* flavors.
5403                  */
5404                 switch (errno) {
5405 #define ERROR_MATCH(a, b) case a: dev->result = b; break;
5406                         ERROR_MATCH(EACCES, ISC_R_NOPERM);
5407                         ERROR_MATCH(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL);
5408                         ERROR_MATCH(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL);
5409                         ERROR_MATCH(ECONNREFUSED, ISC_R_CONNREFUSED);
5410                         ERROR_MATCH(EHOSTUNREACH, ISC_R_HOSTUNREACH);
5411 #ifdef EHOSTDOWN
5412                         ERROR_MATCH(EHOSTDOWN, ISC_R_HOSTUNREACH);
5413 #endif
5414                         ERROR_MATCH(ENETUNREACH, ISC_R_NETUNREACH);
5415                         ERROR_MATCH(ENOBUFS, ISC_R_NORESOURCES);
5416                         ERROR_MATCH(EPERM, ISC_R_HOSTUNREACH);
5417                         ERROR_MATCH(EPIPE, ISC_R_NOTCONNECTED);
5418                         ERROR_MATCH(ETIMEDOUT, ISC_R_TIMEDOUT);
5419                         ERROR_MATCH(ECONNRESET, ISC_R_CONNECTIONRESET);
5420 #undef ERROR_MATCH
5421                 default:
5422                         dev->result = ISC_R_UNEXPECTED;
5423                         isc_sockaddr_format(&sock->peer_address, peerbuf,
5424                                             sizeof(peerbuf));
5425                         isc__strerror(errno, strbuf, sizeof(strbuf));
5426                         UNEXPECTED_ERROR(__FILE__, __LINE__,
5427                                          "internal_connect: connect(%s) %s",
5428                                          peerbuf, strbuf);
5429                 }
5430         } else {
5431                 inc_stats(sock->manager->stats,
5432                           sock->statsindex[STATID_CONNECT]);
5433                 dev->result = ISC_R_SUCCESS;
5434                 sock->connected = 1;
5435                 sock->bound = 1;
5436         }
5437
5438         sock->connect_ev = NULL;
5439
5440         UNLOCK(&sock->lock);
5441
5442         task = dev->ev_sender;
5443         dev->ev_sender = sock;
5444         isc_task_sendanddetach(&task, ISC_EVENT_PTR(&dev));
5445 }
5446
5447 ISC_SOCKETFUNC_SCOPE isc_result_t
5448 isc__socket_getpeername(isc_socket_t *sock0, isc_sockaddr_t *addressp) {
5449         isc__socket_t *sock = (isc__socket_t *)sock0;
5450         isc_result_t result;
5451
5452         REQUIRE(VALID_SOCKET(sock));
5453         REQUIRE(addressp != NULL);
5454
5455         LOCK(&sock->lock);
5456
5457         if (sock->connected) {
5458                 *addressp = sock->peer_address;
5459                 result = ISC_R_SUCCESS;
5460         } else {
5461                 result = ISC_R_NOTCONNECTED;
5462         }
5463
5464         UNLOCK(&sock->lock);
5465
5466         return (result);
5467 }
5468
5469 ISC_SOCKETFUNC_SCOPE isc_result_t
5470 isc__socket_getsockname(isc_socket_t *sock0, isc_sockaddr_t *addressp) {
5471         isc__socket_t *sock = (isc__socket_t *)sock0;
5472         ISC_SOCKADDR_LEN_T len;
5473         isc_result_t result;
5474         char strbuf[ISC_STRERRORSIZE];
5475
5476         REQUIRE(VALID_SOCKET(sock));
5477         REQUIRE(addressp != NULL);
5478
5479         LOCK(&sock->lock);
5480
5481         if (!sock->bound) {
5482                 result = ISC_R_NOTBOUND;
5483                 goto out;
5484         }
5485
5486         result = ISC_R_SUCCESS;
5487
5488         len = sizeof(addressp->type);
5489         if (getsockname(sock->fd, &addressp->type.sa, (void *)&len) < 0) {
5490                 isc__strerror(errno, strbuf, sizeof(strbuf));
5491                 UNEXPECTED_ERROR(__FILE__, __LINE__, "getsockname: %s",
5492                                  strbuf);
5493                 result = ISC_R_UNEXPECTED;
5494                 goto out;
5495         }
5496         addressp->length = (unsigned int)len;
5497
5498  out:
5499         UNLOCK(&sock->lock);
5500
5501         return (result);
5502 }
5503
5504 /*
5505  * Run through the list of events on this socket, and cancel the ones
5506  * queued for task "task" of type "how".  "how" is a bitmask.
5507  */
5508 ISC_SOCKETFUNC_SCOPE void
5509 isc__socket_cancel(isc_socket_t *sock0, isc_task_t *task, unsigned int how) {
5510         isc__socket_t *sock = (isc__socket_t *)sock0;
5511
5512         REQUIRE(VALID_SOCKET(sock));
5513
5514         /*
5515          * Quick exit if there is nothing to do.  Don't even bother locking
5516          * in this case.
5517          */
5518         if (how == 0)
5519                 return;
5520
5521         LOCK(&sock->lock);
5522
5523         /*
5524          * All of these do the same thing, more or less.
5525          * Each will:
5526          *      o If the internal event is marked as "posted" try to
5527          *        remove it from the task's queue.  If this fails, mark it
5528          *        as canceled instead, and let the task clean it up later.
5529          *      o For each I/O request for that task of that type, post
5530          *        its done event with status of "ISC_R_CANCELED".
5531          *      o Reset any state needed.
5532          */
5533         if (((how & ISC_SOCKCANCEL_RECV) == ISC_SOCKCANCEL_RECV)
5534             && !ISC_LIST_EMPTY(sock->recv_list)) {
5535                 isc_socketevent_t      *dev;
5536                 isc_socketevent_t      *next;
5537                 isc_task_t             *current_task;
5538
5539                 dev = ISC_LIST_HEAD(sock->recv_list);
5540
5541                 while (dev != NULL) {
5542                         current_task = dev->ev_sender;
5543                         next = ISC_LIST_NEXT(dev, ev_link);
5544
5545                         if ((task == NULL) || (task == current_task)) {
5546                                 dev->result = ISC_R_CANCELED;
5547                                 send_recvdone_event(sock, &dev);
5548                         }
5549                         dev = next;
5550                 }
5551         }
5552
5553         if (((how & ISC_SOCKCANCEL_SEND) == ISC_SOCKCANCEL_SEND)
5554             && !ISC_LIST_EMPTY(sock->send_list)) {
5555                 isc_socketevent_t      *dev;
5556                 isc_socketevent_t      *next;
5557                 isc_task_t             *current_task;
5558
5559                 dev = ISC_LIST_HEAD(sock->send_list);
5560
5561                 while (dev != NULL) {
5562                         current_task = dev->ev_sender;
5563                         next = ISC_LIST_NEXT(dev, ev_link);
5564
5565                         if ((task == NULL) || (task == current_task)) {
5566                                 dev->result = ISC_R_CANCELED;
5567                                 send_senddone_event(sock, &dev);
5568                         }
5569                         dev = next;
5570                 }
5571         }
5572
5573         if (((how & ISC_SOCKCANCEL_ACCEPT) == ISC_SOCKCANCEL_ACCEPT)
5574             && !ISC_LIST_EMPTY(sock->accept_list)) {
5575                 isc_socket_newconnev_t *dev;
5576                 isc_socket_newconnev_t *next;
5577                 isc_task_t             *current_task;
5578
5579                 dev = ISC_LIST_HEAD(sock->accept_list);
5580                 while (dev != NULL) {
5581                         current_task = dev->ev_sender;
5582                         next = ISC_LIST_NEXT(dev, ev_link);
5583
5584                         if ((task == NULL) || (task == current_task)) {
5585
5586                                 ISC_LIST_UNLINK(sock->accept_list, dev,
5587                                                 ev_link);
5588
5589                                 NEWCONNSOCK(dev)->references--;
5590                                 free_socket((isc__socket_t **)&dev->newsocket);
5591
5592                                 dev->result = ISC_R_CANCELED;
5593                                 dev->ev_sender = sock;
5594                                 isc_task_sendanddetach(&current_task,
5595                                                        ISC_EVENT_PTR(&dev));
5596                         }
5597
5598                         dev = next;
5599                 }
5600         }
5601
5602         /*
5603          * Connecting is not a list.
5604          */
5605         if (((how & ISC_SOCKCANCEL_CONNECT) == ISC_SOCKCANCEL_CONNECT)
5606             && sock->connect_ev != NULL) {
5607                 isc_socket_connev_t    *dev;
5608                 isc_task_t             *current_task;
5609
5610                 INSIST(sock->connecting);
5611                 sock->connecting = 0;
5612
5613                 dev = sock->connect_ev;
5614                 current_task = dev->ev_sender;
5615
5616                 if ((task == NULL) || (task == current_task)) {
5617                         sock->connect_ev = NULL;
5618
5619                         dev->result = ISC_R_CANCELED;
5620                         dev->ev_sender = sock;
5621                         isc_task_sendanddetach(&current_task,
5622                                                ISC_EVENT_PTR(&dev));
5623                 }
5624         }
5625
5626         UNLOCK(&sock->lock);
5627 }
5628
5629 ISC_SOCKETFUNC_SCOPE isc_sockettype_t
5630 isc__socket_gettype(isc_socket_t *sock0) {
5631         isc__socket_t *sock = (isc__socket_t *)sock0;
5632
5633         REQUIRE(VALID_SOCKET(sock));
5634
5635         return (sock->type);
5636 }
5637
5638 ISC_SOCKETFUNC_SCOPE isc_boolean_t
5639 isc__socket_isbound(isc_socket_t *sock0) {
5640         isc__socket_t *sock = (isc__socket_t *)sock0;
5641         isc_boolean_t val;
5642
5643         REQUIRE(VALID_SOCKET(sock));
5644
5645         LOCK(&sock->lock);
5646         val = ((sock->bound) ? ISC_TRUE : ISC_FALSE);
5647         UNLOCK(&sock->lock);
5648
5649         return (val);
5650 }
5651
5652 ISC_SOCKETFUNC_SCOPE void
5653 isc__socket_ipv6only(isc_socket_t *sock0, isc_boolean_t yes) {
5654         isc__socket_t *sock = (isc__socket_t *)sock0;
5655 #if defined(IPV6_V6ONLY)
5656         int onoff = yes ? 1 : 0;
5657 #else
5658         UNUSED(yes);
5659         UNUSED(sock);
5660 #endif
5661
5662         REQUIRE(VALID_SOCKET(sock));
5663
5664 #ifdef IPV6_V6ONLY
5665         if (sock->pf == AF_INET6) {
5666                 if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY,
5667                                (void *)&onoff, sizeof(int)) < 0) {
5668                         char strbuf[ISC_STRERRORSIZE];
5669                         isc__strerror(errno, strbuf, sizeof(strbuf));
5670                         UNEXPECTED_ERROR(__FILE__, __LINE__,
5671                                          "setsockopt(%d, IPV6_V6ONLY) "
5672                                          "%s: %s", sock->fd,
5673                                          isc_msgcat_get(isc_msgcat,
5674                                                         ISC_MSGSET_GENERAL,
5675                                                         ISC_MSG_FAILED,
5676                                                         "failed"),
5677                                          strbuf);
5678                 }
5679         }
5680         FIX_IPV6_RECVPKTINFO(sock);     /* AIX */
5681 #endif
5682 }
5683
5684 #ifndef USE_WATCHER_THREAD
5685 /*
5686  * In our assumed scenario, we can simply use a single static object.
5687  * XXX: this is not true if the application uses multiple threads with
5688  *      'multi-context' mode.  Fixing this is a future TODO item.
5689  */
5690 static isc_socketwait_t swait_private;
5691
5692 int
5693 isc__socketmgr_waitevents(isc_socketmgr_t *manager0, struct timeval *tvp,
5694                           isc_socketwait_t **swaitp)
5695 {
5696         isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
5697
5698
5699         int n;
5700 #ifdef USE_KQUEUE
5701         struct timespec ts, *tsp;
5702 #endif
5703 #ifdef USE_EPOLL
5704         int timeout;
5705 #endif
5706 #ifdef USE_DEVPOLL
5707         struct dvpoll dvp;
5708 #endif
5709
5710         REQUIRE(swaitp != NULL && *swaitp == NULL);
5711
5712 #ifdef USE_SHARED_MANAGER
5713         if (manager == NULL)
5714                 manager = socketmgr;
5715 #endif
5716         if (manager == NULL)
5717                 return (0);
5718
5719 #ifdef USE_KQUEUE
5720         if (tvp != NULL) {
5721                 ts.tv_sec = tvp->tv_sec;
5722                 ts.tv_nsec = tvp->tv_usec * 1000;
5723                 tsp = &ts;
5724         } else
5725                 tsp = NULL;
5726         swait_private.nevents = kevent(manager->kqueue_fd, NULL, 0,
5727                                        manager->events, manager->nevents,
5728                                        tsp);
5729         n = swait_private.nevents;
5730 #elif defined(USE_EPOLL)
5731         if (tvp != NULL)
5732                 timeout = tvp->tv_sec * 1000 + (tvp->tv_usec + 999) / 1000;
5733         else
5734                 timeout = -1;
5735         swait_private.nevents = epoll_wait(manager->epoll_fd,
5736                                            manager->events,
5737                                            manager->nevents, timeout);
5738         n = swait_private.nevents;
5739 #elif defined(USE_DEVPOLL)
5740         dvp.dp_fds = manager->events;
5741         dvp.dp_nfds = manager->nevents;
5742         if (tvp != NULL) {
5743                 dvp.dp_timeout = tvp->tv_sec * 1000 +
5744                         (tvp->tv_usec + 999) / 1000;
5745         } else
5746                 dvp.dp_timeout = -1;
5747         swait_private.nevents = ioctl(manager->devpoll_fd, DP_POLL, &dvp);
5748         n = swait_private.nevents;
5749 #elif defined(USE_SELECT)
5750         memcpy(manager->read_fds_copy, manager->read_fds,  manager->fd_bufsize);
5751         memcpy(manager->write_fds_copy, manager->write_fds,
5752                manager->fd_bufsize);
5753
5754         swait_private.readset = manager->read_fds_copy;
5755         swait_private.writeset = manager->write_fds_copy;
5756         swait_private.maxfd = manager->maxfd + 1;
5757
5758         n = select(swait_private.maxfd, swait_private.readset,
5759                    swait_private.writeset, NULL, tvp);
5760 #endif
5761
5762         *swaitp = &swait_private;
5763         return (n);
5764 }
5765
5766 isc_result_t
5767 isc__socketmgr_dispatch(isc_socketmgr_t *manager0, isc_socketwait_t *swait) {
5768         isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
5769
5770         REQUIRE(swait == &swait_private);
5771
5772 #ifdef USE_SHARED_MANAGER
5773         if (manager == NULL)
5774                 manager = socketmgr;
5775 #endif
5776         if (manager == NULL)
5777                 return (ISC_R_NOTFOUND);
5778
5779 #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL)
5780         (void)process_fds(manager, manager->events, swait->nevents);
5781         return (ISC_R_SUCCESS);
5782 #elif defined(USE_SELECT)
5783         process_fds(manager, swait->maxfd, swait->readset, swait->writeset);
5784         return (ISC_R_SUCCESS);
5785 #endif
5786 }
5787 #endif /* USE_WATCHER_THREAD */
5788
5789 #ifdef BIND9
5790 void
5791 isc__socket_setname(isc_socket_t *socket0, const char *name, void *tag) {
5792         isc__socket_t *socket = (isc__socket_t *)socket0;
5793
5794         /*
5795          * Name 'socket'.
5796          */
5797
5798         REQUIRE(VALID_SOCKET(socket));
5799
5800         LOCK(&socket->lock);
5801         memset(socket->name, 0, sizeof(socket->name));
5802         strncpy(socket->name, name, sizeof(socket->name) - 1);
5803         socket->tag = tag;
5804         UNLOCK(&socket->lock);
5805 }
5806
5807 ISC_SOCKETFUNC_SCOPE const char *
5808 isc__socket_getname(isc_socket_t *socket0) {
5809         isc__socket_t *socket = (isc__socket_t *)socket0;
5810
5811         return (socket->name);
5812 }
5813
5814 void *
5815 isc__socket_gettag(isc_socket_t *socket0) {
5816         isc__socket_t *socket = (isc__socket_t *)socket0;
5817
5818         return (socket->tag);
5819 }
5820 #endif  /* BIND9 */
5821
5822 #ifdef USE_SOCKETIMPREGISTER
5823 isc_result_t
5824 isc__socket_register() {
5825         return (isc_socket_register(isc__socketmgr_create));
5826 }
5827 #endif
5828
5829 #if defined(HAVE_LIBXML2) && defined(BIND9)
5830
5831 static const char *
5832 _socktype(isc_sockettype_t type)
5833 {
5834         if (type == isc_sockettype_udp)
5835                 return ("udp");
5836         else if (type == isc_sockettype_tcp)
5837                 return ("tcp");
5838         else if (type == isc_sockettype_unix)
5839                 return ("unix");
5840         else if (type == isc_sockettype_fdwatch)
5841                 return ("fdwatch");
5842         else
5843                 return ("not-initialized");
5844 }
5845
5846 ISC_SOCKETFUNC_SCOPE void
5847 isc_socketmgr_renderxml(isc_socketmgr_t *mgr0, xmlTextWriterPtr writer) {
5848         isc__socketmgr_t *mgr = (isc__socketmgr_t *)mgr0;
5849         isc__socket_t *sock;
5850         char peerbuf[ISC_SOCKADDR_FORMATSIZE];
5851         isc_sockaddr_t addr;
5852         ISC_SOCKADDR_LEN_T len;
5853
5854         LOCK(&mgr->lock);
5855
5856 #ifdef USE_SHARED_MANAGER
5857         xmlTextWriterStartElement(writer, ISC_XMLCHAR "references");
5858         xmlTextWriterWriteFormatString(writer, "%d", mgr->refs);
5859         xmlTextWriterEndElement(writer);
5860 #endif  /* USE_SHARED_MANAGER */
5861
5862         xmlTextWriterStartElement(writer, ISC_XMLCHAR "sockets");
5863         sock = ISC_LIST_HEAD(mgr->socklist);
5864         while (sock != NULL) {
5865                 LOCK(&sock->lock);
5866                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "socket");
5867
5868                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "id");
5869                 xmlTextWriterWriteFormatString(writer, "%p", sock);
5870                 xmlTextWriterEndElement(writer);
5871
5872                 if (sock->name[0] != 0) {
5873                         xmlTextWriterStartElement(writer, ISC_XMLCHAR "name");
5874                         xmlTextWriterWriteFormatString(writer, "%s",
5875                                                        sock->name);
5876                         xmlTextWriterEndElement(writer); /* name */
5877                 }
5878
5879                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "references");
5880                 xmlTextWriterWriteFormatString(writer, "%d", sock->references);
5881                 xmlTextWriterEndElement(writer);
5882
5883                 xmlTextWriterWriteElement(writer, ISC_XMLCHAR "type",
5884                                           ISC_XMLCHAR _socktype(sock->type));
5885
5886                 if (sock->connected) {
5887                         isc_sockaddr_format(&sock->peer_address, peerbuf,
5888                                             sizeof(peerbuf));
5889                         xmlTextWriterWriteElement(writer,
5890                                                   ISC_XMLCHAR "peer-address",
5891                                                   ISC_XMLCHAR peerbuf);
5892                 }
5893
5894                 len = sizeof(addr);
5895                 if (getsockname(sock->fd, &addr.type.sa, (void *)&len) == 0) {
5896                         isc_sockaddr_format(&addr, peerbuf, sizeof(peerbuf));
5897                         xmlTextWriterWriteElement(writer,
5898                                                   ISC_XMLCHAR "local-address",
5899                                                   ISC_XMLCHAR peerbuf);
5900                 }
5901
5902                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "states");
5903                 if (sock->pending_recv)
5904                         xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state",
5905                                                 ISC_XMLCHAR "pending-receive");
5906                 if (sock->pending_send)
5907                         xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state",
5908                                                   ISC_XMLCHAR "pending-send");
5909                 if (sock->pending_accept)
5910                         xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state",
5911                                                  ISC_XMLCHAR "pending_accept");
5912                 if (sock->listener)
5913                         xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state",
5914                                                   ISC_XMLCHAR "listener");
5915                 if (sock->connected)
5916                         xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state",
5917                                                   ISC_XMLCHAR "connected");
5918                 if (sock->connecting)
5919                         xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state",
5920                                                   ISC_XMLCHAR "connecting");
5921                 if (sock->bound)
5922                         xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state",
5923                                                   ISC_XMLCHAR "bound");
5924
5925                 xmlTextWriterEndElement(writer); /* states */
5926
5927                 xmlTextWriterEndElement(writer); /* socket */
5928
5929                 UNLOCK(&sock->lock);
5930                 sock = ISC_LIST_NEXT(sock, link);
5931         }
5932         xmlTextWriterEndElement(writer); /* sockets */
5933
5934         UNLOCK(&mgr->lock);
5935 }
5936 #endif /* HAVE_LIBXML2 */