coredns.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. /*
  2. * dnscore.c -- part of dns.mod
  3. * This file contains all core functions needed for the eggdrop dns module.
  4. * Many of them are only minimaly modified from the original source.
  5. *
  6. * Modified/written by Fabian Knittel <fknittel@gmx.de>
  7. *
  8. */
  9. /*
  10. * Borrowed from mtr -- a network diagnostic tool
  11. * Copyright (C) 1997,1998 Matt Kimball <mkimball@xmission.com>
  12. * Released under the GPL, as above.
  13. *
  14. * Non-blocking DNS portion --
  15. * Copyright (C) 1998 Simon Kirby <sim@neato.org>
  16. * Released under the GPL, as above.
  17. */
  18. #include <sys/socket.h>
  19. #include <netinet/in.h>
  20. #include <arpa/inet.h>
  21. #include <arpa/nameser.h>
  22. #include <resolv.h>
  23. #include <errno.h>
  24. /* Defines */
  25. #define BASH_SIZE 8192 /* Size of hash tables */
  26. #define HOSTNAMELEN 255 /* From RFC */
  27. #define RES_RETRYDELAY 3
  28. #define RES_MAXSENDS 4
  29. #define RES_FAILEDDELAY 600 /* TTL for failed records (in
  30. seconds). */
  31. #define RES_MAX_TTL 86400 /* Maximum TTL (in seconds). */
  32. #define RES_ERR "DNS Resolver error: "
  33. #define RES_MSG "DNS Resolver: "
  34. #define RES_WRN "DNS Resolver warning: "
  35. #define MAX_PACKETSIZE (PACKETSZ)
  36. #define MAX_DOMAINLEN (MAXDNAME)
  37. /* Macros */
  38. #define nonull(s) (s) ? s : nullstring
  39. #define BASH_MODULO(x) ((x) & 8191) /* Modulo for hash table size */
  40. /* Non-blocking nameserver interface routines */
  41. #ifdef DEBUG_DNS
  42. # define RESPONSECODES_COUNT 6
  43. static char *responsecodes[RESPONSECODES_COUNT + 1] = {
  44. "no error",
  45. "format error in query",
  46. "server failure",
  47. "queried domain name does not exist",
  48. "requested query type not implemented",
  49. "refused by name server",
  50. "unknown error",
  51. };
  52. #endif /* DEBUG_DNS */
  53. #ifdef DEBUG_DNS
  54. # define RESOURCETYPES_COUNT 17
  55. static const char *resourcetypes[RESOURCETYPES_COUNT + 1] = {
  56. "unknown type",
  57. "A: host address",
  58. "NS: authoritative name server",
  59. "MD: mail destination (OBSOLETE)",
  60. "MF: mail forwarder (OBSOLETE)",
  61. "CNAME: name alias",
  62. "SOA: authority record",
  63. "MB: mailbox domain name (EXPERIMENTAL)",
  64. "MG: mail group member (EXPERIMENTAL)",
  65. "MR: mail rename domain name (EXPERIMENTAL)",
  66. "NULL: NULL RR (EXPERIMENTAL)",
  67. "WKS: well known service description",
  68. "PTR: domain name pointer",
  69. "HINFO: host information",
  70. "MINFO: mailbox or mail list information",
  71. "MX: mail exchange",
  72. "TXT: text string",
  73. "unknown type",
  74. };
  75. #endif /* DEBUG_DNS */
  76. #ifdef DEBUG_DNS
  77. # define CLASSTYPES_COUNT 5
  78. static const char *classtypes[CLASSTYPES_COUNT + 1] = {
  79. "unknown class",
  80. "IN: the Internet",
  81. "CS: CSNET (OBSOLETE)",
  82. "CH: CHAOS",
  83. "HS: Hesoid [Dyer 87]",
  84. "unknown class"
  85. };
  86. #endif /* DEBUG_DNS */
  87. typedef struct {
  88. u_16bit_t id; /* Packet id */
  89. u_8bit_t databyte_a;
  90. /* rd:1 recursion desired
  91. * tc:1 truncated message
  92. * aa:1 authoritive answer
  93. * opcode:4 purpose of message
  94. * qr:1 response flag
  95. */
  96. u_8bit_t databyte_b;
  97. /* rcode:4 response code
  98. * unassigned:2 unassigned bits
  99. * pr:1 primary server required (non standard)
  100. * ra:1 recursion available
  101. */
  102. u_16bit_t qdcount; /* Query record count */
  103. u_16bit_t ancount; /* Answer record count */
  104. u_16bit_t nscount; /* Authority reference record count */
  105. u_16bit_t arcount; /* Resource reference record count */
  106. } packetheader;
  107. #ifndef HFIXEDSZ
  108. #define HFIXEDSZ (sizeof(packetheader))
  109. #endif
  110. /*
  111. * Byte order independent macros for packetheader
  112. */
  113. #define getheader_rd(x) (x->databyte_a & 1)
  114. #define getheader_tc(x) ((x->databyte_a >> 1) & 1)
  115. #define getheader_aa(x) ((x->databyte_a >> 2) & 1)
  116. #define getheader_opcode(x) ((x->databyte_a >> 3) & 15)
  117. #define getheader_qr(x) (x->databyte_a >> 7)
  118. #define getheader_rcode(x) (x->databyte_b & 15)
  119. #define getheader_pr(x) ((x->databyte_b >> 6) & 1)
  120. #define getheader_ra(x) (x->databyte_b >> 7)
  121. #define sucknetword(x) ((x)+=2,((u_16bit_t) (((x)[-2] << 8) | ((x)[-1] << 0))))
  122. #define sucknetshort(x) ((x)+=2,((short) (((x)[-2] << 8) | ((x)[-1] << 0))))
  123. #define sucknetdword(x) ((x)+=4,((dword) (((x)[-4] << 24) | ((x)[-3] << 16) | \
  124. ((x)[-2] << 8) | ((x)[-1] << 0))))
  125. #define sucknetlong(x) ((x)+=4,((long) (((x)[-4] << 24) | ((x)[-3] << 16) | \
  126. ((x)[-2] << 8) | ((x)[-1] << 0))))
  127. static u_32bit_t resrecvbuf[(MAX_PACKETSIZE + 7) >> 2]; /* MUST BE DWORD ALIGNED */
  128. static struct resolve *idbash[BASH_SIZE];
  129. static struct resolve *ipbash[BASH_SIZE];
  130. static struct resolve *hostbash[BASH_SIZE];
  131. static struct resolve *expireresolves = NULL;
  132. static IP localhost;
  133. static long idseed = 0xdeadbeef;
  134. static long aseed;
  135. static int resfd;
  136. static char tempstring[512];
  137. static char namestring[1024 + 1];
  138. static char stackstring[1024 + 1];
  139. #ifdef DEBUG_DNS
  140. static char sendstring[1024 + 1];
  141. #endif /* DEBUG_DNS */
  142. static const char nullstring[] = "";
  143. /*
  144. * Miscellaneous helper functions
  145. */
  146. #ifdef DEBUG_DNS
  147. /* Displays the time difference passed in signeddiff.
  148. */
  149. static char *strtdiff(char *d, long signeddiff)
  150. {
  151. u_32bit_t diff;
  152. u_32bit_t seconds, minutes, hours;
  153. long day;
  154. if ((diff = labs(signeddiff))) {
  155. seconds = diff % 60;
  156. diff /= 60;
  157. minutes = diff % 60;
  158. diff /= 60;
  159. hours = diff % 24;
  160. day = signeddiff / (60 * 60 * 24);
  161. if (day)
  162. sprintf(d, "%lid", day);
  163. else
  164. *d = '\0';
  165. if (hours)
  166. sprintf(d + strlen(d), "%uh", hours);
  167. if (minutes)
  168. sprintf(d + strlen(d), "%um", minutes);
  169. if (seconds)
  170. sprintf(d + strlen(d), "%us", seconds);
  171. } else
  172. sprintf(d, "0s");
  173. return d;
  174. }
  175. #endif /* DEBUG_DNS */
  176. /* Allocate memory to hold one resolve request structure.
  177. */
  178. static struct resolve *allocresolve()
  179. {
  180. struct resolve *rp;
  181. rp = (struct resolve *) malloc(sizeof(struct resolve));
  182. egg_bzero(rp, sizeof(struct resolve));
  183. return rp;
  184. }
  185. /*
  186. * Hash and linked-list related functions
  187. */
  188. /* Return the hash bucket number for id.
  189. */
  190. inline static u_32bit_t getidbash(u_16bit_t id)
  191. {
  192. return (u_32bit_t) BASH_MODULO(id);
  193. }
  194. /* Return the hash bucket number for ip.
  195. */
  196. inline static u_32bit_t getipbash(IP ip)
  197. {
  198. return (u_32bit_t) BASH_MODULO(ip);
  199. }
  200. /* Return the hash bucket number for host.
  201. */
  202. static u_32bit_t gethostbash(char *host)
  203. {
  204. u_32bit_t bashvalue = 0;
  205. for (; *host; host++) {
  206. bashvalue ^= *host;
  207. bashvalue += (*host >> 1) + (bashvalue >> 1);
  208. }
  209. return BASH_MODULO(bashvalue);
  210. }
  211. /* Insert request structure addrp into the id hash table.
  212. */
  213. static void linkresolveid(struct resolve *addrp)
  214. {
  215. struct resolve *rp;
  216. u_32bit_t bashnum;
  217. bashnum = getidbash(addrp->id);
  218. rp = idbash[bashnum];
  219. if (rp) {
  220. while ((rp->nextid) && (addrp->id > rp->nextid->id))
  221. rp = rp->nextid;
  222. while ((rp->previousid) && (addrp->id < rp->previousid->id))
  223. rp = rp->previousid;
  224. if (rp->id < addrp->id) {
  225. addrp->previousid = rp;
  226. addrp->nextid = rp->nextid;
  227. if (rp->nextid)
  228. rp->nextid->previousid = addrp;
  229. rp->nextid = addrp;
  230. } else if (rp->id > addrp->id) {
  231. addrp->previousid = rp->previousid;
  232. addrp->nextid = rp;
  233. if (rp->previousid)
  234. rp->previousid->nextid = addrp;
  235. rp->previousid = addrp;
  236. } else /* Trying to add the same id! */
  237. return;
  238. } else
  239. addrp->nextid = addrp->previousid = NULL;
  240. idbash[bashnum] = addrp;
  241. }
  242. /* Remove request structure rp from the id hash table.
  243. */
  244. static void unlinkresolveid(struct resolve *rp)
  245. {
  246. u_32bit_t bashnum;
  247. bashnum = getidbash(rp->id);
  248. if (idbash[bashnum] == rp) {
  249. if (rp->previousid)
  250. idbash[bashnum] = rp->previousid;
  251. else
  252. idbash[bashnum] = rp->nextid;
  253. }
  254. if (rp->nextid)
  255. rp->nextid->previousid = rp->previousid;
  256. if (rp->previousid)
  257. rp->previousid->nextid = rp->nextid;
  258. }
  259. /* Insert request structure addrp into the host hash table.
  260. */
  261. static void linkresolvehost(struct resolve *addrp)
  262. {
  263. struct resolve *rp;
  264. u_32bit_t bashnum;
  265. int ret;
  266. bashnum = gethostbash(addrp->hostn);
  267. rp = hostbash[bashnum];
  268. if (rp) {
  269. while ((rp->nexthost) &&
  270. (egg_strcasecmp(addrp->hostn, rp->nexthost->hostn) < 0))
  271. rp = rp->nexthost;
  272. while ((rp->previoushost) &&
  273. (egg_strcasecmp(addrp->hostn, rp->previoushost->hostn) > 0))
  274. rp = rp->previoushost;
  275. ret = egg_strcasecmp(addrp->hostn, rp->hostn);
  276. if (ret < 0) {
  277. addrp->previoushost = rp;
  278. addrp->nexthost = rp->nexthost;
  279. if (rp->nexthost)
  280. rp->nexthost->previoushost = addrp;
  281. rp->nexthost = addrp;
  282. } else if (ret > 0) {
  283. addrp->previoushost = rp->previoushost;
  284. addrp->nexthost = rp;
  285. if (rp->previoushost)
  286. rp->previoushost->nexthost = addrp;
  287. rp->previoushost = addrp;
  288. } else /* Trying to add the same host! */
  289. return;
  290. } else
  291. addrp->nexthost = addrp->previoushost = NULL;
  292. hostbash[bashnum] = addrp;
  293. }
  294. /* Remove request structure rp from the host hash table.
  295. */
  296. static void unlinkresolvehost(struct resolve *rp)
  297. {
  298. u_32bit_t bashnum;
  299. bashnum = gethostbash(rp->hostn);
  300. if (hostbash[bashnum] == rp) {
  301. if (rp->previoushost)
  302. hostbash[bashnum] = rp->previoushost;
  303. else
  304. hostbash[bashnum] = rp->nexthost;
  305. }
  306. if (rp->nexthost)
  307. rp->nexthost->previoushost = rp->previoushost;
  308. if (rp->previoushost)
  309. rp->previoushost->nexthost = rp->nexthost;
  310. free(rp->hostn);
  311. }
  312. /* Insert request structure addrp into the ip hash table.
  313. */
  314. static void linkresolveip(struct resolve *addrp)
  315. {
  316. struct resolve *rp;
  317. u_32bit_t bashnum;
  318. bashnum = getipbash(addrp->ip);
  319. rp = ipbash[bashnum];
  320. if (rp) {
  321. while ((rp->nextip) && (addrp->ip > rp->nextip->ip))
  322. rp = rp->nextip;
  323. while ((rp->previousip) && (addrp->ip < rp->previousip->ip))
  324. rp = rp->previousip;
  325. if (rp->ip < addrp->ip) {
  326. addrp->previousip = rp;
  327. addrp->nextip = rp->nextip;
  328. if (rp->nextip)
  329. rp->nextip->previousip = addrp;
  330. rp->nextip = addrp;
  331. } else if (rp->ip > addrp->ip) {
  332. addrp->previousip = rp->previousip;
  333. addrp->nextip = rp;
  334. if (rp->previousip)
  335. rp->previousip->nextip = addrp;
  336. rp->previousip = addrp;
  337. } else /* Trying to add the same ip! */
  338. return;
  339. } else
  340. addrp->nextip = addrp->previousip = NULL;
  341. ipbash[bashnum] = addrp;
  342. }
  343. /* Remove request structure rp from the ip hash table.
  344. */
  345. static void unlinkresolveip(struct resolve *rp)
  346. {
  347. u_32bit_t bashnum;
  348. bashnum = getipbash(rp->ip);
  349. if (ipbash[bashnum] == rp) {
  350. if (rp->previousip)
  351. ipbash[bashnum] = rp->previousip;
  352. else
  353. ipbash[bashnum] = rp->nextip;
  354. }
  355. if (rp->nextip)
  356. rp->nextip->previousip = rp->previousip;
  357. if (rp->previousip)
  358. rp->previousip->nextip = rp->nextip;
  359. }
  360. /* Add request structure rp to the expireresolves list. Entries are sorted
  361. * by expire time.
  362. */
  363. static void linkresolve(struct resolve *rp)
  364. {
  365. struct resolve *irp;
  366. if (expireresolves) {
  367. irp = expireresolves;
  368. while ((irp->next) && (rp->expiretime >= irp->expiretime))
  369. irp = irp->next;
  370. if (rp->expiretime >= irp->expiretime) {
  371. rp->next = NULL;
  372. rp->previous = irp;
  373. irp->next = rp;
  374. } else {
  375. rp->previous = irp->previous;
  376. rp->next = irp;
  377. if (irp->previous)
  378. irp->previous->next = rp;
  379. else
  380. expireresolves = rp;
  381. irp->previous = rp;
  382. }
  383. } else {
  384. rp->next = NULL;
  385. rp->previous = NULL;
  386. expireresolves = rp;
  387. }
  388. }
  389. /* Remove reqeust structure rp from the expireresolves list.
  390. */
  391. static void untieresolve(struct resolve *rp)
  392. {
  393. if (rp->previous)
  394. rp->previous->next = rp->next;
  395. else
  396. expireresolves = rp->next;
  397. if (rp->next)
  398. rp->next->previous = rp->previous;
  399. }
  400. /* Remove request structure rp from all lists and hash tables and
  401. * then delete and free the structure
  402. */
  403. static void unlinkresolve(struct resolve *rp)
  404. {
  405. untieresolve(rp); /* Not really needed. Left in to be on the
  406. safe side. */
  407. unlinkresolveid(rp);
  408. unlinkresolveip(rp);
  409. if (rp->hostn)
  410. unlinkresolvehost(rp);
  411. free(rp);
  412. }
  413. /* Find request structure using the id.
  414. */
  415. static struct resolve *findid(u_16bit_t id)
  416. {
  417. struct resolve *rp;
  418. int bashnum;
  419. bashnum = getidbash(id);
  420. rp = idbash[bashnum];
  421. if (rp) {
  422. while ((rp->nextid) && (id >= rp->nextid->id))
  423. rp = rp->nextid;
  424. while ((rp->previousid) && (id <= rp->previousid->id))
  425. rp = rp->previousid;
  426. if (id == rp->id) {
  427. idbash[bashnum] = rp;
  428. return rp;
  429. } else
  430. return NULL;
  431. }
  432. return rp; /* NULL */
  433. }
  434. /* Find request structure using the host.
  435. */
  436. static struct resolve *findhost(char *hostn)
  437. {
  438. struct resolve *rp;
  439. int bashnum;
  440. bashnum = gethostbash(hostn);
  441. rp = hostbash[bashnum];
  442. if (rp) {
  443. while ((rp->nexthost)
  444. && (egg_strcasecmp(hostn, rp->nexthost->hostn) >= 0))
  445. rp = rp->nexthost;
  446. while ((rp->previoushost)
  447. && (egg_strcasecmp(hostn, rp->previoushost->hostn) <= 0))
  448. rp = rp->previoushost;
  449. if (egg_strcasecmp(hostn, rp->hostn))
  450. return NULL;
  451. else {
  452. hostbash[bashnum] = rp;
  453. return rp;
  454. }
  455. }
  456. return rp; /* NULL */
  457. }
  458. /* Find request structure using the ip.
  459. */
  460. static struct resolve *findip(IP ip)
  461. {
  462. struct resolve *rp;
  463. u_32bit_t bashnum;
  464. bashnum = getipbash(ip);
  465. rp = ipbash[bashnum];
  466. if (rp) {
  467. while ((rp->nextip) && (ip >= rp->nextip->ip))
  468. rp = rp->nextip;
  469. while ((rp->previousip) && (ip <= rp->previousip->ip))
  470. rp = rp->previousip;
  471. if (ip == rp->ip) {
  472. ipbash[bashnum] = rp;
  473. return rp;
  474. } else
  475. return NULL;
  476. }
  477. return rp; /* NULL */
  478. }
  479. /*
  480. * Network and resolver related functions
  481. */
  482. /* Create packet for the request and send it to all available nameservers.
  483. */
  484. static void dorequest(char *s, int type, u_16bit_t id)
  485. {
  486. packetheader *hp;
  487. int r, i;
  488. u_8bit_t buf[(MAX_PACKETSIZE / sizeof(char)) + 1];
  489. r = res_mkquery(QUERY, s, C_IN, type, NULL, 0, NULL, buf,
  490. MAX_PACKETSIZE);
  491. if (r == -1) {
  492. ddebug0(RES_ERR "Query too large.");
  493. return;
  494. }
  495. hp = (packetheader *) buf;
  496. hp->id = id; /* htons() deliberately left out (redundant) */
  497. for (i = 0; i < _res.nscount; i++)
  498. (void) sendto(resfd, buf, r, 0,
  499. (struct sockaddr *) &_res.nsaddr_list[i],
  500. sizeof(struct sockaddr));
  501. }
  502. /* (Re-)send request with existing id.
  503. */
  504. static void resendrequest(struct resolve *rp, int type)
  505. {
  506. rp->sends++;
  507. /* Update expire time */
  508. rp->expiretime = now + (RES_RETRYDELAY * rp->sends);
  509. /* Add (back) to expire list */
  510. linkresolve(rp);
  511. if (type == T_A) {
  512. dorequest(rp->hostn, type, rp->id);
  513. ddebug1(RES_MSG "Sent domain lookup request for \"%s\".",
  514. rp->hostn);
  515. } else if (type == T_PTR) {
  516. sprintf(tempstring, "%u.%u.%u.%u.in-addr.arpa",
  517. ((u_8bit_t *) & rp->ip)[3],
  518. ((u_8bit_t *) & rp->ip)[2],
  519. ((u_8bit_t *) & rp->ip)[1], ((u_8bit_t *) & rp->ip)[0]);
  520. dorequest(tempstring, type, rp->id);
  521. ddebug1(RES_MSG "Sent domain lookup request for \"%s\".",
  522. iptostr(rp->ip));
  523. }
  524. }
  525. /* Send request for the first time.
  526. */
  527. static void sendrequest(struct resolve *rp, int type)
  528. {
  529. /* Create unique id */
  530. do {
  531. idseed = (((idseed + idseed) | (long) time(NULL))
  532. + idseed - 0x54bad4a) ^ aseed;
  533. aseed ^= idseed;
  534. rp->id = (u_16bit_t) idseed;
  535. } while (findid(rp->id));
  536. linkresolveid(rp); /* Add id to id hash table */
  537. resendrequest(rp, type); /* Send request */
  538. }
  539. /* Gets called as soon as the request turns out to have failed. Calls
  540. * the eggdrop hook.
  541. */
  542. static void failrp(struct resolve *rp, int type)
  543. {
  544. if (rp->state == STATE_FINISHED)
  545. return;
  546. rp->expiretime = now + RES_FAILEDDELAY;
  547. rp->state = STATE_FAILED;
  548. /* Expire time was changed, reinsert entry to maintain order */
  549. untieresolve(rp);
  550. linkresolve(rp);
  551. ddebug0(RES_MSG "Lookup failed.");
  552. dns_event_failure(rp, type);
  553. }
  554. /* Gets called as soon as the request turns out to be successful. Calls
  555. * the eggdrop hook.
  556. */
  557. static void passrp(struct resolve *rp, long ttl, int type)
  558. {
  559. rp->state = STATE_FINISHED;
  560. /* Do not cache entries for too long. */
  561. if (ttl < RES_MAX_TTL)
  562. rp->expiretime = now + (time_t) ttl;
  563. else
  564. rp->expiretime = now + RES_MAX_TTL;
  565. /* Expire time was changed, reinsert entry to maintain order */
  566. untieresolve(rp);
  567. linkresolve(rp);
  568. ddebug1(RES_MSG "Lookup successful: %s", rp->hostn);
  569. dns_event_success(rp, type);
  570. }
  571. /* Parses the response packets received.
  572. */
  573. static void parserespacket(u_8bit_t *s, int l)
  574. {
  575. struct resolve *rp;
  576. packetheader *hp;
  577. u_8bit_t *eob;
  578. u_8bit_t *c;
  579. long ttl;
  580. int r, usefulanswer;
  581. u_16bit_t rr, datatype, class, qdatatype, qclass;
  582. u_8bit_t rdatalength;
  583. if (l < sizeof(packetheader)) {
  584. debug0(RES_ERR "Packet smaller than standard header size.");
  585. return;
  586. }
  587. if (l == sizeof(packetheader)) {
  588. debug0(RES_ERR "Packet has empty body.");
  589. return;
  590. }
  591. hp = (packetheader *) s;
  592. /* Convert data to host byte order
  593. *
  594. * hp->id does not need to be redundantly byte-order flipped, it
  595. * is only echoed by nameserver
  596. */
  597. rp = findid(hp->id);
  598. if (!rp)
  599. return;
  600. if ((rp->state == STATE_FINISHED) || (rp->state == STATE_FAILED))
  601. return;
  602. hp->qdcount = ntohs(hp->qdcount);
  603. hp->ancount = ntohs(hp->ancount);
  604. hp->nscount = ntohs(hp->nscount);
  605. hp->arcount = ntohs(hp->arcount);
  606. if (getheader_tc(hp)) { /* Packet truncated */
  607. ddebug0(RES_ERR "Nameserver packet truncated.");
  608. return;
  609. }
  610. if (!getheader_qr(hp)) { /* Not a reply */
  611. ddebug0(RES_ERR "Query packet received on nameserver communication socket.");
  612. return;
  613. }
  614. if (getheader_opcode(hp)) { /* Not opcode 0 (standard query) */
  615. ddebug0(RES_ERR "Invalid opcode in response packet.");
  616. return;
  617. }
  618. eob = s + l;
  619. c = s + HFIXEDSZ;
  620. switch (getheader_rcode(hp)) {
  621. case NOERROR:
  622. if (hp->ancount) {
  623. ddebug4(RES_MSG
  624. "Received nameserver reply. (qd:%u an:%u ns:%u ar:%u)",
  625. hp->qdcount, hp->ancount, hp->nscount, hp->arcount);
  626. if (hp->qdcount != 1) {
  627. ddebug0(RES_ERR "Reply does not contain one query.");
  628. return;
  629. }
  630. if (c > eob) {
  631. ddebug0(RES_ERR "Reply too short.");
  632. return;
  633. }
  634. switch (rp->state) { /* Construct expected query reply */
  635. case STATE_PTRREQ:
  636. sprintf(stackstring,
  637. "%u.%u.%u.%u.in-addr.arpa",
  638. ((u_8bit_t *) & rp->ip)[3],
  639. ((u_8bit_t *) & rp->ip)[2],
  640. ((u_8bit_t *) & rp->ip)[1], ((u_8bit_t *) & rp->ip)[0]);
  641. break;
  642. case STATE_AREQ:
  643. strncpy(stackstring, rp->hostn, 1024);
  644. }
  645. *namestring = '\0';
  646. r = dn_expand(s, s + l, c, namestring, MAXDNAME);
  647. if (r == -1) {
  648. ddebug0(RES_ERR "dn_expand() failed while expanding query domain.");
  649. return;
  650. }
  651. namestring[strlen(stackstring)] = '\0';
  652. if (egg_strcasecmp(stackstring, namestring)) {
  653. ddebug2(RES_MSG "Unknown query packet dropped. (\"%s\" does not match \"%s\")", stackstring, namestring);
  654. return;
  655. }
  656. ddebug1(RES_MSG "Queried domain name: \"%s\"", namestring);
  657. c += r;
  658. if (c + 4 > eob) {
  659. ddebug0(RES_ERR "Query resource record truncated.");
  660. return;
  661. }
  662. qdatatype = sucknetword(c);
  663. qclass = sucknetword(c);
  664. if (qclass != C_IN) {
  665. ddebug2(RES_ERR "Received unsupported query class: %u (%s)",
  666. qclass, qclass < CLASSTYPES_COUNT ?
  667. classtypes[qclass] :
  668. classtypes[CLASSTYPES_COUNT]);
  669. }
  670. switch (qdatatype) {
  671. case T_PTR:
  672. if (!IS_PTR(rp)) {
  673. ddebug0(RES_WRN "Ignoring response with unexpected query type \"PTR\".");
  674. return;
  675. }
  676. break;
  677. case T_A:
  678. if (!IS_A(rp)) {
  679. ddebug0(RES_WRN "Ignoring response with unexpected query type \"PTR\".");
  680. return;
  681. }
  682. break;
  683. default:
  684. ddebug2(RES_ERR "Received unimplemented query type: %u (%s)",
  685. qdatatype,
  686. qdatatype < RESOURCETYPES_COUNT ?
  687. resourcetypes[qdatatype] :
  688. resourcetypes[RESOURCETYPES_COUNT]);
  689. }
  690. for (rr = hp->ancount + hp->nscount + hp->arcount; rr; rr--) {
  691. if (c > eob) {
  692. ddebug0(RES_ERR "Packet does not contain all specified resouce records.");
  693. return;
  694. }
  695. *namestring = '\0';
  696. r = dn_expand(s, s + l, c, namestring, MAXDNAME);
  697. if (r == -1) {
  698. ddebug0(RES_ERR "dn_expand() failed while expanding answer domain.");
  699. return;
  700. }
  701. namestring[strlen(stackstring)] = '\0';
  702. if (egg_strcasecmp(stackstring, namestring))
  703. usefulanswer = 0;
  704. else
  705. usefulanswer = 1;
  706. ddebug1(RES_MSG "answered domain query: \"%s\"", namestring);
  707. c += r;
  708. if (c + 10 > eob) {
  709. ddebug0(RES_ERR "Resource record truncated.");
  710. return;
  711. }
  712. datatype = sucknetword(c);
  713. class = sucknetword(c);
  714. ttl = sucknetlong(c);
  715. rdatalength = sucknetword(c);
  716. if (class != qclass) {
  717. ddebug2(RES_MSG "query class: %u (%s)",
  718. qclass,
  719. qclass < CLASSTYPES_COUNT ?
  720. classtypes[qclass] :
  721. classtypes[CLASSTYPES_COUNT]);
  722. ddebug2(RES_MSG "rr class: %u (%s)", class,
  723. class < CLASSTYPES_COUNT ?
  724. classtypes[class] :
  725. classtypes[CLASSTYPES_COUNT]);
  726. ddebug0(RES_ERR "Answered class does not match queried class.");
  727. return;
  728. }
  729. if (!rdatalength) {
  730. ddebug0(RES_ERR "Zero size rdata.");
  731. return;
  732. }
  733. if (c + rdatalength > eob) {
  734. ddebug0(RES_ERR "Specified rdata length exceeds packet size.");
  735. return;
  736. }
  737. if (datatype == qdatatype) {
  738. ddebug1(RES_MSG "TTL: %s", strtdiff(sendstring, ttl));
  739. ddebug1(RES_MSG "TYPE: %s", datatype < RESOURCETYPES_COUNT ?
  740. resourcetypes[datatype] :
  741. resourcetypes[RESOURCETYPES_COUNT]);
  742. if (usefulanswer)
  743. switch (datatype) {
  744. case T_A:
  745. if (rdatalength != 4) {
  746. ddebug1(RES_ERR "Unsupported rdata format for \"A\" type. (%u bytes)", rdatalength);
  747. return;
  748. }
  749. my_memcpy(&rp->ip, (IP *) c, sizeof(IP));
  750. linkresolveip(rp);
  751. passrp(rp, ttl, T_A);
  752. return;
  753. case T_PTR:
  754. *namestring = '\0';
  755. r = dn_expand(s, s + l, c, namestring, MAXDNAME);
  756. if (r == -1) {
  757. ddebug0(RES_ERR "dn_expand() failed while expanding domain in rdata.");
  758. return;
  759. }
  760. ddebug1(RES_MSG "Answered domain: \"%s\"",
  761. namestring);
  762. if (r > HOSTNAMELEN) {
  763. ddebug0(RES_ERR "Domain name too long.");
  764. failrp(rp, T_PTR);
  765. return;
  766. }
  767. if (!rp->hostn) {
  768. rp->hostn = strdup(namestring);
  769. linkresolvehost(rp);
  770. passrp(rp, ttl, T_PTR);
  771. return;
  772. }
  773. break;
  774. default:
  775. ddebug2(RES_ERR "Received unimplemented data type: %u (%s)",
  776. datatype,
  777. datatype < RESOURCETYPES_COUNT ?
  778. resourcetypes[datatype] :
  779. resourcetypes[RESOURCETYPES_COUNT]);
  780. }
  781. } else if (datatype == T_CNAME) {
  782. *namestring = '\0';
  783. r = dn_expand(s, s + l, c, namestring, MAXDNAME);
  784. if (r == -1) {
  785. ddebug0(RES_ERR "dn_expand() failed while expanding domain in rdata.");
  786. return;
  787. }
  788. ddebug1(RES_MSG "answered domain is CNAME for: %s",
  789. namestring);
  790. /* The next responses will be related to the domain
  791. * pointed to by CNAME, so we need to update which
  792. * respones we regard as important.
  793. */
  794. strncpy(stackstring, namestring, 1024);
  795. } else {
  796. ddebug2(RES_MSG "Ignoring resource type %u. (%s)",
  797. datatype, datatype < RESOURCETYPES_COUNT ?
  798. resourcetypes[datatype] :
  799. resourcetypes[RESOURCETYPES_COUNT]);
  800. }
  801. c += rdatalength;
  802. }
  803. } else
  804. ddebug0(RES_ERR "No error returned but no answers given.");
  805. break;
  806. case NXDOMAIN:
  807. ddebug0(RES_MSG "Host not found.");
  808. switch (rp->state) {
  809. case STATE_PTRREQ:
  810. failrp(rp, T_PTR);
  811. break;
  812. case STATE_AREQ:
  813. failrp(rp, T_A);
  814. break;
  815. default:
  816. failrp(rp, 0);
  817. break;
  818. }
  819. break;
  820. default:
  821. ddebug2(RES_MSG "Received error response %u. (%s)",
  822. getheader_rcode(hp),
  823. getheader_rcode(hp) < RESPONSECODES_COUNT ?
  824. responsecodes[getheader_rcode(hp)] :
  825. responsecodes[RESPONSECODES_COUNT]);
  826. }
  827. }
  828. /* Read data received on our dns socket. This function is called
  829. * as soon as traffic is detected.
  830. */
  831. static void dns_ack(void)
  832. {
  833. struct sockaddr_in from;
  834. unsigned int fromlen = sizeof(struct sockaddr_in);
  835. int r, i;
  836. r = recvfrom(resfd, (u_8bit_t *) resrecvbuf, MAX_PACKETSIZE, 0,
  837. (struct sockaddr *) &from, &fromlen);
  838. if (r <= 0) {
  839. ddebug1(RES_MSG "Socket error: %s", strerror(errno));
  840. return;
  841. }
  842. /* Check to see if this server is actually one we sent to */
  843. if (from.sin_addr.s_addr == localhost) {
  844. for (i = 0; i < _res.nscount; i++)
  845. /* 0.0.0.0 replies as 127.0.0.1 */
  846. if ((_res.nsaddr_list[i].sin_addr.s_addr == from.sin_addr.s_addr)
  847. || (!_res.nsaddr_list[i].sin_addr.s_addr))
  848. break;
  849. } else {
  850. for (i = 0; i < _res.nscount; i++)
  851. if (_res.nsaddr_list[i].sin_addr.s_addr == from.sin_addr.s_addr)
  852. break;
  853. }
  854. if (i == _res.nscount) {
  855. ddebug1(RES_ERR "Received reply from unknown source: %s",
  856. iptostr(from.sin_addr.s_addr));
  857. } else
  858. parserespacket((u_8bit_t *) resrecvbuf, r);
  859. }
  860. /* Remove or resend expired requests. Called once a second.
  861. */
  862. static void dns_check_expires(void)
  863. {
  864. struct resolve *rp, *nextrp;
  865. /* Walk through sorted list ... */
  866. for (rp = expireresolves; (rp) && (now >= rp->expiretime);
  867. rp = nextrp) {
  868. nextrp = rp->next;
  869. untieresolve(rp);
  870. switch (rp->state) {
  871. case STATE_FINISHED: /* TTL has expired */
  872. case STATE_FAILED: /* Fake TTL has expired */
  873. ddebug4(RES_MSG "Cache record for \"%s\" (%s) has expired. (state: %u) Marked for expire at: %ld.",
  874. nonull(rp->hostn), iptostr(rp->ip), rp->state,
  875. rp->expiretime);
  876. unlinkresolve(rp);
  877. break;
  878. case STATE_PTRREQ: /* T_PTR send timed out */
  879. if (rp->sends <= RES_MAXSENDS) {
  880. ddebug1(RES_MSG "Resend #%d for \"PTR\" query...", rp->sends - 1);
  881. resendrequest(rp, T_PTR);
  882. } else {
  883. ddebug0(RES_MSG "\"PTR\" query timed out.");
  884. failrp(rp, T_PTR);
  885. }
  886. break;
  887. case STATE_AREQ: /* T_A send timed out */
  888. if (rp->sends <= RES_MAXSENDS) {
  889. ddebug1(RES_MSG "Resend #%d for \"A\" query...", rp->sends - 1);
  890. resendrequest(rp, T_A);
  891. } else {
  892. ddebug0(RES_MSG "\"A\" query timed out.");
  893. failrp(rp, T_A);
  894. }
  895. break;
  896. default: /* Unknown state, let it expire */
  897. ddebug1(RES_WRN "Unknown request state %d. Request expired.",
  898. rp->state);
  899. failrp(rp, 0);
  900. }
  901. }
  902. }
  903. /* Start searching for a host-name, using it's ip-address.
  904. */
  905. static void dns_lookup(IP ip)
  906. {
  907. struct resolve *rp;
  908. ip = htonl(ip);
  909. if ((rp = findip(ip))) {
  910. if (rp->state == STATE_FINISHED || rp->state == STATE_FAILED) {
  911. if (rp->state == STATE_FINISHED && rp->hostn) {
  912. ddebug2(RES_MSG "Used cached record: %s == \"%s\".",
  913. iptostr(ip), rp->hostn);
  914. dns_event_success(rp, T_PTR);
  915. } else {
  916. ddebug1(RES_MSG "Used failed record: %s == ???", iptostr(ip));
  917. dns_event_failure(rp, T_PTR);
  918. }
  919. }
  920. return;
  921. }
  922. ddebug0(RES_MSG "Creating new record");
  923. rp = allocresolve();
  924. rp->state = STATE_PTRREQ;
  925. rp->sends = 1;
  926. rp->ip = ip;
  927. linkresolveip(rp);
  928. sendrequest(rp, T_PTR);
  929. }
  930. /* Start searching for an ip-address, using it's host-name.
  931. */
  932. static void dns_forward(char *hostn)
  933. {
  934. struct resolve *rp;
  935. struct in_addr inaddr;
  936. /* Check if someone passed us an IP address as hostname
  937. * and return it straight away.
  938. */
  939. if (egg_inet_aton(hostn, &inaddr)) {
  940. call_ipbyhost(hostn, ntohl(inaddr.s_addr), 1);
  941. return;
  942. }
  943. if ((rp = findhost(hostn))) {
  944. if (rp->state == STATE_FINISHED || rp->state == STATE_FAILED) {
  945. if (rp->state == STATE_FINISHED && rp->ip) {
  946. ddebug2(RES_MSG "Used cached record: %s == \"%s\".", hostn,
  947. iptostr(rp->ip));
  948. dns_event_success(rp, T_A);
  949. } else {
  950. ddebug1(RES_MSG "Used failed record: %s == ???", hostn);
  951. dns_event_failure(rp, T_A);
  952. }
  953. }
  954. return;
  955. }
  956. ddebug0(RES_MSG "Creating new record");
  957. rp = allocresolve();
  958. rp->state = STATE_AREQ;
  959. rp->sends = 1;
  960. rp->hostn = strdup(hostn);
  961. linkresolvehost(rp);
  962. sendrequest(rp, T_A);
  963. }
  964. /* Initialise the network.
  965. */
  966. static int init_dns_network(void)
  967. {
  968. int option;
  969. struct in_addr inaddr;
  970. resfd = socket(AF_INET, SOCK_DGRAM, 0);
  971. if (resfd == -1) {
  972. putlog(LOG_MISC, "*",
  973. "Unable to allocate socket for nameserver communication: %s",
  974. strerror(errno));
  975. return 0;
  976. }
  977. (void) allocsock(resfd, SOCK_PASS);
  978. option = 1;
  979. if (setsockopt(resfd, SOL_SOCKET, SO_BROADCAST, (char *) &option,
  980. sizeof(option))) {
  981. putlog(LOG_MISC, "*",
  982. "Unable to setsockopt() on nameserver communication socket: %s",
  983. strerror(errno));
  984. killsock(resfd);
  985. return 0;
  986. }
  987. egg_inet_aton("127.0.0.1", &inaddr);
  988. localhost = inaddr.s_addr;
  989. return 1;
  990. }
  991. /* Initialise the core dns system, returns 1 if all goes well, 0 if not.
  992. */
  993. static int init_dns_core(void)
  994. {
  995. int i;
  996. /* Initialise the resolv library. */
  997. res_init();
  998. if (!_res.nscount) {
  999. putlog(LOG_MISC, "*", "No nameservers defined.");
  1000. return 0;
  1001. }
  1002. _res.options |= RES_RECURSE | RES_DEFNAMES | RES_DNSRCH;
  1003. for (i = 0; i < _res.nscount; i++)
  1004. _res.nsaddr_list[i].sin_family = AF_INET;
  1005. if (!init_dns_network())
  1006. return 0;
  1007. /* Initialise the hash tables. */
  1008. aseed = time(NULL) ^ (time(NULL) << 3) ^ (u_32bit_t) getpid();
  1009. for (i = 0; i < BASH_SIZE; i++) {
  1010. idbash[i] = NULL;
  1011. ipbash[i] = NULL;
  1012. hostbash[i] = NULL;
  1013. }
  1014. expireresolves = NULL;
  1015. return 1;
  1016. }