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