adns.c 32 KB

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