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