2
0

doh.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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.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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifndef CURL_DISABLE_DOH
  26. #include "urldata.h"
  27. #include "curl_addrinfo.h"
  28. #include "doh.h"
  29. #include "sendf.h"
  30. #include "multiif.h"
  31. #include "url.h"
  32. #include "share.h"
  33. #include "curl_base64.h"
  34. #include "connect.h"
  35. #include "strdup.h"
  36. #include "dynbuf.h"
  37. /* The last 3 #include files should be in this order */
  38. #include "curl_printf.h"
  39. #include "curl_memory.h"
  40. #include "memdebug.h"
  41. #include "escape.h"
  42. #define DNS_CLASS_IN 0x01
  43. /* local_print_buf truncates if the hex string will be more than this */
  44. #define LOCAL_PB_HEXMAX 400
  45. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  46. static const char * const errors[]={
  47. "",
  48. "Bad label",
  49. "Out of range",
  50. "Label loop",
  51. "Too small",
  52. "Out of memory",
  53. "RDATA length",
  54. "Malformat",
  55. "Bad RCODE",
  56. "Unexpected TYPE",
  57. "Unexpected CLASS",
  58. "No content",
  59. "Bad ID",
  60. "Name too long"
  61. };
  62. static const char *doh_strerror(DOHcode code)
  63. {
  64. if((code >= DOH_OK) && (code <= DOH_DNS_NAME_TOO_LONG))
  65. return errors[code];
  66. return "bad error code";
  67. }
  68. struct curl_trc_feat Curl_doh_trc = {
  69. "DoH",
  70. CURL_LOG_LVL_NONE,
  71. };
  72. #endif /* !CURL_DISABLE_VERBOSE_STRINGS */
  73. /* @unittest 1655
  74. */
  75. UNITTEST DOHcode doh_encode(const char *host,
  76. DNStype dnstype,
  77. unsigned char *dnsp, /* buffer */
  78. size_t len, /* buffer size */
  79. size_t *olen) /* output length */
  80. {
  81. const size_t hostlen = strlen(host);
  82. unsigned char *orig = dnsp;
  83. const char *hostp = host;
  84. /* The expected output length is 16 bytes more than the length of
  85. * the QNAME-encoding of the hostname.
  86. *
  87. * A valid DNS name may not contain a zero-length label, except at
  88. * the end. For this reason, a name beginning with a dot, or
  89. * containing a sequence of two or more consecutive dots, is invalid
  90. * and cannot be encoded as a QNAME.
  91. *
  92. * If the hostname ends with a trailing dot, the corresponding
  93. * QNAME-encoding is one byte longer than the hostname. If (as is
  94. * also valid) the hostname is shortened by the omission of the
  95. * trailing dot, then its QNAME-encoding will be two bytes longer
  96. * than the hostname.
  97. *
  98. * Each [ label, dot ] pair is encoded as [ length, label ],
  99. * preserving overall length. A final [ label ] without a dot is
  100. * also encoded as [ length, label ], increasing overall length
  101. * by one. The encoding is completed by appending a zero byte,
  102. * representing the zero-length root label, again increasing
  103. * the overall length by one.
  104. */
  105. size_t expected_len;
  106. DEBUGASSERT(hostlen);
  107. expected_len = 12 + 1 + hostlen + 4;
  108. if(host[hostlen-1]!='.')
  109. expected_len++;
  110. if(expected_len > (256 + 16)) /* RFCs 1034, 1035 */
  111. return DOH_DNS_NAME_TOO_LONG;
  112. if(len < expected_len)
  113. return DOH_TOO_SMALL_BUFFER;
  114. *dnsp++ = 0; /* 16 bit id */
  115. *dnsp++ = 0;
  116. *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */
  117. *dnsp++ = '\0'; /* |RA| Z | RCODE | */
  118. *dnsp++ = '\0';
  119. *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */
  120. *dnsp++ = '\0';
  121. *dnsp++ = '\0'; /* ANCOUNT */
  122. *dnsp++ = '\0';
  123. *dnsp++ = '\0'; /* NSCOUNT */
  124. *dnsp++ = '\0';
  125. *dnsp++ = '\0'; /* ARCOUNT */
  126. /* encode each label and store it in the QNAME */
  127. while(*hostp) {
  128. size_t labellen;
  129. char *dot = strchr(hostp, '.');
  130. if(dot)
  131. labellen = dot - hostp;
  132. else
  133. labellen = strlen(hostp);
  134. if((labellen > 63) || (!labellen)) {
  135. /* label is too long or too short, error out */
  136. *olen = 0;
  137. return DOH_DNS_BAD_LABEL;
  138. }
  139. /* label is non-empty, process it */
  140. *dnsp++ = (unsigned char)labellen;
  141. memcpy(dnsp, hostp, labellen);
  142. dnsp += labellen;
  143. hostp += labellen;
  144. /* advance past dot, but only if there is one */
  145. if(dot)
  146. hostp++;
  147. } /* next label */
  148. *dnsp++ = 0; /* append zero-length label for root */
  149. /* There are assigned TYPE codes beyond 255: use range [1..65535] */
  150. *dnsp++ = (unsigned char)(255 & (dnstype>>8)); /* upper 8 bit TYPE */
  151. *dnsp++ = (unsigned char)(255 & dnstype); /* lower 8 bit TYPE */
  152. *dnsp++ = '\0'; /* upper 8 bit CLASS */
  153. *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */
  154. *olen = dnsp - orig;
  155. /* verify that our estimation of length is valid, since
  156. * this has led to buffer overflows in this function */
  157. DEBUGASSERT(*olen == expected_len);
  158. return DOH_OK;
  159. }
  160. static size_t
  161. doh_write_cb(const void *contents, size_t size, size_t nmemb, void *userp)
  162. {
  163. size_t realsize = size * nmemb;
  164. struct dynbuf *mem = (struct dynbuf *)userp;
  165. if(Curl_dyn_addn(mem, contents, realsize))
  166. return 0;
  167. return realsize;
  168. }
  169. #if defined(USE_HTTPSRR) && defined(DEBUGBUILD)
  170. static void local_print_buf(struct Curl_easy *data,
  171. const char *prefix,
  172. unsigned char *buf, size_t len)
  173. {
  174. unsigned char hexstr[LOCAL_PB_HEXMAX];
  175. size_t hlen = LOCAL_PB_HEXMAX;
  176. bool truncated = false;
  177. if(len > (LOCAL_PB_HEXMAX / 2))
  178. truncated = true;
  179. Curl_hexencode(buf, len, hexstr, hlen);
  180. if(!truncated)
  181. infof(data, "%s: len=%d, val=%s", prefix, (int)len, hexstr);
  182. else
  183. infof(data, "%s: len=%d (truncated)val=%s", prefix, (int)len, hexstr);
  184. return;
  185. }
  186. #endif
  187. /* called from multi.c when this DoH transfer is complete */
  188. static int doh_done(struct Curl_easy *doh, CURLcode result)
  189. {
  190. struct Curl_easy *data = doh->set.dohfor;
  191. struct dohdata *dohp = data->req.doh;
  192. /* so one of the DoH request done for the 'data' transfer is now complete! */
  193. dohp->pending--;
  194. infof(doh, "a DoH request is completed, %u to go", dohp->pending);
  195. if(result)
  196. infof(doh, "DoH request %s", curl_easy_strerror(result));
  197. if(!dohp->pending) {
  198. /* DoH completed */
  199. curl_slist_free_all(dohp->headers);
  200. dohp->headers = NULL;
  201. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  202. }
  203. return 0;
  204. }
  205. #define ERROR_CHECK_SETOPT(x,y) \
  206. do { \
  207. result = curl_easy_setopt(doh, x, y); \
  208. if(result && \
  209. result != CURLE_NOT_BUILT_IN && \
  210. result != CURLE_UNKNOWN_OPTION) \
  211. goto error; \
  212. } while(0)
  213. static CURLcode dohprobe(struct Curl_easy *data,
  214. struct dnsprobe *p, DNStype dnstype,
  215. const char *host,
  216. const char *url, CURLM *multi,
  217. struct curl_slist *headers)
  218. {
  219. struct Curl_easy *doh = NULL;
  220. CURLcode result = CURLE_OK;
  221. timediff_t timeout_ms;
  222. DOHcode d = doh_encode(host, dnstype, p->dohbuffer, sizeof(p->dohbuffer),
  223. &p->dohlen);
  224. if(d) {
  225. failf(data, "Failed to encode DoH packet [%d]", d);
  226. return CURLE_OUT_OF_MEMORY;
  227. }
  228. p->dnstype = dnstype;
  229. Curl_dyn_init(&p->serverdoh, DYN_DOH_RESPONSE);
  230. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  231. if(timeout_ms <= 0) {
  232. result = CURLE_OPERATION_TIMEDOUT;
  233. goto error;
  234. }
  235. /* Curl_open() is the internal version of curl_easy_init() */
  236. result = Curl_open(&doh);
  237. if(!result) {
  238. /* pass in the struct pointer via a local variable to please coverity and
  239. the gcc typecheck helpers */
  240. struct dynbuf *resp = &p->serverdoh;
  241. doh->state.internal = true;
  242. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  243. doh->state.feat = &Curl_doh_trc;
  244. #endif
  245. ERROR_CHECK_SETOPT(CURLOPT_URL, url);
  246. ERROR_CHECK_SETOPT(CURLOPT_DEFAULT_PROTOCOL, "https");
  247. ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb);
  248. ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, resp);
  249. ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->dohbuffer);
  250. ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->dohlen);
  251. ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers);
  252. #ifdef USE_HTTP2
  253. ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
  254. ERROR_CHECK_SETOPT(CURLOPT_PIPEWAIT, 1L);
  255. #endif
  256. #ifndef DEBUGBUILD
  257. /* enforce HTTPS if not debug */
  258. ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
  259. #else
  260. /* in debug mode, also allow http */
  261. ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS);
  262. #endif
  263. ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms);
  264. ERROR_CHECK_SETOPT(CURLOPT_SHARE, data->share);
  265. if(data->set.err && data->set.err != stderr)
  266. ERROR_CHECK_SETOPT(CURLOPT_STDERR, data->set.err);
  267. if(Curl_trc_ft_is_verbose(data, &Curl_doh_trc))
  268. ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L);
  269. if(data->set.no_signal)
  270. ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L);
  271. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST,
  272. data->set.doh_verifyhost ? 2L : 0L);
  273. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER,
  274. data->set.doh_verifypeer ? 1L : 0L);
  275. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS,
  276. data->set.doh_verifystatus ? 1L : 0L);
  277. /* Inherit *some* SSL options from the user's transfer. This is a
  278. best-guess as to which options are needed for compatibility. #3661
  279. Note DoH does not inherit the user's proxy server so proxy SSL settings
  280. have no effect and are not inherited. If that changes then two new
  281. options should be added to check doh proxy insecure separately,
  282. CURLOPT_DOH_PROXY_SSL_VERIFYHOST and CURLOPT_DOH_PROXY_SSL_VERIFYPEER.
  283. */
  284. if(data->set.ssl.falsestart)
  285. ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L);
  286. if(data->set.str[STRING_SSL_CAFILE]) {
  287. ERROR_CHECK_SETOPT(CURLOPT_CAINFO,
  288. data->set.str[STRING_SSL_CAFILE]);
  289. }
  290. if(data->set.blobs[BLOB_CAINFO]) {
  291. ERROR_CHECK_SETOPT(CURLOPT_CAINFO_BLOB,
  292. data->set.blobs[BLOB_CAINFO]);
  293. }
  294. if(data->set.str[STRING_SSL_CAPATH]) {
  295. ERROR_CHECK_SETOPT(CURLOPT_CAPATH,
  296. data->set.str[STRING_SSL_CAPATH]);
  297. }
  298. if(data->set.str[STRING_SSL_CRLFILE]) {
  299. ERROR_CHECK_SETOPT(CURLOPT_CRLFILE,
  300. data->set.str[STRING_SSL_CRLFILE]);
  301. }
  302. if(data->set.ssl.certinfo)
  303. ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L);
  304. if(data->set.ssl.fsslctx)
  305. ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx);
  306. if(data->set.ssl.fsslctxp)
  307. ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp);
  308. if(data->set.fdebug)
  309. ERROR_CHECK_SETOPT(CURLOPT_DEBUGFUNCTION, data->set.fdebug);
  310. if(data->set.debugdata)
  311. ERROR_CHECK_SETOPT(CURLOPT_DEBUGDATA, data->set.debugdata);
  312. if(data->set.str[STRING_SSL_EC_CURVES]) {
  313. ERROR_CHECK_SETOPT(CURLOPT_SSL_EC_CURVES,
  314. data->set.str[STRING_SSL_EC_CURVES]);
  315. }
  316. {
  317. long mask =
  318. (data->set.ssl.enable_beast ?
  319. CURLSSLOPT_ALLOW_BEAST : 0) |
  320. (data->set.ssl.no_revoke ?
  321. CURLSSLOPT_NO_REVOKE : 0) |
  322. (data->set.ssl.no_partialchain ?
  323. CURLSSLOPT_NO_PARTIALCHAIN : 0) |
  324. (data->set.ssl.revoke_best_effort ?
  325. CURLSSLOPT_REVOKE_BEST_EFFORT : 0) |
  326. (data->set.ssl.native_ca_store ?
  327. CURLSSLOPT_NATIVE_CA : 0) |
  328. (data->set.ssl.auto_client_cert ?
  329. CURLSSLOPT_AUTO_CLIENT_CERT : 0);
  330. (void)curl_easy_setopt(doh, CURLOPT_SSL_OPTIONS, mask);
  331. }
  332. doh->set.fmultidone = doh_done;
  333. doh->set.dohfor = data; /* identify for which transfer this is done */
  334. p->easy = doh;
  335. /* DoH handles must not inherit private_data. The handles may be passed to
  336. the user via callbacks and the user will be able to identify them as
  337. internal handles because private data is not set. The user can then set
  338. private_data via CURLOPT_PRIVATE if they so choose. */
  339. DEBUGASSERT(!doh->set.private_data);
  340. if(curl_multi_add_handle(multi, doh))
  341. goto error;
  342. }
  343. else
  344. goto error;
  345. return CURLE_OK;
  346. error:
  347. Curl_close(&doh);
  348. return result;
  349. }
  350. /*
  351. * Curl_doh() resolves a name using DoH. It resolves a name and returns a
  352. * 'Curl_addrinfo *' with the address information.
  353. */
  354. struct Curl_addrinfo *Curl_doh(struct Curl_easy *data,
  355. const char *hostname,
  356. int port,
  357. int *waitp)
  358. {
  359. CURLcode result = CURLE_OK;
  360. struct dohdata *dohp;
  361. struct connectdata *conn = data->conn;
  362. #ifdef USE_HTTPSRR
  363. /* for now, this is only used when ECH is enabled */
  364. # ifdef USE_ECH
  365. char *qname = NULL;
  366. # endif
  367. #endif
  368. *waitp = FALSE;
  369. (void)hostname;
  370. (void)port;
  371. DEBUGASSERT(!data->req.doh);
  372. DEBUGASSERT(conn);
  373. /* start clean, consider allocating this struct on demand */
  374. dohp = data->req.doh = calloc(1, sizeof(struct dohdata));
  375. if(!dohp)
  376. return NULL;
  377. conn->bits.doh = TRUE;
  378. dohp->host = hostname;
  379. dohp->port = port;
  380. dohp->headers =
  381. curl_slist_append(NULL,
  382. "Content-Type: application/dns-message");
  383. if(!dohp->headers)
  384. goto error;
  385. /* create IPv4 DoH request */
  386. result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V4],
  387. DNS_TYPE_A, hostname, data->set.str[STRING_DOH],
  388. data->multi, dohp->headers);
  389. if(result)
  390. goto error;
  391. dohp->pending++;
  392. #ifdef USE_IPV6
  393. if((conn->ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) {
  394. /* create IPv6 DoH request */
  395. result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V6],
  396. DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH],
  397. data->multi, dohp->headers);
  398. if(result)
  399. goto error;
  400. dohp->pending++;
  401. }
  402. #endif
  403. #ifdef USE_HTTPSRR
  404. /*
  405. * TODO: Figure out the conditions under which we want to make
  406. * a request for an HTTPS RR when we are not doing ECH. For now,
  407. * making this request breaks a bunch of DoH tests, e.g. test2100,
  408. * where the additional request does not match the pre-cooked data
  409. * files, so there is a bit of work attached to making the request
  410. * in a non-ECH use-case. For the present, we will only make the
  411. * request when ECH is enabled in the build and is being used for
  412. * the curl operation.
  413. */
  414. # ifdef USE_ECH
  415. if(data->set.tls_ech & CURLECH_ENABLE
  416. || data->set.tls_ech & CURLECH_HARD) {
  417. if(port == 443)
  418. qname = strdup(hostname);
  419. else
  420. qname = aprintf("_%d._https.%s", port, hostname);
  421. if(!qname)
  422. goto error;
  423. result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_HTTPS],
  424. DNS_TYPE_HTTPS, qname, data->set.str[STRING_DOH],
  425. data->multi, dohp->headers);
  426. Curl_safefree(qname);
  427. if(result)
  428. goto error;
  429. dohp->pending++;
  430. }
  431. # endif
  432. #endif
  433. *waitp = TRUE; /* this never returns synchronously */
  434. return NULL;
  435. error:
  436. Curl_doh_cleanup(data);
  437. return NULL;
  438. }
  439. static DOHcode skipqname(const unsigned char *doh, size_t dohlen,
  440. unsigned int *indexp)
  441. {
  442. unsigned char length;
  443. do {
  444. if(dohlen < (*indexp + 1))
  445. return DOH_DNS_OUT_OF_RANGE;
  446. length = doh[*indexp];
  447. if((length & 0xc0) == 0xc0) {
  448. /* name pointer, advance over it and be done */
  449. if(dohlen < (*indexp + 2))
  450. return DOH_DNS_OUT_OF_RANGE;
  451. *indexp += 2;
  452. break;
  453. }
  454. if(length & 0xc0)
  455. return DOH_DNS_BAD_LABEL;
  456. if(dohlen < (*indexp + 1 + length))
  457. return DOH_DNS_OUT_OF_RANGE;
  458. *indexp += (unsigned int)(1 + length);
  459. } while(length);
  460. return DOH_OK;
  461. }
  462. static unsigned short get16bit(const unsigned char *doh, unsigned int index)
  463. {
  464. return (unsigned short)((doh[index] << 8) | doh[index + 1]);
  465. }
  466. static unsigned int get32bit(const unsigned char *doh, unsigned int index)
  467. {
  468. /* make clang and gcc optimize this to bswap by incrementing
  469. the pointer first. */
  470. doh += index;
  471. /* avoid undefined behavior by casting to unsigned before shifting
  472. 24 bits, possibly into the sign bit. codegen is same, but
  473. ub sanitizer will not be upset */
  474. return ((unsigned)doh[0] << 24) | ((unsigned)doh[1] << 16) |
  475. ((unsigned)doh[2] << 8) | doh[3];
  476. }
  477. static DOHcode store_a(const unsigned char *doh, int index, struct dohentry *d)
  478. {
  479. /* silently ignore addresses over the limit */
  480. if(d->numaddr < DOH_MAX_ADDR) {
  481. struct dohaddr *a = &d->addr[d->numaddr];
  482. a->type = DNS_TYPE_A;
  483. memcpy(&a->ip.v4, &doh[index], 4);
  484. d->numaddr++;
  485. }
  486. return DOH_OK;
  487. }
  488. static DOHcode store_aaaa(const unsigned char *doh,
  489. int index,
  490. struct dohentry *d)
  491. {
  492. /* silently ignore addresses over the limit */
  493. if(d->numaddr < DOH_MAX_ADDR) {
  494. struct dohaddr *a = &d->addr[d->numaddr];
  495. a->type = DNS_TYPE_AAAA;
  496. memcpy(&a->ip.v6, &doh[index], 16);
  497. d->numaddr++;
  498. }
  499. return DOH_OK;
  500. }
  501. #ifdef USE_HTTPSRR
  502. static DOHcode store_https(const unsigned char *doh,
  503. int index,
  504. struct dohentry *d,
  505. uint16_t len)
  506. {
  507. /* silently ignore RRs over the limit */
  508. if(d->numhttps_rrs < DOH_MAX_HTTPS) {
  509. struct dohhttps_rr *h = &d->https_rrs[d->numhttps_rrs];
  510. h->val = Curl_memdup(&doh[index], len);
  511. if(!h->val)
  512. return DOH_OUT_OF_MEM;
  513. h->len = len;
  514. d->numhttps_rrs++;
  515. }
  516. return DOH_OK;
  517. }
  518. #endif
  519. static DOHcode store_cname(const unsigned char *doh,
  520. size_t dohlen,
  521. unsigned int index,
  522. struct dohentry *d)
  523. {
  524. struct dynbuf *c;
  525. unsigned int loop = 128; /* a valid DNS name can never loop this much */
  526. unsigned char length;
  527. if(d->numcname == DOH_MAX_CNAME)
  528. return DOH_OK; /* skip! */
  529. c = &d->cname[d->numcname++];
  530. do {
  531. if(index >= dohlen)
  532. return DOH_DNS_OUT_OF_RANGE;
  533. length = doh[index];
  534. if((length & 0xc0) == 0xc0) {
  535. int newpos;
  536. /* name pointer, get the new offset (14 bits) */
  537. if((index + 1) >= dohlen)
  538. return DOH_DNS_OUT_OF_RANGE;
  539. /* move to the new index */
  540. newpos = (length & 0x3f) << 8 | doh[index + 1];
  541. index = (unsigned int)newpos;
  542. continue;
  543. }
  544. else if(length & 0xc0)
  545. return DOH_DNS_BAD_LABEL; /* bad input */
  546. else
  547. index++;
  548. if(length) {
  549. if(Curl_dyn_len(c)) {
  550. if(Curl_dyn_addn(c, STRCONST(".")))
  551. return DOH_OUT_OF_MEM;
  552. }
  553. if((index + length) > dohlen)
  554. return DOH_DNS_BAD_LABEL;
  555. if(Curl_dyn_addn(c, &doh[index], length))
  556. return DOH_OUT_OF_MEM;
  557. index += length;
  558. }
  559. } while(length && --loop);
  560. if(!loop)
  561. return DOH_DNS_LABEL_LOOP;
  562. return DOH_OK;
  563. }
  564. static DOHcode rdata(const unsigned char *doh,
  565. size_t dohlen,
  566. unsigned short rdlength,
  567. unsigned short type,
  568. int index,
  569. struct dohentry *d)
  570. {
  571. /* RDATA
  572. - A (TYPE 1): 4 bytes
  573. - AAAA (TYPE 28): 16 bytes
  574. - NS (TYPE 2): N bytes
  575. - HTTPS (TYPE 65): N bytes */
  576. DOHcode rc;
  577. switch(type) {
  578. case DNS_TYPE_A:
  579. if(rdlength != 4)
  580. return DOH_DNS_RDATA_LEN;
  581. rc = store_a(doh, index, d);
  582. if(rc)
  583. return rc;
  584. break;
  585. case DNS_TYPE_AAAA:
  586. if(rdlength != 16)
  587. return DOH_DNS_RDATA_LEN;
  588. rc = store_aaaa(doh, index, d);
  589. if(rc)
  590. return rc;
  591. break;
  592. #ifdef USE_HTTPSRR
  593. case DNS_TYPE_HTTPS:
  594. rc = store_https(doh, index, d, rdlength);
  595. if(rc)
  596. return rc;
  597. break;
  598. #endif
  599. case DNS_TYPE_CNAME:
  600. rc = store_cname(doh, dohlen, (unsigned int)index, d);
  601. if(rc)
  602. return rc;
  603. break;
  604. case DNS_TYPE_DNAME:
  605. /* explicit for clarity; just skip; rely on synthesized CNAME */
  606. break;
  607. default:
  608. /* unsupported type, just skip it */
  609. break;
  610. }
  611. return DOH_OK;
  612. }
  613. UNITTEST void de_init(struct dohentry *de)
  614. {
  615. int i;
  616. memset(de, 0, sizeof(*de));
  617. de->ttl = INT_MAX;
  618. for(i = 0; i < DOH_MAX_CNAME; i++)
  619. Curl_dyn_init(&de->cname[i], DYN_DOH_CNAME);
  620. }
  621. UNITTEST DOHcode doh_decode(const unsigned char *doh,
  622. size_t dohlen,
  623. DNStype dnstype,
  624. struct dohentry *d)
  625. {
  626. unsigned char rcode;
  627. unsigned short qdcount;
  628. unsigned short ancount;
  629. unsigned short type = 0;
  630. unsigned short rdlength;
  631. unsigned short nscount;
  632. unsigned short arcount;
  633. unsigned int index = 12;
  634. DOHcode rc;
  635. if(dohlen < 12)
  636. return DOH_TOO_SMALL_BUFFER; /* too small */
  637. if(!doh || doh[0] || doh[1])
  638. return DOH_DNS_BAD_ID; /* bad ID */
  639. rcode = doh[3] & 0x0f;
  640. if(rcode)
  641. return DOH_DNS_BAD_RCODE; /* bad rcode */
  642. qdcount = get16bit(doh, 4);
  643. while(qdcount) {
  644. rc = skipqname(doh, dohlen, &index);
  645. if(rc)
  646. return rc; /* bad qname */
  647. if(dohlen < (index + 4))
  648. return DOH_DNS_OUT_OF_RANGE;
  649. index += 4; /* skip question's type and class */
  650. qdcount--;
  651. }
  652. ancount = get16bit(doh, 6);
  653. while(ancount) {
  654. unsigned short class;
  655. unsigned int ttl;
  656. rc = skipqname(doh, dohlen, &index);
  657. if(rc)
  658. return rc; /* bad qname */
  659. if(dohlen < (index + 2))
  660. return DOH_DNS_OUT_OF_RANGE;
  661. type = get16bit(doh, index);
  662. if((type != DNS_TYPE_CNAME) /* may be synthesized from DNAME */
  663. && (type != DNS_TYPE_DNAME) /* if present, accept and ignore */
  664. && (type != dnstype))
  665. /* Not the same type as was asked for nor CNAME nor DNAME */
  666. return DOH_DNS_UNEXPECTED_TYPE;
  667. index += 2;
  668. if(dohlen < (index + 2))
  669. return DOH_DNS_OUT_OF_RANGE;
  670. class = get16bit(doh, index);
  671. if(DNS_CLASS_IN != class)
  672. return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
  673. index += 2;
  674. if(dohlen < (index + 4))
  675. return DOH_DNS_OUT_OF_RANGE;
  676. ttl = get32bit(doh, index);
  677. if(ttl < d->ttl)
  678. d->ttl = ttl;
  679. index += 4;
  680. if(dohlen < (index + 2))
  681. return DOH_DNS_OUT_OF_RANGE;
  682. rdlength = get16bit(doh, index);
  683. index += 2;
  684. if(dohlen < (index + rdlength))
  685. return DOH_DNS_OUT_OF_RANGE;
  686. rc = rdata(doh, dohlen, rdlength, type, (int)index, d);
  687. if(rc)
  688. return rc; /* bad rdata */
  689. index += rdlength;
  690. ancount--;
  691. }
  692. nscount = get16bit(doh, 8);
  693. while(nscount) {
  694. rc = skipqname(doh, dohlen, &index);
  695. if(rc)
  696. return rc; /* bad qname */
  697. if(dohlen < (index + 8))
  698. return DOH_DNS_OUT_OF_RANGE;
  699. index += 2 + 2 + 4; /* type, class and ttl */
  700. if(dohlen < (index + 2))
  701. return DOH_DNS_OUT_OF_RANGE;
  702. rdlength = get16bit(doh, index);
  703. index += 2;
  704. if(dohlen < (index + rdlength))
  705. return DOH_DNS_OUT_OF_RANGE;
  706. index += rdlength;
  707. nscount--;
  708. }
  709. arcount = get16bit(doh, 10);
  710. while(arcount) {
  711. rc = skipqname(doh, dohlen, &index);
  712. if(rc)
  713. return rc; /* bad qname */
  714. if(dohlen < (index + 8))
  715. return DOH_DNS_OUT_OF_RANGE;
  716. index += 2 + 2 + 4; /* type, class and ttl */
  717. if(dohlen < (index + 2))
  718. return DOH_DNS_OUT_OF_RANGE;
  719. rdlength = get16bit(doh, index);
  720. index += 2;
  721. if(dohlen < (index + rdlength))
  722. return DOH_DNS_OUT_OF_RANGE;
  723. index += rdlength;
  724. arcount--;
  725. }
  726. if(index != dohlen)
  727. return DOH_DNS_MALFORMAT; /* something is wrong */
  728. #ifdef USE_HTTTPS
  729. if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr && !d->numhttps_rrs)
  730. #else
  731. if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr)
  732. #endif
  733. /* nothing stored! */
  734. return DOH_NO_CONTENT;
  735. return DOH_OK; /* ok */
  736. }
  737. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  738. static void showdoh(struct Curl_easy *data,
  739. const struct dohentry *d)
  740. {
  741. int i;
  742. infof(data, "[DoH] TTL: %u seconds", d->ttl);
  743. for(i = 0; i < d->numaddr; i++) {
  744. const struct dohaddr *a = &d->addr[i];
  745. if(a->type == DNS_TYPE_A) {
  746. infof(data, "[DoH] A: %u.%u.%u.%u",
  747. a->ip.v4[0], a->ip.v4[1],
  748. a->ip.v4[2], a->ip.v4[3]);
  749. }
  750. else if(a->type == DNS_TYPE_AAAA) {
  751. int j;
  752. char buffer[128];
  753. char *ptr;
  754. size_t len;
  755. len = msnprintf(buffer, 128, "[DoH] AAAA: ");
  756. ptr = &buffer[len];
  757. len = sizeof(buffer) - len;
  758. for(j = 0; j < 16; j += 2) {
  759. size_t l;
  760. msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j],
  761. d->addr[i].ip.v6[j + 1]);
  762. l = strlen(ptr);
  763. len -= l;
  764. ptr += l;
  765. }
  766. infof(data, "%s", buffer);
  767. }
  768. }
  769. #ifdef USE_HTTPSRR
  770. for(i = 0; i < d->numhttps_rrs; i++) {
  771. # ifdef DEBUGBUILD
  772. local_print_buf(data, "DoH HTTPS",
  773. d->https_rrs[i].val, d->https_rrs[i].len);
  774. # else
  775. infof(data, "DoH HTTPS RR: length %d", d->https_rrs[i].len);
  776. # endif
  777. }
  778. #endif
  779. for(i = 0; i < d->numcname; i++) {
  780. infof(data, "CNAME: %s", Curl_dyn_ptr(&d->cname[i]));
  781. }
  782. }
  783. #else
  784. #define showdoh(x,y)
  785. #endif
  786. /*
  787. * doh2ai()
  788. *
  789. * This function returns a pointer to the first element of a newly allocated
  790. * Curl_addrinfo struct linked list filled with the data from a set of DoH
  791. * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for
  792. * a IPv6 stack, but usable also for IPv4, all hosts and environments.
  793. *
  794. * The memory allocated by this function *MUST* be free'd later on calling
  795. * Curl_freeaddrinfo(). For each successful call to this function there
  796. * must be an associated call later to Curl_freeaddrinfo().
  797. */
  798. static CURLcode doh2ai(const struct dohentry *de, const char *hostname,
  799. int port, struct Curl_addrinfo **aip)
  800. {
  801. struct Curl_addrinfo *ai;
  802. struct Curl_addrinfo *prevai = NULL;
  803. struct Curl_addrinfo *firstai = NULL;
  804. struct sockaddr_in *addr;
  805. #ifdef USE_IPV6
  806. struct sockaddr_in6 *addr6;
  807. #endif
  808. CURLcode result = CURLE_OK;
  809. int i;
  810. size_t hostlen = strlen(hostname) + 1; /* include null-terminator */
  811. DEBUGASSERT(de);
  812. if(!de->numaddr)
  813. return CURLE_COULDNT_RESOLVE_HOST;
  814. for(i = 0; i < de->numaddr; i++) {
  815. size_t ss_size;
  816. CURL_SA_FAMILY_T addrtype;
  817. if(de->addr[i].type == DNS_TYPE_AAAA) {
  818. #ifndef USE_IPV6
  819. /* we cannot handle IPv6 addresses */
  820. continue;
  821. #else
  822. ss_size = sizeof(struct sockaddr_in6);
  823. addrtype = AF_INET6;
  824. #endif
  825. }
  826. else {
  827. ss_size = sizeof(struct sockaddr_in);
  828. addrtype = AF_INET;
  829. }
  830. ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen);
  831. if(!ai) {
  832. result = CURLE_OUT_OF_MEMORY;
  833. break;
  834. }
  835. ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
  836. ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size);
  837. memcpy(ai->ai_canonname, hostname, hostlen);
  838. if(!firstai)
  839. /* store the pointer we want to return from this function */
  840. firstai = ai;
  841. if(prevai)
  842. /* make the previous entry point to this */
  843. prevai->ai_next = ai;
  844. ai->ai_family = addrtype;
  845. /* we return all names as STREAM, so when using this address for TFTP
  846. the type must be ignored and conn->socktype be used instead! */
  847. ai->ai_socktype = SOCK_STREAM;
  848. ai->ai_addrlen = (curl_socklen_t)ss_size;
  849. /* leave the rest of the struct filled with zero */
  850. switch(ai->ai_family) {
  851. case AF_INET:
  852. addr = (void *)ai->ai_addr; /* storage area for this info */
  853. DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
  854. memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
  855. #ifdef __MINGW32__
  856. addr->sin_family = (short)addrtype;
  857. #else
  858. addr->sin_family = addrtype;
  859. #endif
  860. addr->sin_port = htons((unsigned short)port);
  861. break;
  862. #ifdef USE_IPV6
  863. case AF_INET6:
  864. addr6 = (void *)ai->ai_addr; /* storage area for this info */
  865. DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
  866. memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
  867. #ifdef __MINGW32__
  868. addr6->sin6_family = (short)addrtype;
  869. #else
  870. addr6->sin6_family = addrtype;
  871. #endif
  872. addr6->sin6_port = htons((unsigned short)port);
  873. break;
  874. #endif
  875. }
  876. prevai = ai;
  877. }
  878. if(result) {
  879. Curl_freeaddrinfo(firstai);
  880. firstai = NULL;
  881. }
  882. *aip = firstai;
  883. return result;
  884. }
  885. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  886. static const char *type2name(DNStype dnstype)
  887. {
  888. switch(dnstype) {
  889. case DNS_TYPE_A:
  890. return "A";
  891. case DNS_TYPE_AAAA:
  892. return "AAAA";
  893. #ifdef USE_HTTPSRR
  894. case DNS_TYPE_HTTPS:
  895. return "HTTPS";
  896. #endif
  897. default:
  898. return "unknown";
  899. }
  900. }
  901. #endif
  902. UNITTEST void de_cleanup(struct dohentry *d)
  903. {
  904. int i = 0;
  905. for(i = 0; i < d->numcname; i++) {
  906. Curl_dyn_free(&d->cname[i]);
  907. }
  908. #ifdef USE_HTTPSRR
  909. for(i = 0; i < d->numhttps_rrs; i++)
  910. Curl_safefree(d->https_rrs[i].val);
  911. #endif
  912. }
  913. #ifdef USE_HTTPSRR
  914. /*
  915. * @brief decode the DNS name in a binary RRData
  916. * @param buf points to the buffer (in/out)
  917. * @param remaining points to the remaining buffer length (in/out)
  918. * @param dnsname returns the string form name on success
  919. * @return is 1 for success, error otherwise
  920. *
  921. * The encoding here is defined in
  922. * https://tools.ietf.org/html/rfc1035#section-3.1
  923. *
  924. * The input buffer pointer will be modified so it points to
  925. * just after the end of the DNS name encoding on output. (And
  926. * that is why it is an "unsigned char **" :-)
  927. */
  928. static CURLcode local_decode_rdata_name(unsigned char **buf, size_t *remaining,
  929. char **dnsname)
  930. {
  931. unsigned char *cp = NULL;
  932. int rem = 0;
  933. unsigned char clen = 0; /* chunk len */
  934. struct dynbuf thename;
  935. DEBUGASSERT(buf && remaining && dnsname);
  936. if(!buf || !remaining || !dnsname)
  937. return CURLE_OUT_OF_MEMORY;
  938. rem = (int)*remaining;
  939. if(rem <= 0) {
  940. Curl_dyn_free(&thename);
  941. return CURLE_OUT_OF_MEMORY;
  942. }
  943. Curl_dyn_init(&thename, CURL_MAXLEN_host_name);
  944. cp = *buf;
  945. clen = *cp++;
  946. if(clen == 0) {
  947. /* special case - return "." as name */
  948. if(Curl_dyn_addn(&thename, ".", 1))
  949. return CURLE_OUT_OF_MEMORY;
  950. }
  951. while(clen) {
  952. if(clen >= rem) {
  953. Curl_dyn_free(&thename);
  954. return CURLE_OUT_OF_MEMORY;
  955. }
  956. if(Curl_dyn_addn(&thename, cp, clen) ||
  957. Curl_dyn_addn(&thename, ".", 1))
  958. return CURLE_TOO_LARGE;
  959. cp += clen;
  960. rem -= (clen + 1);
  961. if(rem <= 0) {
  962. Curl_dyn_free(&thename);
  963. return CURLE_OUT_OF_MEMORY;
  964. }
  965. clen = *cp++;
  966. }
  967. *buf = cp;
  968. *remaining = rem - 1;
  969. *dnsname = Curl_dyn_ptr(&thename);
  970. return CURLE_OK;
  971. }
  972. static CURLcode local_decode_rdata_alpn(unsigned char *rrval, size_t len,
  973. char **alpns)
  974. {
  975. /*
  976. * spec here is as per draft-ietf-dnsop-svcb-https, section-7.1.1
  977. * encoding is catenated list of strings each preceded by a one
  978. * octet length
  979. * output is comma-sep list of the strings
  980. * implementations may or may not handle quoting of comma within
  981. * string values, so we might see a comma within the wire format
  982. * version of a string, in which case we will precede that by a
  983. * backslash - same goes for a backslash character, and of course
  984. * we need to use two backslashes in strings when we mean one;-)
  985. */
  986. int remaining = (int) len;
  987. char *oval;
  988. size_t i;
  989. unsigned char *cp = rrval;
  990. struct dynbuf dval;
  991. if(!alpns)
  992. return CURLE_OUT_OF_MEMORY;
  993. Curl_dyn_init(&dval, DYN_DOH_RESPONSE);
  994. remaining = (int)len;
  995. cp = rrval;
  996. while(remaining > 0) {
  997. size_t tlen = (size_t) *cp++;
  998. /* if not 1st time, add comma */
  999. if(remaining != (int)len && Curl_dyn_addn(&dval, ",", 1))
  1000. goto err;
  1001. remaining--;
  1002. if(tlen > (size_t)remaining)
  1003. goto err;
  1004. /* add escape char if needed, clunky but easier to read */
  1005. for(i = 0; i != tlen; i++) {
  1006. if('\\' == *cp || ',' == *cp) {
  1007. if(Curl_dyn_addn(&dval, "\\", 1))
  1008. goto err;
  1009. }
  1010. if(Curl_dyn_addn(&dval, cp++, 1))
  1011. goto err;
  1012. }
  1013. remaining -= (int)tlen;
  1014. }
  1015. /* this string is always null terminated */
  1016. oval = Curl_dyn_ptr(&dval);
  1017. if(!oval)
  1018. goto err;
  1019. *alpns = oval;
  1020. return CURLE_OK;
  1021. err:
  1022. Curl_dyn_free(&dval);
  1023. return CURLE_BAD_CONTENT_ENCODING;
  1024. }
  1025. #ifdef DEBUGBUILD
  1026. static CURLcode test_alpn_escapes(void)
  1027. {
  1028. /* we will use an example from draft-ietf-dnsop-svcb, figure 10 */
  1029. static unsigned char example[] = {
  1030. 0x08, /* length 8 */
  1031. 0x66, 0x5c, 0x6f, 0x6f, 0x2c, 0x62, 0x61, 0x72, /* value "f\\oo,bar" */
  1032. 0x02, /* length 2 */
  1033. 0x68, 0x32 /* value "h2" */
  1034. };
  1035. size_t example_len = sizeof(example);
  1036. char *aval = NULL;
  1037. static const char *expected = "f\\\\oo\\,bar,h2";
  1038. if(local_decode_rdata_alpn(example, example_len, &aval) != CURLE_OK)
  1039. return CURLE_BAD_CONTENT_ENCODING;
  1040. if(strlen(aval) != strlen(expected))
  1041. return CURLE_BAD_CONTENT_ENCODING;
  1042. if(memcmp(aval, expected, strlen(aval)))
  1043. return CURLE_BAD_CONTENT_ENCODING;
  1044. return CURLE_OK;
  1045. }
  1046. #endif
  1047. static CURLcode Curl_doh_decode_httpsrr(unsigned char *rrval, size_t len,
  1048. struct Curl_https_rrinfo **hrr)
  1049. {
  1050. size_t remaining = len;
  1051. unsigned char *cp = rrval;
  1052. uint16_t pcode = 0, plen = 0;
  1053. struct Curl_https_rrinfo *lhrr = NULL;
  1054. char *dnsname = NULL;
  1055. #ifdef DEBUGBUILD
  1056. /* a few tests of escaping, should not be here but ok for now */
  1057. if(test_alpn_escapes() != CURLE_OK)
  1058. return CURLE_OUT_OF_MEMORY;
  1059. #endif
  1060. lhrr = calloc(1, sizeof(struct Curl_https_rrinfo));
  1061. if(!lhrr)
  1062. return CURLE_OUT_OF_MEMORY;
  1063. lhrr->val = Curl_memdup(rrval, len);
  1064. if(!lhrr->val)
  1065. goto err;
  1066. lhrr->len = len;
  1067. if(remaining <= 2)
  1068. goto err;
  1069. lhrr->priority = (uint16_t)((cp[0] << 8) + cp[1]);
  1070. cp += 2;
  1071. remaining -= (uint16_t)2;
  1072. if(local_decode_rdata_name(&cp, &remaining, &dnsname) != CURLE_OK)
  1073. goto err;
  1074. lhrr->target = dnsname;
  1075. while(remaining >= 4) {
  1076. pcode = (uint16_t)((*cp << 8) + (*(cp + 1)));
  1077. cp += 2;
  1078. plen = (uint16_t)((*cp << 8) + (*(cp + 1)));
  1079. cp += 2;
  1080. remaining -= 4;
  1081. if(pcode == HTTPS_RR_CODE_ALPN) {
  1082. if(local_decode_rdata_alpn(cp, plen, &lhrr->alpns) != CURLE_OK)
  1083. goto err;
  1084. }
  1085. if(pcode == HTTPS_RR_CODE_NO_DEF_ALPN)
  1086. lhrr->no_def_alpn = TRUE;
  1087. else if(pcode == HTTPS_RR_CODE_IPV4) {
  1088. if(!plen)
  1089. goto err;
  1090. lhrr->ipv4hints = Curl_memdup(cp, plen);
  1091. if(!lhrr->ipv4hints)
  1092. goto err;
  1093. lhrr->ipv4hints_len = (size_t)plen;
  1094. }
  1095. else if(pcode == HTTPS_RR_CODE_ECH) {
  1096. if(!plen)
  1097. goto err;
  1098. lhrr->echconfiglist = Curl_memdup(cp, plen);
  1099. if(!lhrr->echconfiglist)
  1100. goto err;
  1101. lhrr->echconfiglist_len = (size_t)plen;
  1102. }
  1103. else if(pcode == HTTPS_RR_CODE_IPV6) {
  1104. if(!plen)
  1105. goto err;
  1106. lhrr->ipv6hints = Curl_memdup(cp, plen);
  1107. if(!lhrr->ipv6hints)
  1108. goto err;
  1109. lhrr->ipv6hints_len = (size_t)plen;
  1110. }
  1111. if(plen > 0 && plen <= remaining) {
  1112. cp += plen;
  1113. remaining -= plen;
  1114. }
  1115. }
  1116. DEBUGASSERT(!remaining);
  1117. *hrr = lhrr;
  1118. return CURLE_OK;
  1119. err:
  1120. if(lhrr) {
  1121. Curl_safefree(lhrr->target);
  1122. Curl_safefree(lhrr->echconfiglist);
  1123. Curl_safefree(lhrr->val);
  1124. Curl_safefree(lhrr->alpns);
  1125. Curl_safefree(lhrr);
  1126. }
  1127. return CURLE_OUT_OF_MEMORY;
  1128. }
  1129. # ifdef DEBUGBUILD
  1130. static void local_print_httpsrr(struct Curl_easy *data,
  1131. struct Curl_https_rrinfo *hrr)
  1132. {
  1133. DEBUGASSERT(hrr);
  1134. infof(data, "HTTPS RR: priority %d, target: %s",
  1135. hrr->priority, hrr->target);
  1136. if(hrr->alpns)
  1137. infof(data, "HTTPS RR: alpns %s", hrr->alpns);
  1138. else
  1139. infof(data, "HTTPS RR: no alpns");
  1140. if(hrr->no_def_alpn)
  1141. infof(data, "HTTPS RR: no_def_alpn set");
  1142. else
  1143. infof(data, "HTTPS RR: no_def_alpn not set");
  1144. if(hrr->ipv4hints) {
  1145. local_print_buf(data, "HTTPS RR: ipv4hints",
  1146. hrr->ipv4hints, hrr->ipv4hints_len);
  1147. }
  1148. else
  1149. infof(data, "HTTPS RR: no ipv4hints");
  1150. if(hrr->echconfiglist) {
  1151. local_print_buf(data, "HTTPS RR: ECHConfigList",
  1152. hrr->echconfiglist, hrr->echconfiglist_len);
  1153. }
  1154. else
  1155. infof(data, "HTTPS RR: no ECHConfigList");
  1156. if(hrr->ipv6hints) {
  1157. local_print_buf(data, "HTTPS RR: ipv6hint",
  1158. hrr->ipv6hints, hrr->ipv6hints_len);
  1159. }
  1160. else
  1161. infof(data, "HTTPS RR: no ipv6hints");
  1162. return;
  1163. }
  1164. # endif
  1165. #endif
  1166. CURLcode Curl_doh_is_resolved(struct Curl_easy *data,
  1167. struct Curl_dns_entry **dnsp)
  1168. {
  1169. CURLcode result;
  1170. struct dohdata *dohp = data->req.doh;
  1171. *dnsp = NULL; /* defaults to no response */
  1172. if(!dohp)
  1173. return CURLE_OUT_OF_MEMORY;
  1174. if(!dohp->probe[DOH_PROBE_SLOT_IPADDR_V4].easy &&
  1175. !dohp->probe[DOH_PROBE_SLOT_IPADDR_V6].easy) {
  1176. failf(data, "Could not DoH-resolve: %s", data->state.async.hostname);
  1177. return CONN_IS_PROXIED(data->conn)?CURLE_COULDNT_RESOLVE_PROXY:
  1178. CURLE_COULDNT_RESOLVE_HOST;
  1179. }
  1180. else if(!dohp->pending) {
  1181. #ifndef USE_HTTPSRR
  1182. DOHcode rc[DOH_PROBE_SLOTS] = {
  1183. DOH_OK, DOH_OK
  1184. };
  1185. #else
  1186. DOHcode rc[DOH_PROBE_SLOTS] = {
  1187. DOH_OK, DOH_OK, DOH_OK
  1188. };
  1189. #endif
  1190. struct dohentry de;
  1191. int slot;
  1192. /* remove DoH handles from multi handle and close them */
  1193. Curl_doh_close(data);
  1194. /* parse the responses, create the struct and return it! */
  1195. de_init(&de);
  1196. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  1197. struct dnsprobe *p = &dohp->probe[slot];
  1198. if(!p->dnstype)
  1199. continue;
  1200. rc[slot] = doh_decode(Curl_dyn_uptr(&p->serverdoh),
  1201. Curl_dyn_len(&p->serverdoh),
  1202. p->dnstype,
  1203. &de);
  1204. Curl_dyn_free(&p->serverdoh);
  1205. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1206. if(rc[slot]) {
  1207. infof(data, "DoH: %s type %s for %s", doh_strerror(rc[slot]),
  1208. type2name(p->dnstype), dohp->host);
  1209. }
  1210. #endif
  1211. } /* next slot */
  1212. result = CURLE_COULDNT_RESOLVE_HOST; /* until we know better */
  1213. if(!rc[DOH_PROBE_SLOT_IPADDR_V4] || !rc[DOH_PROBE_SLOT_IPADDR_V6]) {
  1214. /* we have an address, of one kind or other */
  1215. struct Curl_dns_entry *dns;
  1216. struct Curl_addrinfo *ai;
  1217. if(Curl_trc_ft_is_verbose(data, &Curl_doh_trc)) {
  1218. infof(data, "[DoH] hostname: %s", dohp->host);
  1219. showdoh(data, &de);
  1220. }
  1221. result = doh2ai(&de, dohp->host, dohp->port, &ai);
  1222. if(result) {
  1223. de_cleanup(&de);
  1224. return result;
  1225. }
  1226. if(data->share)
  1227. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  1228. /* we got a response, store it in the cache */
  1229. dns = Curl_cache_addr(data, ai, dohp->host, 0, dohp->port);
  1230. if(data->share)
  1231. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  1232. if(!dns) {
  1233. /* returned failure, bail out nicely */
  1234. Curl_freeaddrinfo(ai);
  1235. }
  1236. else {
  1237. data->state.async.dns = dns;
  1238. *dnsp = dns;
  1239. result = CURLE_OK; /* address resolution OK */
  1240. }
  1241. } /* address processing done */
  1242. /* Now process any build-specific attributes retrieved from DNS */
  1243. #ifdef USE_HTTPSRR
  1244. if(de.numhttps_rrs > 0 && result == CURLE_OK && *dnsp) {
  1245. struct Curl_https_rrinfo *hrr = NULL;
  1246. result = Curl_doh_decode_httpsrr(de.https_rrs->val, de.https_rrs->len,
  1247. &hrr);
  1248. if(result) {
  1249. infof(data, "Failed to decode HTTPS RR");
  1250. return result;
  1251. }
  1252. infof(data, "Some HTTPS RR to process");
  1253. # ifdef DEBUGBUILD
  1254. local_print_httpsrr(data, hrr);
  1255. # endif
  1256. (*dnsp)->hinfo = hrr;
  1257. }
  1258. #endif
  1259. /* All done */
  1260. de_cleanup(&de);
  1261. Curl_safefree(data->req.doh);
  1262. return result;
  1263. } /* !dohp->pending */
  1264. /* else wait for pending DoH transactions to complete */
  1265. return CURLE_OK;
  1266. }
  1267. void Curl_doh_close(struct Curl_easy *data)
  1268. {
  1269. struct dohdata *doh = data->req.doh;
  1270. if(doh) {
  1271. size_t slot;
  1272. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  1273. if(!doh->probe[slot].easy)
  1274. continue;
  1275. /* data->multi might already be reset at this time */
  1276. if(doh->probe[slot].easy->multi)
  1277. curl_multi_remove_handle(doh->probe[slot].easy->multi,
  1278. doh->probe[slot].easy);
  1279. Curl_close(&doh->probe[slot].easy);
  1280. }
  1281. }
  1282. }
  1283. void Curl_doh_cleanup(struct Curl_easy *data)
  1284. {
  1285. struct dohdata *doh = data->req.doh;
  1286. if(doh) {
  1287. Curl_doh_close(data);
  1288. curl_slist_free_all(doh->headers);
  1289. data->req.doh->headers = NULL;
  1290. Curl_safefree(data->req.doh);
  1291. }
  1292. }
  1293. #endif /* CURL_DISABLE_DOH */