http_client.c 51 KB

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