adns.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. /*
  2. * Copyright (C) 1997 Robey Pointer
  3. * Copyright (C) 1999 - 2002 Eggheads Development Team
  4. * Copyright (C) 2002 - 2008 Bryan Drewery
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. */
  20. /* async dns
  21. *
  22. */
  23. #include "common.h"
  24. #include "adns.h"
  25. #include "egg_timer.h"
  26. #include "main.h"
  27. #include "net.h"
  28. #include "misc.h"
  29. #include "socket.h"
  30. #include <netinet/in.h>
  31. #include <sys/socket.h>
  32. #include <arpa/inet.h>
  33. typedef struct {
  34. char **list;
  35. time_t ttl;
  36. int len;
  37. } dns_answer_t;
  38. typedef struct dns_query {
  39. struct dns_query *next;
  40. dns_answer_t answer;
  41. dns_callback_t callback;
  42. void *client_data;
  43. time_t expiretime;
  44. char *query;
  45. char *ip;
  46. int id;
  47. // int timer_id;
  48. int answers;
  49. int remaining;
  50. } dns_query_t;
  51. /* RFC1035
  52. 1 1 1 1 1 1
  53. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
  54. 1 1 1 1 1 0 9 8 7 6 5 4 3 2 1 0
  55. 5 4 3 2 1 1
  56. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  57. | ID |
  58. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  59. |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
  60. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  61. | QDCOUNT |
  62. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  63. | ANCOUNT |
  64. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  65. | NSCOUNT |
  66. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  67. | ARCOUNT |
  68. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  69. */
  70. typedef struct {
  71. unsigned short id;
  72. unsigned short flags;
  73. unsigned short question_count;
  74. unsigned short answer_count;
  75. unsigned short ns_count;
  76. unsigned short ar_count;
  77. } dns_header_t;
  78. #define GET_QR(x) (((x) >> 15) & BIT0)
  79. #define GET_OPCODE(x) (((x) >> 11) & (BIT3|BIT2|BIT1|BIT0))
  80. #define GET_AA(x) (((x) >> 10) & BIT0)
  81. #define GET_TC(x) (((x) >> 9) & BIT0)
  82. #define GET_RD(x) (((x) >> 8) & BIT0)
  83. #define GET_RA(x) (((x) >> 7) & BIT0)
  84. #define GET_RCODE(x) ((x) & (BIT3|BIT2|BIT1|BIT0))
  85. #define SET_RD(x) (x) |= ((x) | (1 << 8))
  86. #define HEAD_SIZE 12
  87. typedef struct {
  88. /* char name[]; */
  89. unsigned short type;
  90. unsigned short dclass;
  91. int ttl;
  92. unsigned short rdlength;
  93. /* char rdata[]; */
  94. } dns_rr_t;
  95. #define RR_SIZE 10
  96. /* Entries from resolv.conf */
  97. typedef struct dns_server {
  98. char *ip;
  99. int idx;
  100. } dns_server_t;
  101. /* Entries from hosts */
  102. typedef struct {
  103. char *host;
  104. char *ip;
  105. } dns_host_t;
  106. typedef struct {
  107. dns_answer_t answer;
  108. char *query;
  109. time_t expiretime;
  110. } dns_cache_t;
  111. static int query_id = 1;
  112. static dns_header_t _dns_header = {0, 0, 0, 0, 0, 0};
  113. static dns_query_t *query_head = NULL;
  114. static dns_host_t *hosts = NULL;
  115. static int nhosts = 0;
  116. static dns_cache_t *cache = NULL;
  117. static int ncache = 0;
  118. static dns_server_t *servers = NULL;
  119. static int nservers = 0;
  120. static int cur_server = -1;
  121. static char separators[] = " ,\t\r\n";
  122. int dns_idx = -1;
  123. int dns_sock = -1;
  124. const char *dns_ip = NULL;
  125. static int make_header(char *buf, int id);
  126. static int cut_host(const char *host, char *query);
  127. static int reverse_ip(const char *host, char *reverse);
  128. static int read_resolv(char *fname);
  129. static void read_hosts(char *fname);
  130. static int get_dns_idx();
  131. //static void dns_resend_queries();
  132. static int cache_find(const char *);
  133. //static int dns_on_read(void *client_data, int idx, char *buf, int len);
  134. //static int dns_on_eof(void *client_data, int idx, int err, const char *errmsg);
  135. static void dns_on_read(int idx, char *buf, int atr);
  136. static void dns_on_eof(int idx);
  137. static const char *dns_next_server();
  138. static int parse_reply(char *response, size_t nbytes, const char* server_ip);
  139. interval_t async_lookup_timeout = 30;
  140. interval_t async_server_timeout = 40;
  141. //int resend_on_read = 0;
  142. static void
  143. dns_display(int idx, char *buf, size_t bufsiz)
  144. {
  145. simple_snprintf(buf, bufsiz, "named waited %ds", (int) (now - dcc[idx].timeval));
  146. }
  147. static void
  148. dns_reinit(int idx)
  149. {
  150. sdprintf("Re-opening dns socket...");
  151. killsock(dcc[idx].sock);
  152. lostdcc(idx);
  153. dns_idx = -1;
  154. dns_sock = -1;
  155. dns_ip = NULL;
  156. if (!get_dns_idx())
  157. sdprintf("Successfully reopened dns socket");
  158. else
  159. sdprintf("Failed to reopen dns socket");
  160. }
  161. static void
  162. dns_timeout(int idx)
  163. {
  164. sdprintf("DNS socket timed out");
  165. /*egg_dns_cancel(dcc[idx].u.dns_id, 1);*/
  166. // resend_on_read = 1;
  167. dns_reinit(idx);
  168. // sleep(2);
  169. // dns_resend_queries();
  170. }
  171. static struct dcc_table dns_handler = {
  172. "adns",
  173. DCT_VALIDIDX,
  174. dns_on_eof,
  175. dns_on_read,
  176. NULL,
  177. dns_timeout,
  178. dns_display,
  179. NULL,
  180. NULL,
  181. NULL
  182. };
  183. static void dcc_dnswait(int idx, char *buf, int len)
  184. {
  185. /* Ignore anything now. */
  186. }
  187. static void eof_dcc_dnswait(int idx)
  188. {
  189. putlog(LOG_MISC, "*", "Lost connection while resolving hostname [%s/%d]",
  190. iptostr(htonl(dcc[idx].addr)), dcc[idx].port);
  191. killsock(dcc[idx].sock);
  192. lostdcc(idx);
  193. }
  194. static void display_dcc_dnswait(int idx, char *buf, size_t bufsiz)
  195. {
  196. simple_snprintf(buf, bufsiz, "dns waited %ds", (int) (now - dcc[idx].timeval));
  197. }
  198. static void kill_dcc_dnswait(int idx, void *x)
  199. {
  200. struct dns_info *p = (struct dns_info *) x;
  201. if (p) {
  202. if (p->cbuf)
  203. free(p->cbuf);
  204. }
  205. }
  206. struct dcc_table DCC_DNSWAIT = {
  207. "DNSWAIT",
  208. DCT_VALIDIDX,
  209. eof_dcc_dnswait,
  210. dcc_dnswait,
  211. NULL,
  212. NULL,
  213. display_dcc_dnswait,
  214. kill_dcc_dnswait,
  215. NULL,
  216. NULL
  217. };
  218. /*
  219. static void async_timeout(void *client_data)
  220. {
  221. int id = (int) client_data;
  222. sdprintf("%d timed out", id);
  223. egg_dns_cancel(id, 1);
  224. }
  225. */
  226. static void answer_init(dns_answer_t *answer)
  227. {
  228. memset(answer, 0, sizeof(*answer));
  229. }
  230. char s1_7[3] = "",s2_3[3] = "",s2_2[3] = "";
  231. static void answer_add(dns_answer_t *answer, const char *what)
  232. {
  233. answer->list = (char **) my_realloc(answer->list, sizeof(*answer->list) * (answer->len+2));
  234. answer->list[answer->len] = strdup(what);
  235. answer->len++;
  236. answer->list[answer->len] = NULL;
  237. }
  238. static void answer_free(dns_answer_t *answer)
  239. {
  240. int i;
  241. for (i = 0; i < answer->len; i++) free(answer->list[i]);
  242. if (answer->list) free(answer->list);
  243. }
  244. static dns_query_t *alloc_query(void *client_data, dns_callback_t callback, const char *query)
  245. {
  246. dns_query_t *q = (dns_query_t *) my_calloc(1, sizeof(*q));
  247. q->id = query_id++;
  248. q->query = strdup(query);
  249. q->answers = 0;
  250. q->callback = callback;
  251. q->client_data = client_data;
  252. q->expiretime = now + async_lookup_timeout;
  253. q->next = query_head;
  254. query_head = q;
  255. return q;
  256. }
  257. static int get_dns_idx()
  258. {
  259. int i, sock;
  260. sock = -1;
  261. for (i = 0; i < nservers; i++) {
  262. if (!dns_ip) dns_ip = dns_next_server();
  263. sock = socket_create(dns_ip, DNS_PORT, NULL, 0, SOCKET_CLIENT | SOCKET_NONBLOCK | SOCKET_UDP);
  264. if (sock < 0) {
  265. /* Try the next server. */
  266. dns_ip = NULL;
  267. }
  268. else break;
  269. }
  270. if (i == nservers) return 1;
  271. // dns_idx = sockbuf_new();
  272. // sockbuf_set_handler(dns_idx, &dns_handler, NULL);
  273. // sockbuf_set_sock(dns_idx, sock, 0);
  274. // allocsock(sock, SOCK_CONNECT);
  275. if (sock >= 0 && dns_ip) {
  276. dns_idx = new_dcc(&dns_handler, 0);
  277. if (dns_idx < 0) {
  278. putlog(LOG_SERV, "*", "NO MORE DCC CONNECTIONS -- Can't create dns connection.");
  279. killsock(sock);
  280. return 1;
  281. }
  282. sdprintf("dns_idx: %d", dns_idx);
  283. dcc[dns_idx].sock = sock;
  284. dns_sock = sock;
  285. sdprintf("dns_sock: %d", dcc[dns_idx].sock);
  286. strlcpy(dcc[dns_idx].host, dns_ip, UHOSTLEN);
  287. strlcpy(dcc[dns_idx].nick, "(adns)", NICKLEN);
  288. sdprintf("dns_ip: %s", dns_ip);
  289. dcc[dns_idx].timeval = now;
  290. dns_handler.timeout_val = 0;
  291. return 0;
  292. }
  293. return 1;
  294. }
  295. void egg_dns_send(char *query, int len)
  296. {
  297. if (dns_idx >= 0 && dcc[dns_idx].sock == -1) {
  298. lostdcc(dns_idx);
  299. dns_idx = -1;
  300. }
  301. if (dns_idx < 0) {
  302. if (get_dns_idx()) {
  303. sdprintf("get_dns_idx() failed in egg_dns_send");
  304. return;
  305. }
  306. }
  307. if (!dns_handler.timeout_val) {
  308. dns_handler.timeout_val = &async_server_timeout;
  309. sdprintf("SETTING TIMEOUT to %d", async_server_timeout);
  310. dcc[dns_idx].timeval = now;
  311. }
  312. write(dcc[dns_idx].sock, query, len);
  313. // sockbuf_write(dns_idx, query, len);
  314. }
  315. dns_query_t *find_query(const char *host)
  316. {
  317. dns_query_t *q = NULL;
  318. for (q = query_head; q; q = q->next)
  319. if (!egg_strcasecmp(q->query, host))
  320. return q;
  321. return NULL;
  322. }
  323. void dns_send_query(dns_query_t *q)
  324. {
  325. char buf[512] = "";
  326. int len;
  327. if (!q->ip) {
  328. /* Send the ipv4 query. */
  329. q->remaining = 1;
  330. len = make_header(buf, q->id);
  331. len += cut_host(q->query, buf + len);
  332. buf[len] = 0; len++; buf[len] = DNS_A; len++;
  333. buf[len] = 0; len++; buf[len] = 1; len++;
  334. egg_dns_send(buf, len);
  335. #ifdef USE_IPV6
  336. /* Now send the ipv6 query. */
  337. q->remaining++;
  338. len = make_header(buf, q->id);
  339. len += cut_host(q->query, buf + len);
  340. buf[len] = 0; len++; buf[len] = DNS_AAAA; len++;
  341. buf[len] = 0; len++; buf[len] = 1; len++;
  342. egg_dns_send(buf, len);
  343. #endif
  344. } else if (q->ip) {
  345. q->remaining = 1;
  346. len = make_header(buf, q->id);
  347. len += cut_host(q->ip, buf + len);
  348. buf[len] = 0; len++; buf[len] = DNS_PTR; len++;
  349. buf[len] = 0; len++; buf[len] = 1; len++;
  350. egg_dns_send(buf, len);
  351. }
  352. }
  353. /*
  354. void dns_resend_queries()
  355. {
  356. dns_query_t *q = NULL;
  357. for (q = query_head; q; q = q->next) {
  358. if (now >= q->expiretime) {
  359. sdprintf("RESENDING: %s", q->query);
  360. dns_send_query(q);
  361. }
  362. }
  363. }
  364. */
  365. /*
  366. void dns_create_timeout_timer(dns_query_t **qm, const char *query, int timeout)
  367. {
  368. dns_query_t *q = *qm;
  369. egg_timeval_t howlong;
  370. howlong.sec = timeout;
  371. howlong.usec = 0;
  372. q->timer_id = timer_create_complex(&howlong, query, (Function) async_timeout, (void *) q->id, 0);
  373. }
  374. */
  375. /* Perform an async dns lookup. This is host -> ip. For ip -> host, use
  376. * egg_dns_reverse(). We return a dns id that you can use to cancel the
  377. * lookup. */
  378. int egg_dns_lookup(const char *host, interval_t timeout, dns_callback_t callback, void *client_data)
  379. {
  380. dns_query_t *q = NULL;
  381. int i, cache_id;
  382. if (is_dotted_ip(host)) {
  383. /* If it's already an ip, we're done. */
  384. dns_answer_t answer;
  385. sdprintf("egg_dns_lookup(%s, %d): Already an ip.", host, timeout);
  386. answer_init(&answer);
  387. answer_add(&answer, host);
  388. callback(-1, client_data, host, answer.list);
  389. answer_free(&answer);
  390. return(-1);
  391. }
  392. /* Ok, now see if it's in our host cache. */
  393. for (i = 0; i < nhosts; i++) {
  394. if (!egg_strcasecmp(host, hosts[i].host)) {
  395. dns_answer_t answer;
  396. sdprintf("egg_dns_lookup(%s, %d): Found in hosts -> %s", host, timeout, hosts[i].ip);
  397. answer_init(&answer);
  398. answer_add(&answer, hosts[i].ip);
  399. callback(-1, client_data, host, answer.list);
  400. answer_free(&answer);
  401. return(-1);
  402. }
  403. }
  404. cache_id = cache_find(host);
  405. if (cache_id >= 0) {
  406. shuffleArray(cache[cache_id].answer.list, cache[cache_id].answer.len);
  407. sdprintf("egg_dns_lookup(%s, %d): Found in cache -> %s", host, timeout, cache[cache_id].answer.list[0]);
  408. callback(-1, client_data, host, cache[cache_id].answer.list);
  409. return(-1);
  410. }
  411. /* check if the query was already made */
  412. if ((q = find_query(host))) {
  413. sdprintf("egg_dns_lookup(%s, %d): Already querying -> %d", host, timeout, q->id);
  414. return(-2);
  415. }
  416. /* Allocate our query struct. */
  417. q = alloc_query(client_data, callback, host);
  418. sdprintf("egg_dns_lookup(%s, %d) -> %d", host, timeout, q->id);
  419. dns_send_query(q);
  420. // /* setup a timer to detect dead ns */
  421. // dns_create_timeout_timer(&q, host, timeout);
  422. /* Send the ipv4 query. */
  423. return(q->id);
  424. }
  425. /* Perform an async dns reverse lookup. This does ip -> host. For host -> ip
  426. * use egg_dns_lookup(). We return a dns id that you can use to cancel the
  427. * lookup. */
  428. int egg_dns_reverse(const char *ip, interval_t timeout, dns_callback_t callback, void *client_data)
  429. {
  430. dns_query_t *q;
  431. int i, cache_id;
  432. if (!is_dotted_ip(ip)) {
  433. /* If it's not a valid ip, don't even make the request. */
  434. sdprintf("egg_dns_reverse(%s, %d): Not an ip.", ip, timeout);
  435. callback(-1, client_data, ip, NULL);
  436. return(-1);
  437. }
  438. /* Ok, see if we have it in our host cache. */
  439. for (i = 0; i < nhosts; i++) {
  440. if (!egg_strcasecmp(hosts[i].ip, ip)) {
  441. dns_answer_t answer;
  442. sdprintf("egg_dns_reverse(%s, %d): Found in hosts -> %s", ip, timeout, hosts[i].host);
  443. answer_init(&answer);
  444. answer_add(&answer, hosts[i].host);
  445. callback(-1, client_data, ip, answer.list);
  446. answer_free(&answer);
  447. return(-1);
  448. }
  449. }
  450. cache_id = cache_find(ip);
  451. if (cache_id >= 0) {
  452. shuffleArray(cache[cache_id].answer.list, cache[cache_id].answer.len);
  453. sdprintf("egg_dns_reverse(%s, %d): Found in cache -> %s", ip, timeout, cache[cache_id].answer.list[0]);
  454. callback(-1, client_data, ip, cache[cache_id].answer.list);
  455. return(-1);
  456. }
  457. /* check if the query was already made */
  458. if ((q = find_query(ip))) {
  459. sdprintf("egg_dns_reverse(%s, %d): Already querying -> %d", ip, timeout, q->id);
  460. return(-1);
  461. }
  462. q = alloc_query(client_data, callback, ip);
  463. sdprintf("egg_dns_reverse(%s, %d) -> %d", ip, timeout, q->id);
  464. /* We need to transform the ip address into the proper form
  465. * for reverse lookup. */
  466. if (strchr(ip, ':')) {
  467. char temp[128] = "";
  468. socket_ipv6_to_dots(ip, temp);
  469. sdprintf("dots: %s", temp);
  470. size_t iplen = strlen(temp) + 9 + 1;
  471. q->ip = (char *) my_calloc(1, iplen);
  472. // reverse_ip(temp, q->ip);
  473. strlcat(q->ip, temp, iplen);
  474. strlcat(q->ip, "ip6.arpa", iplen);
  475. sdprintf("reversed ipv6 ip: %s", q->ip);
  476. }
  477. else {
  478. size_t iplen = strlen(ip) + 13 + 1;
  479. q->ip = (char *) my_calloc(1, iplen);
  480. reverse_ip(ip, q->ip);
  481. strlcat(q->ip, ".in-addr.arpa", iplen);
  482. }
  483. dns_send_query(q);
  484. // /* setup timer to detect dead ns */
  485. // dns_create_timeout_timer(&q, ip, timeout);
  486. return(q->id);
  487. }
  488. //static int dns_on_read(void *client_data, int idx, char *buf, int len)
  489. static void dns_on_read(int idx, char *buf, int atr)
  490. {
  491. dcc[idx].timeval = now;
  492. // if (resend_on_read) {
  493. // resend_on_read = 0;
  494. // dns_resend_queries();
  495. // return;
  496. // }
  497. atr = read(dcc[idx].sock, buf, 512);
  498. if (atr == -1) {
  499. if (errno == EAGAIN)
  500. atr = read(dcc[idx].sock, buf, 512);
  501. if (atr == -1) {
  502. dns_on_eof(idx);
  503. return;
  504. }
  505. }
  506. sdprintf("SETTING TIMEOUT to 0");
  507. dns_handler.timeout_val = 0;
  508. if (parse_reply(buf, atr, dns_ip))
  509. dns_on_eof(idx);
  510. return;
  511. }
  512. static void dns_on_eof(int idx)
  513. {
  514. sdprintf("EOF on dns idx: %d sock: %d (%s)", idx, dcc[idx].sock, dcc[idx].host);
  515. dns_reinit(idx);
  516. return;
  517. }
  518. /* for .restart
  519. int egg_dns_shutdown(void)
  520. {
  521. int i;
  522. if (nservers > 0) {
  523. for (i = 0; i < nservers; i++) {
  524. if (servers[i].ip) free(servers[i].ip);
  525. }
  526. free(servers); servers = NULL;
  527. nservers = 0;
  528. }
  529. if (nhosts > 0) {
  530. for (i = 0; i < nhosts; i++) {
  531. if (hosts[i].host) free(hosts[i].host);
  532. if (hosts[i].ip) free(hosts[i].ip);
  533. }
  534. free(hosts); hosts = NULL;
  535. nhosts = 0;
  536. }
  537. return (0);
  538. }
  539. */
  540. static const char *dns_next_server()
  541. {
  542. if (!servers || nservers < 1) return("127.0.0.1");
  543. cur_server++;
  544. if (cur_server >= nservers) cur_server = 0;
  545. return(servers[cur_server].ip);
  546. }
  547. static void add_dns_server(char *ip)
  548. {
  549. servers = (dns_server_t *) my_realloc(servers, (nservers+1)*sizeof(*servers));
  550. servers[nservers].ip = strdup(ip);
  551. nservers++;
  552. sdprintf("Added NS: %s", ip);
  553. }
  554. static void add_host(char *host, char *ip)
  555. {
  556. hosts = (dns_host_t *) my_realloc(hosts, (nhosts+1)*sizeof(*hosts));
  557. hosts[nhosts].host = strdup(host);
  558. hosts[nhosts].ip = strdup(ip);
  559. nhosts++;
  560. }
  561. static int cache_expired(int id)
  562. {
  563. if (cache[id].expiretime && (now >= cache[id].expiretime)) return(1);
  564. return (0);
  565. }
  566. static void cache_del(int id)
  567. {
  568. answer_free(&cache[id].answer);
  569. free(cache[id].query);
  570. cache[id].expiretime = 0;
  571. ncache--;
  572. if (id < ncache) egg_memcpy(&cache[id], &cache[ncache], sizeof(dns_cache_t));
  573. else egg_bzero(&cache[id], sizeof(dns_cache_t));
  574. cache = (dns_cache_t *) my_realloc(cache, (ncache+1)*sizeof(*cache));
  575. }
  576. static void cache_add(const char *query, dns_answer_t *answer)
  577. {
  578. int i;
  579. cache = (dns_cache_t *) my_realloc(cache, (ncache+1)*sizeof(*cache));
  580. egg_bzero(&cache[ncache], sizeof(cache[ncache]));
  581. cache[ncache].query = strdup(query);
  582. answer_init(&cache[ncache].answer);
  583. for (i = 0; i < answer->len; i++)
  584. answer_add(&cache[ncache].answer, answer->list[i]);
  585. cache[ncache].expiretime = now + answer->ttl;
  586. ncache++;
  587. }
  588. static int cache_find(const char *query)
  589. {
  590. int i;
  591. for (i = 0; i < ncache; i++)
  592. if (!egg_strcasecmp(cache[i].query, query)) return (i);
  593. return (-1);
  594. }
  595. void dns_cache_flush()
  596. {
  597. int i = 0;
  598. for (i = 0; i < ncache; i++) {
  599. cache_del(i);
  600. if (i == ncache) break;
  601. i--;
  602. }
  603. }
  604. static int read_thing(char *buf, char *ip)
  605. {
  606. int skip, len;
  607. skip = strspn(buf, separators);
  608. buf += skip;
  609. len = strcspn(buf, separators);
  610. egg_memcpy(ip, buf, len);
  611. ip[len] = 0;
  612. return(skip + len);
  613. }
  614. static int read_resolv(char *fname)
  615. {
  616. FILE *fp;
  617. char buf[512], ip[512];
  618. int count = 0;
  619. fp = fopen(fname, "r");
  620. if (!fp) return 0;
  621. while (fgets(buf, sizeof(buf), fp)) {
  622. if (!strncasecmp(buf, "nameserver", 10)) {
  623. read_thing(buf+10, ip);
  624. if (strlen(ip)) {
  625. add_dns_server(ip);
  626. ++count;
  627. }
  628. }
  629. }
  630. fclose(fp);
  631. return count;
  632. }
  633. static void read_hosts(char *fname)
  634. {
  635. FILE *fp;
  636. char buf[512], ip[512], host[512];
  637. int skip, n;
  638. fp = fopen(fname, "r");
  639. if (!fp) return;
  640. while (fgets(buf, sizeof(buf), fp)) {
  641. if (strchr(buf, '#')) continue;
  642. skip = read_thing(buf, ip);
  643. if (!strlen(ip)) continue;
  644. while ((n = read_thing(buf+skip, host))) {
  645. skip += n;
  646. if (strlen(host)) add_host(host, ip);
  647. }
  648. }
  649. fclose(fp);
  650. }
  651. static int make_header(char *buf, int id)
  652. {
  653. _dns_header.question_count = htons(1);
  654. // _dns_header.id = htons(id);
  655. _dns_header.id = id;
  656. egg_memcpy(buf, &_dns_header, HEAD_SIZE);
  657. return(HEAD_SIZE);
  658. }
  659. static int cut_host(const char *host, char *query)
  660. {
  661. char *period, *orig;
  662. int len;
  663. orig = query;
  664. while ((period = strchr(host, '.'))) {
  665. len = period - host;
  666. if (len > 63) return(-1);
  667. *query++ = len;
  668. egg_memcpy(query, host, len);
  669. query += len;
  670. host = period+1;
  671. }
  672. len = strlen(host);
  673. if (len) {
  674. *query++ = len;
  675. egg_memcpy(query, host, len);
  676. query += len;
  677. }
  678. *query++ = 0;
  679. return(query-orig);
  680. }
  681. static int reverse_ip(const char *host, char *reverse)
  682. {
  683. char *period;
  684. int offset, len;
  685. period = strchr(host, '.');
  686. if (!period) {
  687. len = strlen(host);
  688. egg_memcpy(reverse, host, len);
  689. return(len);
  690. }
  691. else {
  692. len = period - host;
  693. offset = reverse_ip(host+len+1, reverse);
  694. reverse[offset++] = '.';
  695. egg_memcpy(reverse+offset, host, len);
  696. reverse[offset+len] = 0;
  697. return(offset+len);
  698. }
  699. }
  700. int egg_dns_cancel(int id, int issue_callback)
  701. {
  702. dns_query_t *q, *prev = NULL;
  703. for (q = query_head; q; q = q->next) {
  704. if (q->id == id) break;
  705. prev = q;
  706. }
  707. if (!q) return(-1);
  708. if (prev) prev->next = q->next;
  709. else query_head = q->next;
  710. sdprintf("Cancelling query: %s", q->query);
  711. if (issue_callback) q->callback(q->id, q->client_data, q->query, NULL);
  712. if (q->ip)
  713. free(q->ip);
  714. free(q->query);
  715. free(q);
  716. return(0);
  717. }
  718. static int skip_name(unsigned char *ptr)
  719. {
  720. int len;
  721. unsigned char *start = ptr;
  722. while ((len = *ptr++) > 0) {
  723. if (len > 63) {
  724. ptr++;
  725. break;
  726. }
  727. else {
  728. ptr += len;
  729. }
  730. }
  731. return(ptr - start);
  732. }
  733. /*
  734. void print_header(dns_header_t &header)
  735. {
  736. #define dofield(_field) sdprintf("%s: %d\n", #_field, _field)
  737. dofield(header.id);
  738. dofield(header.question_count);
  739. dofield(header.answer_count);
  740. dofield(header.ar_count);
  741. dofield(header.ns_count);
  742. #undef dofield
  743. }
  744. void print_reply(dns_rr_t &reply)
  745. {
  746. #define dofield(_field) sdprintf("%s: %d\n", #_field, _field)
  747. dofield(reply.type);
  748. dofield(reply.dclass);
  749. dofield(reply.ttl);
  750. dofield(reply.rdlength);
  751. #undef dofield
  752. }
  753. */
  754. static int parse_reply(char *response, size_t nbytes, const char* server_ip)
  755. {
  756. dns_header_t header;
  757. dns_query_t *q = NULL, *prev = NULL;
  758. dns_rr_t reply;
  759. char result[512] = "";
  760. short rr;
  761. int r = -1;
  762. unsigned const char *eop = (unsigned char *) response + nbytes;
  763. unsigned char *ptr = (unsigned char *) response;
  764. int return_code = 0;
  765. egg_memcpy(&header, ptr, HEAD_SIZE);
  766. ptr += HEAD_SIZE;
  767. /* header.id is already in our order, echoed by the server */
  768. header.flags = ntohs(header.flags);
  769. header.question_count = ntohs(header.question_count);
  770. header.answer_count = ntohs(header.answer_count);
  771. header.ar_count = ntohs(header.ar_count);
  772. header.ns_count = ntohs(header.ns_count);
  773. // print_header(header);
  774. /* Find our copy of the query before proceeding. */
  775. for (q = query_head; q; q = q->next) {
  776. if (q->id == header.id) break;
  777. prev = q;
  778. }
  779. sdprintf("Reply (%d) questions: %d answers: %d ar: %d ns: %d from: %s QR: %d OPCODE: %d AA: %d TC: %d RD: %d RA: %d RCODE: %d",
  780. header.id,
  781. header.question_count,
  782. header.answer_count,
  783. header.ar_count,
  784. header.ns_count,
  785. server_ip,
  786. GET_QR(header.flags),
  787. GET_OPCODE(header.flags),
  788. GET_AA(header.flags),
  789. GET_TC(header.flags),
  790. GET_RD(header.flags),
  791. GET_RA(header.flags),
  792. GET_RCODE(header.flags)
  793. );
  794. if (!q) {
  795. sdprintf("Reply(%d) not found??", header.id);
  796. return 0;
  797. }
  798. /* Did this server give us recursion? */
  799. if (!GET_RA(header.flags)) {
  800. sdprintf("Ignoring reply(%d) from %s: no recusion available.", header.id, server_ip);
  801. return_code = 1; /* get a new server */
  802. q->remaining = 0; /* Force this query to be removed, any further answers are ignored */
  803. goto callback;
  804. }
  805. /* Check for errors */
  806. if (GET_RCODE(header.flags)) {
  807. switch (GET_RCODE(header.flags)) {
  808. case 1: /* Format error */
  809. sdprintf("Ignoring reply(%d) from %s: Format error.", header.id, server_ip);
  810. break;
  811. case 2: /* Server error */
  812. sdprintf("Ignoring reply(%d) from %s: Server error.", header.id, server_ip);
  813. return_code = 1; /* get a new server */
  814. q->remaining = 0; /* Force this query to be removed, any further answers are ignored */
  815. break;
  816. case 3: /* Name error */
  817. sdprintf("Ignoring reply(%d) from %s: NXDOMAIN.", header.id, server_ip);
  818. /* Ignore the incoming AAAA or A reply as it will still be NXDOMAIN */
  819. q->remaining = 0; /* Force this query to be removed, any further answers are ignored */
  820. break;
  821. case 4:
  822. sdprintf("Ignoring reply(%d) from %s: Query not supported", header.id, server_ip);
  823. break;
  824. case 5:
  825. sdprintf("Ignoring reply(%d) from %s: REFUSED", header.id, server_ip);
  826. return_code = 1; /* get a new server */
  827. q->remaining = 0; /* Force this query to be removed, any further answers are ignored */
  828. break;
  829. }
  830. goto callback;
  831. }
  832. // /* destroy our async timeout */
  833. // timer_destroy(q->timer_id);
  834. /* Pass over the questions. */
  835. for (rr = 0; rr < header.question_count; rr++) {
  836. ptr += skip_name(ptr);
  837. ptr += 4;
  838. }
  839. /* End of questions. */
  840. // for (rr = 0; rr < header.answer_count + header.ar_count + header.ns_count; rr++) {
  841. q->answers += header.answer_count;
  842. for (rr = 0; rr < header.answer_count; rr++) {
  843. result[0] = 0;
  844. /* Read in the answer. */
  845. ptr += skip_name(ptr);
  846. egg_memcpy(&reply, ptr, RR_SIZE);
  847. ptr += RR_SIZE;
  848. reply.type = ntohs(reply.type);
  849. reply.dclass = ntohs(reply.dclass);
  850. reply.rdlength = ntohs(reply.rdlength);
  851. reply.ttl = ntohl(reply.ttl);
  852. /* Save the lowest ttl */
  853. if (reply.ttl && ((!q->answer.ttl) || (q->answer.ttl > reply.ttl))) q->answer.ttl = reply.ttl;
  854. // print_reply(reply);
  855. switch (reply.type) {
  856. case DNS_A:
  857. egg_inet_ntop(AF_INET, ptr, result, 512);
  858. answer_add(&q->answer, result);
  859. break;
  860. case DNS_AAAA:
  861. #ifdef USE_IPV6
  862. egg_inet_ntop(AF_INET6, ptr, result, 512);
  863. answer_add(&q->answer, result);
  864. #endif /* USE_IPV6 */
  865. break;
  866. case DNS_PTR:
  867. r = my_dn_expand((const unsigned char *) response, eop, ptr, result, sizeof(result));
  868. if (r != -1 && result[0])
  869. answer_add(&q->answer, result);
  870. break;
  871. default:
  872. sdprintf("Unhandled DNS reply type: %d", reply.type);
  873. break;
  874. }
  875. ptr += reply.rdlength;
  876. if ((size_t) (ptr - (unsigned char*) response) > nbytes) {
  877. sdprintf("MALFORMED/TRUNCATED DNS PACKET detected (need TCP).");
  878. q->remaining = 0; /* Force this query to be removed, any further answers are ignored */
  879. break;
  880. }
  881. }
  882. callback:
  883. /* Don't continue if we haven't gotten all expected replies. */
  884. if (--q->remaining > 0) return 0;
  885. /* Ok, we have, so now issue the callback with the answers. */
  886. if (prev) prev->next = q->next;
  887. else query_head = q->next;
  888. if (q->answer.len > 0) {
  889. cache_add(q->query, &q->answer);
  890. q->callback(q->id, q->client_data, q->query, q->answer.list);
  891. answer_free(&q->answer);
  892. } else {
  893. q->callback(q->id, q->client_data, q->query, NULL);
  894. }
  895. free(q->query);
  896. if (q->ip)
  897. free(q->ip);
  898. free(q);
  899. return return_code;
  900. }
  901. void tell_dnsdebug(int idx)
  902. {
  903. dns_query_t *q = NULL;
  904. int i, n = 0;
  905. dprintf(idx, "NS: %s\n", dns_ip);
  906. for (q = query_head; q; q = q->next)
  907. dprintf(idx, "DNS (%d) (%ds): %s\n", q->id, (int) (q->expiretime - now), q->query);
  908. // for (i = 0; i < nhosts; i++)
  909. // dprintf(idx, "HOST #%d: %s/%s\n", i, hosts[i].host, hosts[i].ip);
  910. for (i = 0; i < ncache; i++) {
  911. dprintf(idx, "cache(%d) %s expires in %ds\n", i, cache[i].query, (int) (cache[i].expiretime - now));
  912. for (n = 0; n < cache[i].answer.len; n++)
  913. dprintf(idx, "%d: %s\n", n, cache[i].answer.list[n]);
  914. }
  915. }
  916. static void expire_queries()
  917. {
  918. dns_query_t *q = NULL, *next = NULL;
  919. int i = 0;
  920. /* need to check for expired queries and either:
  921. a) recheck/change ns
  922. b) expire due to ttl
  923. */
  924. if (query_head) {
  925. for (q = query_head; q; q = q->next) {
  926. if (q->expiretime <= now) { /* set in alloc_query */
  927. if (q->next)
  928. next = q->next;
  929. egg_dns_cancel(q->id, 1);
  930. if (!next) break;
  931. q = next;
  932. }
  933. }
  934. }
  935. for (i = 0; i < ncache; i++) {
  936. if (cache_expired(i)) {
  937. cache_del(i);
  938. if (i == ncache) break;
  939. i--;
  940. }
  941. }
  942. }
  943. /* Read in .hosts and /etc/hosts and .resolv.conf and /etc/resolv.conf */
  944. int egg_dns_init()
  945. {
  946. /* Set RECURSION DESIRED */
  947. SET_RD(_dns_header.flags);
  948. /* Convert flags to network order */
  949. _dns_header.flags = htons(_dns_header.flags);
  950. if (!read_resolv(".resolv.conf")) {
  951. read_resolv("/etc/resolv.conf");
  952. /* some backup servers, probably will never be used. */
  953. add_dns_server("4.2.2.2");
  954. }
  955. // read_hosts("/etc/hosts");
  956. read_hosts(".hosts");
  957. /* root servers for future development (tracing down)
  958. add_dns_server("198.41.0.4");
  959. add_dns_server("192.228.79.201");
  960. add_dns_server("192.33.4.12");
  961. add_dns_server("128.8.10.90");
  962. add_dns_server("192.203.230.10");
  963. add_dns_server("192.5.5.241");
  964. add_dns_server("192.112.36.4");
  965. add_dns_server("128.63.2.53");
  966. add_dns_server("192.36.148.17");
  967. add_dns_server("192.58.128.30");
  968. add_dns_server("193.0.14.129");
  969. add_dns_server("198.32.64.12");
  970. add_dns_server("202.12.27.33");
  971. */
  972. timer_create_secs(3, "adns_check_expires", (Function) expire_queries);
  973. return(0);
  974. }
  975. bool valid_dns_id(int idx, int id)
  976. {
  977. if (id == -1)
  978. return 1;
  979. if (valid_idx(idx) && dcc[idx].dns_id && dcc[idx].dns_id == id)
  980. return 1;
  981. sdprintf("dns_id: %d is not associated with dead idx: %d", id, idx);
  982. return 0;
  983. }