http_client.c 51 KB

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