You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dns.c 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /*
  2. * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
  3. *
  4. * Portions copyright (C) 2004 Anselm M. Hoffmeister
  5. * <stockholm@users.sourceforge.net>.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; either version 2 of the
  10. * License, or any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  20. * 02110-1301, USA.
  21. */
  22. FILE_LICENCE ( GPL2_OR_LATER );
  23. #include <stdint.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdio.h>
  27. #include <errno.h>
  28. #include <byteswap.h>
  29. #include <ipxe/refcnt.h>
  30. #include <ipxe/iobuf.h>
  31. #include <ipxe/xfer.h>
  32. #include <ipxe/open.h>
  33. #include <ipxe/resolv.h>
  34. #include <ipxe/retry.h>
  35. #include <ipxe/tcpip.h>
  36. #include <ipxe/settings.h>
  37. #include <ipxe/features.h>
  38. #include <ipxe/dns.h>
  39. /** @file
  40. *
  41. * DNS protocol
  42. *
  43. */
  44. FEATURE ( FEATURE_PROTOCOL, "DNS", DHCP_EB_FEATURE_DNS, 1 );
  45. /* Disambiguate the various error causes */
  46. #define ENXIO_NO_RECORD __einfo_error ( EINFO_ENXIO_NO_RECORD )
  47. #define EINFO_ENXIO_NO_RECORD \
  48. __einfo_uniqify ( EINFO_ENXIO, 0x01, "DNS name does not exist" )
  49. #define ENXIO_NO_NAMESERVER __einfo_error ( EINFO_ENXIO_NO_NAMESERVER )
  50. #define EINFO_ENXIO_NO_NAMESERVER \
  51. __einfo_uniqify ( EINFO_ENXIO, 0x02, "No DNS servers available" )
  52. /** The DNS server */
  53. static struct sockaddr_tcpip nameserver = {
  54. .st_port = htons ( DNS_PORT ),
  55. };
  56. /** The local domain */
  57. static char *localdomain;
  58. /** A DNS request */
  59. struct dns_request {
  60. /** Reference counter */
  61. struct refcnt refcnt;
  62. /** Name resolution interface */
  63. struct interface resolv;
  64. /** Data transfer interface */
  65. struct interface socket;
  66. /** Retry timer */
  67. struct retry_timer timer;
  68. /** Socket address to fill in with resolved address */
  69. struct sockaddr sa;
  70. /** Current query packet */
  71. struct dns_query query;
  72. /** Location of query info structure within current packet
  73. *
  74. * The query info structure is located immediately after the
  75. * compressed name.
  76. */
  77. struct dns_query_info *qinfo;
  78. /** Recursion counter */
  79. unsigned int recursion;
  80. };
  81. /**
  82. * Mark DNS request as complete
  83. *
  84. * @v dns DNS request
  85. * @v rc Return status code
  86. */
  87. static void dns_done ( struct dns_request *dns, int rc ) {
  88. /* Stop the retry timer */
  89. stop_timer ( &dns->timer );
  90. /* Shut down interfaces */
  91. intf_shutdown ( &dns->socket, rc );
  92. intf_shutdown ( &dns->resolv, rc );
  93. }
  94. /**
  95. * Compare DNS reply name against the query name from the original request
  96. *
  97. * @v dns DNS request
  98. * @v reply DNS reply
  99. * @v rname Reply name
  100. * @ret zero Names match
  101. * @ret non-zero Names do not match
  102. */
  103. static int dns_name_cmp ( struct dns_request *dns,
  104. const struct dns_header *reply,
  105. const char *rname ) {
  106. const char *qname = dns->query.payload;
  107. int i;
  108. while ( 1 ) {
  109. /* Obtain next section of rname */
  110. while ( ( *rname ) & 0xc0 ) {
  111. rname = ( ( ( char * ) reply ) +
  112. ( ntohs( *((uint16_t *)rname) ) & ~0xc000 ));
  113. }
  114. /* Check that lengths match */
  115. if ( *rname != *qname )
  116. return -1;
  117. /* If length is zero, we have reached the end */
  118. if ( ! *qname )
  119. return 0;
  120. /* Check that data matches */
  121. for ( i = *qname + 1; i > 0 ; i-- ) {
  122. if ( *(rname++) != *(qname++) )
  123. return -1;
  124. }
  125. }
  126. }
  127. /**
  128. * Skip over a (possibly compressed) DNS name
  129. *
  130. * @v name DNS name
  131. * @ret name Next DNS name
  132. */
  133. static const char * dns_skip_name ( const char *name ) {
  134. while ( 1 ) {
  135. if ( ! *name ) {
  136. /* End of name */
  137. return ( name + 1);
  138. }
  139. if ( *name & 0xc0 ) {
  140. /* Start of a compressed name */
  141. return ( name + 2 );
  142. }
  143. /* Uncompressed name portion */
  144. name += *name + 1;
  145. }
  146. }
  147. /**
  148. * Find an RR in a reply packet corresponding to our query
  149. *
  150. * @v dns DNS request
  151. * @v reply DNS reply
  152. * @ret rr DNS RR, or NULL if not found
  153. */
  154. static union dns_rr_info * dns_find_rr ( struct dns_request *dns,
  155. const struct dns_header *reply ) {
  156. int i, cmp;
  157. const char *p = ( ( char * ) reply ) + sizeof ( struct dns_header );
  158. union dns_rr_info *rr_info;
  159. /* Skip over the questions section */
  160. for ( i = ntohs ( reply->qdcount ) ; i > 0 ; i-- ) {
  161. p = dns_skip_name ( p ) + sizeof ( struct dns_query_info );
  162. }
  163. /* Process the answers section */
  164. for ( i = ntohs ( reply->ancount ) ; i > 0 ; i-- ) {
  165. cmp = dns_name_cmp ( dns, reply, p );
  166. p = dns_skip_name ( p );
  167. rr_info = ( ( union dns_rr_info * ) p );
  168. if ( cmp == 0 )
  169. return rr_info;
  170. p += ( sizeof ( rr_info->common ) +
  171. ntohs ( rr_info->common.rdlength ) );
  172. }
  173. return NULL;
  174. }
  175. /**
  176. * Append DHCP domain name if available and name is not fully qualified
  177. *
  178. * @v string Name as a NUL-terminated string
  179. * @ret fqdn Fully-qualified domain name, malloc'd copy
  180. *
  181. * The caller must free fqdn which is allocated even if the name is already
  182. * fully qualified.
  183. */
  184. static char * dns_qualify_name ( const char *string ) {
  185. char *fqdn;
  186. /* Leave unchanged if already fully-qualified or no local domain */
  187. if ( ( ! localdomain ) || ( strchr ( string, '.' ) != NULL ) )
  188. return strdup ( string );
  189. /* Append local domain to name */
  190. asprintf ( &fqdn, "%s.%s", string, localdomain );
  191. return fqdn;
  192. }
  193. /**
  194. * Convert a standard NUL-terminated string to a DNS name
  195. *
  196. * @v string Name as a NUL-terminated string
  197. * @v buf Buffer in which to place DNS name
  198. * @ret next Byte following constructed DNS name
  199. *
  200. * DNS names consist of "<length>element" pairs.
  201. */
  202. static char * dns_make_name ( const char *string, char *buf ) {
  203. char *length_byte;
  204. char c;
  205. length_byte = buf++;
  206. *length_byte = 0;
  207. do {
  208. c = *(string++);
  209. if ( ( c == '.' ) || ( c == '\0' ) ) {
  210. if ( *length_byte ) {
  211. length_byte = buf++;
  212. *length_byte = 0;
  213. }
  214. } else {
  215. *(buf++) = c;
  216. (*length_byte)++;
  217. }
  218. } while ( c );
  219. return buf;
  220. }
  221. /**
  222. * Convert an uncompressed DNS name to a NUL-terminated string
  223. *
  224. * @v name DNS name
  225. * @ret string NUL-terminated string
  226. *
  227. * Produce a printable version of a DNS name. Used only for debugging.
  228. */
  229. static inline char * dns_unmake_name ( char *name ) {
  230. char *p;
  231. unsigned int len;
  232. p = name;
  233. while ( ( len = *p ) ) {
  234. *(p++) = '.';
  235. p += len;
  236. }
  237. return name + 1;
  238. }
  239. /**
  240. * Decompress a DNS name
  241. *
  242. * @v reply DNS replay
  243. * @v name DNS name
  244. * @v buf Buffer into which to decompress DNS name
  245. * @ret next Byte following decompressed DNS name
  246. */
  247. static char * dns_decompress_name ( const struct dns_header *reply,
  248. const char *name, char *buf ) {
  249. int i, len;
  250. do {
  251. /* Obtain next section of name */
  252. while ( ( *name ) & 0xc0 ) {
  253. name = ( ( char * ) reply +
  254. ( ntohs ( *((uint16_t *)name) ) & ~0xc000 ) );
  255. }
  256. /* Copy data */
  257. len = *name;
  258. for ( i = len + 1 ; i > 0 ; i-- ) {
  259. *(buf++) = *(name++);
  260. }
  261. } while ( len );
  262. return buf;
  263. }
  264. /**
  265. * Send next packet in DNS request
  266. *
  267. * @v dns DNS request
  268. */
  269. static int dns_send_packet ( struct dns_request *dns ) {
  270. static unsigned int qid = 0;
  271. size_t qlen;
  272. /* Increment query ID */
  273. dns->query.dns.id = htons ( ++qid );
  274. DBGC ( dns, "DNS %p sending query ID %d\n", dns, qid );
  275. /* Start retransmission timer */
  276. start_timer ( &dns->timer );
  277. /* Send the data */
  278. qlen = ( ( ( void * ) dns->qinfo ) - ( ( void * ) &dns->query )
  279. + sizeof ( dns->qinfo ) );
  280. return xfer_deliver_raw ( &dns->socket, &dns->query, qlen );
  281. }
  282. /**
  283. * Handle DNS retransmission timer expiry
  284. *
  285. * @v timer Retry timer
  286. * @v fail Failure indicator
  287. */
  288. static void dns_timer_expired ( struct retry_timer *timer, int fail ) {
  289. struct dns_request *dns =
  290. container_of ( timer, struct dns_request, timer );
  291. if ( fail ) {
  292. dns_done ( dns, -ETIMEDOUT );
  293. } else {
  294. dns_send_packet ( dns );
  295. }
  296. }
  297. /**
  298. * Receive new data
  299. *
  300. * @v dns DNS request
  301. * @v iobuf I/O buffer
  302. * @v meta Data transfer metadata
  303. * @ret rc Return status code
  304. */
  305. static int dns_xfer_deliver ( struct dns_request *dns,
  306. struct io_buffer *iobuf,
  307. struct xfer_metadata *meta __unused ) {
  308. const struct dns_header *reply = iobuf->data;
  309. union dns_rr_info *rr_info;
  310. struct sockaddr_in *sin;
  311. unsigned int qtype = dns->qinfo->qtype;
  312. int rc;
  313. /* Sanity check */
  314. if ( iob_len ( iobuf ) < sizeof ( *reply ) ) {
  315. DBGC ( dns, "DNS %p received underlength packet length %zd\n",
  316. dns, iob_len ( iobuf ) );
  317. rc = -EINVAL;
  318. goto done;
  319. }
  320. /* Check reply ID matches query ID */
  321. if ( reply->id != dns->query.dns.id ) {
  322. DBGC ( dns, "DNS %p received unexpected reply ID %d "
  323. "(wanted %d)\n", dns, ntohs ( reply->id ),
  324. ntohs ( dns->query.dns.id ) );
  325. rc = -EINVAL;
  326. goto done;
  327. }
  328. DBGC ( dns, "DNS %p received reply ID %d\n", dns, ntohs ( reply->id ));
  329. /* Stop the retry timer. After this point, each code path
  330. * must either restart the timer by calling dns_send_packet(),
  331. * or mark the DNS operation as complete by calling
  332. * dns_done()
  333. */
  334. stop_timer ( &dns->timer );
  335. /* Search through response for useful answers. Do this
  336. * multiple times, to take advantage of useful nameservers
  337. * which send us e.g. the CNAME *and* the A record for the
  338. * pointed-to name.
  339. */
  340. while ( ( rr_info = dns_find_rr ( dns, reply ) ) ) {
  341. switch ( rr_info->common.type ) {
  342. case htons ( DNS_TYPE_A ):
  343. /* Found the target A record */
  344. DBGC ( dns, "DNS %p found address %s\n",
  345. dns, inet_ntoa ( rr_info->a.in_addr ) );
  346. sin = ( struct sockaddr_in * ) &dns->sa;
  347. sin->sin_family = AF_INET;
  348. sin->sin_addr = rr_info->a.in_addr;
  349. /* Return resolved address */
  350. resolv_done ( &dns->resolv, &dns->sa );
  351. /* Mark operation as complete */
  352. dns_done ( dns, 0 );
  353. rc = 0;
  354. goto done;
  355. case htons ( DNS_TYPE_CNAME ):
  356. /* Found a CNAME record; update query and recurse */
  357. DBGC ( dns, "DNS %p found CNAME\n", dns );
  358. dns->qinfo = ( void * ) dns_decompress_name ( reply,
  359. rr_info->cname.cname,
  360. dns->query.payload );
  361. dns->qinfo->qtype = htons ( DNS_TYPE_A );
  362. dns->qinfo->qclass = htons ( DNS_CLASS_IN );
  363. /* Terminate the operation if we recurse too far */
  364. if ( ++dns->recursion > DNS_MAX_CNAME_RECURSION ) {
  365. DBGC ( dns, "DNS %p recursion exceeded\n",
  366. dns );
  367. dns_done ( dns, -ELOOP );
  368. rc = 0;
  369. goto done;
  370. }
  371. break;
  372. default:
  373. DBGC ( dns, "DNS %p got unknown record type %d\n",
  374. dns, ntohs ( rr_info->common.type ) );
  375. break;
  376. }
  377. }
  378. /* Determine what to do next based on the type of query we
  379. * issued and the response we received
  380. */
  381. switch ( qtype ) {
  382. case htons ( DNS_TYPE_A ):
  383. /* We asked for an A record and got nothing;
  384. * try the CNAME.
  385. */
  386. DBGC ( dns, "DNS %p found no A record; trying CNAME\n", dns );
  387. dns->qinfo->qtype = htons ( DNS_TYPE_CNAME );
  388. dns_send_packet ( dns );
  389. rc = 0;
  390. goto done;
  391. case htons ( DNS_TYPE_CNAME ):
  392. /* We asked for a CNAME record. If we got a response
  393. * (i.e. if the next A query is already set up), then
  394. * issue it, otherwise abort.
  395. */
  396. if ( dns->qinfo->qtype == htons ( DNS_TYPE_A ) ) {
  397. dns_send_packet ( dns );
  398. rc = 0;
  399. goto done;
  400. } else {
  401. DBGC ( dns, "DNS %p found no CNAME record\n", dns );
  402. dns_done ( dns, -ENXIO_NO_RECORD );
  403. rc = 0;
  404. goto done;
  405. }
  406. default:
  407. assert ( 0 );
  408. dns_done ( dns, -EINVAL );
  409. rc = -EINVAL;
  410. goto done;
  411. }
  412. done:
  413. /* Free I/O buffer */
  414. free_iob ( iobuf );
  415. return rc;
  416. }
  417. /**
  418. * Receive new data
  419. *
  420. * @v dns DNS request
  421. * @v rc Reason for close
  422. */
  423. static void dns_xfer_close ( struct dns_request *dns, int rc ) {
  424. if ( ! rc )
  425. rc = -ECONNABORTED;
  426. dns_done ( dns, rc );
  427. }
  428. /** DNS socket interface operations */
  429. static struct interface_operation dns_socket_operations[] = {
  430. INTF_OP ( xfer_deliver, struct dns_request *, dns_xfer_deliver ),
  431. INTF_OP ( intf_close, struct dns_request *, dns_xfer_close ),
  432. };
  433. /** DNS socket interface descriptor */
  434. static struct interface_descriptor dns_socket_desc =
  435. INTF_DESC ( struct dns_request, socket, dns_socket_operations );
  436. /** DNS resolver interface operations */
  437. static struct interface_operation dns_resolv_op[] = {
  438. INTF_OP ( intf_close, struct dns_request *, dns_done ),
  439. };
  440. /** DNS resolver interface descriptor */
  441. static struct interface_descriptor dns_resolv_desc =
  442. INTF_DESC ( struct dns_request, resolv, dns_resolv_op );
  443. /**
  444. * Resolve name using DNS
  445. *
  446. * @v resolv Name resolution interface
  447. * @v name Name to resolve
  448. * @v sa Socket address to fill in
  449. * @ret rc Return status code
  450. */
  451. static int dns_resolv ( struct interface *resolv,
  452. const char *name, struct sockaddr *sa ) {
  453. struct dns_request *dns;
  454. char *fqdn;
  455. int rc;
  456. /* Fail immediately if no DNS servers */
  457. if ( ! nameserver.st_family ) {
  458. DBG ( "DNS not attempting to resolve \"%s\": "
  459. "no DNS servers\n", name );
  460. rc = -ENXIO_NO_NAMESERVER;
  461. goto err_no_nameserver;
  462. }
  463. /* Ensure fully-qualified domain name if DHCP option was given */
  464. fqdn = dns_qualify_name ( name );
  465. if ( ! fqdn ) {
  466. rc = -ENOMEM;
  467. goto err_qualify_name;
  468. }
  469. /* Allocate DNS structure */
  470. dns = zalloc ( sizeof ( *dns ) );
  471. if ( ! dns ) {
  472. rc = -ENOMEM;
  473. goto err_alloc_dns;
  474. }
  475. ref_init ( &dns->refcnt, NULL );
  476. intf_init ( &dns->resolv, &dns_resolv_desc, &dns->refcnt );
  477. intf_init ( &dns->socket, &dns_socket_desc, &dns->refcnt );
  478. timer_init ( &dns->timer, dns_timer_expired, &dns->refcnt );
  479. memcpy ( &dns->sa, sa, sizeof ( dns->sa ) );
  480. /* Create query */
  481. dns->query.dns.flags = htons ( DNS_FLAG_QUERY | DNS_FLAG_OPCODE_QUERY |
  482. DNS_FLAG_RD );
  483. dns->query.dns.qdcount = htons ( 1 );
  484. dns->qinfo = ( void * ) dns_make_name ( fqdn, dns->query.payload );
  485. dns->qinfo->qtype = htons ( DNS_TYPE_A );
  486. dns->qinfo->qclass = htons ( DNS_CLASS_IN );
  487. /* Open UDP connection */
  488. if ( ( rc = xfer_open_socket ( &dns->socket, SOCK_DGRAM,
  489. ( struct sockaddr * ) &nameserver,
  490. NULL ) ) != 0 ) {
  491. DBGC ( dns, "DNS %p could not open socket: %s\n",
  492. dns, strerror ( rc ) );
  493. goto err_open_socket;
  494. }
  495. /* Send first DNS packet */
  496. dns_send_packet ( dns );
  497. /* Attach parent interface, mortalise self, and return */
  498. intf_plug_plug ( &dns->resolv, resolv );
  499. ref_put ( &dns->refcnt );
  500. free ( fqdn );
  501. return 0;
  502. err_open_socket:
  503. err_alloc_dns:
  504. ref_put ( &dns->refcnt );
  505. err_qualify_name:
  506. free ( fqdn );
  507. err_no_nameserver:
  508. return rc;
  509. }
  510. /** DNS name resolver */
  511. struct resolver dns_resolver __resolver ( RESOLV_NORMAL ) = {
  512. .name = "DNS",
  513. .resolv = dns_resolv,
  514. };
  515. /******************************************************************************
  516. *
  517. * Settings
  518. *
  519. ******************************************************************************
  520. */
  521. /** DNS server setting */
  522. struct setting dns_setting __setting ( SETTING_IPv4_EXTRA ) = {
  523. .name = "dns",
  524. .description = "DNS server",
  525. .tag = DHCP_DNS_SERVERS,
  526. .type = &setting_type_ipv4,
  527. };
  528. /**
  529. * Apply DNS settings
  530. *
  531. * @ret rc Return status code
  532. */
  533. static int apply_dns_settings ( void ) {
  534. struct sockaddr_in *sin_nameserver =
  535. ( struct sockaddr_in * ) &nameserver;
  536. int len;
  537. /* Fetch DNS server address */
  538. nameserver.st_family = 0;
  539. if ( ( len = fetch_ipv4_setting ( NULL, &dns_setting,
  540. &sin_nameserver->sin_addr ) ) >= 0 ){
  541. nameserver.st_family = AF_INET;
  542. DBG ( "DNS using nameserver %s\n",
  543. inet_ntoa ( sin_nameserver->sin_addr ) );
  544. }
  545. /* Get local domain DHCP option */
  546. free ( localdomain );
  547. if ( ( len = fetch_string_setting_copy ( NULL, &domain_setting,
  548. &localdomain ) ) < 0 ) {
  549. DBG ( "DNS could not fetch local domain: %s\n",
  550. strerror ( len ) );
  551. }
  552. if ( localdomain )
  553. DBG ( "DNS local domain %s\n", localdomain );
  554. return 0;
  555. }
  556. /** DNS settings applicator */
  557. struct settings_applicator dns_applicator __settings_applicator = {
  558. .apply = apply_dns_settings,
  559. };