dns.c 13KB

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