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 15KB

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