2
0

http_client.c 51 KB

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