PageRenderTime 80ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/contrib/bind9/lib/isc/unix/socket.c

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