dnresolve.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  1. /*
  2. * domain name resolvers, see rfcs 1035 and 1123
  3. */
  4. #include <u.h>
  5. #include <libc.h>
  6. #include <ip.h>
  7. #include <bio.h>
  8. #include <ndb.h>
  9. #include "dns.h"
  10. #define NS2MS(ns) ((ns) / 1000000L)
  11. #define S2MS(s) ((s) * 1000)
  12. #define MS2S(ms) ((ms) / 1000)
  13. typedef struct Dest Dest;
  14. typedef struct Ipaddr Ipaddr;
  15. typedef struct Query Query;
  16. enum
  17. {
  18. Udp, Tcp,
  19. Maxdest= 24, /* maximum destinations for a request message */
  20. Maxtrans= 3, /* maximum transmissions to a server */
  21. Destmagic= 0xcafebabe,
  22. Querymagic= 0xdeadbeef,
  23. };
  24. enum { Hurry, Patient, };
  25. enum { Outns, Inns, };
  26. enum { Remntretry = 15, }; /* min. sec.s between remount attempts */
  27. struct Ipaddr {
  28. Ipaddr *next;
  29. uchar ip[IPaddrlen];
  30. };
  31. struct Dest
  32. {
  33. uchar a[IPaddrlen]; /* ip address */
  34. DN *s; /* name server */
  35. int nx; /* number of transmissions */
  36. int code; /* response code; used to clear dp->respcode */
  37. ulong magic;
  38. };
  39. /*
  40. * Query has a QLock in it, thus it can't be an automatic
  41. * variable, since each process would see a separate copy
  42. * of the lock on its stack.
  43. */
  44. struct Query {
  45. DN *dp; /* domain */
  46. ushort type; /* and type to look up */
  47. Request *req;
  48. RR *nsrp; /* name servers to consult */
  49. /* dest must not be on the stack due to forking in slave() */
  50. Dest *dest; /* array of destinations */
  51. Dest *curdest; /* pointer to one of them */
  52. int ndest;
  53. int udpfd;
  54. QLock tcplock; /* only one tcp call at a time per query */
  55. int tcpset;
  56. int tcpfd; /* if Tcp, read replies from here */
  57. int tcpctlfd;
  58. uchar tcpip[IPaddrlen];
  59. ulong magic;
  60. };
  61. /* estimated % probability of such a record existing at all */
  62. int likely[] = {
  63. [Ta] 95,
  64. [Taaaa] 10,
  65. [Tcname] 15,
  66. [Tmx] 60,
  67. [Tns] 90,
  68. [Tnull] 5,
  69. [Tptr] 35,
  70. [Tsoa] 90,
  71. [Tsrv] 60,
  72. [Ttxt] 15,
  73. [Tall] 95,
  74. };
  75. static RR* dnresolve1(char*, int, int, Request*, int, int);
  76. static int netquery(Query *, int);
  77. /*
  78. * reading /proc/pid/args yields either "name" or "name [display args]",
  79. * so return only display args, if any.
  80. */
  81. static char *
  82. procgetname(void)
  83. {
  84. int fd, n;
  85. char *lp, *rp;
  86. char buf[256];
  87. snprint(buf, sizeof buf, "#p/%d/args", getpid());
  88. if((fd = open(buf, OREAD)) < 0)
  89. return strdup("");
  90. *buf = '\0';
  91. n = read(fd, buf, sizeof buf-1);
  92. close(fd);
  93. if (n >= 0)
  94. buf[n] = '\0';
  95. if ((lp = strchr(buf, '[')) == nil ||
  96. (rp = strrchr(buf, ']')) == nil)
  97. return strdup("");
  98. *rp = '\0';
  99. return strdup(lp+1);
  100. }
  101. /*
  102. * lookup 'type' info for domain name 'name'. If it doesn't exist, try
  103. * looking it up as a canonical name.
  104. */
  105. RR*
  106. dnresolve(char *name, int class, int type, Request *req, RR **cn, int depth,
  107. int recurse, int rooted, int *status)
  108. {
  109. RR *rp, *nrp, *drp;
  110. DN *dp;
  111. int loops;
  112. char *procname;
  113. char nname[Domlen];
  114. if(status)
  115. *status = 0;
  116. if(depth > 12) /* in a recursive loop? */
  117. return nil;
  118. procname = procgetname();
  119. /*
  120. * hack for systems that don't have resolve search
  121. * lists. Just look up the simple name in the database.
  122. */
  123. if(!rooted && strchr(name, '.') == nil){
  124. rp = nil;
  125. drp = domainlist(class);
  126. for(nrp = drp; rp == nil && nrp != nil; nrp = nrp->next){
  127. snprint(nname, sizeof nname, "%s.%s", name,
  128. nrp->ptr->name);
  129. rp = dnresolve(nname, class, type, req, cn, depth+1,
  130. recurse, rooted, status);
  131. rrfreelist(rrremneg(&rp));
  132. }
  133. if(drp != nil)
  134. rrfreelist(drp);
  135. procsetname(procname);
  136. free(procname);
  137. return rp;
  138. }
  139. /*
  140. * try the name directly
  141. */
  142. rp = dnresolve1(name, class, type, req, depth, recurse);
  143. if(rp == nil) {
  144. /*
  145. * try it as a canonical name if we weren't told
  146. * that the name didn't exist
  147. */
  148. dp = dnlookup(name, class, 0);
  149. if(type != Tptr && dp->respcode != Rname)
  150. for(loops = 0; rp == nil && loops < 32; loops++){
  151. rp = dnresolve1(name, class, Tcname, req,
  152. depth, recurse);
  153. if(rp == nil)
  154. break;
  155. /* rp->host == nil shouldn't happen, but does */
  156. if(rp->negative || rp->host == nil){
  157. rrfreelist(rp);
  158. rp = nil;
  159. break;
  160. }
  161. name = rp->host->name;
  162. if(cn)
  163. rrcat(cn, rp);
  164. else
  165. rrfreelist(rp);
  166. rp = dnresolve1(name, class, type, req,
  167. depth, recurse);
  168. }
  169. /* distinction between not found and not good */
  170. if(rp == nil && status != nil && dp->respcode != 0)
  171. *status = dp->respcode;
  172. }
  173. procsetname(procname);
  174. free(procname);
  175. return randomize(rp);
  176. }
  177. static void
  178. queryinit(Query *qp, DN *dp, int type, Request *req)
  179. {
  180. memset(qp, 0, sizeof *qp);
  181. qp->udpfd = qp->tcpfd = qp->tcpctlfd = -1;
  182. qp->dp = dp;
  183. qp->type = type;
  184. if (qp->type != type)
  185. dnslog("queryinit: bogus type %d", type);
  186. qp->req = req;
  187. qp->nsrp = nil;
  188. qp->dest = qp->curdest = nil;
  189. qp->magic = Querymagic;
  190. }
  191. static void
  192. queryck(Query *qp)
  193. {
  194. assert(qp);
  195. assert(qp->magic == Querymagic);
  196. }
  197. static void
  198. querydestroy(Query *qp)
  199. {
  200. queryck(qp);
  201. /* leave udpfd alone */
  202. if (qp->tcpfd > 0)
  203. close(qp->tcpfd);
  204. if (qp->tcpctlfd > 0) {
  205. hangup(qp->tcpctlfd);
  206. close(qp->tcpctlfd);
  207. }
  208. free(qp->dest);
  209. memset(qp, 0, sizeof *qp); /* prevent accidents */
  210. qp->udpfd = qp->tcpfd = qp->tcpctlfd = -1;
  211. }
  212. static void
  213. destinit(Dest *p)
  214. {
  215. memset(p, 0, sizeof *p);
  216. p->magic = Destmagic;
  217. }
  218. static void
  219. destck(Dest *p)
  220. {
  221. assert(p);
  222. assert(p->magic == Destmagic);
  223. }
  224. static void
  225. destdestroy(Dest *p)
  226. {
  227. USED(p);
  228. }
  229. /*
  230. * if the response to a query hasn't arrived within 100 ms.,
  231. * it's unlikely to arrive at all. after 1 s., it's really unlikely.
  232. * queries for missing RRs are likely to produce time-outs rather than
  233. * negative responses, so cname and aaaa queries are likely to time out,
  234. * thus we don't wait very long for them.
  235. */
  236. static void
  237. notestats(vlong start, int tmout, int type)
  238. {
  239. qlock(&stats);
  240. if (tmout) {
  241. stats.tmout++;
  242. if (type == Taaaa)
  243. stats.tmoutv6++;
  244. else if (type == Tcname)
  245. stats.tmoutcname++;
  246. } else {
  247. long wait10ths = NS2MS(nsec() - start) / 100;
  248. if (wait10ths <= 0)
  249. stats.under10ths[0]++;
  250. else if (wait10ths >= nelem(stats.under10ths))
  251. stats.under10ths[nelem(stats.under10ths) - 1]++;
  252. else
  253. stats.under10ths[wait10ths]++;
  254. }
  255. qunlock(&stats);
  256. }
  257. static void
  258. noteinmem(void)
  259. {
  260. qlock(&stats);
  261. stats.answinmem++;
  262. qunlock(&stats);
  263. }
  264. static RR*
  265. issuequery(Query *qp, char *name, int class, int depth, int recurse)
  266. {
  267. char *cp;
  268. DN *nsdp;
  269. RR *rp, *nsrp, *dbnsrp;
  270. /*
  271. * if we're running as just a resolver, query our
  272. * designated name servers
  273. */
  274. if(cfg.resolver){
  275. nsrp = randomize(getdnsservers(class));
  276. if(nsrp != nil) {
  277. qp->nsrp = nsrp;
  278. if(netquery(qp, depth+1)){
  279. rrfreelist(nsrp);
  280. return rrlookup(qp->dp, qp->type, OKneg);
  281. }
  282. rrfreelist(nsrp);
  283. }
  284. }
  285. /*
  286. * walk up the domain name looking for
  287. * a name server for the domain.
  288. */
  289. for(cp = name; cp; cp = walkup(cp)){
  290. /*
  291. * if this is a local (served by us) domain,
  292. * return answer
  293. */
  294. dbnsrp = randomize(dblookup(cp, class, Tns, 0, 0));
  295. if(dbnsrp && dbnsrp->local){
  296. rp = dblookup(name, class, qp->type, 1, dbnsrp->ttl);
  297. rrfreelist(dbnsrp);
  298. return rp;
  299. }
  300. /*
  301. * if recursion isn't set, just accept local
  302. * entries
  303. */
  304. if(recurse == Dontrecurse){
  305. if(dbnsrp)
  306. rrfreelist(dbnsrp);
  307. continue;
  308. }
  309. /* look for ns in cache */
  310. nsdp = dnlookup(cp, class, 0);
  311. nsrp = nil;
  312. if(nsdp)
  313. nsrp = randomize(rrlookup(nsdp, Tns, NOneg));
  314. /* if the entry timed out, ignore it */
  315. if(nsrp && nsrp->ttl < now){
  316. rrfreelist(nsrp);
  317. nsrp = nil;
  318. }
  319. if(nsrp){
  320. rrfreelist(dbnsrp);
  321. /* query the name servers found in cache */
  322. qp->nsrp = nsrp;
  323. if(netquery(qp, depth+1)){
  324. rrfreelist(nsrp);
  325. return rrlookup(qp->dp, qp->type, OKneg);
  326. }
  327. rrfreelist(nsrp);
  328. continue;
  329. }
  330. /* use ns from db */
  331. if(dbnsrp){
  332. /* try the name servers found in db */
  333. qp->nsrp = dbnsrp;
  334. if(netquery(qp, depth+1)){
  335. /* we got an answer */
  336. rrfreelist(dbnsrp);
  337. return rrlookup(qp->dp, qp->type, NOneg);
  338. }
  339. rrfreelist(dbnsrp);
  340. }
  341. }
  342. return nil;
  343. }
  344. static RR*
  345. dnresolve1(char *name, int class, int type, Request *req, int depth,
  346. int recurse)
  347. {
  348. Area *area;
  349. DN *dp;
  350. RR *rp;
  351. Query *qp;
  352. if(debug)
  353. dnslog("[%d] dnresolve1 %s %d %d", getpid(), name, type, class);
  354. /* only class Cin implemented so far */
  355. if(class != Cin)
  356. return nil;
  357. dp = dnlookup(name, class, 1);
  358. /*
  359. * Try the cache first
  360. */
  361. rp = rrlookup(dp, type, OKneg);
  362. if(rp)
  363. if(rp->db){
  364. /* unauthoritative db entries are hints */
  365. if(rp->auth) {
  366. noteinmem();
  367. return rp;
  368. }
  369. } else
  370. /* cached entry must still be valid */
  371. if(rp->ttl > now)
  372. /* but Tall entries are special */
  373. if(type != Tall || rp->query == Tall) {
  374. noteinmem();
  375. return rp;
  376. }
  377. rrfreelist(rp);
  378. rp = nil; /* accident prevention */
  379. USED(rp);
  380. /*
  381. * try the cache for a canonical name. if found punt
  382. * since we'll find it during the canonical name search
  383. * in dnresolve().
  384. */
  385. if(type != Tcname){
  386. rp = rrlookup(dp, Tcname, NOneg);
  387. rrfreelist(rp);
  388. if(rp)
  389. return nil;
  390. }
  391. /*
  392. * if the domain name is within an area of ours,
  393. * we should have found its data in memory by now.
  394. */
  395. area = inmyarea(dp->name);
  396. if (area || strncmp(dp->name, "local#", 6) == 0) {
  397. // char buf[32];
  398. // dnslog("%s %s: no data in area %s", dp->name,
  399. // rrname(type, buf, sizeof buf), area->soarr->owner->name);
  400. return nil;
  401. }
  402. qp = emalloc(sizeof *qp);
  403. queryinit(qp, dp, type, req);
  404. rp = issuequery(qp, name, class, depth, recurse);
  405. querydestroy(qp);
  406. free(qp);
  407. if(rp)
  408. return rp;
  409. /* settle for a non-authoritative answer */
  410. rp = rrlookup(dp, type, OKneg);
  411. if(rp)
  412. return rp;
  413. /* noone answered. try the database, we might have a chance. */
  414. return dblookup(name, class, type, 0, 0);
  415. }
  416. /*
  417. * walk a domain name one element to the right.
  418. * return a pointer to that element.
  419. * in other words, return a pointer to the parent domain name.
  420. */
  421. char*
  422. walkup(char *name)
  423. {
  424. char *cp;
  425. cp = strchr(name, '.');
  426. if(cp)
  427. return cp+1;
  428. else if(*name)
  429. return "";
  430. else
  431. return 0;
  432. }
  433. /*
  434. * Get a udp port for sending requests and reading replies. Put the port
  435. * into "headers" mode.
  436. */
  437. static char *hmsg = "headers";
  438. int
  439. udpport(char *mtpt)
  440. {
  441. int fd, ctl;
  442. char ds[64], adir[64];
  443. /* get a udp port */
  444. snprint(ds, sizeof ds, "%s/udp!*!0", (mtpt? mtpt: "/net"));
  445. ctl = announce(ds, adir);
  446. if(ctl < 0){
  447. /* warning("can't get udp port"); */
  448. return -1;
  449. }
  450. /* turn on header style interface */
  451. if(write(ctl, hmsg, strlen(hmsg)) , 0){
  452. close(ctl);
  453. warning(hmsg);
  454. return -1;
  455. }
  456. /* grab the data file */
  457. snprint(ds, sizeof ds, "%s/data", adir);
  458. fd = open(ds, ORDWR);
  459. close(ctl);
  460. if(fd < 0)
  461. warning("can't open udp port %s: %r", ds);
  462. return fd;
  463. }
  464. /* generate a DNS UDP query packet */
  465. int
  466. mkreq(DN *dp, int type, uchar *buf, int flags, ushort reqno)
  467. {
  468. DNSmsg m;
  469. int len;
  470. Udphdr *uh = (Udphdr*)buf;
  471. /* stuff port number into output buffer */
  472. memset(uh, 0, sizeof *uh);
  473. hnputs(uh->rport, 53);
  474. /* make request and convert it to output format */
  475. memset(&m, 0, sizeof m);
  476. m.flags = flags;
  477. m.id = reqno;
  478. m.qd = rralloc(type);
  479. m.qd->owner = dp;
  480. m.qd->type = type;
  481. if (m.qd->type != type)
  482. dnslog("mkreq: bogus type %d", type);
  483. len = convDNS2M(&m, &buf[Udphdrsize], Maxudp);
  484. rrfree(m.qd);
  485. memset(&m, 0, sizeof m); /* cause trouble */
  486. return len;
  487. }
  488. /* for alarms in readreply */
  489. static void
  490. ding(void*, char *msg)
  491. {
  492. if(strstr(msg, "alarm") != nil)
  493. noted(NCONT); /* resume with system call error */
  494. else
  495. noted(NDFLT); /* die */
  496. }
  497. void
  498. freeanswers(DNSmsg *mp)
  499. {
  500. rrfreelist(mp->qd);
  501. rrfreelist(mp->an);
  502. rrfreelist(mp->ns);
  503. rrfreelist(mp->ar);
  504. mp->qd = mp->an = mp->ns = mp->ar = nil;
  505. }
  506. /* sets srcip */
  507. static int
  508. readnet(Query *qp, int medium, uchar *ibuf, ulong endtime, uchar **replyp,
  509. uchar *srcip)
  510. {
  511. int len, fd;
  512. long ms;
  513. vlong startns = nsec();
  514. uchar *reply;
  515. uchar lenbuf[2];
  516. /* timed read of reply */
  517. ms = S2MS(endtime) - NS2MS(startns);
  518. if (ms < 2000)
  519. ms = 2000; /* give the remote ns a fighting chance */
  520. reply = ibuf;
  521. len = -1; /* pessimism */
  522. memset(srcip, 0, IPaddrlen);
  523. if (medium == Udp)
  524. if (qp->udpfd <= 0)
  525. dnslog("readnet: qp->udpfd closed");
  526. else {
  527. alarm(ms);
  528. len = read(qp->udpfd, ibuf, Udphdrsize+Maxudpin);
  529. alarm(0);
  530. notestats(startns, len < 0, qp->type);
  531. if (len >= IPaddrlen)
  532. memmove(srcip, ibuf, IPaddrlen);
  533. if (len >= Udphdrsize) {
  534. len -= Udphdrsize;
  535. reply += Udphdrsize;
  536. }
  537. }
  538. else {
  539. if (!qp->tcpset)
  540. dnslog("readnet: tcp params not set");
  541. alarm(ms);
  542. fd = qp->tcpfd;
  543. if (fd <= 0)
  544. dnslog("readnet: %s: tcp fd unset for dest %I",
  545. qp->dp->name, qp->tcpip);
  546. else if (readn(fd, lenbuf, 2) != 2) {
  547. dnslog("readnet: short read of tcp size from %I",
  548. qp->tcpip);
  549. /* probably a time-out */
  550. notestats(startns, 1, qp->type);
  551. } else {
  552. len = lenbuf[0]<<8 | lenbuf[1];
  553. if (readn(fd, ibuf, len) != len) {
  554. dnslog("readnet: short read of tcp data from %I",
  555. qp->tcpip);
  556. /* probably a time-out */
  557. notestats(startns, 1, qp->type);
  558. len = -1;
  559. }
  560. }
  561. alarm(0);
  562. memmove(srcip, qp->tcpip, IPaddrlen);
  563. }
  564. *replyp = reply;
  565. return len;
  566. }
  567. /*
  568. * read replies to a request and remember the rrs in the answer(s).
  569. * ignore any of the wrong type.
  570. * wait at most until endtime.
  571. */
  572. static int
  573. readreply(Query *qp, int medium, ushort req, uchar *ibuf, DNSmsg *mp,
  574. ulong endtime)
  575. {
  576. int len, rv;
  577. char *err;
  578. char tbuf[32];
  579. uchar *reply;
  580. uchar srcip[IPaddrlen];
  581. RR *rp;
  582. static int first = 1;
  583. if (first) {
  584. first = 0;
  585. notify(ding);
  586. }
  587. queryck(qp);
  588. rv = 0;
  589. memset(mp, 0, sizeof *mp);
  590. if (time(nil) >= endtime)
  591. return -1; /* timed out before we started */
  592. memset(srcip, 0, sizeof srcip);
  593. if (0)
  594. len = -1;
  595. for (; time(nil) < endtime &&
  596. (len = readnet(qp, medium, ibuf, endtime, &reply, srcip)) >= 0;
  597. freeanswers(mp)){
  598. /* convert into internal format */
  599. memset(mp, 0, sizeof *mp);
  600. err = convM2DNS(reply, len, mp, nil);
  601. if (mp->flags & Ftrunc) {
  602. free(err);
  603. freeanswers(mp);
  604. /* notify our caller to retry the query via tcp. */
  605. return -1;
  606. } else if(err){
  607. dnslog("readreply: %s: input err, len %d: %s: %I",
  608. qp->dp->name, len, err, srcip);
  609. free(err);
  610. continue;
  611. }
  612. if(debug)
  613. logreply(qp->req->id, srcip, mp);
  614. /* answering the right question? */
  615. if(mp->id != req)
  616. dnslog("%d: id %d instead of %d: %I", qp->req->id,
  617. mp->id, req, srcip);
  618. else if(mp->qd == 0)
  619. dnslog("%d: no question RR: %I", qp->req->id, srcip);
  620. else if(mp->qd->owner != qp->dp)
  621. dnslog("%d: owner %s instead of %s: %I", qp->req->id,
  622. mp->qd->owner->name, qp->dp->name, srcip);
  623. else if(mp->qd->type != qp->type)
  624. dnslog("%d: qp->type %d instead of %d: %I",
  625. qp->req->id, mp->qd->type, qp->type, srcip);
  626. else {
  627. /* remember what request this is in answer to */
  628. for(rp = mp->an; rp; rp = rp->next)
  629. rp->query = qp->type;
  630. return rv;
  631. }
  632. }
  633. if (time(nil) >= endtime) {
  634. ; /* query expired */
  635. } else if (0) {
  636. /* this happens routinely when a read times out */
  637. dnslog("readreply: %s type %s: ns %I read error or eof "
  638. "(returned %d): %r", qp->dp->name, rrname(qp->type,
  639. tbuf, sizeof tbuf), srcip, len);
  640. if (medium == Udp)
  641. for (rp = qp->nsrp; rp != nil; rp = rp->next)
  642. if (rp->type == Tns)
  643. dnslog("readreply: %s: query sent to "
  644. "ns %s", qp->dp->name,
  645. rp->host->name);
  646. }
  647. return -1;
  648. }
  649. /*
  650. * return non-0 if first list includes second list
  651. */
  652. int
  653. contains(RR *rp1, RR *rp2)
  654. {
  655. RR *trp1, *trp2;
  656. for(trp2 = rp2; trp2; trp2 = trp2->next){
  657. for(trp1 = rp1; trp1; trp1 = trp1->next)
  658. if(trp1->type == trp2->type)
  659. if(trp1->host == trp2->host)
  660. if(trp1->owner == trp2->owner)
  661. break;
  662. if(trp1 == nil)
  663. return 0;
  664. }
  665. return 1;
  666. }
  667. /*
  668. * return multicast version if any
  669. */
  670. int
  671. ipisbm(uchar *ip)
  672. {
  673. if(isv4(ip)){
  674. if (ip[IPv4off] >= 0xe0 && ip[IPv4off] < 0xf0 ||
  675. ipcmp(ip, IPv4bcast) == 0)
  676. return 4;
  677. } else
  678. if(ip[0] == 0xff)
  679. return 6;
  680. return 0;
  681. }
  682. /*
  683. * Get next server address
  684. */
  685. static int
  686. serveraddrs(Query *qp, int nd, int depth)
  687. {
  688. RR *rp, *arp, *trp;
  689. Dest *cur;
  690. if(nd >= Maxdest)
  691. return 0;
  692. /*
  693. * look for a server whose address we already know.
  694. * if we find one, mark it so we ignore this on
  695. * subsequent passes.
  696. */
  697. arp = 0;
  698. for(rp = qp->nsrp; rp; rp = rp->next){
  699. assert(rp->magic == RRmagic);
  700. if(rp->marker)
  701. continue;
  702. arp = rrlookup(rp->host, Ta, NOneg);
  703. if(arp){
  704. rp->marker = 1;
  705. break;
  706. }
  707. arp = dblookup(rp->host->name, Cin, Ta, 0, 0);
  708. if(arp){
  709. rp->marker = 1;
  710. break;
  711. }
  712. }
  713. /*
  714. * if the cache and database lookup didn't find any new
  715. * server addresses, try resolving one via the network.
  716. * Mark any we try to resolve so we don't try a second time.
  717. */
  718. if(arp == 0)
  719. for(rp = qp->nsrp; rp; rp = rp->next){
  720. if(rp->marker)
  721. continue;
  722. rp->marker = 1;
  723. /*
  724. * avoid loops looking up a server under itself
  725. */
  726. if(subsume(rp->owner->name, rp->host->name))
  727. continue;
  728. arp = dnresolve(rp->host->name, Cin, Ta, qp->req, 0,
  729. depth+1, Recurse, 1, 0);
  730. rrfreelist(rrremneg(&arp));
  731. if(arp)
  732. break;
  733. }
  734. /* use any addresses that we found */
  735. for(trp = arp; trp && nd < Maxdest; trp = trp->next){
  736. cur = &qp->dest[nd];
  737. parseip(cur->a, trp->ip->name);
  738. /*
  739. * straddling servers can reject all nameservers if they are all
  740. * inside, so be sure to list at least one outside ns at
  741. * the end of the ns list in /lib/ndb for `dom='.
  742. */
  743. if (ipisbm(cur->a) ||
  744. cfg.straddle && !insideaddr(qp->dp->name) && insidens(cur->a))
  745. continue;
  746. cur->nx = 0;
  747. cur->s = trp->owner;
  748. cur->code = Rtimeout;
  749. nd++;
  750. }
  751. rrfreelist(arp);
  752. return nd;
  753. }
  754. /*
  755. * cache negative responses
  756. */
  757. static void
  758. cacheneg(DN *dp, int type, int rcode, RR *soarr)
  759. {
  760. RR *rp;
  761. DN *soaowner;
  762. ulong ttl;
  763. stats.negcached++;
  764. /* no cache time specified, don't make anything up */
  765. if(soarr != nil){
  766. if(soarr->next != nil){
  767. rrfreelist(soarr->next);
  768. soarr->next = nil;
  769. }
  770. soaowner = soarr->owner;
  771. } else
  772. soaowner = nil;
  773. /* the attach can cause soarr to be freed so mine it now */
  774. if(soarr != nil && soarr->soa != nil)
  775. ttl = soarr->soa->minttl+now;
  776. else
  777. ttl = 5*Min;
  778. /* add soa and negative RR to the database */
  779. rrattach(soarr, Authoritative);
  780. rp = rralloc(type);
  781. rp->owner = dp;
  782. rp->negative = 1;
  783. rp->negsoaowner = soaowner;
  784. rp->negrcode = rcode;
  785. rp->ttl = ttl;
  786. rrattach(rp, Authoritative);
  787. }
  788. static int
  789. setdestoutns(Dest *p, int n)
  790. {
  791. uchar *outns = outsidens(n);
  792. destck(p);
  793. destinit(p);
  794. if (outns == nil) {
  795. if (n == 0)
  796. dnslog("[%d] no outside-ns in ndb", getpid());
  797. return -1;
  798. }
  799. memmove(p->a, outns, sizeof p->a);
  800. p->s = dnlookup("outside-ns-ips", Cin, 1);
  801. return 0;
  802. }
  803. /*
  804. * issue query via UDP or TCP as appropriate.
  805. * for TCP, returns with qp->tcpip set from udppkt header.
  806. */
  807. static int
  808. mydnsquery(Query *qp, int medium, uchar *udppkt, int len)
  809. {
  810. int rv = -1, nfd;
  811. char *domain;
  812. char conndir[40];
  813. uchar belen[2];
  814. NetConnInfo *nci;
  815. queryck(qp);
  816. domain = smprint("%I", udppkt);
  817. if (myaddr(domain)) {
  818. dnslog("mydnsquery: trying to send to myself (%s); bzzzt",
  819. domain);
  820. free(domain);
  821. return rv;
  822. }
  823. switch (medium) {
  824. case Udp:
  825. free(domain);
  826. nfd = dup(qp->udpfd, -1);
  827. if (nfd < 0) {
  828. warning("mydnsquery: qp->udpfd %d: %r", qp->udpfd);
  829. close(qp->udpfd); /* ensure it's closed */
  830. qp->udpfd = -1; /* poison it */
  831. return rv;
  832. }
  833. close(nfd);
  834. if (qp->udpfd <= 0)
  835. dnslog("mydnsquery: qp->udpfd %d closed", qp->udpfd);
  836. else {
  837. if (write(qp->udpfd, udppkt, len+Udphdrsize) !=
  838. len+Udphdrsize)
  839. warning("sending udp msg: %r");
  840. else {
  841. stats.qsent++;
  842. rv = 0;
  843. }
  844. }
  845. break;
  846. case Tcp:
  847. /* send via TCP & keep fd around for reply */
  848. alarm(10*1000);
  849. qp->tcpfd = rv = dial(netmkaddr(domain, "tcp", "dns"), nil,
  850. conndir, &qp->tcpctlfd);
  851. alarm(0);
  852. if (qp->tcpfd < 0) {
  853. dnslog("can't dial tcp!%s!dns: %r", domain);
  854. free(domain);
  855. break;
  856. }
  857. free(domain);
  858. nci = getnetconninfo(conndir, qp->tcpfd);
  859. if (nci) {
  860. parseip(qp->tcpip, nci->rsys);
  861. freenetconninfo(nci);
  862. } else
  863. dnslog("mydnsquery: getnetconninfo failed");
  864. qp->tcpset = 1;
  865. belen[0] = len >> 8;
  866. belen[1] = len;
  867. if (write(qp->tcpfd, belen, 2) != 2 ||
  868. write(qp->tcpfd, udppkt + Udphdrsize, len) != len)
  869. warning("sending tcp msg: %r");
  870. break;
  871. default:
  872. sysfatal("mydnsquery: bad medium");
  873. }
  874. return rv;
  875. }
  876. /*
  877. * send query to all UDP destinations or one TCP destination,
  878. * taken from obuf (udp packet) header
  879. */
  880. static int
  881. xmitquery(Query *qp, int medium, int depth, uchar *obuf, int inns, int len)
  882. {
  883. int j, n;
  884. char buf[32];
  885. Dest *p;
  886. queryck(qp);
  887. if(time(nil) >= qp->req->aborttime)
  888. return -1;
  889. /*
  890. * get a nameserver address if we need one.
  891. * serveraddrs populates qp->dest.
  892. */
  893. p = qp->dest;
  894. destck(p);
  895. if (qp->ndest < 0 || qp->ndest > Maxdest)
  896. dnslog("qp->ndest %d out of range", qp->ndest);
  897. if (qp->ndest > qp->curdest - p)
  898. qp->curdest = &qp->dest[serveraddrs(qp, qp->curdest - p, depth)];
  899. destck(qp->curdest);
  900. /* no servers, punt */
  901. if (qp->curdest == qp->dest)
  902. if (cfg.straddle && cfg.inside) {
  903. /* get ips of "outside-ns-ips" */
  904. p = qp->curdest = qp->dest;
  905. for(n = 0; n < Maxdest; n++, qp->curdest++)
  906. if (setdestoutns(qp->curdest, n) < 0)
  907. break;
  908. } else {
  909. /* it's probably just a bogus domain, don't log it */
  910. // dnslog("xmitquery: %s: no nameservers", qp->dp->name);
  911. return -1;
  912. }
  913. /* send to first 'qp->ndest' destinations */
  914. j = 0;
  915. if (medium == Tcp) {
  916. j++;
  917. queryck(qp);
  918. assert(qp->dp);
  919. procsetname("tcp %sside query for %s %s", (inns? "in": "out"),
  920. qp->dp->name, rrname(qp->type, buf, sizeof buf));
  921. mydnsquery(qp, medium, obuf, len); /* sets qp->tcpip from obuf */
  922. if(debug)
  923. logsend(qp->req->id, depth, qp->tcpip, "", qp->dp->name,
  924. qp->type);
  925. } else
  926. for(; p < &qp->dest[qp->ndest] && p < qp->curdest; p++){
  927. /* skip destinations we've finished with */
  928. if(p->nx >= Maxtrans)
  929. continue;
  930. j++;
  931. /* exponential backoff of requests */
  932. if((1<<p->nx) > qp->ndest)
  933. continue;
  934. procsetname("udp %sside query to %I/%s %s %s",
  935. (inns? "in": "out"), p->a, p->s->name,
  936. qp->dp->name, rrname(qp->type, buf, sizeof buf));
  937. if(debug)
  938. logsend(qp->req->id, depth, p->a, p->s->name,
  939. qp->dp->name, qp->type);
  940. /* fill in UDP destination addr & send it */
  941. memmove(obuf, p->a, sizeof p->a);
  942. mydnsquery(qp, medium, obuf, len);
  943. p->nx++;
  944. }
  945. if(j == 0) {
  946. // dnslog("xmitquery: %s: no destinations left", qp->dp->name);
  947. return -1;
  948. }
  949. return 0;
  950. }
  951. static int lckindex[Maxlcks] = {
  952. 0, /* all others map here */
  953. Ta,
  954. Tns,
  955. Tcname,
  956. Tsoa,
  957. Tptr,
  958. Tmx,
  959. Ttxt,
  960. Taaaa,
  961. };
  962. static int
  963. qtype2lck(int qtype) /* map query type to querylck index */
  964. {
  965. int i;
  966. for (i = 1; i < nelem(lckindex); i++)
  967. if (lckindex[i] == qtype)
  968. return i;
  969. return 0;
  970. }
  971. /* is mp a cachable negative response (with Rname set)? */
  972. static int
  973. isnegrname(DNSmsg *mp)
  974. {
  975. /* TODO: could add || cfg.justforw to RHS of && */
  976. return mp->an == nil && (mp->flags & Rmask) == Rname;
  977. }
  978. static int
  979. procansw(Query *qp, DNSmsg *mp, uchar *srcip, int depth, Dest *p)
  980. {
  981. int rv;
  982. // int lcktype;
  983. char buf[32];
  984. DN *ndp;
  985. Query *nqp;
  986. RR *tp, *soarr;
  987. if (mp->an == nil)
  988. stats.negans++;
  989. /* ignore any error replies */
  990. if((mp->flags & Rmask) == Rserver){
  991. stats.negserver++;
  992. freeanswers(mp);
  993. if(p != qp->curdest)
  994. p->code = Rserver;
  995. return -1;
  996. }
  997. /* ignore any bad delegations */
  998. if(mp->ns && baddelegation(mp->ns, qp->nsrp, srcip)){
  999. stats.negbaddeleg++;
  1000. if(mp->an == nil){
  1001. stats.negbdnoans++;
  1002. freeanswers(mp);
  1003. if(p != qp->curdest)
  1004. p->code = Rserver;
  1005. return -1;
  1006. }
  1007. rrfreelist(mp->ns);
  1008. mp->ns = nil;
  1009. }
  1010. /* remove any soa's from the authority section */
  1011. soarr = rrremtype(&mp->ns, Tsoa);
  1012. /* incorporate answers */
  1013. unique(mp->an);
  1014. unique(mp->ns);
  1015. unique(mp->ar);
  1016. if(mp->an)
  1017. rrattach(mp->an, (mp->flags & Fauth) != 0);
  1018. if(mp->ar)
  1019. rrattach(mp->ar, Notauthoritative);
  1020. if(mp->ns && !cfg.justforw){
  1021. ndp = mp->ns->owner;
  1022. rrattach(mp->ns, Notauthoritative);
  1023. } else {
  1024. ndp = nil;
  1025. rrfreelist(mp->ns);
  1026. mp->ns = nil;
  1027. }
  1028. /* free the question */
  1029. if(mp->qd) {
  1030. rrfreelist(mp->qd);
  1031. mp->qd = nil;
  1032. }
  1033. /*
  1034. * Any reply from an authoritative server,
  1035. * or a positive reply terminates the search.
  1036. * A negative response now also terminates the search.
  1037. */
  1038. if(mp->an != nil || (mp->flags & Fauth)){
  1039. if(isnegrname(mp))
  1040. qp->dp->respcode = Rname;
  1041. else
  1042. qp->dp->respcode = 0;
  1043. /*
  1044. * cache any negative responses, free soarr.
  1045. * negative responses need not be authoritative:
  1046. * they can legitimately come from a cache.
  1047. */
  1048. if( /* (mp->flags & Fauth) && */ mp->an == nil)
  1049. cacheneg(qp->dp, qp->type, (mp->flags & Rmask), soarr);
  1050. else
  1051. rrfreelist(soarr);
  1052. return 1;
  1053. } else if (isnegrname(mp)) {
  1054. qp->dp->respcode = Rname;
  1055. /*
  1056. * cache negative response.
  1057. * negative responses need not be authoritative:
  1058. * they can legitimately come from a cache.
  1059. */
  1060. cacheneg(qp->dp, qp->type, (mp->flags & Rmask), soarr);
  1061. return 1;
  1062. }
  1063. stats.negnorname++;
  1064. rrfreelist(soarr);
  1065. /*
  1066. * if we've been given better name servers, recurse.
  1067. * if we're a pure resolver, don't recurse, we have
  1068. * to forward to a fixed set of named servers.
  1069. */
  1070. if(!mp->ns || cfg.resolver && cfg.justforw)
  1071. return 0;
  1072. tp = rrlookup(ndp, Tns, NOneg);
  1073. if(contains(qp->nsrp, tp)){
  1074. rrfreelist(tp);
  1075. return 0;
  1076. }
  1077. procsetname("recursive query for %s %s", qp->dp->name,
  1078. rrname(qp->type, buf, sizeof buf));
  1079. /*
  1080. * we're called from udpquery, called from
  1081. * netquery, which current holds qp->dp->querylck,
  1082. * so release it now and acquire it upon return.
  1083. */
  1084. // lcktype = qtype2lck(qp->type);
  1085. // qunlock(&qp->dp->querylck[lcktype]);
  1086. nqp = emalloc(sizeof *nqp);
  1087. queryinit(nqp, qp->dp, qp->type, qp->req);
  1088. nqp->nsrp = tp;
  1089. rv = netquery(nqp, depth+1);
  1090. // qlock(&qp->dp->querylck[lcktype]);
  1091. rrfreelist(nqp->nsrp);
  1092. querydestroy(nqp);
  1093. free(nqp);
  1094. return rv;
  1095. }
  1096. /*
  1097. * send a query via tcp to a single address (from ibuf's udp header)
  1098. * and read the answer(s) into mp->an.
  1099. */
  1100. static int
  1101. tcpquery(Query *qp, DNSmsg *mp, int depth, uchar *ibuf, uchar *obuf, int len,
  1102. int waitsecs, int inns, ushort req)
  1103. {
  1104. int rv = 0;
  1105. ulong endtime;
  1106. endtime = time(nil) + waitsecs;
  1107. if(endtime > qp->req->aborttime)
  1108. endtime = qp->req->aborttime;
  1109. if (0)
  1110. dnslog("%s: udp reply truncated; retrying query via tcp to %I",
  1111. qp->dp->name, qp->tcpip);
  1112. qlock(&qp->tcplock);
  1113. memmove(obuf, ibuf, IPaddrlen); /* send back to respondent */
  1114. /* sets qp->tcpip from obuf's udp header */
  1115. if (xmitquery(qp, Tcp, depth, obuf, inns, len) < 0 ||
  1116. readreply(qp, Tcp, req, ibuf, mp, endtime) < 0)
  1117. rv = -1;
  1118. if (qp->tcpfd > 0) {
  1119. hangup(qp->tcpctlfd);
  1120. close(qp->tcpctlfd);
  1121. close(qp->tcpfd);
  1122. }
  1123. qp->tcpfd = qp->tcpctlfd = -1;
  1124. qunlock(&qp->tcplock);
  1125. return rv;
  1126. }
  1127. /*
  1128. * query name servers. If the name server returns a pointer to another
  1129. * name server, recurse.
  1130. */
  1131. static int
  1132. queryns(Query *qp, int depth, uchar *ibuf, uchar *obuf, int waitsecs, int inns)
  1133. {
  1134. int ndest, len, replywaits, rv;
  1135. ushort req;
  1136. ulong endtime;
  1137. char buf[12];
  1138. uchar srcip[IPaddrlen];
  1139. Dest *p, *np, *dest;
  1140. // Dest dest[Maxdest];
  1141. /* pack request into a udp message */
  1142. req = rand();
  1143. len = mkreq(qp->dp, qp->type, obuf, Frecurse|Oquery, req);
  1144. /* no server addresses yet */
  1145. queryck(qp);
  1146. dest = emalloc(Maxdest * sizeof *dest); /* dest can't be on stack */
  1147. for (p = dest; p < dest + Maxdest; p++)
  1148. destinit(p);
  1149. /* this dest array is local to this call of queryns() */
  1150. free(qp->dest);
  1151. qp->curdest = qp->dest = dest;
  1152. /*
  1153. * transmit udp requests and wait for answers.
  1154. * at most Maxtrans attempts to each address.
  1155. * each cycle send one more message than the previous.
  1156. * retry a query via tcp if its response is truncated.
  1157. */
  1158. for(ndest = 1; ndest < Maxdest; ndest++){
  1159. qp->ndest = ndest;
  1160. qp->tcpset = 0;
  1161. if (xmitquery(qp, Udp, depth, obuf, inns, len) < 0)
  1162. break;
  1163. endtime = time(nil) + waitsecs;
  1164. if(endtime > qp->req->aborttime)
  1165. endtime = qp->req->aborttime;
  1166. for(replywaits = 0; replywaits < ndest; replywaits++){
  1167. DNSmsg m;
  1168. procsetname("reading %sside reply from %I: %s %s from %s",
  1169. (inns? "in": "out"), obuf, qp->dp->name,
  1170. rrname(qp->type, buf, sizeof buf), qp->req->from);
  1171. /* read udp answer into m */
  1172. if (readreply(qp, Udp, req, ibuf, &m, endtime) >= 0)
  1173. memmove(srcip, ibuf, IPaddrlen);
  1174. else if (!(m.flags & Ftrunc)) {
  1175. freeanswers(&m);
  1176. break; /* timed out on this dest */
  1177. } else {
  1178. /* whoops, it was truncated! ask again via tcp */
  1179. freeanswers(&m);
  1180. rv = tcpquery(qp, &m, depth, ibuf, obuf, len,
  1181. waitsecs, inns, req); /* answer in m */
  1182. if (rv < 0) {
  1183. freeanswers(&m);
  1184. break; /* failed via tcp too */
  1185. }
  1186. memmove(srcip, qp->tcpip, IPaddrlen);
  1187. }
  1188. /* find responder */
  1189. // dnslog("queryns got reply from %I", srcip);
  1190. for(p = qp->dest; p < qp->curdest; p++)
  1191. if(memcmp(p->a, srcip, sizeof p->a) == 0)
  1192. break;
  1193. /* remove all addrs of responding server from list */
  1194. for(np = qp->dest; np < qp->curdest; np++)
  1195. if(np->s == p->s)
  1196. p->nx = Maxtrans;
  1197. /* free or incorporate RRs in m */
  1198. rv = procansw(qp, &m, srcip, depth, p);
  1199. if (rv > 0) {
  1200. free(qp->dest);
  1201. qp->dest = qp->curdest = nil; /* prevent accidents */
  1202. return rv;
  1203. }
  1204. }
  1205. }
  1206. /* if all servers returned failure, propagate it */
  1207. qp->dp->respcode = Rserver;
  1208. for(p = dest; p < qp->curdest; p++) {
  1209. destck(p);
  1210. if(p->code != Rserver)
  1211. qp->dp->respcode = 0;
  1212. p->magic = 0; /* prevent accidents */
  1213. }
  1214. // if (qp->dp->respcode)
  1215. // dnslog("queryns setting Rserver for %s", qp->dp->name);
  1216. free(qp->dest);
  1217. qp->dest = qp->curdest = nil; /* prevent accidents */
  1218. return 0;
  1219. }
  1220. /*
  1221. * run a command with a supplied fd as standard input
  1222. */
  1223. char *
  1224. system(int fd, char *cmd)
  1225. {
  1226. int pid, p, i;
  1227. static Waitmsg msg;
  1228. if((pid = fork()) == -1)
  1229. sysfatal("fork failed: %r");
  1230. else if(pid == 0){
  1231. dup(fd, 0);
  1232. close(fd);
  1233. for (i = 3; i < 200; i++)
  1234. close(i); /* don't leak fds */
  1235. execl("/bin/rc", "rc", "-c", cmd, nil);
  1236. sysfatal("exec rc: %r");
  1237. }
  1238. for(p = waitpid(); p >= 0; p = waitpid())
  1239. if(p == pid)
  1240. return msg.msg;
  1241. return "lost child";
  1242. }
  1243. /* compute wait, weighted by probability of success, with minimum */
  1244. static ulong
  1245. weight(ulong ms, unsigned pcntprob)
  1246. {
  1247. ulong wait;
  1248. wait = (ms * pcntprob) / 100;
  1249. if (wait < 1500)
  1250. wait = 1500;
  1251. return wait;
  1252. }
  1253. /*
  1254. * in principle we could use a single descriptor for a udp port
  1255. * to send all queries and receive all the answers to them,
  1256. * but we'd have to sort out the answers by dns-query id.
  1257. */
  1258. static int
  1259. udpquery(Query *qp, char *mntpt, int depth, int patient, int inns)
  1260. {
  1261. int fd, rv;
  1262. long now;
  1263. ulong pcntprob, wait, reqtm;
  1264. char *msg;
  1265. uchar *obuf, *ibuf;
  1266. static QLock mntlck;
  1267. static ulong lastmount;
  1268. /* use alloced buffers rather than ones from the stack */
  1269. // ibuf = emalloc(Maxudpin+Udphdrsize);
  1270. ibuf = emalloc(64*1024); /* max. tcp reply size */
  1271. obuf = emalloc(Maxudp+Udphdrsize);
  1272. fd = udpport(mntpt);
  1273. while (fd < 0 && cfg.straddle && strcmp(mntpt, "/net.alt") == 0) {
  1274. /* HACK: remount /net.alt */
  1275. now = time(nil);
  1276. if (now < lastmount + Remntretry)
  1277. sleep((lastmount + Remntretry - now)*1000);
  1278. qlock(&mntlck);
  1279. fd = udpport(mntpt); /* try again under lock */
  1280. if (fd < 0) {
  1281. dnslog("[%d] remounting /net.alt", getpid());
  1282. unmount(nil, "/net.alt");
  1283. msg = system(open("/dev/null", ORDWR), "outside");
  1284. lastmount = time(nil);
  1285. if (msg && *msg) {
  1286. dnslog("[%d] can't remount /net.alt: %s",
  1287. getpid(), msg);
  1288. sleep(10*1000); /* don't spin wildly */
  1289. } else
  1290. fd = udpport(mntpt);
  1291. }
  1292. qunlock(&mntlck);
  1293. }
  1294. if (fd < 0) {
  1295. dnslog("can't get udpport for %s query of name %s: %r",
  1296. mntpt, qp->dp->name);
  1297. sysfatal("out of udp conversations"); /* we're buggered */
  1298. }
  1299. /*
  1300. * Our QIP servers are busted, don't answer AAAA and
  1301. * take forever to answer CNAME if there isn't one.
  1302. * They rarely set Rname.
  1303. * make time-to-wait proportional to estimated probability of an
  1304. * RR of that type existing.
  1305. */
  1306. if (qp->type >= nelem(likely))
  1307. pcntprob = 35; /* unpopular query type */
  1308. else
  1309. pcntprob = likely[qp->type];
  1310. reqtm = (patient? 2*Maxreqtm: Maxreqtm);
  1311. /* time for a single outgoing udp query */
  1312. wait = weight(S2MS(reqtm)/3, pcntprob);
  1313. qp->req->aborttime = time(nil) + MS2S(3*wait); /* for all udp queries */
  1314. qp->udpfd = fd;
  1315. rv = queryns(qp, depth, ibuf, obuf, MS2S(wait), inns);
  1316. close(fd);
  1317. qp->udpfd = -1;
  1318. free(obuf);
  1319. free(ibuf);
  1320. return rv;
  1321. }
  1322. /* look up (qp->dp->name,qp->type) rr in dns, via *nsrp with results in *reqp */
  1323. static int
  1324. netquery(Query *qp, int depth)
  1325. {
  1326. int lock, rv, triedin, inname, cnt;
  1327. // char buf[32];
  1328. RR *rp;
  1329. DN *dp;
  1330. Querylck *qlp;
  1331. static int whined;
  1332. rv = 0; /* pessimism */
  1333. if(depth > 12) /* in a recursive loop? */
  1334. return 0;
  1335. slave(qp->req);
  1336. /*
  1337. * slave might have forked. if so, the parent process longjmped to
  1338. * req->mret; we're usually the child slave, but if there are too
  1339. * many children already, we're still the same process.
  1340. */
  1341. /*
  1342. * don't lock before call to slave so only children can block.
  1343. * just lock at top-level invocation.
  1344. */
  1345. lock = depth <= 1 && qp->req->isslave;
  1346. dp = qp->dp; /* ensure that it doesn't change underfoot */
  1347. qlp = nil;
  1348. if(lock) {
  1349. // procsetname("query lock wait: %s %s from %s", dp->name,
  1350. // rrname(qp->type, buf, sizeof buf), qp->req->from);
  1351. /*
  1352. * don't make concurrent queries for this name.
  1353. * dozens of processes blocking here probably indicates
  1354. * an error in our dns data that causes us to not
  1355. * recognise a zone (area) as one of our own, thus
  1356. * causing us to query other nameservers.
  1357. */
  1358. qlp = &dp->querylck[qtype2lck(qp->type)];
  1359. incref(qlp);
  1360. qlock(qlp);
  1361. cnt = qlp->Ref.ref;
  1362. qunlock(qlp);
  1363. if (cnt > 10) {
  1364. decref(qlp);
  1365. if (!whined) {
  1366. whined = 1;
  1367. dnslog("too many outstanding queries for %s; "
  1368. "dropping this one; "
  1369. "no further logging of drops",
  1370. dp->name);
  1371. }
  1372. return 0;
  1373. }
  1374. }
  1375. procsetname("netquery: %s", dp->name);
  1376. /* prepare server RR's for incremental lookup */
  1377. for(rp = qp->nsrp; rp; rp = rp->next)
  1378. rp->marker = 0;
  1379. triedin = 0;
  1380. /*
  1381. * normal resolvers and servers will just use mntpt for all addresses,
  1382. * even on the outside. straddling servers will use mntpt (/net)
  1383. * for inside addresses and /net.alt for outside addresses,
  1384. * thus bypassing other inside nameservers.
  1385. */
  1386. inname = insideaddr(dp->name);
  1387. if (!cfg.straddle || inname) {
  1388. rv = udpquery(qp, mntpt, depth, Hurry, (cfg.inside? Inns: Outns));
  1389. triedin = 1;
  1390. }
  1391. /*
  1392. * if we're still looking, are inside, and have an outside domain,
  1393. * try it on our outside interface, if any.
  1394. */
  1395. if (rv == 0 && cfg.inside && !inname) {
  1396. if (triedin)
  1397. dnslog(
  1398. "[%d] netquery: internal nameservers failed for %s; trying external",
  1399. getpid(), dp->name);
  1400. /* prepare server RR's for incremental lookup */
  1401. for(rp = qp->nsrp; rp; rp = rp->next)
  1402. rp->marker = 0;
  1403. rv = udpquery(qp, "/net.alt", depth, Patient, Outns);
  1404. }
  1405. // if (rv == 0) /* could ask /net.alt/dns directly */
  1406. // askoutdns(dp, qp->type);
  1407. if(lock && qlp)
  1408. decref(qlp);
  1409. return rv;
  1410. }
  1411. int
  1412. seerootns(void)
  1413. {
  1414. int rv;
  1415. char root[] = "";
  1416. Request req;
  1417. Query *qp;
  1418. memset(&req, 0, sizeof req);
  1419. req.isslave = 1;
  1420. req.aborttime = now + Maxreqtm;
  1421. req.from = "internal";
  1422. qp = emalloc(sizeof *qp);
  1423. queryinit(qp, dnlookup(root, Cin, 1), Tns, &req);
  1424. qp->nsrp = dblookup(root, Cin, Tns, 0, 0);
  1425. rv = netquery(qp, 0);
  1426. rrfreelist(qp->nsrp);
  1427. querydestroy(qp);
  1428. free(qp);
  1429. return rv;
  1430. }