doh.c 41 KB

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