http_client.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. /*
  2. * Copyright 2001-2022 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright Siemens AG 2018-2020
  4. *
  5. * Licensed under the Apache License 2.0 (the "License"). You may not use
  6. * this file except in compliance with the License. You can obtain a copy
  7. * in the file LICENSE in the source distribution or at
  8. * https://www.openssl.org/source/license.html
  9. */
  10. #include "internal/e_os.h"
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include "crypto/ctype.h"
  14. #include <string.h>
  15. #include <openssl/asn1.h>
  16. #include <openssl/evp.h>
  17. #include <openssl/err.h>
  18. #include <openssl/httperr.h>
  19. #include <openssl/cmperr.h>
  20. #include <openssl/buffer.h>
  21. #include <openssl/http.h>
  22. #include <openssl/trace.h>
  23. #include "internal/sockets.h"
  24. #include "internal/common.h" /* for ossl_assert() */
  25. #define HTTP_PREFIX "HTTP/"
  26. #define HTTP_VERSION_PATT "1." /* allow 1.x */
  27. #define HTTP_VERSION_STR_LEN sizeof(HTTP_VERSION_PATT) /* == strlen("1.0") */
  28. #define HTTP_PREFIX_VERSION HTTP_PREFIX""HTTP_VERSION_PATT
  29. #define HTTP_1_0 HTTP_PREFIX_VERSION"0" /* "HTTP/1.0" */
  30. #define HTTP_LINE1_MINLEN (sizeof(HTTP_PREFIX_VERSION "x 200\n") - 1)
  31. #define HTTP_VERSION_MAX_REDIRECTIONS 50
  32. #define HTTP_STATUS_CODE_OK 200
  33. #define HTTP_STATUS_CODE_MOVED_PERMANENTLY 301
  34. #define HTTP_STATUS_CODE_FOUND 302
  35. /* Stateful HTTP request code, supporting blocking and non-blocking I/O */
  36. /* Opaque HTTP request status structure */
  37. struct ossl_http_req_ctx_st {
  38. int state; /* Current I/O state */
  39. unsigned char *buf; /* Buffer to write request or read response */
  40. int buf_size; /* Buffer size */
  41. int free_wbio; /* wbio allocated internally, free with ctx */
  42. BIO *wbio; /* BIO to write/send request to */
  43. BIO *rbio; /* BIO to read/receive response from */
  44. OSSL_HTTP_bio_cb_t upd_fn; /* Optional BIO update callback used for TLS */
  45. void *upd_arg; /* Optional arg for update callback function */
  46. int use_ssl; /* Use HTTPS */
  47. char *proxy; /* Optional proxy name or URI */
  48. char *server; /* Optional server hostname */
  49. char *port; /* Optional server port */
  50. BIO *mem; /* Mem BIO holding request header or response */
  51. BIO *req; /* BIO holding the request provided by caller */
  52. int method_POST; /* HTTP method is POST (else GET) */
  53. int text; /* Request content type is (likely) text */
  54. char *expected_ct; /* Optional expected Content-Type */
  55. int expect_asn1; /* Response must be ASN.1-encoded */
  56. unsigned char *pos; /* Current position sending data */
  57. long len_to_send; /* Number of bytes still to send */
  58. size_t resp_len; /* Length of response */
  59. size_t max_resp_len; /* Maximum length of response, or 0 */
  60. int keep_alive; /* Persistent conn. 0=no, 1=prefer, 2=require */
  61. time_t max_time; /* Maximum end time of current transfer, or 0 */
  62. time_t max_total_time; /* Maximum end time of total transfer, or 0 */
  63. char *redirection_url; /* Location obtained from HTTP status 301/302 */
  64. };
  65. /* HTTP states */
  66. #define OHS_NOREAD 0x1000 /* If set no reading should be performed */
  67. #define OHS_ERROR (0 | OHS_NOREAD) /* Error condition */
  68. #define OHS_ADD_HEADERS (1 | OHS_NOREAD) /* Adding header lines to request */
  69. #define OHS_WRITE_INIT (2 | OHS_NOREAD) /* 1st call: ready to start send */
  70. #define OHS_WRITE_HDR1 (3 | OHS_NOREAD) /* Request header to be sent */
  71. #define OHS_WRITE_HDR (4 | OHS_NOREAD) /* Request header being sent */
  72. #define OHS_WRITE_REQ (5 | OHS_NOREAD) /* Request content being sent */
  73. #define OHS_FLUSH (6 | OHS_NOREAD) /* Request being flushed */
  74. #define OHS_FIRSTLINE 1 /* First line of response being read */
  75. #define OHS_HEADERS 2 /* MIME headers of response being read */
  76. #define OHS_HEADERS_ERROR 3 /* MIME headers of resp. being read after error */
  77. #define OHS_REDIRECT 4 /* MIME headers being read, expecting Location */
  78. #define OHS_ASN1_HEADER 5 /* ASN1 sequence header (tag+length) being read */
  79. #define OHS_ASN1_CONTENT 6 /* ASN1 content octets being read */
  80. #define OHS_ASN1_DONE (7 | OHS_NOREAD) /* ASN1 content read completed */
  81. #define OHS_STREAM (8 | OHS_NOREAD) /* HTTP content stream to be read */
  82. /* Low-level HTTP API implementation */
  83. OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int buf_size)
  84. {
  85. OSSL_HTTP_REQ_CTX *rctx;
  86. if (wbio == NULL || rbio == NULL) {
  87. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  88. return NULL;
  89. }
  90. if ((rctx = OPENSSL_zalloc(sizeof(*rctx))) == NULL)
  91. return NULL;
  92. rctx->state = OHS_ERROR;
  93. rctx->buf_size = buf_size > 0 ? buf_size : OSSL_HTTP_DEFAULT_MAX_LINE_LEN;
  94. rctx->buf = OPENSSL_malloc(rctx->buf_size);
  95. rctx->wbio = wbio;
  96. rctx->rbio = rbio;
  97. if (rctx->buf == NULL) {
  98. OPENSSL_free(rctx);
  99. return NULL;
  100. }
  101. rctx->max_resp_len = OSSL_HTTP_DEFAULT_MAX_RESP_LEN;
  102. /* everything else is 0, e.g. rctx->len_to_send, or NULL, e.g. rctx->mem */
  103. return rctx;
  104. }
  105. void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx)
  106. {
  107. if (rctx == NULL)
  108. return;
  109. /*
  110. * Use BIO_free_all() because bio_update_fn may prepend or append to cbio.
  111. * This also frees any (e.g., SSL/TLS) BIOs linked with bio and,
  112. * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer.
  113. */
  114. if (rctx->free_wbio)
  115. BIO_free_all(rctx->wbio);
  116. /* do not free rctx->rbio */
  117. BIO_free(rctx->mem);
  118. BIO_free(rctx->req);
  119. OPENSSL_free(rctx->buf);
  120. OPENSSL_free(rctx->proxy);
  121. OPENSSL_free(rctx->server);
  122. OPENSSL_free(rctx->port);
  123. OPENSSL_free(rctx->expected_ct);
  124. OPENSSL_free(rctx);
  125. }
  126. BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX *rctx)
  127. {
  128. if (rctx == NULL) {
  129. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  130. return NULL;
  131. }
  132. return rctx->mem;
  133. }
  134. size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX *rctx)
  135. {
  136. if (rctx == NULL) {
  137. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  138. return 0;
  139. }
  140. return rctx->resp_len;
  141. }
  142. void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx,
  143. unsigned long len)
  144. {
  145. if (rctx == NULL) {
  146. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  147. return;
  148. }
  149. rctx->max_resp_len = len != 0 ? (size_t)len : OSSL_HTTP_DEFAULT_MAX_RESP_LEN;
  150. }
  151. /*
  152. * Create request line using |rctx| and |path| (or "/" in case |path| is NULL).
  153. * Server name (and port) must be given if and only if plain HTTP proxy is used.
  154. */
  155. int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX *rctx, int method_POST,
  156. const char *server, const char *port,
  157. const char *path)
  158. {
  159. if (rctx == NULL) {
  160. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  161. return 0;
  162. }
  163. BIO_free(rctx->mem);
  164. if ((rctx->mem = BIO_new(BIO_s_mem())) == NULL)
  165. return 0;
  166. rctx->method_POST = method_POST != 0;
  167. if (BIO_printf(rctx->mem, "%s ", rctx->method_POST ? "POST" : "GET") <= 0)
  168. return 0;
  169. if (server != NULL) { /* HTTP (but not HTTPS) proxy is used */
  170. /*
  171. * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only
  172. * allowed when using a proxy
  173. */
  174. if (BIO_printf(rctx->mem, OSSL_HTTP_PREFIX"%s", server) <= 0)
  175. return 0;
  176. if (port != NULL && BIO_printf(rctx->mem, ":%s", port) <= 0)
  177. return 0;
  178. }
  179. /* Make sure path includes a forward slash */
  180. if (path == NULL)
  181. path = "/";
  182. if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0)
  183. return 0;
  184. /*
  185. * Add (the rest of) the path and the HTTP version,
  186. * which is fixed to 1.0 for straightforward implementation of keep-alive
  187. */
  188. if (BIO_printf(rctx->mem, "%s "HTTP_1_0"\r\n", path) <= 0)
  189. return 0;
  190. rctx->resp_len = 0;
  191. rctx->state = OHS_ADD_HEADERS;
  192. return 1;
  193. }
  194. int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx,
  195. const char *name, const char *value)
  196. {
  197. if (rctx == NULL || name == NULL) {
  198. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  199. return 0;
  200. }
  201. if (rctx->mem == NULL) {
  202. ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  203. return 0;
  204. }
  205. if (BIO_puts(rctx->mem, name) <= 0)
  206. return 0;
  207. if (value != NULL) {
  208. if (BIO_write(rctx->mem, ": ", 2) != 2)
  209. return 0;
  210. if (BIO_puts(rctx->mem, value) <= 0)
  211. return 0;
  212. }
  213. return BIO_write(rctx->mem, "\r\n", 2) == 2;
  214. }
  215. int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX *rctx,
  216. const char *content_type, int asn1,
  217. int timeout, int keep_alive)
  218. {
  219. if (rctx == NULL) {
  220. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  221. return 0;
  222. }
  223. if (keep_alive != 0
  224. && rctx->state != OHS_ERROR && rctx->state != OHS_ADD_HEADERS) {
  225. /* Cannot anymore set keep-alive in request header */
  226. ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  227. return 0;
  228. }
  229. OPENSSL_free(rctx->expected_ct);
  230. rctx->expected_ct = NULL;
  231. if (content_type != NULL
  232. && (rctx->expected_ct = OPENSSL_strdup(content_type)) == NULL)
  233. return 0;
  234. rctx->expect_asn1 = asn1;
  235. if (timeout >= 0)
  236. rctx->max_time = timeout > 0 ? time(NULL) + timeout : 0;
  237. else /* take over any |overall_timeout| arg of OSSL_HTTP_open(), else 0 */
  238. rctx->max_time = rctx->max_total_time;
  239. rctx->keep_alive = keep_alive;
  240. return 1;
  241. }
  242. static int set1_content(OSSL_HTTP_REQ_CTX *rctx,
  243. const char *content_type, BIO *req)
  244. {
  245. long req_len = 0;
  246. #ifndef OPENSSL_NO_STDIO
  247. FILE *fp = NULL;
  248. #endif
  249. if (rctx == NULL || (req == NULL && content_type != NULL)) {
  250. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  251. return 0;
  252. }
  253. if (rctx->keep_alive != 0
  254. && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Connection", "keep-alive"))
  255. return 0;
  256. BIO_free(rctx->req);
  257. rctx->req = NULL;
  258. if (req == NULL)
  259. return 1;
  260. if (!rctx->method_POST) {
  261. ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  262. return 0;
  263. }
  264. if (content_type == NULL) {
  265. rctx->text = 1; /* assuming text by default, used just for tracing */
  266. } else {
  267. if (OPENSSL_strncasecmp(content_type, "text/", 5) == 0)
  268. rctx->text = 1;
  269. if (BIO_printf(rctx->mem, "Content-Type: %s\r\n", content_type) <= 0)
  270. return 0;
  271. }
  272. /*
  273. * BIO_CTRL_INFO yields the data length at least for memory BIOs, but for
  274. * file-based BIOs it gives the current position, which is not what we need.
  275. */
  276. if (BIO_method_type(req) == BIO_TYPE_FILE) {
  277. #ifndef OPENSSL_NO_STDIO
  278. if (BIO_get_fp(req, &fp) == 1 && fseek(fp, 0, SEEK_END) == 0) {
  279. req_len = ftell(fp);
  280. (void)fseek(fp, 0, SEEK_SET);
  281. } else {
  282. fp = NULL;
  283. }
  284. #endif
  285. } else {
  286. req_len = BIO_ctrl(req, BIO_CTRL_INFO, 0, NULL);
  287. /*
  288. * Streaming BIOs likely will not support querying the size at all,
  289. * and we assume we got a correct value if req_len > 0.
  290. */
  291. }
  292. if ((
  293. #ifndef OPENSSL_NO_STDIO
  294. fp != NULL /* definitely correct req_len */ ||
  295. #endif
  296. req_len > 0)
  297. && BIO_printf(rctx->mem, "Content-Length: %ld\r\n", req_len) < 0)
  298. return 0;
  299. if (!BIO_up_ref(req))
  300. return 0;
  301. rctx->req = req;
  302. return 1;
  303. }
  304. int OSSL_HTTP_REQ_CTX_set1_req(OSSL_HTTP_REQ_CTX *rctx, const char *content_type,
  305. const ASN1_ITEM *it, const ASN1_VALUE *req)
  306. {
  307. BIO *mem = NULL;
  308. int res = 1;
  309. if (req != NULL)
  310. res = (mem = ASN1_item_i2d_mem_bio(it, req)) != NULL;
  311. res = res && set1_content(rctx, content_type, mem);
  312. BIO_free(mem);
  313. return res;
  314. }
  315. static int add1_headers(OSSL_HTTP_REQ_CTX *rctx,
  316. const STACK_OF(CONF_VALUE) *headers, const char *host)
  317. {
  318. int i;
  319. int add_host = host != NULL && *host != '\0';
  320. CONF_VALUE *hdr;
  321. for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
  322. hdr = sk_CONF_VALUE_value(headers, i);
  323. if (add_host && OPENSSL_strcasecmp("host", hdr->name) == 0)
  324. add_host = 0;
  325. if (!OSSL_HTTP_REQ_CTX_add1_header(rctx, hdr->name, hdr->value))
  326. return 0;
  327. }
  328. if (add_host && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Host", host))
  329. return 0;
  330. return 1;
  331. }
  332. /* Create OSSL_HTTP_REQ_CTX structure using the values provided. */
  333. static OSSL_HTTP_REQ_CTX *http_req_ctx_new(int free_wbio, BIO *wbio, BIO *rbio,
  334. OSSL_HTTP_bio_cb_t bio_update_fn,
  335. void *arg, int use_ssl,
  336. const char *proxy,
  337. const char *server, const char *port,
  338. int buf_size, int overall_timeout)
  339. {
  340. OSSL_HTTP_REQ_CTX *rctx = OSSL_HTTP_REQ_CTX_new(wbio, rbio, buf_size);
  341. if (rctx == NULL)
  342. return NULL;
  343. rctx->free_wbio = free_wbio;
  344. rctx->upd_fn = bio_update_fn;
  345. rctx->upd_arg = arg;
  346. rctx->use_ssl = use_ssl;
  347. if (proxy != NULL
  348. && (rctx->proxy = OPENSSL_strdup(proxy)) == NULL)
  349. goto err;
  350. if (server != NULL
  351. && (rctx->server = OPENSSL_strdup(server)) == NULL)
  352. goto err;
  353. if (port != NULL
  354. && (rctx->port = OPENSSL_strdup(port)) == NULL)
  355. goto err;
  356. rctx->max_total_time =
  357. overall_timeout > 0 ? time(NULL) + overall_timeout : 0;
  358. return rctx;
  359. err:
  360. OSSL_HTTP_REQ_CTX_free(rctx);
  361. return NULL;
  362. }
  363. /*
  364. * Parse first HTTP response line. This should be like this: "HTTP/1.0 200 OK".
  365. * We need to obtain the status code and (optional) informational message.
  366. * Return any received HTTP response status code, or 0 on fatal error.
  367. */
  368. static int parse_http_line1(char *line, int *found_keep_alive)
  369. {
  370. int i, retcode, err;
  371. char *code, *reason, *end;
  372. if (!CHECK_AND_SKIP_PREFIX(line, HTTP_PREFIX_VERSION))
  373. goto err;
  374. /* above HTTP 1.0, connection persistence is the default */
  375. *found_keep_alive = *line > '0';
  376. /* Skip to first whitespace (past protocol info) */
  377. for (code = line; *code != '\0' && !ossl_isspace(*code); code++)
  378. continue;
  379. if (*code == '\0')
  380. goto err;
  381. /* Skip past whitespace to start of response code */
  382. while (*code != '\0' && ossl_isspace(*code))
  383. code++;
  384. if (*code == '\0')
  385. goto err;
  386. /* Find end of response code: first whitespace after start of code */
  387. for (reason = code; *reason != '\0' && !ossl_isspace(*reason); reason++)
  388. continue;
  389. if (*reason == '\0')
  390. goto err;
  391. /* Set end of response code and start of message */
  392. *reason++ = '\0';
  393. /* Attempt to parse numeric code */
  394. retcode = strtoul(code, &end, 10);
  395. if (*end != '\0')
  396. goto err;
  397. /* Skip over any leading whitespace in message */
  398. while (*reason != '\0' && ossl_isspace(*reason))
  399. reason++;
  400. if (*reason != '\0') {
  401. /*
  402. * Finally zap any trailing whitespace in message (include CRLF)
  403. */
  404. /* chop any trailing whitespace from reason */
  405. /* We know reason has a non-whitespace character so this is OK */
  406. for (end = reason + strlen(reason) - 1; ossl_isspace(*end); end--)
  407. *end = '\0';
  408. }
  409. switch (retcode) {
  410. case HTTP_STATUS_CODE_OK:
  411. case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
  412. case HTTP_STATUS_CODE_FOUND:
  413. return retcode;
  414. default:
  415. err = HTTP_R_RECEIVED_ERROR;
  416. if (retcode < 400)
  417. err = HTTP_R_STATUS_CODE_UNSUPPORTED;
  418. if (*reason == '\0')
  419. ERR_raise_data(ERR_LIB_HTTP, err, "code=%s", code);
  420. else
  421. ERR_raise_data(ERR_LIB_HTTP, err, "code=%s, reason=%s", code,
  422. reason);
  423. return retcode;
  424. }
  425. err:
  426. for (i = 0; i < 60 && line[i] != '\0'; i++)
  427. if (!ossl_isprint(line[i]))
  428. line[i] = ' ';
  429. line[i] = '\0';
  430. ERR_raise_data(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR, "content=%s", line);
  431. return 0;
  432. }
  433. static int check_set_resp_len(OSSL_HTTP_REQ_CTX *rctx, size_t len)
  434. {
  435. if (rctx->max_resp_len != 0 && len > rctx->max_resp_len)
  436. ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MAX_RESP_LEN_EXCEEDED,
  437. "length=%zu, max=%zu", len, rctx->max_resp_len);
  438. if (rctx->resp_len != 0 && rctx->resp_len != len)
  439. ERR_raise_data(ERR_LIB_HTTP, HTTP_R_INCONSISTENT_CONTENT_LENGTH,
  440. "ASN.1 length=%zu, Content-Length=%zu",
  441. len, rctx->resp_len);
  442. rctx->resp_len = len;
  443. return 1;
  444. }
  445. static int may_still_retry(time_t max_time, int *ptimeout)
  446. {
  447. time_t time_diff, now = time(NULL);
  448. if (max_time != 0) {
  449. if (max_time < now) {
  450. ERR_raise(ERR_LIB_HTTP, HTTP_R_RETRY_TIMEOUT);
  451. return 0;
  452. }
  453. time_diff = max_time - now;
  454. *ptimeout = time_diff > INT_MAX ? INT_MAX : (int)time_diff;
  455. }
  456. return 1;
  457. }
  458. /*
  459. * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx.
  460. * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry.
  461. */
  462. int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx)
  463. {
  464. int i, found_expected_ct = 0, found_keep_alive = 0;
  465. int got_text = 1;
  466. long n;
  467. size_t resp_len;
  468. const unsigned char *p;
  469. char *buf, *key, *value, *line_end = NULL;
  470. if (rctx == NULL) {
  471. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  472. return 0;
  473. }
  474. if (rctx->mem == NULL || rctx->wbio == NULL || rctx->rbio == NULL) {
  475. ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  476. return 0;
  477. }
  478. rctx->redirection_url = NULL;
  479. next_io:
  480. buf = (char *)rctx->buf;
  481. if ((rctx->state & OHS_NOREAD) == 0) {
  482. if (rctx->expect_asn1) {
  483. n = BIO_read(rctx->rbio, rctx->buf, rctx->buf_size);
  484. } else {
  485. (void)ERR_set_mark();
  486. n = BIO_gets(rctx->rbio, buf, rctx->buf_size);
  487. if (n == -2) { /* some BIOs, such as SSL, do not support "gets" */
  488. (void)ERR_pop_to_mark();
  489. n = BIO_get_line(rctx->rbio, buf, rctx->buf_size);
  490. } else {
  491. (void)ERR_clear_last_mark();
  492. }
  493. }
  494. if (n <= 0) {
  495. if (BIO_should_retry(rctx->rbio))
  496. return -1;
  497. ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA);
  498. return 0;
  499. }
  500. /* Write data to memory BIO */
  501. if (BIO_write(rctx->mem, rctx->buf, n) != n)
  502. return 0;
  503. }
  504. switch (rctx->state) {
  505. case OHS_ADD_HEADERS:
  506. /* Last operation was adding headers: need a final \r\n */
  507. if (BIO_write(rctx->mem, "\r\n", 2) != 2) {
  508. rctx->state = OHS_ERROR;
  509. return 0;
  510. }
  511. rctx->state = OHS_WRITE_INIT;
  512. /* fall through */
  513. case OHS_WRITE_INIT:
  514. rctx->len_to_send = BIO_get_mem_data(rctx->mem, &rctx->pos);
  515. rctx->state = OHS_WRITE_HDR1;
  516. /* fall through */
  517. case OHS_WRITE_HDR1:
  518. case OHS_WRITE_HDR:
  519. /* Copy some chunk of data from rctx->mem to rctx->wbio */
  520. case OHS_WRITE_REQ:
  521. /* Copy some chunk of data from rctx->req to rctx->wbio */
  522. if (rctx->len_to_send > 0) {
  523. size_t sz;
  524. if (!BIO_write_ex(rctx->wbio, rctx->pos, rctx->len_to_send, &sz)) {
  525. if (BIO_should_retry(rctx->wbio))
  526. return -1;
  527. rctx->state = OHS_ERROR;
  528. return 0;
  529. }
  530. if (OSSL_TRACE_ENABLED(HTTP) && rctx->state == OHS_WRITE_HDR1)
  531. OSSL_TRACE(HTTP, "Sending request: [\n");
  532. OSSL_TRACE_STRING(HTTP, rctx->state != OHS_WRITE_REQ || rctx->text,
  533. rctx->state != OHS_WRITE_REQ, rctx->pos, sz);
  534. if (rctx->state == OHS_WRITE_HDR1)
  535. rctx->state = OHS_WRITE_HDR;
  536. rctx->pos += sz;
  537. rctx->len_to_send -= sz;
  538. goto next_io;
  539. }
  540. if (rctx->state == OHS_WRITE_HDR) {
  541. (void)BIO_reset(rctx->mem);
  542. rctx->state = OHS_WRITE_REQ;
  543. }
  544. if (rctx->req != NULL && !BIO_eof(rctx->req)) {
  545. n = BIO_read(rctx->req, rctx->buf, rctx->buf_size);
  546. if (n <= 0) {
  547. if (BIO_should_retry(rctx->req))
  548. return -1;
  549. ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA);
  550. return 0;
  551. }
  552. rctx->pos = rctx->buf;
  553. rctx->len_to_send = n;
  554. goto next_io;
  555. }
  556. if (OSSL_TRACE_ENABLED(HTTP))
  557. OSSL_TRACE(HTTP, "]\n");
  558. rctx->state = OHS_FLUSH;
  559. /* fall through */
  560. case OHS_FLUSH:
  561. i = BIO_flush(rctx->wbio);
  562. if (i > 0) {
  563. rctx->state = OHS_FIRSTLINE;
  564. goto next_io;
  565. }
  566. if (BIO_should_retry(rctx->wbio))
  567. return -1;
  568. rctx->state = OHS_ERROR;
  569. return 0;
  570. case OHS_ERROR:
  571. return 0;
  572. case OHS_FIRSTLINE:
  573. case OHS_HEADERS:
  574. case OHS_REDIRECT:
  575. /* Attempt to read a line in */
  576. next_line:
  577. /*
  578. * Due to strange memory BIO behavior with BIO_gets we have to check
  579. * there's a complete line in there before calling BIO_gets or we'll
  580. * just get a partial read.
  581. */
  582. n = BIO_get_mem_data(rctx->mem, &p);
  583. if (n <= 0 || memchr(p, '\n', n) == 0) {
  584. if (n >= rctx->buf_size) {
  585. rctx->state = OHS_ERROR;
  586. return 0;
  587. }
  588. goto next_io;
  589. }
  590. n = BIO_gets(rctx->mem, buf, rctx->buf_size);
  591. if (n <= 0) {
  592. if (BIO_should_retry(rctx->mem))
  593. goto next_io;
  594. rctx->state = OHS_ERROR;
  595. return 0;
  596. }
  597. /* Don't allow excessive lines */
  598. if (n == rctx->buf_size) {
  599. ERR_raise(ERR_LIB_HTTP, HTTP_R_RESPONSE_LINE_TOO_LONG);
  600. rctx->state = OHS_ERROR;
  601. return 0;
  602. }
  603. /* dump all response header lines */
  604. if (OSSL_TRACE_ENABLED(HTTP)) {
  605. if (rctx->state == OHS_FIRSTLINE)
  606. OSSL_TRACE(HTTP, "Received response header: [\n");
  607. OSSL_TRACE1(HTTP, "%s", buf);
  608. }
  609. /* First line */
  610. if (rctx->state == OHS_FIRSTLINE) {
  611. switch (parse_http_line1(buf, &found_keep_alive)) {
  612. case HTTP_STATUS_CODE_OK:
  613. rctx->state = OHS_HEADERS;
  614. goto next_line;
  615. case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
  616. case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */
  617. if (!rctx->method_POST) { /* method is GET */
  618. rctx->state = OHS_REDIRECT;
  619. goto next_line;
  620. }
  621. ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
  622. /* redirection is not supported/recommended for POST */
  623. /* fall through */
  624. default:
  625. rctx->state = OHS_HEADERS_ERROR;
  626. goto next_line; /* continue parsing and reporting header */
  627. }
  628. }
  629. key = buf;
  630. value = strchr(key, ':');
  631. if (value != NULL) {
  632. *(value++) = '\0';
  633. while (ossl_isspace(*value))
  634. value++;
  635. line_end = strchr(value, '\r');
  636. if (line_end == NULL)
  637. line_end = strchr(value, '\n');
  638. if (line_end != NULL)
  639. *line_end = '\0';
  640. }
  641. if (value != NULL && line_end != NULL) {
  642. if (rctx->state == OHS_REDIRECT
  643. && OPENSSL_strcasecmp(key, "Location") == 0) {
  644. rctx->redirection_url = value;
  645. return 0;
  646. }
  647. if (OPENSSL_strcasecmp(key, "Content-Type") == 0) {
  648. got_text = OPENSSL_strncasecmp(value, "text/", 5) == 0;
  649. if (rctx->state == OHS_HEADERS
  650. && rctx->expected_ct != NULL) {
  651. const char *semicolon;
  652. if (OPENSSL_strcasecmp(rctx->expected_ct, value) != 0
  653. /* ignore past ';' unless expected_ct contains ';' */
  654. && (strchr(rctx->expected_ct, ';') != NULL
  655. || (semicolon = strchr(value, ';')) == NULL
  656. || (size_t)(semicolon - value) != strlen(rctx->expected_ct)
  657. || OPENSSL_strncasecmp(rctx->expected_ct, value,
  658. semicolon - value) != 0)) {
  659. ERR_raise_data(ERR_LIB_HTTP,
  660. HTTP_R_UNEXPECTED_CONTENT_TYPE,
  661. "expected=%s, actual=%s",
  662. rctx->expected_ct, value);
  663. return 0;
  664. }
  665. found_expected_ct = 1;
  666. }
  667. }
  668. /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
  669. if (OPENSSL_strcasecmp(key, "Connection") == 0) {
  670. if (OPENSSL_strcasecmp(value, "keep-alive") == 0)
  671. found_keep_alive = 1;
  672. else if (OPENSSL_strcasecmp(value, "close") == 0)
  673. found_keep_alive = 0;
  674. } else if (OPENSSL_strcasecmp(key, "Content-Length") == 0) {
  675. resp_len = (size_t)strtoul(value, &line_end, 10);
  676. if (line_end == value || *line_end != '\0') {
  677. ERR_raise_data(ERR_LIB_HTTP,
  678. HTTP_R_ERROR_PARSING_CONTENT_LENGTH,
  679. "input=%s", value);
  680. return 0;
  681. }
  682. if (!check_set_resp_len(rctx, resp_len))
  683. return 0;
  684. }
  685. }
  686. /* Look for blank line indicating end of headers */
  687. for (p = rctx->buf; *p != '\0'; p++) {
  688. if (*p != '\r' && *p != '\n')
  689. break;
  690. }
  691. if (*p != '\0') /* not end of headers */
  692. goto next_line;
  693. if (OSSL_TRACE_ENABLED(HTTP))
  694. OSSL_TRACE(HTTP, "]\n");
  695. if (rctx->keep_alive != 0 /* do not let server initiate keep_alive */
  696. && !found_keep_alive /* otherwise there is no change */) {
  697. if (rctx->keep_alive == 2) {
  698. rctx->keep_alive = 0;
  699. ERR_raise(ERR_LIB_HTTP, HTTP_R_SERVER_CANCELED_CONNECTION);
  700. return 0;
  701. }
  702. rctx->keep_alive = 0;
  703. }
  704. if (rctx->state == OHS_HEADERS_ERROR) {
  705. if (OSSL_TRACE_ENABLED(HTTP)) {
  706. int printed_final_nl = 0;
  707. OSSL_TRACE(HTTP, "Received error response body: [\n");
  708. while ((n = BIO_read(rctx->rbio, rctx->buf, rctx->buf_size)) > 0
  709. || (OSSL_sleep(100), BIO_should_retry(rctx->rbio))) {
  710. OSSL_TRACE_STRING(HTTP, got_text, 1, rctx->buf, n);
  711. if (n > 0)
  712. printed_final_nl = rctx->buf[n - 1] == '\n';
  713. }
  714. OSSL_TRACE1(HTTP, "%s]\n", printed_final_nl ? "" : "\n");
  715. (void)printed_final_nl; /* avoid warning unless enable-trace */
  716. }
  717. return 0;
  718. }
  719. if (rctx->expected_ct != NULL && !found_expected_ct) {
  720. ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MISSING_CONTENT_TYPE,
  721. "expected=%s", rctx->expected_ct);
  722. return 0;
  723. }
  724. if (rctx->state == OHS_REDIRECT) {
  725. /* http status code indicated redirect but there was no Location */
  726. ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_REDIRECT_LOCATION);
  727. return 0;
  728. }
  729. if (!rctx->expect_asn1) {
  730. rctx->state = OHS_STREAM;
  731. return 1;
  732. }
  733. rctx->state = OHS_ASN1_HEADER;
  734. /* Fall thru */
  735. case OHS_ASN1_HEADER:
  736. /*
  737. * Now reading ASN1 header: can read at least 2 bytes which is enough
  738. * for ASN1 SEQUENCE header and either length field or at least the
  739. * length of the length field.
  740. */
  741. n = BIO_get_mem_data(rctx->mem, &p);
  742. if (n < 2)
  743. goto next_io;
  744. /* Check it is an ASN1 SEQUENCE */
  745. if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
  746. ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_ASN1_ENCODING);
  747. return 0;
  748. }
  749. /* Check out length field */
  750. if ((*p & 0x80) != 0) {
  751. /*
  752. * If MSB set on initial length octet we can now always read 6
  753. * octets: make sure we have them.
  754. */
  755. if (n < 6)
  756. goto next_io;
  757. n = *p & 0x7F;
  758. /* Not NDEF or excessive length */
  759. if (n == 0 || (n > 4)) {
  760. ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_ASN1_LENGTH);
  761. return 0;
  762. }
  763. p++;
  764. resp_len = 0;
  765. for (i = 0; i < n; i++) {
  766. resp_len <<= 8;
  767. resp_len |= *p++;
  768. }
  769. resp_len += n + 2;
  770. } else {
  771. resp_len = *p + 2;
  772. }
  773. if (!check_set_resp_len(rctx, resp_len))
  774. return 0;
  775. rctx->state = OHS_ASN1_CONTENT;
  776. /* Fall thru */
  777. case OHS_ASN1_CONTENT:
  778. default:
  779. n = BIO_get_mem_data(rctx->mem, NULL);
  780. if (n < 0 || (size_t)n < rctx->resp_len)
  781. goto next_io;
  782. rctx->state = OHS_ASN1_DONE;
  783. return 1;
  784. }
  785. }
  786. int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX *rctx,
  787. ASN1_VALUE **pval, const ASN1_ITEM *it)
  788. {
  789. const unsigned char *p;
  790. int rv;
  791. *pval = NULL;
  792. if ((rv = OSSL_HTTP_REQ_CTX_nbio(rctx)) != 1)
  793. return rv;
  794. *pval = ASN1_item_d2i(NULL, &p, BIO_get_mem_data(rctx->mem, &p), it);
  795. return *pval != NULL;
  796. }
  797. #ifndef OPENSSL_NO_SOCK
  798. /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
  799. static BIO *http_new_bio(const char *server /* optionally includes ":port" */,
  800. const char *server_port /* explicit server port */,
  801. int use_ssl,
  802. const char *proxy /* optionally includes ":port" */,
  803. const char *proxy_port /* explicit proxy port */)
  804. {
  805. const char *host = server;
  806. const char *port = server_port;
  807. BIO *cbio;
  808. if (!ossl_assert(server != NULL))
  809. return NULL;
  810. if (proxy != NULL) {
  811. host = proxy;
  812. port = proxy_port;
  813. }
  814. if (port == NULL && strchr(host, ':') == NULL)
  815. port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
  816. cbio = BIO_new_connect(host /* optionally includes ":port" */);
  817. if (cbio == NULL)
  818. goto end;
  819. if (port != NULL)
  820. (void)BIO_set_conn_port(cbio, port);
  821. end:
  822. return cbio;
  823. }
  824. #endif /* OPENSSL_NO_SOCK */
  825. /* Exchange request and response via HTTP on (non-)blocking BIO */
  826. BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx)
  827. {
  828. int rv;
  829. if (rctx == NULL) {
  830. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  831. return NULL;
  832. }
  833. for (;;) {
  834. rv = OSSL_HTTP_REQ_CTX_nbio(rctx);
  835. if (rv != -1)
  836. break;
  837. /* BIO_should_retry was true */
  838. /* will not actually wait if rctx->max_time == 0 */
  839. if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0)
  840. return NULL;
  841. }
  842. if (rv == 0) {
  843. if (rctx->redirection_url == NULL) { /* an error occurred */
  844. if (rctx->len_to_send > 0)
  845. ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_SENDING);
  846. else
  847. ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_RECEIVING);
  848. }
  849. return NULL;
  850. }
  851. return rctx->state == OHS_STREAM ? rctx->rbio : rctx->mem;
  852. }
  853. int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx)
  854. {
  855. return rctx != NULL && rctx->keep_alive != 0;
  856. }
  857. /* High-level HTTP API implementation */
  858. /* Initiate an HTTP session using bio, else use given server, proxy, etc. */
  859. OSSL_HTTP_REQ_CTX *OSSL_HTTP_open(const char *server, const char *port,
  860. const char *proxy, const char *no_proxy,
  861. int use_ssl, BIO *bio, BIO *rbio,
  862. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  863. int buf_size, int overall_timeout)
  864. {
  865. BIO *cbio; /* == bio if supplied, used as connection BIO if rbio is NULL */
  866. OSSL_HTTP_REQ_CTX *rctx = NULL;
  867. if (use_ssl && bio_update_fn == NULL) {
  868. ERR_raise(ERR_LIB_HTTP, HTTP_R_TLS_NOT_ENABLED);
  869. return NULL;
  870. }
  871. if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) {
  872. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
  873. return NULL;
  874. }
  875. if (bio != NULL) {
  876. cbio = bio;
  877. if (proxy != NULL || no_proxy != NULL) {
  878. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
  879. return NULL;
  880. }
  881. } else {
  882. #ifndef OPENSSL_NO_SOCK
  883. char *proxy_host = NULL, *proxy_port = NULL;
  884. if (server == NULL) {
  885. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  886. return NULL;
  887. }
  888. if (port != NULL && *port == '\0')
  889. port = NULL;
  890. if (port == NULL && strchr(server, ':') == NULL)
  891. port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
  892. proxy = OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl);
  893. if (proxy != NULL
  894. && !OSSL_HTTP_parse_url(proxy, NULL /* use_ssl */, NULL /* user */,
  895. &proxy_host, &proxy_port, NULL /* num */,
  896. NULL /* path */, NULL, NULL))
  897. return NULL;
  898. cbio = http_new_bio(server, port, use_ssl, proxy_host, proxy_port);
  899. OPENSSL_free(proxy_host);
  900. OPENSSL_free(proxy_port);
  901. if (cbio == NULL)
  902. return NULL;
  903. #else
  904. ERR_raise(ERR_LIB_HTTP, HTTP_R_SOCK_NOT_SUPPORTED);
  905. return NULL;
  906. #endif
  907. }
  908. (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
  909. if (rbio == NULL && BIO_do_connect_retry(cbio, overall_timeout, -1) <= 0) {
  910. if (bio == NULL) /* cbio was not provided by caller */
  911. BIO_free_all(cbio);
  912. goto end;
  913. }
  914. /* now overall_timeout is guaranteed to be >= 0 */
  915. /* adapt in order to fix callback design flaw, see #17088 */
  916. /* callback can be used to wrap or prepend TLS session */
  917. if (bio_update_fn != NULL) {
  918. BIO *orig_bio = cbio;
  919. cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl != 0);
  920. if (cbio == NULL) {
  921. if (bio == NULL) /* cbio was not provided by caller */
  922. BIO_free_all(orig_bio);
  923. goto end;
  924. }
  925. }
  926. rctx = http_req_ctx_new(bio == NULL, cbio, rbio != NULL ? rbio : cbio,
  927. bio_update_fn, arg, use_ssl, proxy, server, port,
  928. buf_size, overall_timeout);
  929. end:
  930. if (rctx != NULL)
  931. /* remove any spurious error queue entries by ssl_add_cert_chain() */
  932. (void)ERR_pop_to_mark();
  933. else
  934. (void)ERR_clear_last_mark();
  935. return rctx;
  936. }
  937. int OSSL_HTTP_set1_request(OSSL_HTTP_REQ_CTX *rctx, const char *path,
  938. const STACK_OF(CONF_VALUE) *headers,
  939. const char *content_type, BIO *req,
  940. const char *expected_content_type, int expect_asn1,
  941. size_t max_resp_len, int timeout, int keep_alive)
  942. {
  943. int use_http_proxy;
  944. if (rctx == NULL) {
  945. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  946. return 0;
  947. }
  948. use_http_proxy = rctx->proxy != NULL && !rctx->use_ssl;
  949. if (use_http_proxy && rctx->server == NULL) {
  950. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
  951. return 0;
  952. }
  953. rctx->max_resp_len = max_resp_len; /* allows for 0: indefinite */
  954. return OSSL_HTTP_REQ_CTX_set_request_line(rctx, req != NULL,
  955. use_http_proxy ? rctx->server
  956. : NULL, rctx->port, path)
  957. && add1_headers(rctx, headers, rctx->server)
  958. && OSSL_HTTP_REQ_CTX_set_expected(rctx, expected_content_type,
  959. expect_asn1, timeout, keep_alive)
  960. && set1_content(rctx, content_type, req);
  961. }
  962. /*-
  963. * Exchange single HTTP request and response according to rctx.
  964. * If rctx->method_POST then use POST, else use GET and ignore content_type.
  965. * The redirection_url output (freed by caller) parameter is used only for GET.
  966. */
  967. BIO *OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX *rctx, char **redirection_url)
  968. {
  969. BIO *resp;
  970. if (rctx == NULL) {
  971. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  972. return NULL;
  973. }
  974. if (redirection_url != NULL)
  975. *redirection_url = NULL; /* do this beforehand to prevent dbl free */
  976. resp = OSSL_HTTP_REQ_CTX_exchange(rctx);
  977. if (resp == NULL) {
  978. if (rctx->redirection_url != NULL) {
  979. if (redirection_url == NULL)
  980. ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
  981. else
  982. /* may be NULL if out of memory: */
  983. *redirection_url = OPENSSL_strdup(rctx->redirection_url);
  984. } else {
  985. char buf[200];
  986. unsigned long err = ERR_peek_error();
  987. int lib = ERR_GET_LIB(err);
  988. int reason = ERR_GET_REASON(err);
  989. if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP
  990. || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT)
  991. || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR)
  992. #ifndef OPENSSL_NO_CMP
  993. || (lib == ERR_LIB_CMP
  994. && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
  995. #endif
  996. ) {
  997. if (rctx->server != NULL) {
  998. BIO_snprintf(buf, sizeof(buf), "server=http%s://%s%s%s",
  999. rctx->use_ssl ? "s" : "", rctx->server,
  1000. rctx->port != NULL ? ":" : "",
  1001. rctx->port != NULL ? rctx->port : "");
  1002. ERR_add_error_data(1, buf);
  1003. }
  1004. if (rctx->proxy != NULL)
  1005. ERR_add_error_data(2, " proxy=", rctx->proxy);
  1006. if (err == 0) {
  1007. BIO_snprintf(buf, sizeof(buf), " peer has disconnected%s",
  1008. rctx->use_ssl ? " violating the protocol" :
  1009. ", likely because it requires the use of TLS");
  1010. ERR_add_error_data(1, buf);
  1011. }
  1012. }
  1013. }
  1014. }
  1015. if (resp != NULL && !BIO_up_ref(resp))
  1016. resp = NULL;
  1017. return resp;
  1018. }
  1019. static int redirection_ok(int n_redir, const char *old_url, const char *new_url)
  1020. {
  1021. if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) {
  1022. ERR_raise(ERR_LIB_HTTP, HTTP_R_TOO_MANY_REDIRECTIONS);
  1023. return 0;
  1024. }
  1025. if (*new_url == '/') /* redirection to same server => same protocol */
  1026. return 1;
  1027. if (HAS_PREFIX(old_url, OSSL_HTTPS_NAME":") &&
  1028. !HAS_PREFIX(new_url, OSSL_HTTPS_NAME":")) {
  1029. ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP);
  1030. return 0;
  1031. }
  1032. return 1;
  1033. }
  1034. /* Get data via HTTP from server at given URL, potentially with redirection */
  1035. BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy,
  1036. BIO *bio, BIO *rbio,
  1037. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  1038. int buf_size, const STACK_OF(CONF_VALUE) *headers,
  1039. const char *expected_ct, int expect_asn1,
  1040. size_t max_resp_len, int timeout)
  1041. {
  1042. char *current_url, *redirection_url = NULL;
  1043. int n_redirs = 0;
  1044. char *host;
  1045. char *port;
  1046. char *path;
  1047. int use_ssl;
  1048. OSSL_HTTP_REQ_CTX *rctx;
  1049. BIO *resp = NULL;
  1050. time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
  1051. if (url == NULL) {
  1052. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  1053. return NULL;
  1054. }
  1055. if ((current_url = OPENSSL_strdup(url)) == NULL)
  1056. return NULL;
  1057. for (;;) {
  1058. if (!OSSL_HTTP_parse_url(current_url, &use_ssl, NULL /* user */, &host,
  1059. &port, NULL /* port_num */, &path, NULL, NULL))
  1060. break;
  1061. rctx = OSSL_HTTP_open(host, port, proxy, no_proxy,
  1062. use_ssl, bio, rbio, bio_update_fn, arg,
  1063. buf_size, timeout);
  1064. new_rpath:
  1065. if (rctx != NULL) {
  1066. if (!OSSL_HTTP_set1_request(rctx, path, headers,
  1067. NULL /* content_type */,
  1068. NULL /* req */,
  1069. expected_ct, expect_asn1, max_resp_len,
  1070. -1 /* use same max time (timeout) */,
  1071. 0 /* no keep_alive */))
  1072. OSSL_HTTP_REQ_CTX_free(rctx);
  1073. else
  1074. resp = OSSL_HTTP_exchange(rctx, &redirection_url);
  1075. }
  1076. OPENSSL_free(path);
  1077. if (resp == NULL && redirection_url != NULL) {
  1078. if (redirection_ok(++n_redirs, current_url, redirection_url)
  1079. && may_still_retry(max_time, &timeout)) {
  1080. (void)BIO_reset(bio);
  1081. OPENSSL_free(current_url);
  1082. current_url = redirection_url;
  1083. if (*redirection_url == '/') { /* redirection to same server */
  1084. path = OPENSSL_strdup(redirection_url);
  1085. if (path == NULL) {
  1086. OPENSSL_free(host);
  1087. OPENSSL_free(port);
  1088. (void)OSSL_HTTP_close(rctx, 1);
  1089. BIO_free(resp);
  1090. OPENSSL_free(current_url);
  1091. return NULL;
  1092. }
  1093. goto new_rpath;
  1094. }
  1095. OPENSSL_free(host);
  1096. OPENSSL_free(port);
  1097. (void)OSSL_HTTP_close(rctx, 1);
  1098. continue;
  1099. }
  1100. /* if redirection not allowed, ignore it */
  1101. OPENSSL_free(redirection_url);
  1102. }
  1103. OPENSSL_free(host);
  1104. OPENSSL_free(port);
  1105. if (!OSSL_HTTP_close(rctx, resp != NULL)) {
  1106. BIO_free(resp);
  1107. resp = NULL;
  1108. }
  1109. break;
  1110. }
  1111. OPENSSL_free(current_url);
  1112. return resp;
  1113. }
  1114. /* Exchange request and response over a connection managed via |prctx| */
  1115. BIO *OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX **prctx,
  1116. const char *server, const char *port,
  1117. const char *path, int use_ssl,
  1118. const char *proxy, const char *no_proxy,
  1119. BIO *bio, BIO *rbio,
  1120. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  1121. int buf_size, const STACK_OF(CONF_VALUE) *headers,
  1122. const char *content_type, BIO *req,
  1123. const char *expected_ct, int expect_asn1,
  1124. size_t max_resp_len, int timeout, int keep_alive)
  1125. {
  1126. OSSL_HTTP_REQ_CTX *rctx = prctx == NULL ? NULL : *prctx;
  1127. BIO *resp = NULL;
  1128. if (rctx == NULL) {
  1129. rctx = OSSL_HTTP_open(server, port, proxy, no_proxy,
  1130. use_ssl, bio, rbio, bio_update_fn, arg,
  1131. buf_size, timeout);
  1132. timeout = -1; /* Already set during opening the connection */
  1133. }
  1134. if (rctx != NULL) {
  1135. if (OSSL_HTTP_set1_request(rctx, path, headers, content_type, req,
  1136. expected_ct, expect_asn1,
  1137. max_resp_len, timeout, keep_alive))
  1138. resp = OSSL_HTTP_exchange(rctx, NULL);
  1139. if (resp == NULL || !OSSL_HTTP_is_alive(rctx)) {
  1140. if (!OSSL_HTTP_close(rctx, resp != NULL)) {
  1141. BIO_free(resp);
  1142. resp = NULL;
  1143. }
  1144. rctx = NULL;
  1145. }
  1146. }
  1147. if (prctx != NULL)
  1148. *prctx = rctx;
  1149. return resp;
  1150. }
  1151. int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX *rctx, int ok)
  1152. {
  1153. BIO *wbio;
  1154. int ret = 1;
  1155. /* callback can be used to finish TLS session and free its BIO */
  1156. if (rctx != NULL && rctx->upd_fn != NULL) {
  1157. wbio = (*rctx->upd_fn)(rctx->wbio, rctx->upd_arg,
  1158. 0 /* disconnect */, ok);
  1159. ret = wbio != NULL;
  1160. if (ret)
  1161. rctx->wbio = wbio;
  1162. }
  1163. OSSL_HTTP_REQ_CTX_free(rctx);
  1164. return ret;
  1165. }
  1166. /* BASE64 encoder used for encoding basic proxy authentication credentials */
  1167. static char *base64encode(const void *buf, size_t len)
  1168. {
  1169. int i;
  1170. size_t outl;
  1171. char *out;
  1172. /* Calculate size of encoded data */
  1173. outl = (len / 3);
  1174. if (len % 3 > 0)
  1175. outl++;
  1176. outl <<= 2;
  1177. out = OPENSSL_malloc(outl + 1);
  1178. if (out == NULL)
  1179. return 0;
  1180. i = EVP_EncodeBlock((unsigned char *)out, buf, len);
  1181. if (!ossl_assert(0 <= i && (size_t)i <= outl)) {
  1182. OPENSSL_free(out);
  1183. return NULL;
  1184. }
  1185. return out;
  1186. }
  1187. /*
  1188. * Promote the given connection BIO using the CONNECT method for a TLS proxy.
  1189. * This is typically called by an app, so bio_err and prog are used unless NULL
  1190. * to print additional diagnostic information in a user-oriented way.
  1191. */
  1192. int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
  1193. const char *proxyuser, const char *proxypass,
  1194. int timeout, BIO *bio_err, const char *prog)
  1195. {
  1196. #undef BUF_SIZE
  1197. #define BUF_SIZE (8 * 1024)
  1198. char *mbuf = OPENSSL_malloc(BUF_SIZE);
  1199. char *mbufp;
  1200. int read_len = 0;
  1201. int ret = 0;
  1202. BIO *fbio = BIO_new(BIO_f_buffer());
  1203. int rv;
  1204. time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
  1205. if (bio == NULL || server == NULL
  1206. || (bio_err != NULL && prog == NULL)) {
  1207. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  1208. goto end;
  1209. }
  1210. if (port == NULL || *port == '\0')
  1211. port = OSSL_HTTPS_PORT;
  1212. if (mbuf == NULL || fbio == NULL) {
  1213. BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog);
  1214. goto end;
  1215. }
  1216. BIO_push(fbio, bio);
  1217. BIO_printf(fbio, "CONNECT %s:%s "HTTP_1_0"\r\n", server, port);
  1218. /*
  1219. * Workaround for broken proxies which would otherwise close
  1220. * the connection when entering tunnel mode (e.g., Squid 2.6)
  1221. */
  1222. BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n");
  1223. /* Support for basic (base64) proxy authentication */
  1224. if (proxyuser != NULL) {
  1225. size_t len = strlen(proxyuser) + 1;
  1226. char *proxyauth, *proxyauthenc = NULL;
  1227. if (proxypass != NULL)
  1228. len += strlen(proxypass);
  1229. proxyauth = OPENSSL_malloc(len + 1);
  1230. if (proxyauth == NULL)
  1231. goto end;
  1232. if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser,
  1233. proxypass != NULL ? proxypass : "") != (int)len)
  1234. goto proxy_end;
  1235. proxyauthenc = base64encode(proxyauth, len);
  1236. if (proxyauthenc != NULL) {
  1237. BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc);
  1238. OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc));
  1239. }
  1240. proxy_end:
  1241. OPENSSL_clear_free(proxyauth, len);
  1242. if (proxyauthenc == NULL)
  1243. goto end;
  1244. }
  1245. /* Terminate the HTTP CONNECT request */
  1246. BIO_printf(fbio, "\r\n");
  1247. for (;;) {
  1248. if (BIO_flush(fbio) != 0)
  1249. break;
  1250. /* potentially needs to be retried if BIO is non-blocking */
  1251. if (!BIO_should_retry(fbio))
  1252. break;
  1253. }
  1254. for (;;) {
  1255. /* will not actually wait if timeout == 0 */
  1256. rv = BIO_wait(fbio, max_time, 100 /* milliseconds */);
  1257. if (rv <= 0) {
  1258. BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog,
  1259. rv == 0 ? "timed out" : "failed waiting for data");
  1260. goto end;
  1261. }
  1262. /*-
  1263. * The first line is the HTTP response.
  1264. * According to RFC 7230, it is formatted exactly like this:
  1265. * HTTP/d.d ddd reason text\r\n
  1266. */
  1267. read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
  1268. /* the BIO may not block, so we must wait for the 1st line to come in */
  1269. if (read_len < (int)HTTP_LINE1_MINLEN)
  1270. continue;
  1271. /* Check for HTTP/1.x */
  1272. mbufp = mbuf;
  1273. if (!CHECK_AND_SKIP_PREFIX(mbufp, HTTP_PREFIX)) {
  1274. ERR_raise(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR);
  1275. BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n",
  1276. prog);
  1277. /* Wrong protocol, not even HTTP, so stop reading headers */
  1278. goto end;
  1279. }
  1280. if (!HAS_PREFIX(mbufp, HTTP_VERSION_PATT)) {
  1281. ERR_raise(ERR_LIB_HTTP, HTTP_R_RECEIVED_WRONG_HTTP_VERSION);
  1282. BIO_printf(bio_err,
  1283. "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
  1284. prog, (int)HTTP_VERSION_STR_LEN, mbufp);
  1285. goto end;
  1286. }
  1287. mbufp += HTTP_VERSION_STR_LEN;
  1288. /* RFC 7231 4.3.6: any 2xx status code is valid */
  1289. if (!HAS_PREFIX(mbufp, " 2")) {
  1290. if (ossl_isspace(*mbufp))
  1291. mbufp++;
  1292. /* chop any trailing whitespace */
  1293. while (read_len > 0 && ossl_isspace(mbuf[read_len - 1]))
  1294. read_len--;
  1295. mbuf[read_len] = '\0';
  1296. ERR_raise_data(ERR_LIB_HTTP, HTTP_R_CONNECT_FAILURE,
  1297. "reason=%s", mbufp);
  1298. BIO_printf(bio_err, "%s: HTTP CONNECT failed, reason=%s\n",
  1299. prog, mbufp);
  1300. goto end;
  1301. }
  1302. ret = 1;
  1303. break;
  1304. }
  1305. /* Read past all following headers */
  1306. do {
  1307. /*
  1308. * This does not necessarily catch the case when the full
  1309. * HTTP response came in in more than a single TCP message.
  1310. */
  1311. read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
  1312. } while (read_len > 2);
  1313. end:
  1314. if (fbio != NULL) {
  1315. (void)BIO_flush(fbio);
  1316. BIO_pop(fbio);
  1317. BIO_free(fbio);
  1318. }
  1319. OPENSSL_free(mbuf);
  1320. return ret;
  1321. #undef BUF_SIZE
  1322. }