http_client.c 45 KB

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