http_client.c 45 KB

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