PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/contrib/bind9/bin/named/client.c

https://bitbucket.org/freebsd/freebsd-head/
C | 2856 lines | 1992 code | 376 blank | 488 comment | 567 complexity | 6ca06a0de244edc47bd898a31b205e8c 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) 1999-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: client.c,v 1.271.10.4 2012/01/31 23:46:39 tbox Exp $ */
  18. #include <config.h>
  19. #include <isc/formatcheck.h>
  20. #include <isc/mutex.h>
  21. #include <isc/once.h>
  22. #include <isc/platform.h>
  23. #include <isc/print.h>
  24. #include <isc/stats.h>
  25. #include <isc/stdio.h>
  26. #include <isc/string.h>
  27. #include <isc/task.h>
  28. #include <isc/timer.h>
  29. #include <isc/util.h>
  30. #include <dns/db.h>
  31. #include <dns/dispatch.h>
  32. #include <dns/events.h>
  33. #include <dns/message.h>
  34. #include <dns/peer.h>
  35. #include <dns/rcode.h>
  36. #include <dns/rdata.h>
  37. #include <dns/rdataclass.h>
  38. #include <dns/rdatalist.h>
  39. #include <dns/rdataset.h>
  40. #include <dns/resolver.h>
  41. #include <dns/stats.h>
  42. #include <dns/tsig.h>
  43. #include <dns/view.h>
  44. #include <dns/zone.h>
  45. #include <named/interfacemgr.h>
  46. #include <named/log.h>
  47. #include <named/notify.h>
  48. #include <named/os.h>
  49. #include <named/server.h>
  50. #include <named/update.h>
  51. /***
  52. *** Client
  53. ***/
  54. /*! \file
  55. * Client Routines
  56. *
  57. * Important note!
  58. *
  59. * All client state changes, other than that from idle to listening, occur
  60. * as a result of events. This guarantees serialization and avoids the
  61. * need for locking.
  62. *
  63. * If a routine is ever created that allows someone other than the client's
  64. * task to change the client, then the client will have to be locked.
  65. */
  66. #define NS_CLIENT_TRACE
  67. #ifdef NS_CLIENT_TRACE
  68. #define CTRACE(m) ns_client_log(client, \
  69. NS_LOGCATEGORY_CLIENT, \
  70. NS_LOGMODULE_CLIENT, \
  71. ISC_LOG_DEBUG(3), \
  72. "%s", (m))
  73. #define MTRACE(m) isc_log_write(ns_g_lctx, \
  74. NS_LOGCATEGORY_GENERAL, \
  75. NS_LOGMODULE_CLIENT, \
  76. ISC_LOG_DEBUG(3), \
  77. "clientmgr @%p: %s", manager, (m))
  78. #else
  79. #define CTRACE(m) ((void)(m))
  80. #define MTRACE(m) ((void)(m))
  81. #endif
  82. #define TCP_CLIENT(c) (((c)->attributes & NS_CLIENTATTR_TCP) != 0)
  83. #define TCP_BUFFER_SIZE (65535 + 2)
  84. #define SEND_BUFFER_SIZE 4096
  85. #define RECV_BUFFER_SIZE 4096
  86. #ifdef ISC_PLATFORM_USETHREADS
  87. #define NMCTXS 100
  88. /*%<
  89. * Number of 'mctx pools' for clients. (Should this be configurable?)
  90. * When enabling threads, we use a pool of memory contexts shared by
  91. * client objects, since concurrent access to a shared context would cause
  92. * heavy contentions. The above constant is expected to be enough for
  93. * completely avoiding contentions among threads for an authoritative-only
  94. * server.
  95. */
  96. #else
  97. #define NMCTXS 0
  98. /*%<
  99. * If named with built without thread, simply share manager's context. Using
  100. * a separate context in this case would simply waste memory.
  101. */
  102. #endif
  103. /*% nameserver client manager structure */
  104. struct ns_clientmgr {
  105. /* Unlocked. */
  106. unsigned int magic;
  107. isc_mem_t * mctx;
  108. isc_taskmgr_t * taskmgr;
  109. isc_timermgr_t * timermgr;
  110. isc_mutex_t lock;
  111. /* Locked by lock. */
  112. isc_boolean_t exiting;
  113. client_list_t active; /*%< Active clients */
  114. client_list_t recursing; /*%< Recursing clients */
  115. client_list_t inactive; /*%< To be recycled */
  116. #if NMCTXS > 0
  117. /*%< mctx pool for clients. */
  118. unsigned int nextmctx;
  119. isc_mem_t * mctxpool[NMCTXS];
  120. #endif
  121. };
  122. #define MANAGER_MAGIC ISC_MAGIC('N', 'S', 'C', 'm')
  123. #define VALID_MANAGER(m) ISC_MAGIC_VALID(m, MANAGER_MAGIC)
  124. /*!
  125. * Client object states. Ordering is significant: higher-numbered
  126. * states are generally "more active", meaning that the client can
  127. * have more dynamically allocated data, outstanding events, etc.
  128. * In the list below, any such properties listed for state N
  129. * also apply to any state > N.
  130. *
  131. * To force the client into a less active state, set client->newstate
  132. * to that state and call exit_check(). This will cause any
  133. * activities defined for higher-numbered states to be aborted.
  134. */
  135. #define NS_CLIENTSTATE_FREED 0
  136. /*%<
  137. * The client object no longer exists.
  138. */
  139. #define NS_CLIENTSTATE_INACTIVE 1
  140. /*%<
  141. * The client object exists and has a task and timer.
  142. * Its "query" struct and sendbuf are initialized.
  143. * It is on the client manager's list of inactive clients.
  144. * It has a message and OPT, both in the reset state.
  145. */
  146. #define NS_CLIENTSTATE_READY 2
  147. /*%<
  148. * The client object is either a TCP or a UDP one, and
  149. * it is associated with a network interface. It is on the
  150. * client manager's list of active clients.
  151. *
  152. * If it is a TCP client object, it has a TCP listener socket
  153. * and an outstanding TCP listen request.
  154. *
  155. * If it is a UDP client object, it has a UDP listener socket
  156. * and an outstanding UDP receive request.
  157. */
  158. #define NS_CLIENTSTATE_READING 3
  159. /*%<
  160. * The client object is a TCP client object that has received
  161. * a connection. It has a tcpsocket, tcpmsg, TCP quota, and an
  162. * outstanding TCP read request. This state is not used for
  163. * UDP client objects.
  164. */
  165. #define NS_CLIENTSTATE_WORKING 4
  166. /*%<
  167. * The client object has received a request and is working
  168. * on it. It has a view, and it may have any of a non-reset OPT,
  169. * recursion quota, and an outstanding write request.
  170. */
  171. #define NS_CLIENTSTATE_MAX 9
  172. /*%<
  173. * Sentinel value used to indicate "no state". When client->newstate
  174. * has this value, we are not attempting to exit the current state.
  175. * Must be greater than any valid state.
  176. */
  177. /*
  178. * Enable ns_client_dropport() by default.
  179. */
  180. #ifndef NS_CLIENT_DROPPORT
  181. #define NS_CLIENT_DROPPORT 1
  182. #endif
  183. unsigned int ns_client_requests;
  184. static void client_read(ns_client_t *client);
  185. static void client_accept(ns_client_t *client);
  186. static void client_udprecv(ns_client_t *client);
  187. static void clientmgr_destroy(ns_clientmgr_t *manager);
  188. static isc_boolean_t exit_check(ns_client_t *client);
  189. static void ns_client_endrequest(ns_client_t *client);
  190. static void ns_client_checkactive(ns_client_t *client);
  191. static void client_start(isc_task_t *task, isc_event_t *event);
  192. static void client_request(isc_task_t *task, isc_event_t *event);
  193. static void ns_client_dumpmessage(ns_client_t *client, const char *reason);
  194. void
  195. ns_client_recursing(ns_client_t *client) {
  196. REQUIRE(NS_CLIENT_VALID(client));
  197. LOCK(&client->manager->lock);
  198. ISC_LIST_UNLINK(*client->list, client, link);
  199. ISC_LIST_APPEND(client->manager->recursing, client, link);
  200. client->list = &client->manager->recursing;
  201. UNLOCK(&client->manager->lock);
  202. }
  203. void
  204. ns_client_killoldestquery(ns_client_t *client) {
  205. ns_client_t *oldest;
  206. REQUIRE(NS_CLIENT_VALID(client));
  207. LOCK(&client->manager->lock);
  208. oldest = ISC_LIST_HEAD(client->manager->recursing);
  209. if (oldest != NULL) {
  210. ns_query_cancel(oldest);
  211. ISC_LIST_UNLINK(*oldest->list, oldest, link);
  212. ISC_LIST_APPEND(client->manager->active, oldest, link);
  213. oldest->list = &client->manager->active;
  214. }
  215. UNLOCK(&client->manager->lock);
  216. }
  217. void
  218. ns_client_settimeout(ns_client_t *client, unsigned int seconds) {
  219. isc_result_t result;
  220. isc_interval_t interval;
  221. isc_interval_set(&interval, seconds, 0);
  222. result = isc_timer_reset(client->timer, isc_timertype_once, NULL,
  223. &interval, ISC_FALSE);
  224. client->timerset = ISC_TRUE;
  225. if (result != ISC_R_SUCCESS) {
  226. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  227. NS_LOGMODULE_CLIENT, ISC_LOG_ERROR,
  228. "setting timeout: %s",
  229. isc_result_totext(result));
  230. /* Continue anyway. */
  231. }
  232. }
  233. /*%
  234. * Check for a deactivation or shutdown request and take appropriate
  235. * action. Returns ISC_TRUE if either is in progress; in this case
  236. * the caller must no longer use the client object as it may have been
  237. * freed.
  238. */
  239. static isc_boolean_t
  240. exit_check(ns_client_t *client) {
  241. ns_clientmgr_t *locked_manager = NULL;
  242. ns_clientmgr_t *destroy_manager = NULL;
  243. REQUIRE(NS_CLIENT_VALID(client));
  244. if (client->state <= client->newstate)
  245. return (ISC_FALSE); /* Business as usual. */
  246. INSIST(client->newstate < NS_CLIENTSTATE_WORKING);
  247. /*
  248. * We need to detach from the view early when shutting down
  249. * the server to break the following vicious circle:
  250. *
  251. * - The resolver will not shut down until the view refcount is zero
  252. * - The view refcount does not go to zero until all clients detach
  253. * - The client does not detach from the view until references is zero
  254. * - references does not go to zero until the resolver has shut down
  255. *
  256. * Keep the view attached until any outstanding updates complete.
  257. */
  258. if (client->nupdates == 0 &&
  259. client->newstate == NS_CLIENTSTATE_FREED && client->view != NULL)
  260. dns_view_detach(&client->view);
  261. if (client->state == NS_CLIENTSTATE_WORKING) {
  262. INSIST(client->newstate <= NS_CLIENTSTATE_READING);
  263. /*
  264. * Let the update processing complete.
  265. */
  266. if (client->nupdates > 0)
  267. return (ISC_TRUE);
  268. /*
  269. * We are trying to abort request processing.
  270. */
  271. if (client->nsends > 0) {
  272. isc_socket_t *socket;
  273. if (TCP_CLIENT(client))
  274. socket = client->tcpsocket;
  275. else
  276. socket = client->udpsocket;
  277. isc_socket_cancel(socket, client->task,
  278. ISC_SOCKCANCEL_SEND);
  279. }
  280. if (! (client->nsends == 0 && client->nrecvs == 0 &&
  281. client->references == 0))
  282. {
  283. /*
  284. * Still waiting for I/O cancel completion.
  285. * or lingering references.
  286. */
  287. return (ISC_TRUE);
  288. }
  289. /*
  290. * I/O cancel is complete. Burn down all state
  291. * related to the current request. Ensure that
  292. * the client is on the active list and not the
  293. * recursing list.
  294. */
  295. LOCK(&client->manager->lock);
  296. if (client->list == &client->manager->recursing) {
  297. ISC_LIST_UNLINK(*client->list, client, link);
  298. ISC_LIST_APPEND(client->manager->active, client, link);
  299. client->list = &client->manager->active;
  300. }
  301. UNLOCK(&client->manager->lock);
  302. ns_client_endrequest(client);
  303. client->state = NS_CLIENTSTATE_READING;
  304. INSIST(client->recursionquota == NULL);
  305. if (NS_CLIENTSTATE_READING == client->newstate) {
  306. client_read(client);
  307. client->newstate = NS_CLIENTSTATE_MAX;
  308. return (ISC_TRUE); /* We're done. */
  309. }
  310. }
  311. if (client->state == NS_CLIENTSTATE_READING) {
  312. /*
  313. * We are trying to abort the current TCP connection,
  314. * if any.
  315. */
  316. INSIST(client->recursionquota == NULL);
  317. INSIST(client->newstate <= NS_CLIENTSTATE_READY);
  318. if (client->nreads > 0)
  319. dns_tcpmsg_cancelread(&client->tcpmsg);
  320. if (! client->nreads == 0) {
  321. /* Still waiting for read cancel completion. */
  322. return (ISC_TRUE);
  323. }
  324. if (client->tcpmsg_valid) {
  325. dns_tcpmsg_invalidate(&client->tcpmsg);
  326. client->tcpmsg_valid = ISC_FALSE;
  327. }
  328. if (client->tcpsocket != NULL) {
  329. CTRACE("closetcp");
  330. isc_socket_detach(&client->tcpsocket);
  331. }
  332. if (client->tcpquota != NULL)
  333. isc_quota_detach(&client->tcpquota);
  334. if (client->timerset) {
  335. (void)isc_timer_reset(client->timer,
  336. isc_timertype_inactive,
  337. NULL, NULL, ISC_TRUE);
  338. client->timerset = ISC_FALSE;
  339. }
  340. client->peeraddr_valid = ISC_FALSE;
  341. client->state = NS_CLIENTSTATE_READY;
  342. INSIST(client->recursionquota == NULL);
  343. /*
  344. * Now the client is ready to accept a new TCP connection
  345. * or UDP request, but we may have enough clients doing
  346. * that already. Check whether this client needs to remain
  347. * active and force it to go inactive if not.
  348. */
  349. ns_client_checkactive(client);
  350. if (NS_CLIENTSTATE_READY == client->newstate) {
  351. if (TCP_CLIENT(client)) {
  352. client_accept(client);
  353. } else
  354. client_udprecv(client);
  355. client->newstate = NS_CLIENTSTATE_MAX;
  356. return (ISC_TRUE);
  357. }
  358. }
  359. if (client->state == NS_CLIENTSTATE_READY) {
  360. INSIST(client->newstate <= NS_CLIENTSTATE_INACTIVE);
  361. /*
  362. * We are trying to enter the inactive state.
  363. */
  364. if (client->naccepts > 0)
  365. isc_socket_cancel(client->tcplistener, client->task,
  366. ISC_SOCKCANCEL_ACCEPT);
  367. if (! (client->naccepts == 0)) {
  368. /* Still waiting for accept cancel completion. */
  369. return (ISC_TRUE);
  370. }
  371. /* Accept cancel is complete. */
  372. if (client->nrecvs > 0)
  373. isc_socket_cancel(client->udpsocket, client->task,
  374. ISC_SOCKCANCEL_RECV);
  375. if (! (client->nrecvs == 0)) {
  376. /* Still waiting for recv cancel completion. */
  377. return (ISC_TRUE);
  378. }
  379. /* Recv cancel is complete. */
  380. if (client->nctls > 0) {
  381. /* Still waiting for control event to be delivered */
  382. return (ISC_TRUE);
  383. }
  384. /* Deactivate the client. */
  385. if (client->interface)
  386. ns_interface_detach(&client->interface);
  387. INSIST(client->naccepts == 0);
  388. INSIST(client->recursionquota == NULL);
  389. if (client->tcplistener != NULL)
  390. isc_socket_detach(&client->tcplistener);
  391. if (client->udpsocket != NULL)
  392. isc_socket_detach(&client->udpsocket);
  393. if (client->dispatch != NULL)
  394. dns_dispatch_detach(&client->dispatch);
  395. client->attributes = 0;
  396. client->mortal = ISC_FALSE;
  397. LOCK(&client->manager->lock);
  398. /*
  399. * Put the client on the inactive list. If we are aiming for
  400. * the "freed" state, it will be removed from the inactive
  401. * list shortly, and we need to keep the manager locked until
  402. * that has been done, lest the manager decide to reactivate
  403. * the dying client inbetween.
  404. */
  405. locked_manager = client->manager;
  406. ISC_LIST_UNLINK(*client->list, client, link);
  407. ISC_LIST_APPEND(client->manager->inactive, client, link);
  408. client->list = &client->manager->inactive;
  409. client->state = NS_CLIENTSTATE_INACTIVE;
  410. INSIST(client->recursionquota == NULL);
  411. if (client->state == client->newstate) {
  412. client->newstate = NS_CLIENTSTATE_MAX;
  413. if (client->needshutdown)
  414. isc_task_shutdown(client->task);
  415. goto unlock;
  416. }
  417. }
  418. if (client->state == NS_CLIENTSTATE_INACTIVE) {
  419. INSIST(client->newstate == NS_CLIENTSTATE_FREED);
  420. /*
  421. * We are trying to free the client.
  422. *
  423. * When "shuttingdown" is true, either the task has received
  424. * its shutdown event or no shutdown event has ever been
  425. * set up. Thus, we have no outstanding shutdown
  426. * event at this point.
  427. */
  428. REQUIRE(client->state == NS_CLIENTSTATE_INACTIVE);
  429. INSIST(client->recursionquota == NULL);
  430. ns_query_free(client);
  431. isc_mem_put(client->mctx, client->recvbuf, RECV_BUFFER_SIZE);
  432. isc_event_free((isc_event_t **)&client->sendevent);
  433. isc_event_free((isc_event_t **)&client->recvevent);
  434. isc_timer_detach(&client->timer);
  435. if (client->tcpbuf != NULL)
  436. isc_mem_put(client->mctx, client->tcpbuf, TCP_BUFFER_SIZE);
  437. if (client->opt != NULL) {
  438. INSIST(dns_rdataset_isassociated(client->opt));
  439. dns_rdataset_disassociate(client->opt);
  440. dns_message_puttemprdataset(client->message, &client->opt);
  441. }
  442. dns_message_destroy(&client->message);
  443. if (client->manager != NULL) {
  444. ns_clientmgr_t *manager = client->manager;
  445. if (locked_manager == NULL) {
  446. LOCK(&manager->lock);
  447. locked_manager = manager;
  448. }
  449. ISC_LIST_UNLINK(*client->list, client, link);
  450. client->list = NULL;
  451. if (manager->exiting &&
  452. ISC_LIST_EMPTY(manager->active) &&
  453. ISC_LIST_EMPTY(manager->inactive) &&
  454. ISC_LIST_EMPTY(manager->recursing))
  455. destroy_manager = manager;
  456. }
  457. /*
  458. * Detaching the task must be done after unlinking from
  459. * the manager's lists because the manager accesses
  460. * client->task.
  461. */
  462. if (client->task != NULL)
  463. isc_task_detach(&client->task);
  464. CTRACE("free");
  465. client->magic = 0;
  466. /*
  467. * Check that there are no other external references to
  468. * the memory context.
  469. */
  470. if (ns_g_clienttest && isc_mem_references(client->mctx) != 1) {
  471. isc_mem_stats(client->mctx, stderr);
  472. INSIST(0);
  473. }
  474. isc_mem_putanddetach(&client->mctx, client, sizeof(*client));
  475. goto unlock;
  476. }
  477. unlock:
  478. if (locked_manager != NULL) {
  479. UNLOCK(&locked_manager->lock);
  480. locked_manager = NULL;
  481. }
  482. /*
  483. * Only now is it safe to destroy the client manager (if needed),
  484. * because we have accessed its lock for the last time.
  485. */
  486. if (destroy_manager != NULL)
  487. clientmgr_destroy(destroy_manager);
  488. return (ISC_TRUE);
  489. }
  490. /*%
  491. * The client's task has received the client's control event
  492. * as part of the startup process.
  493. */
  494. static void
  495. client_start(isc_task_t *task, isc_event_t *event) {
  496. ns_client_t *client = (ns_client_t *) event->ev_arg;
  497. INSIST(task == client->task);
  498. UNUSED(task);
  499. INSIST(client->nctls == 1);
  500. client->nctls--;
  501. if (exit_check(client))
  502. return;
  503. if (TCP_CLIENT(client)) {
  504. client_accept(client);
  505. } else {
  506. client_udprecv(client);
  507. }
  508. }
  509. /*%
  510. * The client's task has received a shutdown event.
  511. */
  512. static void
  513. client_shutdown(isc_task_t *task, isc_event_t *event) {
  514. ns_client_t *client;
  515. REQUIRE(event != NULL);
  516. REQUIRE(event->ev_type == ISC_TASKEVENT_SHUTDOWN);
  517. client = event->ev_arg;
  518. REQUIRE(NS_CLIENT_VALID(client));
  519. REQUIRE(task == client->task);
  520. UNUSED(task);
  521. CTRACE("shutdown");
  522. isc_event_free(&event);
  523. if (client->shutdown != NULL) {
  524. (client->shutdown)(client->shutdown_arg, ISC_R_SHUTTINGDOWN);
  525. client->shutdown = NULL;
  526. client->shutdown_arg = NULL;
  527. }
  528. client->newstate = NS_CLIENTSTATE_FREED;
  529. client->needshutdown = ISC_FALSE;
  530. (void)exit_check(client);
  531. }
  532. static void
  533. ns_client_endrequest(ns_client_t *client) {
  534. INSIST(client->naccepts == 0);
  535. INSIST(client->nreads == 0);
  536. INSIST(client->nsends == 0);
  537. INSIST(client->nrecvs == 0);
  538. INSIST(client->nupdates == 0);
  539. INSIST(client->state == NS_CLIENTSTATE_WORKING);
  540. CTRACE("endrequest");
  541. if (client->next != NULL) {
  542. (client->next)(client);
  543. client->next = NULL;
  544. }
  545. if (client->view != NULL)
  546. dns_view_detach(&client->view);
  547. if (client->opt != NULL) {
  548. INSIST(dns_rdataset_isassociated(client->opt));
  549. dns_rdataset_disassociate(client->opt);
  550. dns_message_puttemprdataset(client->message, &client->opt);
  551. }
  552. client->signer = NULL;
  553. client->udpsize = 512;
  554. client->extflags = 0;
  555. client->ednsversion = -1;
  556. dns_message_reset(client->message, DNS_MESSAGE_INTENTPARSE);
  557. if (client->recursionquota != NULL)
  558. isc_quota_detach(&client->recursionquota);
  559. /*
  560. * Clear all client attributes that are specific to
  561. * the request; that's all except the TCP flag.
  562. */
  563. client->attributes &= NS_CLIENTATTR_TCP;
  564. }
  565. static void
  566. ns_client_checkactive(ns_client_t *client) {
  567. if (client->mortal) {
  568. /*
  569. * This client object should normally go inactive
  570. * at this point, but if we have fewer active client
  571. * objects than desired due to earlier quota exhaustion,
  572. * keep it active to make up for the shortage.
  573. */
  574. isc_boolean_t need_another_client = ISC_FALSE;
  575. if (TCP_CLIENT(client) && !ns_g_clienttest) {
  576. LOCK(&client->interface->lock);
  577. if (client->interface->ntcpcurrent <
  578. client->interface->ntcptarget)
  579. need_another_client = ISC_TRUE;
  580. UNLOCK(&client->interface->lock);
  581. } else {
  582. /*
  583. * The UDP client quota is enforced by making
  584. * requests fail rather than by not listening
  585. * for new ones. Therefore, there is always a
  586. * full set of UDP clients listening.
  587. */
  588. }
  589. if (! need_another_client) {
  590. /*
  591. * We don't need this client object. Recycle it.
  592. */
  593. if (client->newstate >= NS_CLIENTSTATE_INACTIVE)
  594. client->newstate = NS_CLIENTSTATE_INACTIVE;
  595. }
  596. }
  597. }
  598. void
  599. ns_client_next(ns_client_t *client, isc_result_t result) {
  600. int newstate;
  601. REQUIRE(NS_CLIENT_VALID(client));
  602. REQUIRE(client->state == NS_CLIENTSTATE_WORKING ||
  603. client->state == NS_CLIENTSTATE_READING);
  604. CTRACE("next");
  605. if (result != ISC_R_SUCCESS)
  606. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  607. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
  608. "request failed: %s", isc_result_totext(result));
  609. /*
  610. * An error processing a TCP request may have left
  611. * the connection out of sync. To be safe, we always
  612. * sever the connection when result != ISC_R_SUCCESS.
  613. */
  614. if (result == ISC_R_SUCCESS && TCP_CLIENT(client))
  615. newstate = NS_CLIENTSTATE_READING;
  616. else
  617. newstate = NS_CLIENTSTATE_READY;
  618. if (client->newstate > newstate)
  619. client->newstate = newstate;
  620. (void)exit_check(client);
  621. }
  622. static void
  623. client_senddone(isc_task_t *task, isc_event_t *event) {
  624. ns_client_t *client;
  625. isc_socketevent_t *sevent = (isc_socketevent_t *) event;
  626. REQUIRE(sevent != NULL);
  627. REQUIRE(sevent->ev_type == ISC_SOCKEVENT_SENDDONE);
  628. client = sevent->ev_arg;
  629. REQUIRE(NS_CLIENT_VALID(client));
  630. REQUIRE(task == client->task);
  631. REQUIRE(sevent == client->sendevent);
  632. UNUSED(task);
  633. CTRACE("senddone");
  634. if (sevent->result != ISC_R_SUCCESS)
  635. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  636. NS_LOGMODULE_CLIENT, ISC_LOG_WARNING,
  637. "error sending response: %s",
  638. isc_result_totext(sevent->result));
  639. INSIST(client->nsends > 0);
  640. client->nsends--;
  641. if (client->tcpbuf != NULL) {
  642. INSIST(TCP_CLIENT(client));
  643. isc_mem_put(client->mctx, client->tcpbuf, TCP_BUFFER_SIZE);
  644. client->tcpbuf = NULL;
  645. }
  646. if (exit_check(client))
  647. return;
  648. ns_client_next(client, ISC_R_SUCCESS);
  649. }
  650. /*%
  651. * We only want to fail with ISC_R_NOSPACE when called from
  652. * ns_client_sendraw() and not when called from ns_client_send(),
  653. * tcpbuffer is NULL when called from ns_client_sendraw() and
  654. * length != 0. tcpbuffer != NULL when called from ns_client_send()
  655. * and length == 0.
  656. */
  657. static isc_result_t
  658. client_allocsendbuf(ns_client_t *client, isc_buffer_t *buffer,
  659. isc_buffer_t *tcpbuffer, isc_uint32_t length,
  660. unsigned char *sendbuf, unsigned char **datap)
  661. {
  662. unsigned char *data;
  663. isc_uint32_t bufsize;
  664. isc_result_t result;
  665. INSIST(datap != NULL);
  666. INSIST((tcpbuffer == NULL && length != 0) ||
  667. (tcpbuffer != NULL && length == 0));
  668. if (TCP_CLIENT(client)) {
  669. INSIST(client->tcpbuf == NULL);
  670. if (length + 2 > TCP_BUFFER_SIZE) {
  671. result = ISC_R_NOSPACE;
  672. goto done;
  673. }
  674. client->tcpbuf = isc_mem_get(client->mctx, TCP_BUFFER_SIZE);
  675. if (client->tcpbuf == NULL) {
  676. result = ISC_R_NOMEMORY;
  677. goto done;
  678. }
  679. data = client->tcpbuf;
  680. if (tcpbuffer != NULL) {
  681. isc_buffer_init(tcpbuffer, data, TCP_BUFFER_SIZE);
  682. isc_buffer_init(buffer, data + 2, TCP_BUFFER_SIZE - 2);
  683. } else {
  684. isc_buffer_init(buffer, data, TCP_BUFFER_SIZE);
  685. INSIST(length <= 0xffff);
  686. isc_buffer_putuint16(buffer, (isc_uint16_t)length);
  687. }
  688. } else {
  689. data = sendbuf;
  690. if (client->udpsize < SEND_BUFFER_SIZE)
  691. bufsize = client->udpsize;
  692. else
  693. bufsize = SEND_BUFFER_SIZE;
  694. if (length > bufsize) {
  695. result = ISC_R_NOSPACE;
  696. goto done;
  697. }
  698. isc_buffer_init(buffer, data, bufsize);
  699. }
  700. *datap = data;
  701. result = ISC_R_SUCCESS;
  702. done:
  703. return (result);
  704. }
  705. static isc_result_t
  706. client_sendpkg(ns_client_t *client, isc_buffer_t *buffer) {
  707. struct in6_pktinfo *pktinfo;
  708. isc_result_t result;
  709. isc_region_t r;
  710. isc_sockaddr_t *address;
  711. isc_socket_t *socket;
  712. isc_netaddr_t netaddr;
  713. int match;
  714. unsigned int sockflags = ISC_SOCKFLAG_IMMEDIATE;
  715. if (TCP_CLIENT(client)) {
  716. socket = client->tcpsocket;
  717. address = NULL;
  718. } else {
  719. socket = client->udpsocket;
  720. address = &client->peeraddr;
  721. isc_netaddr_fromsockaddr(&netaddr, &client->peeraddr);
  722. if (ns_g_server->blackholeacl != NULL &&
  723. dns_acl_match(&netaddr, NULL,
  724. ns_g_server->blackholeacl,
  725. &ns_g_server->aclenv,
  726. &match, NULL) == ISC_R_SUCCESS &&
  727. match > 0)
  728. return (DNS_R_BLACKHOLED);
  729. sockflags |= ISC_SOCKFLAG_NORETRY;
  730. }
  731. if ((client->attributes & NS_CLIENTATTR_PKTINFO) != 0 &&
  732. (client->attributes & NS_CLIENTATTR_MULTICAST) == 0)
  733. pktinfo = &client->pktinfo;
  734. else
  735. pktinfo = NULL;
  736. isc_buffer_usedregion(buffer, &r);
  737. CTRACE("sendto");
  738. result = isc_socket_sendto2(socket, &r, client->task,
  739. address, pktinfo,
  740. client->sendevent, sockflags);
  741. if (result == ISC_R_SUCCESS || result == ISC_R_INPROGRESS) {
  742. client->nsends++;
  743. if (result == ISC_R_SUCCESS)
  744. client_senddone(client->task,
  745. (isc_event_t *)client->sendevent);
  746. result = ISC_R_SUCCESS;
  747. }
  748. return (result);
  749. }
  750. void
  751. ns_client_sendraw(ns_client_t *client, dns_message_t *message) {
  752. isc_result_t result;
  753. unsigned char *data;
  754. isc_buffer_t buffer;
  755. isc_region_t r;
  756. isc_region_t *mr;
  757. unsigned char sendbuf[SEND_BUFFER_SIZE];
  758. REQUIRE(NS_CLIENT_VALID(client));
  759. CTRACE("sendraw");
  760. mr = dns_message_getrawmessage(message);
  761. if (mr == NULL) {
  762. result = ISC_R_UNEXPECTEDEND;
  763. goto done;
  764. }
  765. result = client_allocsendbuf(client, &buffer, NULL, mr->length,
  766. sendbuf, &data);
  767. if (result != ISC_R_SUCCESS)
  768. goto done;
  769. /*
  770. * Copy message to buffer and fixup id.
  771. */
  772. isc_buffer_availableregion(&buffer, &r);
  773. result = isc_buffer_copyregion(&buffer, mr);
  774. if (result != ISC_R_SUCCESS)
  775. goto done;
  776. r.base[0] = (client->message->id >> 8) & 0xff;
  777. r.base[1] = client->message->id & 0xff;
  778. result = client_sendpkg(client, &buffer);
  779. if (result == ISC_R_SUCCESS)
  780. return;
  781. done:
  782. if (client->tcpbuf != NULL) {
  783. isc_mem_put(client->mctx, client->tcpbuf, TCP_BUFFER_SIZE);
  784. client->tcpbuf = NULL;
  785. }
  786. ns_client_next(client, result);
  787. }
  788. void
  789. ns_client_send(ns_client_t *client) {
  790. isc_result_t result;
  791. unsigned char *data;
  792. isc_buffer_t buffer;
  793. isc_buffer_t tcpbuffer;
  794. isc_region_t r;
  795. dns_compress_t cctx;
  796. isc_boolean_t cleanup_cctx = ISC_FALSE;
  797. unsigned char sendbuf[SEND_BUFFER_SIZE];
  798. unsigned int render_opts;
  799. unsigned int preferred_glue;
  800. isc_boolean_t opt_included = ISC_FALSE;
  801. REQUIRE(NS_CLIENT_VALID(client));
  802. CTRACE("send");
  803. if ((client->attributes & NS_CLIENTATTR_RA) != 0)
  804. client->message->flags |= DNS_MESSAGEFLAG_RA;
  805. if ((client->attributes & NS_CLIENTATTR_WANTDNSSEC) != 0)
  806. render_opts = 0;
  807. else
  808. render_opts = DNS_MESSAGERENDER_OMITDNSSEC;
  809. preferred_glue = 0;
  810. if (client->view != NULL) {
  811. if (client->view->preferred_glue == dns_rdatatype_a)
  812. preferred_glue = DNS_MESSAGERENDER_PREFER_A;
  813. else if (client->view->preferred_glue == dns_rdatatype_aaaa)
  814. preferred_glue = DNS_MESSAGERENDER_PREFER_AAAA;
  815. }
  816. #ifdef ALLOW_FILTER_AAAA_ON_V4
  817. /*
  818. * filter-aaaa-on-v4 yes or break-dnssec option to suppress
  819. * AAAA records
  820. * We already know that request came via IPv4,
  821. * that we have both AAAA and A records,
  822. * and that we either have no signatures that the client wants
  823. * or we are supposed to break DNSSEC.
  824. *
  825. * Override preferred glue if necessary.
  826. */
  827. if ((client->attributes & NS_CLIENTATTR_FILTER_AAAA) != 0) {
  828. render_opts |= DNS_MESSAGERENDER_FILTER_AAAA;
  829. if (preferred_glue == DNS_MESSAGERENDER_PREFER_AAAA)
  830. preferred_glue = DNS_MESSAGERENDER_PREFER_A;
  831. }
  832. #endif
  833. /*
  834. * XXXRTH The following doesn't deal with TCP buffer resizing.
  835. */
  836. result = client_allocsendbuf(client, &buffer, &tcpbuffer, 0,
  837. sendbuf, &data);
  838. if (result != ISC_R_SUCCESS)
  839. goto done;
  840. result = dns_compress_init(&cctx, -1, client->mctx);
  841. if (result != ISC_R_SUCCESS)
  842. goto done;
  843. cleanup_cctx = ISC_TRUE;
  844. result = dns_message_renderbegin(client->message, &cctx, &buffer);
  845. if (result != ISC_R_SUCCESS)
  846. goto done;
  847. if (client->opt != NULL) {
  848. result = dns_message_setopt(client->message, client->opt);
  849. opt_included = ISC_TRUE;
  850. client->opt = NULL;
  851. if (result != ISC_R_SUCCESS)
  852. goto done;
  853. }
  854. result = dns_message_rendersection(client->message,
  855. DNS_SECTION_QUESTION, 0);
  856. if (result == ISC_R_NOSPACE) {
  857. client->message->flags |= DNS_MESSAGEFLAG_TC;
  858. goto renderend;
  859. }
  860. if (result != ISC_R_SUCCESS)
  861. goto done;
  862. result = dns_message_rendersection(client->message,
  863. DNS_SECTION_ANSWER,
  864. DNS_MESSAGERENDER_PARTIAL |
  865. render_opts);
  866. if (result == ISC_R_NOSPACE) {
  867. client->message->flags |= DNS_MESSAGEFLAG_TC;
  868. goto renderend;
  869. }
  870. if (result != ISC_R_SUCCESS)
  871. goto done;
  872. result = dns_message_rendersection(client->message,
  873. DNS_SECTION_AUTHORITY,
  874. DNS_MESSAGERENDER_PARTIAL |
  875. render_opts);
  876. if (result == ISC_R_NOSPACE) {
  877. client->message->flags |= DNS_MESSAGEFLAG_TC;
  878. goto renderend;
  879. }
  880. if (result != ISC_R_SUCCESS)
  881. goto done;
  882. result = dns_message_rendersection(client->message,
  883. DNS_SECTION_ADDITIONAL,
  884. preferred_glue | render_opts);
  885. if (result != ISC_R_SUCCESS && result != ISC_R_NOSPACE)
  886. goto done;
  887. renderend:
  888. result = dns_message_renderend(client->message);
  889. if (result != ISC_R_SUCCESS)
  890. goto done;
  891. if (cleanup_cctx) {
  892. dns_compress_invalidate(&cctx);
  893. cleanup_cctx = ISC_FALSE;
  894. }
  895. if (TCP_CLIENT(client)) {
  896. isc_buffer_usedregion(&buffer, &r);
  897. isc_buffer_putuint16(&tcpbuffer, (isc_uint16_t) r.length);
  898. isc_buffer_add(&tcpbuffer, r.length);
  899. result = client_sendpkg(client, &tcpbuffer);
  900. } else
  901. result = client_sendpkg(client, &buffer);
  902. /* update statistics (XXXJT: is it okay to access message->xxxkey?) */
  903. isc_stats_increment(ns_g_server->nsstats, dns_nsstatscounter_response);
  904. if (opt_included) {
  905. isc_stats_increment(ns_g_server->nsstats,
  906. dns_nsstatscounter_edns0out);
  907. }
  908. if (client->message->tsigkey != NULL) {
  909. isc_stats_increment(ns_g_server->nsstats,
  910. dns_nsstatscounter_tsigout);
  911. }
  912. if (client->message->sig0key != NULL) {
  913. isc_stats_increment(ns_g_server->nsstats,
  914. dns_nsstatscounter_sig0out);
  915. }
  916. if ((client->message->flags & DNS_MESSAGEFLAG_TC) != 0)
  917. isc_stats_increment(ns_g_server->nsstats,
  918. dns_nsstatscounter_truncatedresp);
  919. if (result == ISC_R_SUCCESS)
  920. return;
  921. done:
  922. if (client->tcpbuf != NULL) {
  923. isc_mem_put(client->mctx, client->tcpbuf, TCP_BUFFER_SIZE);
  924. client->tcpbuf = NULL;
  925. }
  926. if (cleanup_cctx)
  927. dns_compress_invalidate(&cctx);
  928. ns_client_next(client, result);
  929. }
  930. #if NS_CLIENT_DROPPORT
  931. #define DROPPORT_NO 0
  932. #define DROPPORT_REQUEST 1
  933. #define DROPPORT_RESPONSE 2
  934. /*%
  935. * ns_client_dropport determines if certain requests / responses
  936. * should be dropped based on the port number.
  937. *
  938. * Returns:
  939. * \li 0: Don't drop.
  940. * \li 1: Drop request.
  941. * \li 2: Drop (error) response.
  942. */
  943. static int
  944. ns_client_dropport(in_port_t port) {
  945. switch (port) {
  946. case 7: /* echo */
  947. case 13: /* daytime */
  948. case 19: /* chargen */
  949. case 37: /* time */
  950. return (DROPPORT_REQUEST);
  951. case 464: /* kpasswd */
  952. return (DROPPORT_RESPONSE);
  953. }
  954. return (DROPPORT_NO);
  955. }
  956. #endif
  957. void
  958. ns_client_error(ns_client_t *client, isc_result_t result) {
  959. dns_rcode_t rcode;
  960. dns_message_t *message;
  961. REQUIRE(NS_CLIENT_VALID(client));
  962. CTRACE("error");
  963. message = client->message;
  964. rcode = dns_result_torcode(result);
  965. #if NS_CLIENT_DROPPORT
  966. /*
  967. * Don't send FORMERR to ports on the drop port list.
  968. */
  969. if (rcode == dns_rcode_formerr &&
  970. ns_client_dropport(isc_sockaddr_getport(&client->peeraddr)) !=
  971. DROPPORT_NO) {
  972. char buf[64];
  973. isc_buffer_t b;
  974. isc_buffer_init(&b, buf, sizeof(buf) - 1);
  975. if (dns_rcode_totext(rcode, &b) != ISC_R_SUCCESS)
  976. isc_buffer_putstr(&b, "UNKNOWN RCODE");
  977. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  978. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(10),
  979. "dropped error (%.*s) response: suspicious port",
  980. (int)isc_buffer_usedlength(&b), buf);
  981. ns_client_next(client, ISC_R_SUCCESS);
  982. return;
  983. }
  984. #endif
  985. /*
  986. * Message may be an in-progress reply that we had trouble
  987. * with, in which case QR will be set. We need to clear QR before
  988. * calling dns_message_reply() to avoid triggering an assertion.
  989. */
  990. message->flags &= ~DNS_MESSAGEFLAG_QR;
  991. /*
  992. * AA and AD shouldn't be set.
  993. */
  994. message->flags &= ~(DNS_MESSAGEFLAG_AA | DNS_MESSAGEFLAG_AD);
  995. result = dns_message_reply(message, ISC_TRUE);
  996. if (result != ISC_R_SUCCESS) {
  997. /*
  998. * It could be that we've got a query with a good header,
  999. * but a bad question section, so we try again with
  1000. * want_question_section set to ISC_FALSE.
  1001. */
  1002. result = dns_message_reply(message, ISC_FALSE);
  1003. if (result != ISC_R_SUCCESS) {
  1004. ns_client_next(client, result);
  1005. return;
  1006. }
  1007. }
  1008. message->rcode = rcode;
  1009. /*
  1010. * FORMERR loop avoidance: If we sent a FORMERR message
  1011. * with the same ID to the same client less than two
  1012. * seconds ago, assume that we are in an infinite error
  1013. * packet dialog with a server for some protocol whose
  1014. * error responses look enough like DNS queries to
  1015. * elicit a FORMERR response. Drop a packet to break
  1016. * the loop.
  1017. */
  1018. if (rcode == dns_rcode_formerr) {
  1019. if (isc_sockaddr_equal(&client->peeraddr,
  1020. &client->formerrcache.addr) &&
  1021. message->id == client->formerrcache.id &&
  1022. client->requesttime - client->formerrcache.time < 2) {
  1023. /* Drop packet. */
  1024. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  1025. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(1),
  1026. "possible error packet loop, "
  1027. "FORMERR dropped");
  1028. ns_client_next(client, result);
  1029. return;
  1030. }
  1031. client->formerrcache.addr = client->peeraddr;
  1032. client->formerrcache.time = client->requesttime;
  1033. client->formerrcache.id = message->id;
  1034. }
  1035. ns_client_send(client);
  1036. }
  1037. static inline isc_result_t
  1038. client_addopt(ns_client_t *client) {
  1039. dns_rdataset_t *rdataset;
  1040. dns_rdatalist_t *rdatalist;
  1041. dns_rdata_t *rdata;
  1042. isc_result_t result;
  1043. dns_view_t *view;
  1044. dns_resolver_t *resolver;
  1045. isc_uint16_t udpsize;
  1046. REQUIRE(client->opt == NULL); /* XXXRTH free old. */
  1047. rdatalist = NULL;
  1048. result = dns_message_gettemprdatalist(client->message, &rdatalist);
  1049. if (result != ISC_R_SUCCESS)
  1050. return (result);
  1051. rdata = NULL;
  1052. result = dns_message_gettemprdata(client->message, &rdata);
  1053. if (result != ISC_R_SUCCESS)
  1054. return (result);
  1055. rdataset = NULL;
  1056. result = dns_message_gettemprdataset(client->message, &rdataset);
  1057. if (result != ISC_R_SUCCESS)
  1058. return (result);
  1059. dns_rdataset_init(rdataset);
  1060. rdatalist->type = dns_rdatatype_opt;
  1061. rdatalist->covers = 0;
  1062. /*
  1063. * Set the maximum UDP buffer size.
  1064. */
  1065. view = client->view;
  1066. resolver = (view != NULL) ? view->resolver : NULL;
  1067. if (resolver != NULL)
  1068. udpsize = dns_resolver_getudpsize(resolver);
  1069. else
  1070. udpsize = ns_g_udpsize;
  1071. rdatalist->rdclass = udpsize;
  1072. /*
  1073. * Set EXTENDED-RCODE, VERSION and Z to 0.
  1074. */
  1075. rdatalist->ttl = (client->extflags & DNS_MESSAGEEXTFLAG_REPLYPRESERVE);
  1076. /* Set EDNS options if applicable */
  1077. if (client->attributes & NS_CLIENTATTR_WANTNSID &&
  1078. (ns_g_server->server_id != NULL ||
  1079. ns_g_server->server_usehostname)) {
  1080. /*
  1081. * Space required for NSID data:
  1082. * 2 bytes for opt code
  1083. * + 2 bytes for NSID length
  1084. * + NSID itself
  1085. */
  1086. char nsid[BUFSIZ], *nsidp;
  1087. isc_buffer_t *buffer = NULL;
  1088. if (ns_g_server->server_usehostname) {
  1089. isc_result_t result;
  1090. result = ns_os_gethostname(nsid, sizeof(nsid));
  1091. if (result != ISC_R_SUCCESS) {
  1092. goto no_nsid;
  1093. }
  1094. nsidp = nsid;
  1095. } else
  1096. nsidp = ns_g_server->server_id;
  1097. rdata->length = strlen(nsidp) + 4;
  1098. result = isc_buffer_allocate(client->mctx, &buffer,
  1099. rdata->length);
  1100. if (result != ISC_R_SUCCESS)
  1101. goto no_nsid;
  1102. isc_buffer_putuint16(buffer, DNS_OPT_NSID);
  1103. isc_buffer_putuint16(buffer, strlen(nsidp));
  1104. isc_buffer_putstr(buffer, nsidp);
  1105. rdata->data = buffer->base;
  1106. dns_message_takebuffer(client->message, &buffer);
  1107. } else {
  1108. no_nsid:
  1109. rdata->data = NULL;
  1110. rdata->length = 0;
  1111. }
  1112. rdata->rdclass = rdatalist->rdclass;
  1113. rdata->type = rdatalist->type;
  1114. rdata->flags = 0;
  1115. ISC_LIST_INIT(rdatalist->rdata);
  1116. ISC_LIST_APPEND(rdatalist->rdata, rdata, link);
  1117. RUNTIME_CHECK(dns_rdatalist_tordataset(rdatalist, rdataset)
  1118. == ISC_R_SUCCESS);
  1119. client->opt = rdataset;
  1120. return (ISC_R_SUCCESS);
  1121. }
  1122. static inline isc_boolean_t
  1123. allowed(isc_netaddr_t *addr, dns_name_t *signer, dns_acl_t *acl) {
  1124. int match;
  1125. isc_result_t result;
  1126. if (acl == NULL)
  1127. return (ISC_TRUE);
  1128. result = dns_acl_match(addr, signer, acl, &ns_g_server->aclenv,
  1129. &match, NULL);
  1130. if (result == ISC_R_SUCCESS && match > 0)
  1131. return (ISC_TRUE);
  1132. return (ISC_FALSE);
  1133. }
  1134. /*
  1135. * Callback to see if a non-recursive query coming from 'srcaddr' to
  1136. * 'destaddr', with optional key 'mykey' for class 'rdclass' would be
  1137. * delivered to 'myview'.
  1138. *
  1139. * We run this unlocked as both the view list and the interface list
  1140. * are updated when the appropriate task has exclusivity.
  1141. */
  1142. isc_boolean_t
  1143. ns_client_isself(dns_view_t *myview, dns_tsigkey_t *mykey,
  1144. isc_sockaddr_t *srcaddr, isc_sockaddr_t *dstaddr,
  1145. dns_rdataclass_t rdclass, void *arg)
  1146. {
  1147. dns_view_t *view;
  1148. dns_tsigkey_t *key = NULL;
  1149. dns_name_t *tsig = NULL;
  1150. isc_netaddr_t netsrc;
  1151. isc_netaddr_t netdst;
  1152. UNUSED(arg);
  1153. /*
  1154. * ns_g_server->interfacemgr is task exclusive locked.
  1155. */
  1156. if (ns_g_server->interfacemgr == NULL)
  1157. return (ISC_TRUE);
  1158. if (!ns_interfacemgr_listeningon(ns_g_server->interfacemgr, dstaddr))
  1159. return (ISC_FALSE);
  1160. isc_netaddr_fromsockaddr(&netsrc, srcaddr);
  1161. isc_netaddr_fromsockaddr(&netdst, dstaddr);
  1162. for (view = ISC_LIST_HEAD(ns_g_server->viewlist);
  1163. view != NULL;
  1164. view = ISC_LIST_NEXT(view, link)) {
  1165. if (view->matchrecursiveonly)
  1166. continue;
  1167. if (rdclass != view->rdclass)
  1168. continue;
  1169. if (mykey != NULL) {
  1170. isc_boolean_t match;
  1171. isc_result_t result;
  1172. result = dns_view_gettsig(view, &mykey->name, &key);
  1173. if (result != ISC_R_SUCCESS)
  1174. continue;
  1175. match = dst_key_compare(mykey->key, key->key);
  1176. dns_tsigkey_detach(&key);
  1177. if (!match)
  1178. continue;
  1179. tsig = dns_tsigkey_identity(mykey);
  1180. }
  1181. if (allowed(&netsrc, tsig, view->matchclients) &&
  1182. allowed(&netdst, tsig, view->matchdestinations))
  1183. break;
  1184. }
  1185. return (ISC_TF(view == myview));
  1186. }
  1187. /*
  1188. * Handle an incoming request event from the socket (UDP case)
  1189. * or tcpmsg (TCP case).
  1190. */
  1191. static void
  1192. client_request(isc_task_t *task, isc_event_t *event) {
  1193. ns_client_t *client;
  1194. isc_socketevent_t *sevent;
  1195. isc_result_t result;
  1196. isc_result_t sigresult = ISC_R_SUCCESS;
  1197. isc_buffer_t *buffer;
  1198. isc_buffer_t tbuffer;
  1199. dns_view_t *view;
  1200. dns_rdataset_t *opt;
  1201. dns_name_t *signame;
  1202. isc_boolean_t ra; /* Recursion available. */
  1203. isc_netaddr_t netaddr;
  1204. int match;
  1205. dns_messageid_t id;
  1206. unsigned int flags;
  1207. isc_boolean_t notimp;
  1208. dns_rdata_t rdata;
  1209. isc_uint16_t optcode;
  1210. REQUIRE(event != NULL);
  1211. client = event->ev_arg;
  1212. REQUIRE(NS_CLIENT_VALID(client));
  1213. REQUIRE(task == client->task);
  1214. INSIST(client->recursionquota == NULL);
  1215. INSIST(client->state ==
  1216. TCP_CLIENT(client) ?
  1217. NS_CLIENTSTATE_READING :
  1218. NS_CLIENTSTATE_READY);
  1219. ns_client_requests++;
  1220. if (event->ev_type == ISC_SOCKEVENT_RECVDONE) {
  1221. INSIST(!TCP_CLIENT(client));
  1222. sevent = (isc_socketevent_t *)event;
  1223. REQUIRE(sevent == client->recvevent);
  1224. isc_buffer_init(&tbuffer, sevent->region.base, sevent->n);
  1225. isc_buffer_add(&tbuffer, sevent->n);
  1226. buffer = &tbuffer;
  1227. result = sevent->result;
  1228. if (result == ISC_R_SUCCESS) {
  1229. client->peeraddr = sevent->address;
  1230. client->peeraddr_valid = ISC_TRUE;
  1231. }
  1232. if ((sevent->attributes & ISC_SOCKEVENTATTR_PKTINFO) != 0) {
  1233. client->attributes |= NS_CLIENTATTR_PKTINFO;
  1234. client->pktinfo = sevent->pktinfo;
  1235. }
  1236. if ((sevent->attributes & ISC_SOCKEVENTATTR_MULTICAST) != 0)
  1237. client->attributes |= NS_CLIENTATTR_MULTICAST;
  1238. client->nrecvs--;
  1239. } else {
  1240. INSIST(TCP_CLIENT(client));
  1241. REQUIRE(event->ev_type == DNS_EVENT_TCPMSG);
  1242. REQUIRE(event->ev_sender == &client->tcpmsg);
  1243. buffer = &client->tcpmsg.buffer;
  1244. result = client->tcpmsg.result;
  1245. INSIST(client->nreads == 1);
  1246. /*
  1247. * client->peeraddr was set when the connection was accepted.
  1248. */
  1249. client->nreads--;
  1250. }
  1251. if (exit_check(client))
  1252. goto cleanup;
  1253. client->state = client->newstate = NS_CLIENTSTATE_WORKING;
  1254. isc_task_getcurrenttime(task, &client->requesttime);
  1255. client->now = client->requesttime;
  1256. if (result != ISC_R_SUCCESS) {
  1257. if (TCP_CLIENT(client)) {
  1258. ns_client_next(client, result);
  1259. } else {
  1260. if (result != ISC_R_CANCELED)
  1261. isc_log_write(ns_g_lctx, NS_LOGCATEGORY_CLIENT,
  1262. NS_LOGMODULE_CLIENT,
  1263. ISC_LOG_ERROR,
  1264. "UDP client handler shutting "
  1265. "down due to fatal receive "
  1266. "error: %s",
  1267. isc_result_totext(result));
  1268. isc_task_shutdown(client->task);
  1269. }
  1270. goto cleanup;
  1271. }
  1272. isc_netaddr_fromsockaddr(&netaddr, &client->peeraddr);
  1273. #if NS_CLIENT_DROPPORT
  1274. if (ns_client_dropport(isc_sockaddr_getport(&client->peeraddr)) ==
  1275. DROPPORT_REQUEST) {
  1276. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1277. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(10),
  1278. "dropped request: suspicious port");
  1279. ns_client_next(client, ISC_R_SUCCESS);
  1280. goto cleanup;
  1281. }
  1282. #endif
  1283. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  1284. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
  1285. "%s request",
  1286. TCP_CLIENT(client) ? "TCP" : "UDP");
  1287. /*
  1288. * Check the blackhole ACL for UDP only, since TCP is done in
  1289. * client_newconn.
  1290. */
  1291. if (!TCP_CLIENT(client)) {
  1292. if (ns_g_server->blackholeacl != NULL &&
  1293. dns_acl_match(&netaddr, NULL, ns_g_server->blackholeacl,
  1294. &ns_g_server->aclenv,
  1295. &match, NULL) == ISC_R_SUCCESS &&
  1296. match > 0)
  1297. {
  1298. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1299. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(10),
  1300. "blackholed UDP datagram");
  1301. ns_client_next(client, ISC_R_SUCCESS);
  1302. goto cleanup;
  1303. }
  1304. }
  1305. /*
  1306. * Silently drop multicast requests for the present.
  1307. * XXXMPA revisit this as mDNS spec was published.
  1308. */
  1309. if ((client->attributes & NS_CLIENTATTR_MULTICAST) != 0) {
  1310. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  1311. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(2),
  1312. "dropping multicast request");
  1313. ns_client_next(client, DNS_R_REFUSED);
  1314. goto cleanup;
  1315. }
  1316. result = dns_message_peekheader(buffer, &id, &flags);
  1317. if (result != ISC_R_SUCCESS) {
  1318. /*
  1319. * There isn't enough header to determine whether
  1320. * this was a request or a response. Drop it.
  1321. */
  1322. ns_client_next(client, result);
  1323. goto cleanup;
  1324. }
  1325. /*
  1326. * The client object handles requests, not responses.
  1327. * If this is a UDP response, forward it to the dispatcher.
  1328. * If it's a TCP response, discard it here.
  1329. */
  1330. if ((flags & DNS_MESSAGEFLAG_QR) != 0) {
  1331. if (TCP_CLIENT(client)) {
  1332. CTRACE("unexpected response");
  1333. ns_client_next(client, DNS_R_FORMERR);
  1334. goto cleanup;
  1335. } else {
  1336. dns_dispatch_importrecv(client->dispatch, event);
  1337. ns_client_next(client, ISC_R_SUCCESS);
  1338. goto cleanup;
  1339. }
  1340. }
  1341. /*
  1342. * Update some statistics counters. Don't count responses.
  1343. */
  1344. if (isc_sockaddr_pf(&client->peeraddr) == PF_INET) {
  1345. isc_stats_increment(ns_g_server->nsstats,
  1346. dns_nsstatscounter_requestv4);
  1347. } else {
  1348. isc_stats_increment(ns_g_server->nsstats,
  1349. dns_nsstatscounter_requestv6);
  1350. }
  1351. if (TCP_CLIENT(client))
  1352. isc_stats_increment(ns_g_server->nsstats,
  1353. dns_nsstatscounter_tcp);
  1354. /*
  1355. * It's a request. Parse it.
  1356. */
  1357. result = dns_message_parse(client->message, buffer, 0);
  1358. if (result != ISC_R_SUCCESS) {
  1359. /*
  1360. * Parsing the request failed. Send a response
  1361. * (typically FORMERR or SERVFAIL).
  1362. */
  1363. ns_client_error(client, result);
  1364. goto cleanup;
  1365. }
  1366. dns_opcodestats_increment(ns_g_server->opcodestats,
  1367. client->message->opcode);
  1368. switch (client->message->opcode) {
  1369. case dns_opcode_query:
  1370. case dns_opcode_update:
  1371. case dns_opcode_notify:
  1372. notimp = ISC_FALSE;
  1373. break;
  1374. case dns_opcode_iquery:
  1375. default:
  1376. notimp = ISC_TRUE;
  1377. break;
  1378. }
  1379. client->message->rcode = dns_rcode_noerror;
  1380. /* RFC1123 section 6.1.3.2 */
  1381. if ((client->attributes & NS_CLIENTATTR_MULTICAST) != 0)
  1382. client->message->flags &= ~DNS_MESSAGEFLAG_RD;
  1383. /*
  1384. * Deal with EDNS.
  1385. */
  1386. opt = dns_message_getopt(client->message);
  1387. if (opt != NULL) {
  1388. /*
  1389. * Set the client's UDP buffer size.
  1390. */
  1391. client->udpsize = opt->rdclass;
  1392. /*
  1393. * If the requested UDP buffer size is less than 512,
  1394. * ignore it and use 512.
  1395. */
  1396. if (client->udpsize < 512)
  1397. client->udpsize = 512;
  1398. /*
  1399. * Get the flags out of the OPT record.
  1400. */
  1401. client->extflags = (isc_uint16_t)(opt->ttl & 0xFFFF);
  1402. /*
  1403. * Do we understand this version of EDNS?
  1404. *
  1405. * XXXRTH need library support for this!
  1406. */
  1407. client->ednsversion = (opt->ttl & 0x00FF0000) >> 16;
  1408. if (client->ednsversion > 0) {
  1409. isc_stats_increment(ns_g_server->nsstats,
  1410. dns_nsstatscounter_badednsver);
  1411. result = client_addopt(client);
  1412. if (result == ISC_R_SUCCESS)
  1413. result = DNS_R_BADVERS;
  1414. ns_client_error(client, result);
  1415. goto cleanup;
  1416. }
  1417. /* Check for NSID request */
  1418. result = dns_rdataset_first(opt);
  1419. if (result == ISC_R_SUCCESS) {
  1420. dns_rdata_init(&rdata);
  1421. dns_rdataset_current(opt, &rdata);
  1422. if (rdata.length >= 2) {
  1423. isc_buffer_t nsidbuf;
  1424. isc_buffer_init(&nsidbuf,
  1425. rdata.data, rdata.length);
  1426. isc_buffer_add(&nsidbuf, rdata.length);
  1427. optcode = isc_buffer_getuint16(&nsidbuf);
  1428. if (optcode == DNS_OPT_NSID)
  1429. client->attributes |=
  1430. NS_CLIENTATTR_WANTNSID;
  1431. }
  1432. }
  1433. isc_stats_increment(ns_g_server->nsstats,
  1434. dns_nsstatscounter_edns0in);
  1435. /*
  1436. * Create an OPT for our reply.
  1437. */
  1438. result = client_addopt(client);
  1439. if (result != ISC_R_SUCCESS) {
  1440. ns_client_error(client, result);
  1441. goto cleanup;
  1442. }
  1443. }
  1444. if (client->message->rdclass == 0) {
  1445. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  1446. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(1),
  1447. "message class could not be determined");
  1448. ns_client_dumpmessage(client,
  1449. "message class could not be determined");
  1450. ns_client_error(client, notimp ? DNS_R_NOTIMP : DNS_R_FORMERR);
  1451. goto cleanup;
  1452. }
  1453. /*
  1454. * Determine the destination address. If the receiving interface is
  1455. * bound to a specific address, we simply use it regardless of the
  1456. * address family. All IPv4 queries should fall into this case.
  1457. * Otherwise, if this is a TCP query, get the address from the
  1458. * receiving socket (this needs a system call and can be heavy).
  1459. * For IPv6 UDP queries, we get this from the pktinfo structure (if
  1460. * supported).
  1461. * If all the attempts fail (this can happen due to memory shortage,
  1462. * etc), we regard this as an error for safety.
  1463. */
  1464. if ((client->interface->flags & NS_INTERFACEFLAG_ANYADDR) == 0)
  1465. isc_netaddr_fromsockaddr(&client->destaddr,
  1466. &client->interface->addr);
  1467. else {
  1468. isc_sockaddr_t sockaddr;
  1469. result = ISC_R_FAILURE;
  1470. if (TCP_CLIENT(client))
  1471. result = isc_socket_getsockname(client->tcpsocket,
  1472. &sockaddr);
  1473. if (result == ISC_R_SUCCESS)
  1474. isc_netaddr_fromsockaddr(&client->destaddr, &sockaddr);
  1475. if (result != ISC_R_SUCCESS &&
  1476. client->interface->addr.type.sa.sa_family == AF_INET6 &&
  1477. (client->attributes & NS_CLIENTATTR_PKTINFO) != 0) {
  1478. /*
  1479. * XXXJT technically, we should convert the receiving
  1480. * interface ID to a proper scope zone ID. However,
  1481. * due to the fact there is no standard API for this,
  1482. * we only handle link-local addresses and use the
  1483. * interface index as link ID. Despite the assumption,
  1484. * it should cover most typical cases.
  1485. */
  1486. isc_netaddr_fromin6(&client->destaddr,
  1487. &client->pktinfo.ipi6_addr);
  1488. if (IN6_IS_ADDR_LINKLOCAL(&client->pktinfo.ipi6_addr))
  1489. isc_netaddr_setzone(&client->destaddr,
  1490. client->pktinfo.ipi6_ifindex);
  1491. result = ISC_R_SUCCESS;
  1492. }
  1493. if (result != ISC_R_SUCCESS) {
  1494. UNEXPECTED_ERROR(__FILE__, __LINE__,
  1495. "failed to get request's "
  1496. "destination: %s",
  1497. isc_result_totext(result));
  1498. ns_client_next(client, ISC_R_SUCCESS);
  1499. goto cleanup;
  1500. }
  1501. }
  1502. /*
  1503. * Find a view that matches the client's source address.
  1504. */
  1505. for (view = ISC_LIST_HEAD(ns_g_server->viewlist);
  1506. view != NULL;
  1507. view = ISC_LIST_NEXT(view, link)) {
  1508. if (client->message->rdclass == view->rdclass ||
  1509. client->message->rdclass == dns_rdataclass_any)
  1510. {
  1511. dns_name_t *tsig = NULL;
  1512. sigresult = dns_message_rechecksig(client->message,
  1513. view);
  1514. if (sigresult == ISC_R_SUCCESS)
  1515. tsig = dns_tsigkey_identity(client->message->tsigkey);
  1516. if (allowed(&netaddr, tsig, view->matchclients) &&
  1517. allowed(&client->destaddr, tsig,
  1518. view->matchdestinations) &&
  1519. !((client->message->flags & DNS_MESSAGEFLAG_RD)
  1520. == 0 && view->matchrecursiveonly))
  1521. {
  1522. dns_view_attach(view, &client->view);
  1523. break;
  1524. }
  1525. }
  1526. }
  1527. if (view == NULL) {
  1528. char classname[DNS_RDATACLASS_FORMATSIZE];
  1529. /*
  1530. * Do a dummy TSIG verification attempt so that the
  1531. * response will have a TSIG if the query did, as
  1532. * required by RFC2845.
  1533. */
  1534. isc_buffer_t b;
  1535. isc_region_t *r;
  1536. dns_message_resetsig(client->message);
  1537. r = dns_message_getrawmessage(client->message);
  1538. isc_buffer_init(&b, r->base, r->length);
  1539. isc_buffer_add(&b, r->length);
  1540. (void)dns_tsig_verify(&b, client->message, NULL, NULL);
  1541. dns_rdataclass_format(client->message->rdclass, classname,
  1542. sizeof(classname));
  1543. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  1544. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(1),
  1545. "no matching view in class '%s'", classname);
  1546. ns_client_dumpmessage(client, "no matching view in class");
  1547. ns_client_error(client, notimp ? DNS_R_NOTIMP : DNS_R_REFUSED);
  1548. goto cleanup;
  1549. }
  1550. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  1551. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(5),
  1552. "using view '%s'", view->name);
  1553. /*
  1554. * Check for a signature. We log bad signatures regardless of
  1555. * whether they ultimately cause the request to be rejected or
  1556. * not. We do not log the lack of a signature unless we are
  1557. * debugging.
  1558. */
  1559. client->signer = NULL;
  1560. dns_name_init(&client->signername, NULL);
  1561. result = dns_message_signer(client->message, &client->signername);
  1562. if (result != ISC_R_NOTFOUND) {
  1563. signame = NULL;
  1564. if (dns_message_gettsig(client->message, &signame) != NULL) {
  1565. isc_stats_increment(ns_g_server->nsstats,
  1566. dns_nsstatscounter_tsigin);
  1567. } else {
  1568. isc_stats_increment(ns_g_server->nsstats,
  1569. dns_nsstatscounter_sig0in);
  1570. }
  1571. }
  1572. if (result == ISC_R_SUCCESS) {
  1573. char namebuf[DNS_NAME_FORMATSIZE];
  1574. dns_name_format(&client->signername, namebuf, sizeof(namebuf));
  1575. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1576. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
  1577. "request has valid signature: %s", namebuf);
  1578. client->signer = &client->signername;
  1579. } else if (result == ISC_R_NOTFOUND) {
  1580. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1581. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
  1582. "request is not signed");
  1583. } else if (result == DNS_R_NOIDENTITY) {
  1584. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1585. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
  1586. "request is signed by a nonauthoritative key");
  1587. } else {
  1588. char tsigrcode[64];
  1589. isc_buffer_t b;
  1590. dns_rcode_t status;
  1591. isc_result_t tresult;
  1592. /* There is a signature, but it is bad. */
  1593. isc_stats_increment(ns_g_server->nsstats,
  1594. dns_nsstatscounter_invalidsig);
  1595. signame = NULL;
  1596. if (dns_message_gettsig(client->message, &signame) != NULL) {
  1597. char namebuf[DNS_NAME_FORMATSIZE];
  1598. char cnamebuf[DNS_NAME_FORMATSIZE];
  1599. dns_name_format(signame, namebuf, sizeof(namebuf));
  1600. status = client->message->tsigstatus;
  1601. isc_buffer_init(&b, tsigrcode, sizeof(tsigrcode) - 1);
  1602. tresult = dns_tsigrcode_totext(status, &b);
  1603. INSIST(tresult == ISC_R_SUCCESS);
  1604. tsigrcode[isc_buffer_usedlength(&b)] = '\0';
  1605. if (client->message->tsigkey->generated) {
  1606. dns_name_format(client->message->tsigkey->creator,
  1607. cnamebuf, sizeof(cnamebuf));
  1608. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1609. NS_LOGMODULE_CLIENT,
  1610. ISC_LOG_ERROR,
  1611. "request has invalid signature: "
  1612. "TSIG %s (%s): %s (%s)", namebuf,
  1613. cnamebuf,
  1614. isc_result_totext(result),
  1615. tsigrcode);
  1616. } else {
  1617. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1618. NS_LOGMODULE_CLIENT,
  1619. ISC_LOG_ERROR,
  1620. "request has invalid signature: "
  1621. "TSIG %s: %s (%s)", namebuf,
  1622. isc_result_totext(result),
  1623. tsigrcode);
  1624. }
  1625. } else {
  1626. status = client->message->sig0status;
  1627. isc_buffer_init(&b, tsigrcode, sizeof(tsigrcode) - 1);
  1628. tresult = dns_tsigrcode_totext(status, &b);
  1629. INSIST(tresult == ISC_R_SUCCESS);
  1630. tsigrcode[isc_buffer_usedlength(&b)] = '\0';
  1631. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1632. NS_LOGMODULE_CLIENT, ISC_LOG_ERROR,
  1633. "request has invalid signature: %s (%s)",
  1634. isc_result_totext(result), tsigrcode);
  1635. }
  1636. /*
  1637. * Accept update messages signed by unknown keys so that
  1638. * update forwarding works transparently through slaves
  1639. * that don't have all the same keys as the master.
  1640. */
  1641. if (!(client->message->tsigstatus == dns_tsigerror_badkey &&
  1642. client->message->opcode == dns_opcode_update)) {
  1643. ns_client_error(client, sigresult);
  1644. goto cleanup;
  1645. }
  1646. }
  1647. /*
  1648. * Decide whether recursive service is available to this client.
  1649. * We do this here rather than in the query code so that we can
  1650. * set the RA bit correctly on all kinds of responses, not just
  1651. * responses to ordinary queries. Note if you can't query the
  1652. * cache there is no point in setting RA.
  1653. */
  1654. ra = ISC_FALSE;
  1655. if (client->view->resolver != NULL &&
  1656. client->view->recursion == ISC_TRUE &&
  1657. ns_client_checkaclsilent(client, NULL,
  1658. client->view->recursionacl,
  1659. ISC_TRUE) == ISC_R_SUCCESS &&
  1660. ns_client_checkaclsilent(client, NULL,
  1661. client->view->cacheacl,
  1662. ISC_TRUE) == ISC_R_SUCCESS &&
  1663. ns_client_checkaclsilent(client, &client->destaddr,
  1664. client->view->recursiononacl,
  1665. ISC_TRUE) == ISC_R_SUCCESS &&
  1666. ns_client_checkaclsilent(client, &client->destaddr,
  1667. client->view->cacheonacl,
  1668. ISC_TRUE) == ISC_R_SUCCESS)
  1669. ra = ISC_TRUE;
  1670. if (ra == ISC_TRUE)
  1671. client->attributes |= NS_CLIENTATTR_RA;
  1672. ns_client_log(client, DNS_LOGCATEGORY_SECURITY, NS_LOGMODULE_CLIENT,
  1673. ISC_LOG_DEBUG(3), ra ? "recursion available" :
  1674. "recursion not available");
  1675. /*
  1676. * Adjust maximum UDP response size for this client.
  1677. */
  1678. if (client->udpsize > 512) {
  1679. dns_peer_t *peer = NULL;
  1680. isc_uint16_t udpsize = view->maxudp;
  1681. (void) dns_peerlist_peerbyaddr(view->peers, &netaddr, &peer);
  1682. if (peer != NULL)
  1683. dns_peer_getmaxudp(peer, &udpsize);
  1684. if (client->udpsize > udpsize)
  1685. client->udpsize = udpsize;
  1686. }
  1687. /*
  1688. * Dispatch the request.
  1689. */
  1690. switch (client->message->opcode) {
  1691. case dns_opcode_query:
  1692. CTRACE("query");
  1693. ns_query_start(client);
  1694. break;
  1695. case dns_opcode_update:
  1696. CTRACE("update");
  1697. ns_client_settimeout(client, 60);
  1698. ns_update_start(client, sigresult);
  1699. break;
  1700. case dns_opcode_notify:
  1701. CTRACE("notify");
  1702. ns_client_settimeout(client, 60);
  1703. ns_notify_start(client);
  1704. break;
  1705. case dns_opcode_iquery:
  1706. CTRACE("iquery");
  1707. ns_client_error(client, DNS_R_NOTIMP);
  1708. break;
  1709. default:
  1710. CTRACE("unknown opcode");
  1711. ns_client_error(client, DNS_R_NOTIMP);
  1712. }
  1713. cleanup:
  1714. return;
  1715. }
  1716. static void
  1717. client_timeout(isc_task_t *task, isc_event_t *event) {
  1718. ns_client_t *client;
  1719. REQUIRE(event != NULL);
  1720. REQUIRE(event->ev_type == ISC_TIMEREVENT_LIFE ||
  1721. event->ev_type == ISC_TIMEREVENT_IDLE);
  1722. client = event->ev_arg;
  1723. REQUIRE(NS_CLIENT_VALID(client));
  1724. REQUIRE(task == client->task);
  1725. REQUIRE(client->timer != NULL);
  1726. UNUSED(task);
  1727. CTRACE("timeout");
  1728. isc_event_free(&event);
  1729. if (client->shutdown != NULL) {
  1730. (client->shutdown)(client->shutdown_arg, ISC_R_TIMEDOUT);
  1731. client->shutdown = NULL;
  1732. client->shutdown_arg = NULL;
  1733. }
  1734. if (client->newstate > NS_CLIENTSTATE_READY)
  1735. client->newstate = NS_CLIENTSTATE_READY;
  1736. (void)exit_check(client);
  1737. }
  1738. static isc_result_t
  1739. get_clientmctx(ns_clientmgr_t *manager, isc_mem_t **mctxp) {
  1740. isc_mem_t *clientmctx;
  1741. isc_result_t result;
  1742. /*
  1743. * Caller must be holding the manager lock.
  1744. */
  1745. if (ns_g_clienttest) {
  1746. result = isc_mem_create(0, 0, mctxp);
  1747. if (result == ISC_R_SUCCESS)
  1748. isc_mem_setname(*mctxp, "client", NULL);
  1749. return (result);
  1750. }
  1751. #if NMCTXS > 0
  1752. INSIST(manager->nextmctx < NMCTXS);
  1753. clientmctx = manager->mctxpool[manager->nextmctx];
  1754. if (clientmctx == NULL) {
  1755. result = isc_mem_create(0, 0, &clientmctx);
  1756. if (result != ISC_R_SUCCESS)
  1757. return (result);
  1758. isc_mem_setname(clientmctx, "client", NULL);
  1759. manager->mctxpool[manager->nextmctx] = clientmctx;
  1760. }
  1761. manager->nextmctx++;
  1762. if (manager->nextmctx == NMCTXS)
  1763. manager->nextmctx = 0;
  1764. #else
  1765. clientmctx = manager->mctx;
  1766. #endif
  1767. isc_mem_attach(clientmctx, mctxp);
  1768. return (ISC_R_SUCCESS);
  1769. }
  1770. static isc_result_t
  1771. client_create(ns_clientmgr_t *manager, ns_client_t **clientp) {
  1772. ns_client_t *client;
  1773. isc_result_t result;
  1774. isc_mem_t *mctx = NULL;
  1775. /*
  1776. * Caller must be holding the manager lock.
  1777. *
  1778. * Note: creating a client does not add the client to the
  1779. * manager's client list or set the client's manager pointer.
  1780. * The caller is responsible for that.
  1781. */
  1782. REQUIRE(clientp != NULL && *clientp == NULL);
  1783. result = get_clientmctx(manager, &mctx);
  1784. if (result != ISC_R_SUCCESS)
  1785. return (result);
  1786. client = isc_mem_get(mctx, sizeof(*client));
  1787. if (client == NULL) {
  1788. isc_mem_detach(&mctx);
  1789. return (ISC_R_NOMEMORY);
  1790. }
  1791. client->mctx = mctx;
  1792. client->task = NULL;
  1793. result = isc_task_create(manager->taskmgr, 0, &client->task);
  1794. if (result != ISC_R_SUCCESS)
  1795. goto cleanup_client;
  1796. isc_task_setname(client->task, "client", client);
  1797. client->timer = NULL;
  1798. result = isc_timer_create(manager->timermgr, isc_timertype_inactive,
  1799. NULL, NULL, client->task, client_timeout,
  1800. client, &client->timer);
  1801. if (result != ISC_R_SUCCESS)
  1802. goto cleanup_task;
  1803. client->timerset = ISC_FALSE;
  1804. client->message = NULL;
  1805. result = dns_message_create(client->mctx, DNS_MESSAGE_INTENTPARSE,
  1806. &client->message);
  1807. if (result != ISC_R_SUCCESS)
  1808. goto cleanup_timer;
  1809. /* XXXRTH Hardwired constants */
  1810. client->sendevent = (isc_socketevent_t *)
  1811. isc_event_allocate(client->mctx, client,
  1812. ISC_SOCKEVENT_SENDDONE,
  1813. client_senddone, client,
  1814. sizeof(isc_socketevent_t));
  1815. if (client->sendevent == NULL) {
  1816. result = ISC_R_NOMEMORY;
  1817. goto cleanup_message;
  1818. }
  1819. client->recvbuf = isc_mem_get(client->mctx, RECV_BUFFER_SIZE);
  1820. if (client->recvbuf == NULL) {
  1821. result = ISC_R_NOMEMORY;
  1822. goto cleanup_sendevent;
  1823. }
  1824. client->recvevent = (isc_socketevent_t *)
  1825. isc_event_allocate(client->mctx, client,
  1826. ISC_SOCKEVENT_RECVDONE,
  1827. client_request, client,
  1828. sizeof(isc_socketevent_t));
  1829. if (client->recvevent == NULL) {
  1830. result = ISC_R_NOMEMORY;
  1831. goto cleanup_recvbuf;
  1832. }
  1833. client->magic = NS_CLIENT_MAGIC;
  1834. client->manager = NULL;
  1835. client->state = NS_CLIENTSTATE_INACTIVE;
  1836. client->newstate = NS_CLIENTSTATE_MAX;
  1837. client->naccepts = 0;
  1838. client->nreads = 0;
  1839. client->nsends = 0;
  1840. client->nrecvs = 0;
  1841. client->nupdates = 0;
  1842. client->nctls = 0;
  1843. client->references = 0;
  1844. client->attributes = 0;
  1845. client->view = NULL;
  1846. client->dispatch = NULL;
  1847. client->udpsocket = NULL;
  1848. client->tcplistener = NULL;
  1849. client->tcpsocket = NULL;
  1850. client->tcpmsg_valid = ISC_FALSE;
  1851. client->tcpbuf = NULL;
  1852. client->opt = NULL;
  1853. client->udpsize = 512;
  1854. client->extflags = 0;
  1855. client->ednsversion = -1;
  1856. client->next = NULL;
  1857. client->shutdown = NULL;
  1858. client->shutdown_arg = NULL;
  1859. client->signer = NULL;
  1860. dns_name_init(&client->signername, NULL);
  1861. client->mortal = ISC_FALSE;
  1862. client->tcpquota = NULL;
  1863. client->recursionquota = NULL;
  1864. client->interface = NULL;
  1865. client->peeraddr_valid = ISC_FALSE;
  1866. #ifdef ALLOW_FILTER_AAAA_ON_V4
  1867. client->filter_aaaa = dns_v4_aaaa_ok;
  1868. #endif
  1869. ISC_EVENT_INIT(&client->ctlevent, sizeof(client->ctlevent), 0, NULL,
  1870. NS_EVENT_CLIENTCONTROL, client_start, client, client,
  1871. NULL, NULL);
  1872. /*
  1873. * Initialize FORMERR cache to sentinel value that will not match
  1874. * any actual FORMERR response.
  1875. */
  1876. isc_sockaddr_any(&client->formerrcache.addr);
  1877. client->formerrcache.time = 0;
  1878. client->formerrcache.id = 0;
  1879. ISC_LINK_INIT(client, link);
  1880. client->list = NULL;
  1881. /*
  1882. * We call the init routines for the various kinds of client here,
  1883. * after we have created an otherwise valid client, because some
  1884. * of them call routines that REQUIRE(NS_CLIENT_VALID(client)).
  1885. */
  1886. result = ns_query_init(client);
  1887. if (result != ISC_R_SUCCESS)
  1888. goto cleanup_recvevent;
  1889. result = isc_task_onshutdown(client->task, client_shutdown, client);
  1890. if (result != ISC_R_SUCCESS)
  1891. goto cleanup_query;
  1892. client->needshutdown = ns_g_clienttest;
  1893. CTRACE("create");
  1894. *clientp = client;
  1895. return (ISC_R_SUCCESS);
  1896. cleanup_query:
  1897. ns_query_free(client);
  1898. cleanup_recvevent:
  1899. isc_event_free((isc_event_t **)&client->recvevent);
  1900. cleanup_recvbuf:
  1901. isc_mem_put(client->mctx, client->recvbuf, RECV_BUFFER_SIZE);
  1902. cleanup_sendevent:
  1903. isc_event_free((isc_event_t **)&client->sendevent);
  1904. client->magic = 0;
  1905. cleanup_message:
  1906. dns_message_destroy(&client->message);
  1907. cleanup_timer:
  1908. isc_timer_detach(&client->timer);
  1909. cleanup_task:
  1910. isc_task_detach(&client->task);
  1911. cleanup_client:
  1912. isc_mem_putanddetach(&client->mctx, client, sizeof(*client));
  1913. return (result);
  1914. }
  1915. static void
  1916. client_read(ns_client_t *client) {
  1917. isc_result_t result;
  1918. CTRACE("read");
  1919. result = dns_tcpmsg_readmessage(&client->tcpmsg, client->task,
  1920. client_request, client);
  1921. if (result != ISC_R_SUCCESS)
  1922. goto fail;
  1923. /*
  1924. * Set a timeout to limit the amount of time we will wait
  1925. * for a request on this TCP connection.
  1926. */
  1927. ns_client_settimeout(client, 30);
  1928. client->state = client->newstate = NS_CLIENTSTATE_READING;
  1929. INSIST(client->nreads == 0);
  1930. INSIST(client->recursionquota == NULL);
  1931. client->nreads++;
  1932. return;
  1933. fail:
  1934. ns_client_next(client, result);
  1935. }
  1936. static void
  1937. client_newconn(isc_task_t *task, isc_event_t *event) {
  1938. ns_client_t *client = event->ev_arg;
  1939. isc_socket_newconnev_t *nevent = (isc_socket_newconnev_t *)event;
  1940. isc_result_t result;
  1941. REQUIRE(event->ev_type == ISC_SOCKEVENT_NEWCONN);
  1942. REQUIRE(NS_CLIENT_VALID(client));
  1943. REQUIRE(client->task == task);
  1944. UNUSED(task);
  1945. INSIST(client->state == NS_CLIENTSTATE_READY);
  1946. INSIST(client->naccepts == 1);
  1947. client->naccepts--;
  1948. LOCK(&client->interface->lock);
  1949. INSIST(client->interface->ntcpcurrent > 0);
  1950. client->interface->ntcpcurrent--;
  1951. UNLOCK(&client->interface->lock);
  1952. /*
  1953. * We must take ownership of the new socket before the exit
  1954. * check to make sure it gets destroyed if we decide to exit.
  1955. */
  1956. if (nevent->result == ISC_R_SUCCESS) {
  1957. client->tcpsocket = nevent->newsocket;
  1958. isc_socket_setname(client->tcpsocket, "client-tcp", NULL);
  1959. client->state = NS_CLIENTSTATE_READING;
  1960. INSIST(client->recursionquota == NULL);
  1961. (void)isc_socket_getpeername(client->tcpsocket,
  1962. &client->peeraddr);
  1963. client->peeraddr_valid = ISC_TRUE;
  1964. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  1965. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
  1966. "new TCP connection");
  1967. } else {
  1968. /*
  1969. * XXXRTH What should we do? We're trying to accept but
  1970. * it didn't work. If we just give up, then TCP
  1971. * service may eventually stop.
  1972. *
  1973. * For now, we just go idle.
  1974. *
  1975. * Going idle is probably the right thing if the
  1976. * I/O was canceled.
  1977. */
  1978. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  1979. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
  1980. "accept failed: %s",
  1981. isc_result_totext(nevent->result));
  1982. }
  1983. if (exit_check(client))
  1984. goto freeevent;
  1985. if (nevent->result == ISC_R_SUCCESS) {
  1986. int match;
  1987. isc_netaddr_t netaddr;
  1988. isc_netaddr_fromsockaddr(&netaddr, &client->peeraddr);
  1989. if (ns_g_server->blackholeacl != NULL &&
  1990. dns_acl_match(&netaddr, NULL,
  1991. ns_g_server->blackholeacl,
  1992. &ns_g_server->aclenv,
  1993. &match, NULL) == ISC_R_SUCCESS &&
  1994. match > 0)
  1995. {
  1996. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  1997. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(10),
  1998. "blackholed connection attempt");
  1999. client->newstate = NS_CLIENTSTATE_READY;
  2000. (void)exit_check(client);
  2001. goto freeevent;
  2002. }
  2003. INSIST(client->tcpmsg_valid == ISC_FALSE);
  2004. dns_tcpmsg_init(client->mctx, client->tcpsocket,
  2005. &client->tcpmsg);
  2006. client->tcpmsg_valid = ISC_TRUE;
  2007. /*
  2008. * Let a new client take our place immediately, before
  2009. * we wait for a request packet. If we don't,
  2010. * telnetting to port 53 (once per CPU) will
  2011. * deny service to legitimate TCP clients.
  2012. */
  2013. result = isc_quota_attach(&ns_g_server->tcpquota,
  2014. &client->tcpquota);
  2015. if (result == ISC_R_SUCCESS)
  2016. result = ns_client_replace(client);
  2017. if (result != ISC_R_SUCCESS) {
  2018. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  2019. NS_LOGMODULE_CLIENT, ISC_LOG_WARNING,
  2020. "no more TCP clients: %s",
  2021. isc_result_totext(result));
  2022. }
  2023. client_read(client);
  2024. }
  2025. freeevent:
  2026. isc_event_free(&event);
  2027. }
  2028. static void
  2029. client_accept(ns_client_t *client) {
  2030. isc_result_t result;
  2031. CTRACE("accept");
  2032. result = isc_socket_accept(client->tcplistener, client->task,
  2033. client_newconn, client);
  2034. if (result != ISC_R_SUCCESS) {
  2035. UNEXPECTED_ERROR(__FILE__, __LINE__,
  2036. "isc_socket_accept() failed: %s",
  2037. isc_result_totext(result));
  2038. /*
  2039. * XXXRTH What should we do? We're trying to accept but
  2040. * it didn't work. If we just give up, then TCP
  2041. * service may eventually stop.
  2042. *
  2043. * For now, we just go idle.
  2044. */
  2045. return;
  2046. }
  2047. INSIST(client->naccepts == 0);
  2048. client->naccepts++;
  2049. LOCK(&client->interface->lock);
  2050. client->interface->ntcpcurrent++;
  2051. UNLOCK(&client->interface->lock);
  2052. }
  2053. static void
  2054. client_udprecv(ns_client_t *client) {
  2055. isc_result_t result;
  2056. isc_region_t r;
  2057. CTRACE("udprecv");
  2058. r.base = client->recvbuf;
  2059. r.length = RECV_BUFFER_SIZE;
  2060. result = isc_socket_recv2(client->udpsocket, &r, 1,
  2061. client->task, client->recvevent, 0);
  2062. if (result != ISC_R_SUCCESS) {
  2063. UNEXPECTED_ERROR(__FILE__, __LINE__,
  2064. "isc_socket_recv2() failed: %s",
  2065. isc_result_totext(result));
  2066. /*
  2067. * This cannot happen in the current implementation, since
  2068. * isc_socket_recv2() cannot fail if flags == 0.
  2069. *
  2070. * If this does fail, we just go idle.
  2071. */
  2072. return;
  2073. }
  2074. INSIST(client->nrecvs == 0);
  2075. client->nrecvs++;
  2076. }
  2077. void
  2078. ns_client_attach(ns_client_t *source, ns_client_t **targetp) {
  2079. REQUIRE(NS_CLIENT_VALID(source));
  2080. REQUIRE(targetp != NULL && *targetp == NULL);
  2081. source->references++;
  2082. ns_client_log(source, NS_LOGCATEGORY_CLIENT,
  2083. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(10),
  2084. "ns_client_attach: ref = %d", source->references);
  2085. *targetp = source;
  2086. }
  2087. void
  2088. ns_client_detach(ns_client_t **clientp) {
  2089. ns_client_t *client = *clientp;
  2090. client->references--;
  2091. INSIST(client->references >= 0);
  2092. *clientp = NULL;
  2093. ns_client_log(client, NS_LOGCATEGORY_CLIENT,
  2094. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(10),
  2095. "ns_client_detach: ref = %d", client->references);
  2096. (void)exit_check(client);
  2097. }
  2098. isc_boolean_t
  2099. ns_client_shuttingdown(ns_client_t *client) {
  2100. return (ISC_TF(client->newstate == NS_CLIENTSTATE_FREED));
  2101. }
  2102. isc_result_t
  2103. ns_client_replace(ns_client_t *client) {
  2104. isc_result_t result;
  2105. CTRACE("replace");
  2106. result = ns_clientmgr_createclients(client->manager,
  2107. 1, client->interface,
  2108. (TCP_CLIENT(client) ?
  2109. ISC_TRUE : ISC_FALSE));
  2110. if (result != ISC_R_SUCCESS)
  2111. return (result);
  2112. /*
  2113. * The responsibility for listening for new requests is hereby
  2114. * transferred to the new client. Therefore, the old client
  2115. * should refrain from listening for any more requests.
  2116. */
  2117. client->mortal = ISC_TRUE;
  2118. return (ISC_R_SUCCESS);
  2119. }
  2120. /***
  2121. *** Client Manager
  2122. ***/
  2123. static void
  2124. clientmgr_destroy(ns_clientmgr_t *manager) {
  2125. #if NMCTXS > 0
  2126. int i;
  2127. #endif
  2128. REQUIRE(ISC_LIST_EMPTY(manager->active));
  2129. REQUIRE(ISC_LIST_EMPTY(manager->inactive));
  2130. REQUIRE(ISC_LIST_EMPTY(manager->recursing));
  2131. MTRACE("clientmgr_destroy");
  2132. #if NMCTXS > 0
  2133. for (i = 0; i < NMCTXS; i++) {
  2134. if (manager->mctxpool[i] != NULL)
  2135. isc_mem_detach(&manager->mctxpool[i]);
  2136. }
  2137. #endif
  2138. DESTROYLOCK(&manager->lock);
  2139. manager->magic = 0;
  2140. isc_mem_put(manager->mctx, manager, sizeof(*manager));
  2141. }
  2142. isc_result_t
  2143. ns_clientmgr_create(isc_mem_t *mctx, isc_taskmgr_t *taskmgr,
  2144. isc_timermgr_t *timermgr, ns_clientmgr_t **managerp)
  2145. {
  2146. ns_clientmgr_t *manager;
  2147. isc_result_t result;
  2148. #if NMCTXS > 0
  2149. int i;
  2150. #endif
  2151. manager = isc_mem_get(mctx, sizeof(*manager));
  2152. if (manager == NULL)
  2153. return (ISC_R_NOMEMORY);
  2154. result = isc_mutex_init(&manager->lock);
  2155. if (result != ISC_R_SUCCESS)
  2156. goto cleanup_manager;
  2157. manager->mctx = mctx;
  2158. manager->taskmgr = taskmgr;
  2159. manager->timermgr = timermgr;
  2160. manager->exiting = ISC_FALSE;
  2161. ISC_LIST_INIT(manager->active);
  2162. ISC_LIST_INIT(manager->inactive);
  2163. ISC_LIST_INIT(manager->recursing);
  2164. #if NMCTXS > 0
  2165. manager->nextmctx = 0;
  2166. for (i = 0; i < NMCTXS; i++)
  2167. manager->mctxpool[i] = NULL; /* will be created on-demand */
  2168. #endif
  2169. manager->magic = MANAGER_MAGIC;
  2170. MTRACE("create");
  2171. *managerp = manager;
  2172. return (ISC_R_SUCCESS);
  2173. cleanup_manager:
  2174. isc_mem_put(manager->mctx, manager, sizeof(*manager));
  2175. return (result);
  2176. }
  2177. void
  2178. ns_clientmgr_destroy(ns_clientmgr_t **managerp) {
  2179. ns_clientmgr_t *manager;
  2180. ns_client_t *client;
  2181. isc_boolean_t need_destroy = ISC_FALSE;
  2182. REQUIRE(managerp != NULL);
  2183. manager = *managerp;
  2184. REQUIRE(VALID_MANAGER(manager));
  2185. MTRACE("destroy");
  2186. LOCK(&manager->lock);
  2187. manager->exiting = ISC_TRUE;
  2188. for (client = ISC_LIST_HEAD(manager->recursing);
  2189. client != NULL;
  2190. client = ISC_LIST_NEXT(client, link))
  2191. isc_task_shutdown(client->task);
  2192. for (client = ISC_LIST_HEAD(manager->active);
  2193. client != NULL;
  2194. client = ISC_LIST_NEXT(client, link))
  2195. isc_task_shutdown(client->task);
  2196. for (client = ISC_LIST_HEAD(manager->inactive);
  2197. client != NULL;
  2198. client = ISC_LIST_NEXT(client, link))
  2199. isc_task_shutdown(client->task);
  2200. if (ISC_LIST_EMPTY(manager->active) &&
  2201. ISC_LIST_EMPTY(manager->inactive) &&
  2202. ISC_LIST_EMPTY(manager->recursing))
  2203. need_destroy = ISC_TRUE;
  2204. UNLOCK(&manager->lock);
  2205. if (need_destroy)
  2206. clientmgr_destroy(manager);
  2207. *managerp = NULL;
  2208. }
  2209. isc_result_t
  2210. ns_clientmgr_createclients(ns_clientmgr_t *manager, unsigned int n,
  2211. ns_interface_t *ifp, isc_boolean_t tcp)
  2212. {
  2213. isc_result_t result = ISC_R_SUCCESS;
  2214. unsigned int i;
  2215. ns_client_t *client;
  2216. REQUIRE(VALID_MANAGER(manager));
  2217. REQUIRE(n > 0);
  2218. MTRACE("createclients");
  2219. /*
  2220. * We MUST lock the manager lock for the entire client creation
  2221. * process. If we didn't do this, then a client could get a
  2222. * shutdown event and disappear out from under us.
  2223. */
  2224. LOCK(&manager->lock);
  2225. for (i = 0; i < n; i++) {
  2226. isc_event_t *ev;
  2227. /*
  2228. * Allocate a client. First try to get a recycled one;
  2229. * if that fails, make a new one.
  2230. */
  2231. client = NULL;
  2232. if (!ns_g_clienttest)
  2233. client = ISC_LIST_HEAD(manager->inactive);
  2234. if (client != NULL) {
  2235. MTRACE("recycle");
  2236. ISC_LIST_UNLINK(manager->inactive, client, link);
  2237. client->list = NULL;
  2238. } else {
  2239. MTRACE("create new");
  2240. result = client_create(manager, &client);
  2241. if (result != ISC_R_SUCCESS)
  2242. break;
  2243. }
  2244. ns_interface_attach(ifp, &client->interface);
  2245. client->state = NS_CLIENTSTATE_READY;
  2246. INSIST(client->recursionquota == NULL);
  2247. if (tcp) {
  2248. client->attributes |= NS_CLIENTATTR_TCP;
  2249. isc_socket_attach(ifp->tcpsocket,
  2250. &client->tcplistener);
  2251. } else {
  2252. isc_socket_t *sock;
  2253. dns_dispatch_attach(ifp->udpdispatch,
  2254. &client->dispatch);
  2255. sock = dns_dispatch_getsocket(client->dispatch);
  2256. isc_socket_attach(sock, &client->udpsocket);
  2257. }
  2258. client->manager = manager;
  2259. ISC_LIST_APPEND(manager->active, client, link);
  2260. client->list = &manager->active;
  2261. INSIST(client->nctls == 0);
  2262. client->nctls++;
  2263. ev = &client->ctlevent;
  2264. isc_task_send(client->task, &ev);
  2265. }
  2266. if (i != 0) {
  2267. /*
  2268. * We managed to create at least one client, so we
  2269. * declare victory.
  2270. */
  2271. result = ISC_R_SUCCESS;
  2272. }
  2273. UNLOCK(&manager->lock);
  2274. return (result);
  2275. }
  2276. isc_sockaddr_t *
  2277. ns_client_getsockaddr(ns_client_t *client) {
  2278. return (&client->peeraddr);
  2279. }
  2280. isc_result_t
  2281. ns_client_checkaclsilent(ns_client_t *client, isc_netaddr_t *netaddr,
  2282. dns_acl_t *acl, isc_boolean_t default_allow)
  2283. {
  2284. isc_result_t result;
  2285. isc_netaddr_t tmpnetaddr;
  2286. int match;
  2287. if (acl == NULL) {
  2288. if (default_allow)
  2289. goto allow;
  2290. else
  2291. goto deny;
  2292. }
  2293. if (netaddr == NULL) {
  2294. isc_netaddr_fromsockaddr(&tmpnetaddr, &client->peeraddr);
  2295. netaddr = &tmpnetaddr;
  2296. }
  2297. result = dns_acl_match(netaddr, client->signer, acl,
  2298. &ns_g_server->aclenv, &match, NULL);
  2299. if (result != ISC_R_SUCCESS)
  2300. goto deny; /* Internal error, already logged. */
  2301. if (match > 0)
  2302. goto allow;
  2303. goto deny; /* Negative match or no match. */
  2304. allow:
  2305. return (ISC_R_SUCCESS);
  2306. deny:
  2307. return (DNS_R_REFUSED);
  2308. }
  2309. isc_result_t
  2310. ns_client_checkacl(ns_client_t *client, isc_sockaddr_t *sockaddr,
  2311. const char *opname, dns_acl_t *acl,
  2312. isc_boolean_t default_allow, int log_level)
  2313. {
  2314. isc_result_t result;
  2315. isc_netaddr_t netaddr;
  2316. if (sockaddr != NULL)
  2317. isc_netaddr_fromsockaddr(&netaddr, sockaddr);
  2318. result = ns_client_checkaclsilent(client, sockaddr ? &netaddr : NULL,
  2319. acl, default_allow);
  2320. if (result == ISC_R_SUCCESS)
  2321. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  2322. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
  2323. "%s approved", opname);
  2324. else
  2325. ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
  2326. NS_LOGMODULE_CLIENT,
  2327. log_level, "%s denied", opname);
  2328. return (result);
  2329. }
  2330. static void
  2331. ns_client_name(ns_client_t *client, char *peerbuf, size_t len) {
  2332. if (client->peeraddr_valid)
  2333. isc_sockaddr_format(&client->peeraddr, peerbuf, len);
  2334. else
  2335. snprintf(peerbuf, len, "@%p", client);
  2336. }
  2337. void
  2338. ns_client_logv(ns_client_t *client, isc_logcategory_t *category,
  2339. isc_logmodule_t *module, int level, const char *fmt, va_list ap)
  2340. {
  2341. char msgbuf[2048];
  2342. char peerbuf[ISC_SOCKADDR_FORMATSIZE];
  2343. const char *name = "";
  2344. const char *sep = "";
  2345. vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
  2346. ns_client_name(client, peerbuf, sizeof(peerbuf));
  2347. if (client->view != NULL && strcmp(client->view->name, "_bind") != 0 &&
  2348. strcmp(client->view->name, "_default") != 0) {
  2349. name = client->view->name;
  2350. sep = ": view ";
  2351. }
  2352. isc_log_write(ns_g_lctx, category, module, level,
  2353. "client %s%s%s: %s", peerbuf, sep, name, msgbuf);
  2354. }
  2355. void
  2356. ns_client_log(ns_client_t *client, isc_logcategory_t *category,
  2357. isc_logmodule_t *module, int level, const char *fmt, ...)
  2358. {
  2359. va_list ap;
  2360. if (! isc_log_wouldlog(ns_g_lctx, level))
  2361. return;
  2362. va_start(ap, fmt);
  2363. ns_client_logv(client, category, module, level, fmt, ap);
  2364. va_end(ap);
  2365. }
  2366. void
  2367. ns_client_aclmsg(const char *msg, dns_name_t *name, dns_rdatatype_t type,
  2368. dns_rdataclass_t rdclass, char *buf, size_t len)
  2369. {
  2370. char namebuf[DNS_NAME_FORMATSIZE];
  2371. char typebuf[DNS_RDATATYPE_FORMATSIZE];
  2372. char classbuf[DNS_RDATACLASS_FORMATSIZE];
  2373. dns_name_format(name, namebuf, sizeof(namebuf));
  2374. dns_rdatatype_format(type, typebuf, sizeof(typebuf));
  2375. dns_rdataclass_format(rdclass, classbuf, sizeof(classbuf));
  2376. (void)snprintf(buf, len, "%s '%s/%s/%s'", msg, namebuf, typebuf,
  2377. classbuf);
  2378. }
  2379. static void
  2380. ns_client_dumpmessage(ns_client_t *client, const char *reason) {
  2381. isc_buffer_t buffer;
  2382. char *buf = NULL;
  2383. int len = 1024;
  2384. isc_result_t result;
  2385. /*
  2386. * Note that these are multiline debug messages. We want a newline
  2387. * to appear in the log after each message.
  2388. */
  2389. do {
  2390. buf = isc_mem_get(client->mctx, len);
  2391. if (buf == NULL)
  2392. break;
  2393. isc_buffer_init(&buffer, buf, len);
  2394. result = dns_message_totext(client->message,
  2395. &dns_master_style_debug,
  2396. 0, &buffer);
  2397. if (result == ISC_R_NOSPACE) {
  2398. isc_mem_put(client->mctx, buf, len);
  2399. len += 1024;
  2400. } else if (result == ISC_R_SUCCESS)
  2401. ns_client_log(client, NS_LOGCATEGORY_UNMATCHED,
  2402. NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(1),
  2403. "%s\n%.*s", reason,
  2404. (int)isc_buffer_usedlength(&buffer),
  2405. buf);
  2406. } while (result == ISC_R_NOSPACE);
  2407. if (buf != NULL)
  2408. isc_mem_put(client->mctx, buf, len);
  2409. }
  2410. void
  2411. ns_client_dumprecursing(FILE *f, ns_clientmgr_t *manager) {
  2412. ns_client_t *client;
  2413. char namebuf[DNS_NAME_FORMATSIZE];
  2414. char original[DNS_NAME_FORMATSIZE];
  2415. char peerbuf[ISC_SOCKADDR_FORMATSIZE];
  2416. char typebuf[DNS_RDATATYPE_FORMATSIZE];
  2417. char classbuf[DNS_RDATACLASS_FORMATSIZE];
  2418. const char *name;
  2419. const char *sep;
  2420. const char *origfor;
  2421. dns_rdataset_t *rdataset;
  2422. REQUIRE(VALID_MANAGER(manager));
  2423. LOCK(&manager->lock);
  2424. client = ISC_LIST_HEAD(manager->recursing);
  2425. while (client != NULL) {
  2426. ns_client_name(client, peerbuf, sizeof(peerbuf));
  2427. if (client->view != NULL &&
  2428. strcmp(client->view->name, "_bind") != 0 &&
  2429. strcmp(client->view->name, "_default") != 0) {
  2430. name = client->view->name;
  2431. sep = ": view ";
  2432. } else {
  2433. name = "";
  2434. sep = "";
  2435. }
  2436. dns_name_format(client->query.qname, namebuf, sizeof(namebuf));
  2437. if (client->query.qname != client->query.origqname &&
  2438. client->query.origqname != NULL) {
  2439. origfor = " for ";
  2440. dns_name_format(client->query.origqname, original,
  2441. sizeof(original));
  2442. } else {
  2443. origfor = "";
  2444. original[0] = '\0';
  2445. }
  2446. rdataset = ISC_LIST_HEAD(client->query.qname->list);
  2447. if (rdataset == NULL && client->query.origqname != NULL)
  2448. rdataset = ISC_LIST_HEAD(client->query.origqname->list);
  2449. if (rdataset != NULL) {
  2450. dns_rdatatype_format(rdataset->type, typebuf,
  2451. sizeof(typebuf));
  2452. dns_rdataclass_format(rdataset->rdclass, classbuf,
  2453. sizeof(classbuf));
  2454. } else {
  2455. strcpy(typebuf, "-");
  2456. strcpy(classbuf, "-");
  2457. }
  2458. fprintf(f, "; client %s%s%s: id %u '%s/%s/%s'%s%s "
  2459. "requesttime %d\n", peerbuf, sep, name,
  2460. client->message->id, namebuf, typebuf, classbuf,
  2461. origfor, original, client->requesttime);
  2462. client = ISC_LIST_NEXT(client, link);
  2463. }
  2464. UNLOCK(&manager->lock);
  2465. }
  2466. void
  2467. ns_client_qnamereplace(ns_client_t *client, dns_name_t *name) {
  2468. if (client->manager != NULL)
  2469. LOCK(&client->manager->lock);
  2470. if (client->query.restarts > 0) {
  2471. /*
  2472. * client->query.qname was dynamically allocated.
  2473. */
  2474. dns_message_puttempname(client->message,
  2475. &client->query.qname);
  2476. }
  2477. client->query.qname = name;
  2478. if (client->manager != NULL)
  2479. UNLOCK(&client->manager->lock);
  2480. }