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_resolver.c 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /**************************************************************************
  2. *
  3. * dns_resolver.c: Etherboot support for resolution of host/domain
  4. * names in filename parameters
  5. * Written 2004 by Anselm M. Hoffmeister
  6. * <stockholm@users.sourceforge.net>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  21. *
  22. * This code is using nuts and bolts from throughout etherboot.
  23. * It is a fresh implementation according to the DNS RFC, #1035
  24. *
  25. * $Revision$
  26. * $Author$
  27. * $Date$
  28. *
  29. * REVISION HISTORY:
  30. * ================
  31. * 2004-05-10 File created
  32. * 2004-05-19 First release to CVS
  33. * 2004-05-22 CNAME support first stage finished
  34. * 2004-05-24 First "stable" release to CVS
  35. * 2004-08-28 Improve readability, set recursion flag
  36. ***************************************************************************/
  37. #ifdef DNS_RESOLVER
  38. #include "etherboot.h"
  39. #include "nic.h"
  40. #include "dns_resolver.h"
  41. #define MAX_DNS_RETRIES 3
  42. #define MAX_CNAME_RECURSION 0x30
  43. #undef DNSDEBUG
  44. int donameresolution ( char * hostname, int hnlength, char * deststring );
  45. /*
  46. * dns_resolver
  47. * Function: Main function for name resolution - will be called by other
  48. * parts of etherboot
  49. * Param: string filename (not containing proto prefix like "tftp://")
  50. * Return: string filename, with hostname replaced by IP in dotted quad
  51. * or NULL for resolver error
  52. * In case no substitution is necessary, return will be = param
  53. * The returned string, if not == input, will be temporary and
  54. * probably be overwritten during the next call to dns_resolver
  55. * The returned string may (or may not) only contain an IP
  56. * address, or an IP followed by a ":" or "/", or be NULL(=error)
  57. */
  58. char * dns_resolver ( char * filename ) {
  59. int i = 0, j, k;
  60. static char ipaddr[16] = { 0 };
  61. // Search for "end of hostname" (which might be either ":" or "/")
  62. for ( j = i; (filename[j] != ':') && (filename[j] != '/'); ++j ) {
  63. // If no hostname delimiter was found, assume no name present
  64. if ( filename[j] == 0 ) return filename;
  65. }
  66. // Check if the filename is an IP, in which case, leave unchanged
  67. k = j - i - 1;
  68. while ( ( '.' == filename[i+k] ) ||
  69. ( ( '0' <= filename[i+k] ) && ( '9' >= filename[i+k] ) ) ) {
  70. --k;
  71. if ( k < 0 ) return filename; // Only had nums and dots->IP
  72. }
  73. // Now that we know it's a full hostname, attempt to resolve
  74. if ( donameresolution ( filename + i, j - i, ipaddr ) ) {
  75. return NULL; // Error in resolving - Fatal.
  76. }
  77. // Return the dotted-quad IP which resulted
  78. return ipaddr;
  79. }
  80. /*
  81. * await_dns
  82. * Shall be called on any incoming packet during the resolution process
  83. * (as is the case with all the other await_ functions in etherboot)
  84. * Param: as any await functions
  85. * Return: see dns_resolver.h for constant return values + descriptions
  86. */
  87. static int await_dns (int ival, void *ptr,
  88. unsigned short ptype __unused, struct iphdr *ip __unused,
  89. struct udphdr *udp, struct tcphdr *tcp __unused) {
  90. int i, j, k;
  91. unsigned char *p = (unsigned char *)udp + sizeof(struct udphdr);
  92. // p is set to the beginning of the payload
  93. unsigned char *q;
  94. unsigned int querytype = QUERYTYPE_A;
  95. if ( 0 == udp ) // Parser couldn't find UDP header
  96. return RET_PACK_GARBAG; // Not a UDP packet
  97. if (( UDP_PORT_DNS != ntohs (udp->src )) ||
  98. ( UDP_PORT_DNS != ntohs (udp->dest)) )
  99. // Neither source nor destination port is "53"
  100. return RET_PACK_GARBAG; // UDP port wrong
  101. if (( p[QINDEX_ID ] != 0) ||
  102. ( p[QINDEX_ID+1] != (ival & 0xff)))
  103. // Checking if this packet has set (inside payload)
  104. // the sequence identifier that we expect
  105. return RET_PACK_GARBAG; // Not matching our request ID
  106. if (( p[QINDEX_FLAGS ] & QUERYFLAGS_MASK ) != QUERYFLAGS_WANT )
  107. // We only accept responses to the query(ies) we sent
  108. return RET_PACK_GARBAG; // Is not response=opcode <0>
  109. querytype = (ival & 0xff00) >> 8;
  110. if (((p[QINDEX_NUMANSW+1] + (p[QINDEX_NUMANSW+1]<<8)) == 0 ) ||
  111. ( ERR_NOSUCHNAME == (p[QINDEX_FLAGS+1] & 0x0f) ) ) {
  112. // Answer section has 0 entries, or "no such name" returned
  113. if ( QUERYTYPE_A == querytype) {
  114. // It was an A type query, so we should try if there's
  115. // an alternative "CNAME" record available
  116. return RET_RUN_CNAME_Q; // So try CNAME query next
  117. } else if ( QUERYTYPE_CNAME == querytype) {
  118. // There's no CNAME either, so give up
  119. return RET_NOSUCHNAME;
  120. } else {
  121. // Anything else? No idea what. Should not happen.
  122. return RET_NOSUCHNAME; // Bail out with error
  123. }
  124. }
  125. if ( 0 != ( p[QINDEX_FLAGS+1] & 0x0f ) )
  126. // The response packet's flag section tells us:
  127. return RET_NOSUCHNAME; // Another (unspecific) error occured
  128. // Now we have an answer packet in response to our query. Next thing
  129. // to do is to search the payload for the "answer section", as there is
  130. // a question section first usually that needs to be skipped
  131. // If question section was not repeated, that saves a lot of work :
  132. if ( 0 >= (i = ((p[QINDEX_NUMQUEST] << 8) + p[QINDEX_NUMQUEST+1]))) {
  133. q = p+ QINDEX_QUESTION; // No question section, just continue;
  134. } else if ( i >= 2 ) { // More than one query section? Error!
  135. return RET_NOSUCHNAME; // That's invalid for us anyway -
  136. // We only place one query at a time
  137. } else {
  138. // We have to skip through the question section first to
  139. // find the beginning of the answer section
  140. q = p + QINDEX_QUESTION;
  141. while ( 0 != q[0] )
  142. q += q[0] + 1; // Skip through
  143. q += 5; // Skip over end-\0 and query type section
  144. }
  145. // Now our pointer shows the beginning of the answer section
  146. // So now move it past the (repeated) query string, we only
  147. // want the answer
  148. while ( 0 != q[0] ) {
  149. if ( 0xc0 == ( q[0] & 0xc0 ) ) { // Pointer
  150. ++q;
  151. break;
  152. }
  153. q += q[0] + 1;
  154. }
  155. ++q;
  156. // Now check wether it's an INET host address (resp. CNAME)?
  157. // There seem to be nameservers out there (Bind 9, for example),
  158. // that return CNAMEs when no As are there, e.g. in
  159. // testname.test. IN CNAME othername.test.
  160. // case, bind 9 would return the CNAME record on an A query.
  161. // Accept this case as it saves a lot of work (an extra query)
  162. if (( QUERYTYPE_CNAME == q[1] ) &&
  163. ( QUERYTYPE_A == querytype )) {
  164. // A query, but CNAME response.
  165. // Do simulate having done a CNAME query now and just assume
  166. // the answer we are working on here is that of a CNAME query
  167. // This works for single-depth CNAMEs fine.
  168. // For deeper recursion, we won't parse the answer
  169. // packet deeper but rely on a separate CNAME query
  170. querytype = QUERYTYPE_CNAME;
  171. }
  172. // Now check wether the answer packet is of the expected type
  173. // (remember, we just tweaked CNAME answers to A queries already)
  174. if ( (q[0] != 0) ||
  175. (q[1] != querytype) || // query type matches?
  176. (q[2] != ((QUERYCLASS_INET & 0xff00) >> 8)) ||
  177. (q[3] != (QUERYCLASS_INET & 0x00ff))) { // class IN response?
  178. return RET_DNSERROR; // Should not happen. DNS server bad?
  179. }
  180. q += 8; // skip querytype/-class/ttl which are uninteresting now
  181. if ( querytype == QUERYTYPE_A ) {
  182. // So what we sent was an A query - expect an IPv4 address
  183. // Check if datalength looks satisfactory
  184. if ( ( 0 != q[0] ) || ( 4 != q[1] ) ) {
  185. // Data length is not 4 bytes
  186. return RET_DNSERROR;
  187. }
  188. // Go to the IP address and copy it to the response buffer
  189. p = ptr + QINDEX_STORE_A;
  190. for ( i = 0; i < 4; ++i ) {
  191. p[i] = q[i+2];
  192. }
  193. return RET_GOT_ADDR; // OK! Address RETURNED! VERY FINE!
  194. } else if ( querytype == QUERYTYPE_CNAME ) { // CNAME QUERY
  195. // The pointer "q" now stands on the "payload length" of the
  196. // CNAME data [2 byte field]. We will have to check wether this
  197. // name is referenced in a following response, which would save
  198. // us further queries, or if it is standalone, which calls for
  199. // making a separate query
  200. // This statement above probably needs clarification. To help
  201. // the reader understand what's going on, imagine the DNS
  202. // answer to be 4-section: query(repeating what we sent to the
  203. // DNS server), answer(like the CNAME record we wanted),
  204. // additional (which might hold the A for the CNAME - esp.
  205. // Bind9 seems to provide us with this info when we didn't
  206. // query for it yet) and authoritative (the DNS server's info
  207. // on who is responsible for that data). For compression's
  208. // sake, instead of specifying the full hostname string all
  209. // the time, one can instead specify something like "same as on
  210. // payload offset 0x123" - if this happens here, we can check
  211. // if that payload offset given here by coincidence is that of
  212. // an additional "A" record which saves us sending a separate
  213. // query.
  214. // We will look if there's a/ two or more answer sections
  215. // AND b/ the next is a reference to us.
  216. p = (unsigned char *)udp + sizeof(struct udphdr);
  217. i = q + 2 - p;
  218. if ( p[7] > 1 ) { // More than one answer section
  219. // Check the next if it's a ref
  220. // For that, we have to locate the next. Do this with "q".
  221. p = q + (q[0] * 0x100) + q[1] + 2;
  222. if ( (p[0] == (0xc0 + ((i & 0xf00)/256))) &&
  223. (p[1] == (i & 0xff) ) &&
  224. (p[2] == ((QUERYTYPE_A & 0xff00) >> 8)) &&
  225. (p[3] == (QUERYTYPE_A & 0x00ff)) &&
  226. (p[4] == ((QUERYCLASS_INET & 0xff00) >> 8 )) &&
  227. (p[5] == (QUERYCLASS_INET & 0x00ff)) &&
  228. (p[10]== 0) && // Data length expected
  229. (p[11]== 4)) { // to be <4> (IP-addr)
  230. // Behind that sections: TTL, data length(4)
  231. for ( i = 0; i < 4; ++i ) {
  232. ((unsigned char*)ptr)[QINDEX_STORE_A+i] =
  233. p[12+i];
  234. }
  235. return RET_GOT_ADDR;
  236. }
  237. }
  238. // Reference not found, next query (A) needed (because CNAME
  239. // queries usually return another hostname, not an IP address
  240. // as we need it - that's the point in CNAME, anyway :-)
  241. p = (unsigned char *)udp + sizeof(struct udphdr);
  242. #ifdef DNSDEBUG
  243. printf ( " ->[");
  244. #endif
  245. k = QINDEX_QUESTION;
  246. i = (q-p) + 2;
  247. // Compose the hostname that needs to be queried for
  248. // This looks complicated (and is a little bit) because
  249. // we might not be able to copy verbatim, but need to
  250. // check wether the CNAME looks like
  251. // "servername" "plus what offset 0x123 of the payload says"
  252. // (this saves transfer bandwidth, which is why DNS allows
  253. // this, but it makes programmers' lives more difficult)
  254. while (p[i] != 0) {
  255. if ( (((unsigned char *)p)[i] & 0xc0) != 0 ) {
  256. i = ((p[i] & 0x3f) * 0x100) + p[i+1];
  257. continue;
  258. }
  259. ((unsigned char *)ptr)[k] = p[i];
  260. for ( j = i + 1; j <= i + p[i]; ++j ) {
  261. ((unsigned char *)ptr)[k+j-i] = p[j];
  262. #ifdef DNSDEBUG
  263. printf ( "%c", p[j] );
  264. #endif
  265. }
  266. k += ((unsigned char *)ptr)[k] + 1;
  267. i += p[i] + 1;
  268. #ifdef DNSDEBUG
  269. printf ( (p[i] ? ".": "") );
  270. #endif
  271. }
  272. ((unsigned char *)ptr)[k] = 0;
  273. #ifdef DNSDEBUG
  274. printf ( "].." );
  275. #endif
  276. // So we need to run another query, this time try to
  277. // get an "A" record for the hostname that the last CNAME
  278. // query pointed to
  279. return RET_RUN_NEXT_A;
  280. }
  281. // We only accept CNAME or A replies from the nameserver, every-
  282. // thing else is of no use for us.
  283. // Must be an invalid packet that the nameserver sent.
  284. return RET_DNSERROR;
  285. }
  286. int chars_to_next_dot ( char * countfrom, int maxnum ) {
  287. // Count the number of characters of this part of a hostname
  288. int i;
  289. for ( i = 1; i < maxnum; ++i ) {
  290. if ( countfrom[i] == '.' ) return i;
  291. }
  292. return maxnum;
  293. }
  294. /*
  295. * donameresolution
  296. * Function: Compose the initial query packet, handle answers until
  297. * a/ an IP address is retrieved
  298. * b/ too many CNAME references occured (max. MAX_DNS_RETRIES)
  299. * c/ No matching record for A or CNAME can be found
  300. * Param: string hostname, length (hostname needs no \0-end-marker),
  301. * string to which dotted-quad-IP shall be written
  302. * Return: 0 for success, >0 for failure
  303. */
  304. int donameresolution ( char * hostname, int hnlength, char * deststring ) {
  305. unsigned char querybuf[260+sizeof(struct iphdr)+sizeof(struct udphdr)];
  306. // 256 for the DNS query payload, +4 for the result temporary
  307. unsigned char *query = &querybuf[sizeof(struct iphdr)+sizeof(struct udphdr)];
  308. // Pointer to the payload
  309. int i, h = hnlength;
  310. long timeout;
  311. int retry, recursion;
  312. // Setup the query data
  313. query[QINDEX_ID ] = (QUERYIDENTIFIER & 0xff00) >> 8;
  314. query[QINDEX_ID+1] = QUERYIDENTIFIER & 0xff;
  315. query[QINDEX_FLAGS ] = (QUERYFLAGS & 0xff00) >> 8;
  316. query[QINDEX_FLAGS+1] = QUERYFLAGS & 0xff;
  317. query[QINDEX_NUMQUEST ]= 0;
  318. query[QINDEX_NUMQUEST+1]= 1; // 1 standard query to be sent
  319. query[QINDEX_NUMANSW ] = 0;
  320. query[QINDEX_NUMANSW+1] = 0;
  321. query[QINDEX_NUMAUTH ] = 0;
  322. query[QINDEX_NUMAUTH+1] = 0;
  323. query[QINDEX_NUMADDIT ]= 0;
  324. query[QINDEX_NUMADDIT+1]= 0;
  325. query[QINDEX_QUESTION] = chars_to_next_dot(hostname,h);
  326. if ( h > 236 ) return 1; // Hostnames longer than 236 chars are refused.
  327. // This is an arbitrary decision, SHOULD check
  328. // what the RFCs say about that
  329. for ( i = 0; i < h; ++i ) {
  330. // Compose the query section's hostname - replacing dots (and
  331. // preceding the string) with one-byte substring-length values
  332. // (for the immediately following substring) - \0 terminated
  333. query[QINDEX_QUESTION+i+1] = hostname[i];
  334. if ( hostname[i] == '.' )
  335. query[QINDEX_QUESTION+i+1] = chars_to_next_dot(hostname + i + 1, h - i - 1);
  336. }
  337. query[QINDEX_QTYPE+h ] = (QUERYTYPE_A & 0xff00) >> 8;
  338. query[QINDEX_QTYPE+h+1] = QUERYTYPE_A & 0xff;
  339. // First try an A query, if that
  340. // won't work, try CNAME
  341. printf ( "Resolving hostname [" );
  342. for ( i = 0; i < hnlength; ++i ) { printf ( "%c", hostname[i] ); }
  343. printf ("]" );
  344. for ( recursion = MAX_CNAME_RECURSION; recursion > 0; --recursion ) {
  345. printf ( ".." );
  346. // Try MAX_CNAME_RECURSION CNAME queries maximally, if then no
  347. // A record is found, assume the hostname to not be resolvable
  348. query[QINDEX_QUESTION+h+1] = 0; // Marks the end of
  349. // the query string
  350. query[QINDEX_QCLASS+h ]= (QUERYCLASS_INET & 0xff00) >> 8;
  351. query[QINDEX_QCLASS+h+1]= QUERYCLASS_INET & 0xff;
  352. rx_qdrain(); // Clear NIC packet buffer -
  353. // there won't be anything of interest *now*.
  354. udp_transmit ( arptable[ARP_NAMESERVER].ipaddr.s_addr,
  355. UDP_PORT_DNS, UDP_PORT_DNS,
  356. hnlength + 18 + sizeof(struct iphdr) +
  357. sizeof(struct udphdr), querybuf );
  358. // If no answer comes in in a certain period of time, retry
  359. for (retry = 1; retry <= MAX_DNS_RETRIES; retry++) {
  360. timeout = rfc2131_sleep_interval(TIMEOUT, retry);
  361. i = await_reply ( await_dns,
  362. (query[QINDEX_QTYPE+h+1] << 8) +
  363. ((unsigned char *)query)[QINDEX_ID+1],
  364. query, timeout);
  365. // The parameters given are
  366. // bits 15...8 of integer = Query type (low bits)
  367. // bits 7...0 of integer = Query index (low bits)
  368. // query + QINDEX_STORE_A points to the place
  369. // where A records shall be stored (4 bytes);
  370. // query + 12(QINDEX_QUESTION) points to where
  371. // a CNAME should go in case one is received
  372. if (i) break;
  373. }
  374. switch ( i ) {
  375. case RET_GOT_ADDR: // Address successfully retrieved
  376. sprintf( deststring, "%@",
  377. (long)query[QINDEX_STORE_A ] +
  378. ( (long)query[QINDEX_STORE_A+1] * 256 ) +
  379. ( (long)query[QINDEX_STORE_A+2] * 65536 )+
  380. ( (long)query[QINDEX_STORE_A+3] * 16777216 ));
  381. printf ( " -> IP [%s]\n", deststring );
  382. return RET_DNS_OK;
  383. case RET_RUN_CNAME_Q: // No A record found, try CNAME
  384. query[QINDEX_QTYPE+h ]=(QUERYTYPE_CNAME & 0xff00)>> 8;
  385. query[QINDEX_QTYPE+h+1]= QUERYTYPE_CNAME & 0xff;
  386. break;
  387. case RET_RUN_NEXT_A:
  388. // Found a CNAME, now try A for the name it pointed to
  389. for ( i = 0; query[QINDEX_QUESTION+i] != 0;
  390. i += query[QINDEX_QUESTION+i] + 1 ) {;}
  391. h = i - 1;
  392. query[QINDEX_QTYPE+h ]=(QUERYTYPE_A & 0xff00)>> 8;
  393. query[QINDEX_QTYPE+h+1]= QUERYTYPE_A & 0xff;
  394. break;
  395. case RET_CNAME_FAIL:
  396. // Neither A nor CNAME gave a usable result
  397. printf ("Host name cannot be resolved\n");
  398. return RET_DNS_FAIL;
  399. case RET_NOSUCHNAME:
  400. default:
  401. printf ( "Name resolution failed\n" );
  402. return RET_DNS_FAIL;
  403. }
  404. query[QINDEX_ID ] = 0; // We will probably never have more
  405. // than 256 queries in one run
  406. query[QINDEX_ID+1]++;
  407. }
  408. // To deep recursion
  409. printf ( "CNAME recursion to deep - abort name resolver\n" );
  410. return RET_DNS_FAIL;
  411. }
  412. #endif /* DNS_RESOLVER */