2
0

http_client.c 45 KB

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