doh.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2018 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #ifndef CURL_DISABLE_DOH
  24. #include "urldata.h"
  25. #include "curl_addrinfo.h"
  26. #include "doh.h"
  27. #include "sendf.h"
  28. #include "multiif.h"
  29. #include "url.h"
  30. #include "share.h"
  31. #include "curl_base64.h"
  32. #include "connect.h"
  33. #include "strdup.h"
  34. #include "dynbuf.h"
  35. /* The last 3 #include files should be in this order */
  36. #include "curl_printf.h"
  37. #include "curl_memory.h"
  38. #include "memdebug.h"
  39. #define DNS_CLASS_IN 0x01
  40. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  41. static const char * const errors[]={
  42. "",
  43. "Bad label",
  44. "Out of range",
  45. "Label loop",
  46. "Too small",
  47. "Out of memory",
  48. "RDATA length",
  49. "Malformat",
  50. "Bad RCODE",
  51. "Unexpected TYPE",
  52. "Unexpected CLASS",
  53. "No content",
  54. "Bad ID",
  55. "Name too long"
  56. };
  57. static const char *doh_strerror(DOHcode code)
  58. {
  59. if((code >= DOH_OK) && (code <= DOH_DNS_NAME_TOO_LONG))
  60. return errors[code];
  61. return "bad error code";
  62. }
  63. #endif
  64. #ifdef DEBUGBUILD
  65. #define UNITTEST
  66. #else
  67. #define UNITTEST static
  68. #endif
  69. /* @unittest 1655
  70. */
  71. UNITTEST DOHcode doh_encode(const char *host,
  72. DNStype dnstype,
  73. unsigned char *dnsp, /* buffer */
  74. size_t len, /* buffer size */
  75. size_t *olen) /* output length */
  76. {
  77. const size_t hostlen = strlen(host);
  78. unsigned char *orig = dnsp;
  79. const char *hostp = host;
  80. /* The expected output length is 16 bytes more than the length of
  81. * the QNAME-encoding of the host name.
  82. *
  83. * A valid DNS name may not contain a zero-length label, except at
  84. * the end. For this reason, a name beginning with a dot, or
  85. * containing a sequence of two or more consecutive dots, is invalid
  86. * and cannot be encoded as a QNAME.
  87. *
  88. * If the host name ends with a trailing dot, the corresponding
  89. * QNAME-encoding is one byte longer than the host name. If (as is
  90. * also valid) the hostname is shortened by the omission of the
  91. * trailing dot, then its QNAME-encoding will be two bytes longer
  92. * than the host name.
  93. *
  94. * Each [ label, dot ] pair is encoded as [ length, label ],
  95. * preserving overall length. A final [ label ] without a dot is
  96. * also encoded as [ length, label ], increasing overall length
  97. * by one. The encoding is completed by appending a zero byte,
  98. * representing the zero-length root label, again increasing
  99. * the overall length by one.
  100. */
  101. size_t expected_len;
  102. DEBUGASSERT(hostlen);
  103. expected_len = 12 + 1 + hostlen + 4;
  104. if(host[hostlen-1]!='.')
  105. expected_len++;
  106. if(expected_len > (256 + 16)) /* RFCs 1034, 1035 */
  107. return DOH_DNS_NAME_TOO_LONG;
  108. if(len < expected_len)
  109. return DOH_TOO_SMALL_BUFFER;
  110. *dnsp++ = 0; /* 16 bit id */
  111. *dnsp++ = 0;
  112. *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */
  113. *dnsp++ = '\0'; /* |RA| Z | RCODE | */
  114. *dnsp++ = '\0';
  115. *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */
  116. *dnsp++ = '\0';
  117. *dnsp++ = '\0'; /* ANCOUNT */
  118. *dnsp++ = '\0';
  119. *dnsp++ = '\0'; /* NSCOUNT */
  120. *dnsp++ = '\0';
  121. *dnsp++ = '\0'; /* ARCOUNT */
  122. /* encode each label and store it in the QNAME */
  123. while(*hostp) {
  124. size_t labellen;
  125. char *dot = strchr(hostp, '.');
  126. if(dot)
  127. labellen = dot - hostp;
  128. else
  129. labellen = strlen(hostp);
  130. if((labellen > 63) || (!labellen)) {
  131. /* label is too long or too short, error out */
  132. *olen = 0;
  133. return DOH_DNS_BAD_LABEL;
  134. }
  135. /* label is non-empty, process it */
  136. *dnsp++ = (unsigned char)labellen;
  137. memcpy(dnsp, hostp, labellen);
  138. dnsp += labellen;
  139. hostp += labellen;
  140. /* advance past dot, but only if there is one */
  141. if(dot)
  142. hostp++;
  143. } /* next label */
  144. *dnsp++ = 0; /* append zero-length label for root */
  145. /* There are assigned TYPE codes beyond 255: use range [1..65535] */
  146. *dnsp++ = (unsigned char)(255 & (dnstype>>8)); /* upper 8 bit TYPE */
  147. *dnsp++ = (unsigned char)(255 & dnstype); /* lower 8 bit TYPE */
  148. *dnsp++ = '\0'; /* upper 8 bit CLASS */
  149. *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */
  150. *olen = dnsp - orig;
  151. /* verify that our estimation of length is valid, since
  152. * this has led to buffer overflows in this function */
  153. DEBUGASSERT(*olen == expected_len);
  154. return DOH_OK;
  155. }
  156. static size_t
  157. doh_write_cb(const void *contents, size_t size, size_t nmemb, void *userp)
  158. {
  159. size_t realsize = size * nmemb;
  160. struct dynbuf *mem = (struct dynbuf *)userp;
  161. if(Curl_dyn_addn(mem, contents, realsize))
  162. return 0;
  163. return realsize;
  164. }
  165. /* called from multi.c when this DOH transfer is complete */
  166. static int Curl_doh_done(struct Curl_easy *doh, CURLcode result)
  167. {
  168. struct Curl_easy *data = doh->set.dohfor;
  169. /* so one of the DOH request done for the 'data' transfer is now complete! */
  170. data->req.doh.pending--;
  171. infof(data, "a DOH request is completed, %u to go\n", data->req.doh.pending);
  172. if(result)
  173. infof(data, "DOH request %s\n", curl_easy_strerror(result));
  174. if(!data->req.doh.pending) {
  175. /* DOH completed */
  176. curl_slist_free_all(data->req.doh.headers);
  177. data->req.doh.headers = NULL;
  178. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  179. }
  180. return 0;
  181. }
  182. #define ERROR_CHECK_SETOPT(x,y) \
  183. do { \
  184. result = curl_easy_setopt(doh, x, y); \
  185. if(result) \
  186. goto error; \
  187. } while(0)
  188. static CURLcode dohprobe(struct Curl_easy *data,
  189. struct dnsprobe *p, DNStype dnstype,
  190. const char *host,
  191. const char *url, CURLM *multi,
  192. struct curl_slist *headers)
  193. {
  194. struct Curl_easy *doh = NULL;
  195. char *nurl = NULL;
  196. CURLcode result = CURLE_OK;
  197. timediff_t timeout_ms;
  198. DOHcode d = doh_encode(host, dnstype, p->dohbuffer, sizeof(p->dohbuffer),
  199. &p->dohlen);
  200. if(d) {
  201. failf(data, "Failed to encode DOH packet [%d]\n", d);
  202. return CURLE_OUT_OF_MEMORY;
  203. }
  204. p->dnstype = dnstype;
  205. Curl_dyn_init(&p->serverdoh, DYN_DOH_RESPONSE);
  206. /* Note: this is code for sending the DoH request with GET but there's still
  207. no logic that actually enables this. We should either add that ability or
  208. yank out the GET code. Discuss! */
  209. if(data->set.doh_get) {
  210. char *b64;
  211. size_t b64len;
  212. result = Curl_base64url_encode(data, (char *)p->dohbuffer, p->dohlen,
  213. &b64, &b64len);
  214. if(result)
  215. goto error;
  216. nurl = aprintf("%s?dns=%s", url, b64);
  217. free(b64);
  218. if(!nurl) {
  219. result = CURLE_OUT_OF_MEMORY;
  220. goto error;
  221. }
  222. url = nurl;
  223. }
  224. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  225. if(timeout_ms <= 0) {
  226. result = CURLE_OPERATION_TIMEDOUT;
  227. goto error;
  228. }
  229. /* Curl_open() is the internal version of curl_easy_init() */
  230. result = Curl_open(&doh);
  231. if(!result) {
  232. /* pass in the struct pointer via a local variable to please coverity and
  233. the gcc typecheck helpers */
  234. struct dynbuf *resp = &p->serverdoh;
  235. ERROR_CHECK_SETOPT(CURLOPT_URL, url);
  236. ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb);
  237. ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, resp);
  238. if(!data->set.doh_get) {
  239. ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->dohbuffer);
  240. ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->dohlen);
  241. }
  242. ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers);
  243. #ifdef USE_NGHTTP2
  244. ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
  245. #endif
  246. #ifndef CURLDEBUG
  247. /* enforce HTTPS if not debug */
  248. ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
  249. #else
  250. /* in debug mode, also allow http */
  251. ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS);
  252. #endif
  253. ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms);
  254. if(data->set.verbose)
  255. ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L);
  256. if(data->set.no_signal)
  257. ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L);
  258. /* Inherit *some* SSL options from the user's transfer. This is a
  259. best-guess as to which options are needed for compatibility. #3661 */
  260. if(data->set.ssl.falsestart)
  261. ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L);
  262. if(data->set.ssl.primary.verifyhost)
  263. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST, 2L);
  264. #ifndef CURL_DISABLE_PROXY
  265. if(data->set.proxy_ssl.primary.verifyhost)
  266. ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_VERIFYHOST, 2L);
  267. if(data->set.proxy_ssl.primary.verifypeer)
  268. ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_VERIFYPEER, 1L);
  269. if(data->set.str[STRING_SSL_CAFILE_PROXY]) {
  270. ERROR_CHECK_SETOPT(CURLOPT_PROXY_CAINFO,
  271. data->set.str[STRING_SSL_CAFILE_PROXY]);
  272. }
  273. if(data->set.str[STRING_SSL_CRLFILE_PROXY]) {
  274. ERROR_CHECK_SETOPT(CURLOPT_PROXY_CRLFILE,
  275. data->set.str[STRING_SSL_CRLFILE_PROXY]);
  276. }
  277. if(data->set.proxy_ssl.no_revoke)
  278. ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
  279. else if(data->set.proxy_ssl.revoke_best_effort)
  280. ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_OPTIONS,
  281. CURLSSLOPT_REVOKE_BEST_EFFORT);
  282. if(data->set.str[STRING_SSL_CAPATH_PROXY]) {
  283. ERROR_CHECK_SETOPT(CURLOPT_PROXY_CAPATH,
  284. data->set.str[STRING_SSL_CAPATH_PROXY]);
  285. }
  286. #endif
  287. if(data->set.ssl.primary.verifypeer)
  288. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER, 1L);
  289. if(data->set.ssl.primary.verifystatus)
  290. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS, 1L);
  291. if(data->set.str[STRING_SSL_CAFILE_ORIG]) {
  292. ERROR_CHECK_SETOPT(CURLOPT_CAINFO,
  293. data->set.str[STRING_SSL_CAFILE_ORIG]);
  294. }
  295. if(data->set.str[STRING_SSL_CAPATH_ORIG]) {
  296. ERROR_CHECK_SETOPT(CURLOPT_CAPATH,
  297. data->set.str[STRING_SSL_CAPATH_ORIG]);
  298. }
  299. if(data->set.str[STRING_SSL_CRLFILE_ORIG]) {
  300. ERROR_CHECK_SETOPT(CURLOPT_CRLFILE,
  301. data->set.str[STRING_SSL_CRLFILE_ORIG]);
  302. }
  303. if(data->set.ssl.certinfo)
  304. ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L);
  305. if(data->set.str[STRING_SSL_RANDOM_FILE]) {
  306. ERROR_CHECK_SETOPT(CURLOPT_RANDOM_FILE,
  307. data->set.str[STRING_SSL_RANDOM_FILE]);
  308. }
  309. if(data->set.str[STRING_SSL_EGDSOCKET]) {
  310. ERROR_CHECK_SETOPT(CURLOPT_EGDSOCKET,
  311. data->set.str[STRING_SSL_EGDSOCKET]);
  312. }
  313. if(data->set.ssl.no_revoke)
  314. ERROR_CHECK_SETOPT(CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
  315. else if(data->set.ssl.revoke_best_effort)
  316. ERROR_CHECK_SETOPT(CURLOPT_SSL_OPTIONS, CURLSSLOPT_REVOKE_BEST_EFFORT);
  317. if(data->set.ssl.fsslctx)
  318. ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx);
  319. if(data->set.ssl.fsslctxp)
  320. ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp);
  321. if(data->set.str[STRING_SSL_EC_CURVES]) {
  322. ERROR_CHECK_SETOPT(CURLOPT_SSL_EC_CURVES,
  323. data->set.str[STRING_SSL_EC_CURVES]);
  324. }
  325. doh->set.fmultidone = Curl_doh_done;
  326. doh->set.dohfor = data; /* identify for which transfer this is done */
  327. p->easy = doh;
  328. /* add this transfer to the multi handle */
  329. if(curl_multi_add_handle(multi, doh))
  330. goto error;
  331. }
  332. else
  333. goto error;
  334. free(nurl);
  335. return CURLE_OK;
  336. error:
  337. free(nurl);
  338. Curl_close(&doh);
  339. return result;
  340. }
  341. /*
  342. * Curl_doh() resolves a name using DOH. It resolves a name and returns a
  343. * 'Curl_addrinfo *' with the address information.
  344. */
  345. struct Curl_addrinfo *Curl_doh(struct connectdata *conn,
  346. const char *hostname,
  347. int port,
  348. int *waitp)
  349. {
  350. struct Curl_easy *data = conn->data;
  351. CURLcode result = CURLE_OK;
  352. int slot;
  353. *waitp = TRUE; /* this never returns synchronously */
  354. (void)conn;
  355. (void)hostname;
  356. (void)port;
  357. /* start clean, consider allocating this struct on demand */
  358. memset(&data->req.doh, 0, sizeof(struct dohdata));
  359. conn->bits.doh = TRUE;
  360. data->req.doh.host = hostname;
  361. data->req.doh.port = port;
  362. data->req.doh.headers =
  363. curl_slist_append(NULL,
  364. "Content-Type: application/dns-message");
  365. if(!data->req.doh.headers)
  366. goto error;
  367. if(conn->ip_version != CURL_IPRESOLVE_V6) {
  368. /* create IPv4 DOH request */
  369. result = dohprobe(data, &data->req.doh.probe[DOH_PROBE_SLOT_IPADDR_V4],
  370. DNS_TYPE_A, hostname, data->set.str[STRING_DOH],
  371. data->multi, data->req.doh.headers);
  372. if(result)
  373. goto error;
  374. data->req.doh.pending++;
  375. }
  376. if(conn->ip_version != CURL_IPRESOLVE_V4) {
  377. /* create IPv6 DOH request */
  378. result = dohprobe(data, &data->req.doh.probe[DOH_PROBE_SLOT_IPADDR_V6],
  379. DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH],
  380. data->multi, data->req.doh.headers);
  381. if(result)
  382. goto error;
  383. data->req.doh.pending++;
  384. }
  385. return NULL;
  386. error:
  387. curl_slist_free_all(data->req.doh.headers);
  388. data->req.doh.headers = NULL;
  389. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  390. Curl_close(&data->req.doh.probe[slot].easy);
  391. }
  392. return NULL;
  393. }
  394. static DOHcode skipqname(const unsigned char *doh, size_t dohlen,
  395. unsigned int *indexp)
  396. {
  397. unsigned char length;
  398. do {
  399. if(dohlen < (*indexp + 1))
  400. return DOH_DNS_OUT_OF_RANGE;
  401. length = doh[*indexp];
  402. if((length & 0xc0) == 0xc0) {
  403. /* name pointer, advance over it and be done */
  404. if(dohlen < (*indexp + 2))
  405. return DOH_DNS_OUT_OF_RANGE;
  406. *indexp += 2;
  407. break;
  408. }
  409. if(length & 0xc0)
  410. return DOH_DNS_BAD_LABEL;
  411. if(dohlen < (*indexp + 1 + length))
  412. return DOH_DNS_OUT_OF_RANGE;
  413. *indexp += 1 + length;
  414. } while(length);
  415. return DOH_OK;
  416. }
  417. static unsigned short get16bit(const unsigned char *doh, int index)
  418. {
  419. return (unsigned short)((doh[index] << 8) | doh[index + 1]);
  420. }
  421. static unsigned int get32bit(const unsigned char *doh, int index)
  422. {
  423. /* make clang and gcc optimize this to bswap by incrementing
  424. the pointer first. */
  425. doh += index;
  426. /* avoid undefined behaviour by casting to unsigned before shifting
  427. 24 bits, possibly into the sign bit. codegen is same, but
  428. ub sanitizer won't be upset */
  429. return ( (unsigned)doh[0] << 24) | (doh[1] << 16) |(doh[2] << 8) | doh[3];
  430. }
  431. static DOHcode store_a(const unsigned char *doh, int index, struct dohentry *d)
  432. {
  433. /* silently ignore addresses over the limit */
  434. if(d->numaddr < DOH_MAX_ADDR) {
  435. struct dohaddr *a = &d->addr[d->numaddr];
  436. a->type = DNS_TYPE_A;
  437. memcpy(&a->ip.v4, &doh[index], 4);
  438. d->numaddr++;
  439. }
  440. return DOH_OK;
  441. }
  442. static DOHcode store_aaaa(const unsigned char *doh,
  443. int index,
  444. struct dohentry *d)
  445. {
  446. /* silently ignore addresses over the limit */
  447. if(d->numaddr < DOH_MAX_ADDR) {
  448. struct dohaddr *a = &d->addr[d->numaddr];
  449. a->type = DNS_TYPE_AAAA;
  450. memcpy(&a->ip.v6, &doh[index], 16);
  451. d->numaddr++;
  452. }
  453. return DOH_OK;
  454. }
  455. static DOHcode store_cname(const unsigned char *doh,
  456. size_t dohlen,
  457. unsigned int index,
  458. struct dohentry *d)
  459. {
  460. struct dynbuf *c;
  461. unsigned int loop = 128; /* a valid DNS name can never loop this much */
  462. unsigned char length;
  463. if(d->numcname == DOH_MAX_CNAME)
  464. return DOH_OK; /* skip! */
  465. c = &d->cname[d->numcname++];
  466. do {
  467. if(index >= dohlen)
  468. return DOH_DNS_OUT_OF_RANGE;
  469. length = doh[index];
  470. if((length & 0xc0) == 0xc0) {
  471. int newpos;
  472. /* name pointer, get the new offset (14 bits) */
  473. if((index + 1) >= dohlen)
  474. return DOH_DNS_OUT_OF_RANGE;
  475. /* move to the new index */
  476. newpos = (length & 0x3f) << 8 | doh[index + 1];
  477. index = newpos;
  478. continue;
  479. }
  480. else if(length & 0xc0)
  481. return DOH_DNS_BAD_LABEL; /* bad input */
  482. else
  483. index++;
  484. if(length) {
  485. if(Curl_dyn_len(c)) {
  486. if(Curl_dyn_add(c, "."))
  487. return DOH_OUT_OF_MEM;
  488. }
  489. if((index + length) > dohlen)
  490. return DOH_DNS_BAD_LABEL;
  491. if(Curl_dyn_addn(c, &doh[index], length))
  492. return DOH_OUT_OF_MEM;
  493. index += length;
  494. }
  495. } while(length && --loop);
  496. if(!loop)
  497. return DOH_DNS_LABEL_LOOP;
  498. return DOH_OK;
  499. }
  500. static DOHcode rdata(const unsigned char *doh,
  501. size_t dohlen,
  502. unsigned short rdlength,
  503. unsigned short type,
  504. int index,
  505. struct dohentry *d)
  506. {
  507. /* RDATA
  508. - A (TYPE 1): 4 bytes
  509. - AAAA (TYPE 28): 16 bytes
  510. - NS (TYPE 2): N bytes */
  511. DOHcode rc;
  512. switch(type) {
  513. case DNS_TYPE_A:
  514. if(rdlength != 4)
  515. return DOH_DNS_RDATA_LEN;
  516. rc = store_a(doh, index, d);
  517. if(rc)
  518. return rc;
  519. break;
  520. case DNS_TYPE_AAAA:
  521. if(rdlength != 16)
  522. return DOH_DNS_RDATA_LEN;
  523. rc = store_aaaa(doh, index, d);
  524. if(rc)
  525. return rc;
  526. break;
  527. case DNS_TYPE_CNAME:
  528. rc = store_cname(doh, dohlen, index, d);
  529. if(rc)
  530. return rc;
  531. break;
  532. case DNS_TYPE_DNAME:
  533. /* explicit for clarity; just skip; rely on synthesized CNAME */
  534. break;
  535. default:
  536. /* unsupported type, just skip it */
  537. break;
  538. }
  539. return DOH_OK;
  540. }
  541. UNITTEST void de_init(struct dohentry *de)
  542. {
  543. int i;
  544. memset(de, 0, sizeof(*de));
  545. de->ttl = INT_MAX;
  546. for(i = 0; i < DOH_MAX_CNAME; i++)
  547. Curl_dyn_init(&de->cname[i], DYN_DOH_CNAME);
  548. }
  549. UNITTEST DOHcode doh_decode(const unsigned char *doh,
  550. size_t dohlen,
  551. DNStype dnstype,
  552. struct dohentry *d)
  553. {
  554. unsigned char rcode;
  555. unsigned short qdcount;
  556. unsigned short ancount;
  557. unsigned short type = 0;
  558. unsigned short rdlength;
  559. unsigned short nscount;
  560. unsigned short arcount;
  561. unsigned int index = 12;
  562. DOHcode rc;
  563. if(dohlen < 12)
  564. return DOH_TOO_SMALL_BUFFER; /* too small */
  565. if(!doh || doh[0] || doh[1])
  566. return DOH_DNS_BAD_ID; /* bad ID */
  567. rcode = doh[3] & 0x0f;
  568. if(rcode)
  569. return DOH_DNS_BAD_RCODE; /* bad rcode */
  570. qdcount = get16bit(doh, 4);
  571. while(qdcount) {
  572. rc = skipqname(doh, dohlen, &index);
  573. if(rc)
  574. return rc; /* bad qname */
  575. if(dohlen < (index + 4))
  576. return DOH_DNS_OUT_OF_RANGE;
  577. index += 4; /* skip question's type and class */
  578. qdcount--;
  579. }
  580. ancount = get16bit(doh, 6);
  581. while(ancount) {
  582. unsigned short class;
  583. unsigned int ttl;
  584. rc = skipqname(doh, dohlen, &index);
  585. if(rc)
  586. return rc; /* bad qname */
  587. if(dohlen < (index + 2))
  588. return DOH_DNS_OUT_OF_RANGE;
  589. type = get16bit(doh, index);
  590. if((type != DNS_TYPE_CNAME) /* may be synthesized from DNAME */
  591. && (type != DNS_TYPE_DNAME) /* if present, accept and ignore */
  592. && (type != dnstype))
  593. /* Not the same type as was asked for nor CNAME nor DNAME */
  594. return DOH_DNS_UNEXPECTED_TYPE;
  595. index += 2;
  596. if(dohlen < (index + 2))
  597. return DOH_DNS_OUT_OF_RANGE;
  598. class = get16bit(doh, index);
  599. if(DNS_CLASS_IN != class)
  600. return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
  601. index += 2;
  602. if(dohlen < (index + 4))
  603. return DOH_DNS_OUT_OF_RANGE;
  604. ttl = get32bit(doh, index);
  605. if(ttl < d->ttl)
  606. d->ttl = ttl;
  607. index += 4;
  608. if(dohlen < (index + 2))
  609. return DOH_DNS_OUT_OF_RANGE;
  610. rdlength = get16bit(doh, index);
  611. index += 2;
  612. if(dohlen < (index + rdlength))
  613. return DOH_DNS_OUT_OF_RANGE;
  614. rc = rdata(doh, dohlen, rdlength, type, index, d);
  615. if(rc)
  616. return rc; /* bad rdata */
  617. index += rdlength;
  618. ancount--;
  619. }
  620. nscount = get16bit(doh, 8);
  621. while(nscount) {
  622. rc = skipqname(doh, dohlen, &index);
  623. if(rc)
  624. return rc; /* bad qname */
  625. if(dohlen < (index + 8))
  626. return DOH_DNS_OUT_OF_RANGE;
  627. index += 2 + 2 + 4; /* type, class and ttl */
  628. if(dohlen < (index + 2))
  629. return DOH_DNS_OUT_OF_RANGE;
  630. rdlength = get16bit(doh, index);
  631. index += 2;
  632. if(dohlen < (index + rdlength))
  633. return DOH_DNS_OUT_OF_RANGE;
  634. index += rdlength;
  635. nscount--;
  636. }
  637. arcount = get16bit(doh, 10);
  638. while(arcount) {
  639. rc = skipqname(doh, dohlen, &index);
  640. if(rc)
  641. return rc; /* bad qname */
  642. if(dohlen < (index + 8))
  643. return DOH_DNS_OUT_OF_RANGE;
  644. index += 2 + 2 + 4; /* type, class and ttl */
  645. if(dohlen < (index + 2))
  646. return DOH_DNS_OUT_OF_RANGE;
  647. rdlength = get16bit(doh, index);
  648. index += 2;
  649. if(dohlen < (index + rdlength))
  650. return DOH_DNS_OUT_OF_RANGE;
  651. index += rdlength;
  652. arcount--;
  653. }
  654. if(index != dohlen)
  655. return DOH_DNS_MALFORMAT; /* something is wrong */
  656. if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr)
  657. /* nothing stored! */
  658. return DOH_NO_CONTENT;
  659. return DOH_OK; /* ok */
  660. }
  661. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  662. static void showdoh(struct Curl_easy *data,
  663. const struct dohentry *d)
  664. {
  665. int i;
  666. infof(data, "TTL: %u seconds\n", d->ttl);
  667. for(i = 0; i < d->numaddr; i++) {
  668. const struct dohaddr *a = &d->addr[i];
  669. if(a->type == DNS_TYPE_A) {
  670. infof(data, "DOH A: %u.%u.%u.%u\n",
  671. a->ip.v4[0], a->ip.v4[1],
  672. a->ip.v4[2], a->ip.v4[3]);
  673. }
  674. else if(a->type == DNS_TYPE_AAAA) {
  675. int j;
  676. char buffer[128];
  677. char *ptr;
  678. size_t len;
  679. msnprintf(buffer, 128, "DOH AAAA: ");
  680. ptr = &buffer[10];
  681. len = 118;
  682. for(j = 0; j < 16; j += 2) {
  683. size_t l;
  684. msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j],
  685. d->addr[i].ip.v6[j + 1]);
  686. l = strlen(ptr);
  687. len -= l;
  688. ptr += l;
  689. }
  690. infof(data, "%s\n", buffer);
  691. }
  692. }
  693. for(i = 0; i < d->numcname; i++) {
  694. infof(data, "CNAME: %s\n", Curl_dyn_ptr(&d->cname[i]));
  695. }
  696. }
  697. #else
  698. #define showdoh(x,y)
  699. #endif
  700. /*
  701. * doh2ai()
  702. *
  703. * This function returns a pointer to the first element of a newly allocated
  704. * Curl_addrinfo struct linked list filled with the data from a set of DOH
  705. * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for
  706. * a IPv6 stack, but usable also for IPv4, all hosts and environments.
  707. *
  708. * The memory allocated by this function *MUST* be free'd later on calling
  709. * Curl_freeaddrinfo(). For each successful call to this function there
  710. * must be an associated call later to Curl_freeaddrinfo().
  711. */
  712. static struct Curl_addrinfo *
  713. doh2ai(const struct dohentry *de, const char *hostname, int port)
  714. {
  715. struct Curl_addrinfo *ai;
  716. struct Curl_addrinfo *prevai = NULL;
  717. struct Curl_addrinfo *firstai = NULL;
  718. struct sockaddr_in *addr;
  719. #ifdef ENABLE_IPV6
  720. struct sockaddr_in6 *addr6;
  721. #endif
  722. CURLcode result = CURLE_OK;
  723. int i;
  724. size_t hostlen = strlen(hostname) + 1; /* include zero terminator */
  725. if(!de)
  726. /* no input == no output! */
  727. return NULL;
  728. for(i = 0; i < de->numaddr; i++) {
  729. size_t ss_size;
  730. CURL_SA_FAMILY_T addrtype;
  731. if(de->addr[i].type == DNS_TYPE_AAAA) {
  732. #ifndef ENABLE_IPV6
  733. /* we can't handle IPv6 addresses */
  734. continue;
  735. #else
  736. ss_size = sizeof(struct sockaddr_in6);
  737. addrtype = AF_INET6;
  738. #endif
  739. }
  740. else {
  741. ss_size = sizeof(struct sockaddr_in);
  742. addrtype = AF_INET;
  743. }
  744. ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen);
  745. if(!ai) {
  746. result = CURLE_OUT_OF_MEMORY;
  747. break;
  748. }
  749. ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
  750. ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size);
  751. memcpy(ai->ai_canonname, hostname, hostlen);
  752. if(!firstai)
  753. /* store the pointer we want to return from this function */
  754. firstai = ai;
  755. if(prevai)
  756. /* make the previous entry point to this */
  757. prevai->ai_next = ai;
  758. ai->ai_family = addrtype;
  759. /* we return all names as STREAM, so when using this address for TFTP
  760. the type must be ignored and conn->socktype be used instead! */
  761. ai->ai_socktype = SOCK_STREAM;
  762. ai->ai_addrlen = (curl_socklen_t)ss_size;
  763. /* leave the rest of the struct filled with zero */
  764. switch(ai->ai_family) {
  765. case AF_INET:
  766. addr = (void *)ai->ai_addr; /* storage area for this info */
  767. DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
  768. memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
  769. addr->sin_family = addrtype;
  770. addr->sin_port = htons((unsigned short)port);
  771. break;
  772. #ifdef ENABLE_IPV6
  773. case AF_INET6:
  774. addr6 = (void *)ai->ai_addr; /* storage area for this info */
  775. DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
  776. memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
  777. addr6->sin6_family = addrtype;
  778. addr6->sin6_port = htons((unsigned short)port);
  779. break;
  780. #endif
  781. }
  782. prevai = ai;
  783. }
  784. if(result) {
  785. Curl_freeaddrinfo(firstai);
  786. firstai = NULL;
  787. }
  788. return firstai;
  789. }
  790. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  791. static const char *type2name(DNStype dnstype)
  792. {
  793. return (dnstype == DNS_TYPE_A)?"A":"AAAA";
  794. }
  795. #endif
  796. UNITTEST void de_cleanup(struct dohentry *d)
  797. {
  798. int i = 0;
  799. for(i = 0; i < d->numcname; i++) {
  800. Curl_dyn_free(&d->cname[i]);
  801. }
  802. }
  803. CURLcode Curl_doh_is_resolved(struct connectdata *conn,
  804. struct Curl_dns_entry **dnsp)
  805. {
  806. CURLcode result;
  807. struct Curl_easy *data = conn->data;
  808. *dnsp = NULL; /* defaults to no response */
  809. if(!data->req.doh.probe[DOH_PROBE_SLOT_IPADDR_V4].easy &&
  810. !data->req.doh.probe[DOH_PROBE_SLOT_IPADDR_V6].easy) {
  811. failf(data, "Could not DOH-resolve: %s", conn->async.hostname);
  812. return conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY:
  813. CURLE_COULDNT_RESOLVE_HOST;
  814. }
  815. else if(!data->req.doh.pending) {
  816. DOHcode rc[DOH_PROBE_SLOTS] = {
  817. DOH_OK, DOH_OK
  818. };
  819. struct dohentry de;
  820. int slot;
  821. /* remove DOH handles from multi handle and close them */
  822. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  823. curl_multi_remove_handle(data->multi, data->req.doh.probe[slot].easy);
  824. Curl_close(&data->req.doh.probe[slot].easy);
  825. }
  826. /* parse the responses, create the struct and return it! */
  827. de_init(&de);
  828. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  829. struct dnsprobe *p = &data->req.doh.probe[slot];
  830. if(!p->dnstype)
  831. continue;
  832. rc[slot] = doh_decode(Curl_dyn_uptr(&p->serverdoh),
  833. Curl_dyn_len(&p->serverdoh),
  834. p->dnstype,
  835. &de);
  836. Curl_dyn_free(&p->serverdoh);
  837. if(rc[slot]) {
  838. infof(data, "DOH: %s type %s for %s\n", doh_strerror(rc[slot]),
  839. type2name(p->dnstype), data->req.doh.host);
  840. }
  841. } /* next slot */
  842. result = CURLE_COULDNT_RESOLVE_HOST; /* until we know better */
  843. if(!rc[DOH_PROBE_SLOT_IPADDR_V4] || !rc[DOH_PROBE_SLOT_IPADDR_V6]) {
  844. /* we have an address, of one kind or other */
  845. struct Curl_dns_entry *dns;
  846. struct Curl_addrinfo *ai;
  847. infof(data, "DOH Host name: %s\n", data->req.doh.host);
  848. showdoh(data, &de);
  849. ai = doh2ai(&de, data->req.doh.host, data->req.doh.port);
  850. if(!ai) {
  851. de_cleanup(&de);
  852. return CURLE_OUT_OF_MEMORY;
  853. }
  854. if(data->share)
  855. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  856. /* we got a response, store it in the cache */
  857. dns = Curl_cache_addr(data, ai, data->req.doh.host, data->req.doh.port);
  858. if(data->share)
  859. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  860. if(!dns) {
  861. /* returned failure, bail out nicely */
  862. Curl_freeaddrinfo(ai);
  863. }
  864. else {
  865. conn->async.dns = dns;
  866. *dnsp = dns;
  867. result = CURLE_OK; /* address resolution OK */
  868. }
  869. } /* address processing done */
  870. /* Now process any build-specific attributes retrieved from DNS */
  871. /* All done */
  872. de_cleanup(&de);
  873. return result;
  874. } /* !data->req.doh.pending */
  875. /* else wait for pending DOH transactions to complete */
  876. return CURLE_OK;
  877. }
  878. #endif /* CURL_DISABLE_DOH */