dnresolve.c 39 KB

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