http_client.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  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. static const char *explict_or_default_port(const char *hostserv, const char *port, int use_ssl)
  830. {
  831. if (port == NULL) {
  832. char *service = NULL;
  833. if (!BIO_parse_hostserv(hostserv, NULL, &service, BIO_PARSE_PRIO_HOST))
  834. return NULL;
  835. if (service == NULL) /* implicit port */
  836. port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
  837. OPENSSL_free(service);
  838. } /* otherwise take the explicitly given port */
  839. return port;
  840. }
  841. /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
  842. static BIO *http_new_bio(const char *server /* optionally includes ":port" */,
  843. const char *server_port /* explicit server port */,
  844. int use_ssl,
  845. const char *proxy /* optionally includes ":port" */,
  846. const char *proxy_port /* explicit proxy port */)
  847. {
  848. const char *host = server;
  849. const char *port = server_port;
  850. BIO *cbio;
  851. if (!ossl_assert(server != NULL))
  852. return NULL;
  853. if (proxy != NULL) {
  854. host = proxy;
  855. port = proxy_port;
  856. }
  857. port = explict_or_default_port(host, port, use_ssl);
  858. cbio = BIO_new_connect(host /* optionally includes ":port" */);
  859. if (cbio == NULL)
  860. goto end;
  861. if (port != NULL)
  862. (void)BIO_set_conn_port(cbio, port);
  863. end:
  864. return cbio;
  865. }
  866. #endif /* OPENSSL_NO_SOCK */
  867. /* Exchange request and response via HTTP on (non-)blocking BIO */
  868. BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx)
  869. {
  870. int rv;
  871. if (rctx == NULL) {
  872. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  873. return NULL;
  874. }
  875. for (;;) {
  876. rv = OSSL_HTTP_REQ_CTX_nbio(rctx);
  877. if (rv != -1)
  878. break;
  879. /* BIO_should_retry was true */
  880. /* will not actually wait if rctx->max_time == 0 */
  881. if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0)
  882. return NULL;
  883. }
  884. if (rv == 0) {
  885. if (rctx->redirection_url == NULL) { /* an error occurred */
  886. if (rctx->len_to_send > 0)
  887. ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_SENDING);
  888. else
  889. ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_RECEIVING);
  890. }
  891. return NULL;
  892. }
  893. return rctx->state == OHS_STREAM ? rctx->rbio : rctx->mem;
  894. }
  895. int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx)
  896. {
  897. return rctx != NULL && rctx->keep_alive != 0;
  898. }
  899. /* High-level HTTP API implementation */
  900. /* Initiate an HTTP session using bio, else use given server, proxy, etc. */
  901. OSSL_HTTP_REQ_CTX *OSSL_HTTP_open(const char *server, const char *port,
  902. const char *proxy, const char *no_proxy,
  903. int use_ssl, BIO *bio, BIO *rbio,
  904. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  905. int buf_size, int overall_timeout)
  906. {
  907. BIO *cbio; /* == bio if supplied, used as connection BIO if rbio is NULL */
  908. OSSL_HTTP_REQ_CTX *rctx = NULL;
  909. if (use_ssl && bio_update_fn == NULL) {
  910. ERR_raise(ERR_LIB_HTTP, HTTP_R_TLS_NOT_ENABLED);
  911. return NULL;
  912. }
  913. if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) {
  914. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
  915. return NULL;
  916. }
  917. if (bio != NULL) {
  918. cbio = bio;
  919. if (proxy != NULL || no_proxy != NULL) {
  920. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
  921. return NULL;
  922. }
  923. } else {
  924. #ifndef OPENSSL_NO_SOCK
  925. char *proxy_host = NULL, *proxy_port = NULL;
  926. if (server == NULL) {
  927. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  928. return NULL;
  929. }
  930. if (port != NULL && *port == '\0')
  931. port = NULL;
  932. proxy = OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl);
  933. if (proxy != NULL
  934. && !OSSL_HTTP_parse_url(proxy, NULL /* use_ssl */, NULL /* user */,
  935. &proxy_host, &proxy_port, NULL /* num */,
  936. NULL /* path */, NULL, NULL))
  937. return NULL;
  938. cbio = http_new_bio(server, port, use_ssl, proxy_host, proxy_port);
  939. OPENSSL_free(proxy_host);
  940. OPENSSL_free(proxy_port);
  941. if (cbio == NULL)
  942. return NULL;
  943. #else
  944. ERR_raise(ERR_LIB_HTTP, HTTP_R_SOCK_NOT_SUPPORTED);
  945. return NULL;
  946. #endif
  947. }
  948. (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
  949. if (rbio == NULL && BIO_do_connect_retry(cbio, overall_timeout, -1) <= 0) {
  950. if (bio == NULL) /* cbio was not provided by caller */
  951. BIO_free_all(cbio);
  952. goto end;
  953. }
  954. /* now overall_timeout is guaranteed to be >= 0 */
  955. /* adapt in order to fix callback design flaw, see #17088 */
  956. /* callback can be used to wrap or prepend TLS session */
  957. if (bio_update_fn != NULL) {
  958. BIO *orig_bio = cbio;
  959. cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl != 0);
  960. if (cbio == NULL) {
  961. if (bio == NULL) /* cbio was not provided by caller */
  962. BIO_free_all(orig_bio);
  963. goto end;
  964. }
  965. }
  966. rctx = http_req_ctx_new(bio == NULL, cbio, rbio != NULL ? rbio : cbio,
  967. bio_update_fn, arg, use_ssl, proxy, server, port,
  968. buf_size, overall_timeout);
  969. end:
  970. if (rctx != NULL)
  971. /* remove any spurious error queue entries by ssl_add_cert_chain() */
  972. (void)ERR_pop_to_mark();
  973. else
  974. (void)ERR_clear_last_mark();
  975. return rctx;
  976. }
  977. int OSSL_HTTP_set1_request(OSSL_HTTP_REQ_CTX *rctx, const char *path,
  978. const STACK_OF(CONF_VALUE) *headers,
  979. const char *content_type, BIO *req,
  980. const char *expected_content_type, int expect_asn1,
  981. size_t max_resp_len, int timeout, int keep_alive)
  982. {
  983. int use_http_proxy;
  984. if (rctx == NULL) {
  985. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  986. return 0;
  987. }
  988. use_http_proxy = rctx->proxy != NULL && !rctx->use_ssl;
  989. if (use_http_proxy && rctx->server == NULL) {
  990. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
  991. return 0;
  992. }
  993. rctx->max_resp_len = max_resp_len; /* allows for 0: indefinite */
  994. return OSSL_HTTP_REQ_CTX_set_request_line(rctx, req != NULL,
  995. use_http_proxy ? rctx->server
  996. : NULL, rctx->port, path)
  997. && add1_headers(rctx, headers, rctx->server)
  998. && OSSL_HTTP_REQ_CTX_set_expected(rctx, expected_content_type,
  999. expect_asn1, timeout, keep_alive)
  1000. && set1_content(rctx, content_type, req);
  1001. }
  1002. /*-
  1003. * Exchange single HTTP request and response according to rctx.
  1004. * If rctx->method_POST then use POST, else use GET and ignore content_type.
  1005. * The redirection_url output (freed by caller) parameter is used only for GET.
  1006. */
  1007. BIO *OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX *rctx, char **redirection_url)
  1008. {
  1009. BIO *resp;
  1010. if (rctx == NULL) {
  1011. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  1012. return NULL;
  1013. }
  1014. if (redirection_url != NULL)
  1015. *redirection_url = NULL; /* do this beforehand to prevent dbl free */
  1016. resp = OSSL_HTTP_REQ_CTX_exchange(rctx);
  1017. if (resp == NULL) {
  1018. if (rctx->redirection_url != NULL) {
  1019. if (redirection_url == NULL)
  1020. ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
  1021. else
  1022. /* may be NULL if out of memory: */
  1023. *redirection_url = OPENSSL_strdup(rctx->redirection_url);
  1024. } else {
  1025. char buf[200];
  1026. unsigned long err = ERR_peek_error();
  1027. int lib = ERR_GET_LIB(err);
  1028. int reason = ERR_GET_REASON(err);
  1029. if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP
  1030. || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT)
  1031. || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR)
  1032. #ifndef OPENSSL_NO_CMP
  1033. || (lib == ERR_LIB_CMP
  1034. && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
  1035. #endif
  1036. ) {
  1037. if (rctx->server != NULL) {
  1038. BIO_snprintf(buf, sizeof(buf), "server=http%s://%s%s%s",
  1039. rctx->use_ssl ? "s" : "", rctx->server,
  1040. rctx->port != NULL ? ":" : "",
  1041. rctx->port != NULL ? rctx->port : "");
  1042. ERR_add_error_data(1, buf);
  1043. }
  1044. if (rctx->proxy != NULL)
  1045. ERR_add_error_data(2, " proxy=", rctx->proxy);
  1046. if (err == 0) {
  1047. BIO_snprintf(buf, sizeof(buf), " peer has disconnected%s",
  1048. rctx->use_ssl ? " violating the protocol" :
  1049. ", likely because it requires the use of TLS");
  1050. ERR_add_error_data(1, buf);
  1051. }
  1052. }
  1053. }
  1054. }
  1055. if (resp != NULL && !BIO_up_ref(resp))
  1056. resp = NULL;
  1057. return resp;
  1058. }
  1059. static int redirection_ok(int n_redir, const char *old_url, const char *new_url)
  1060. {
  1061. if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) {
  1062. ERR_raise(ERR_LIB_HTTP, HTTP_R_TOO_MANY_REDIRECTIONS);
  1063. return 0;
  1064. }
  1065. if (*new_url == '/') /* redirection to same server => same protocol */
  1066. return 1;
  1067. if (HAS_PREFIX(old_url, OSSL_HTTPS_NAME":") &&
  1068. !HAS_PREFIX(new_url, OSSL_HTTPS_NAME":")) {
  1069. ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP);
  1070. return 0;
  1071. }
  1072. return 1;
  1073. }
  1074. /* Get data via HTTP from server at given URL, potentially with redirection */
  1075. BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy,
  1076. BIO *bio, BIO *rbio,
  1077. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  1078. int buf_size, const STACK_OF(CONF_VALUE) *headers,
  1079. const char *expected_ct, int expect_asn1,
  1080. size_t max_resp_len, int timeout)
  1081. {
  1082. char *current_url;
  1083. int n_redirs = 0;
  1084. char *host;
  1085. char *port;
  1086. char *path;
  1087. int use_ssl;
  1088. BIO *resp = NULL;
  1089. time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
  1090. if (url == NULL) {
  1091. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  1092. return NULL;
  1093. }
  1094. if ((current_url = OPENSSL_strdup(url)) == NULL)
  1095. return NULL;
  1096. for (;;) {
  1097. OSSL_HTTP_REQ_CTX *rctx;
  1098. char *redirection_url;
  1099. if (!OSSL_HTTP_parse_url(current_url, &use_ssl, NULL /* user */, &host,
  1100. &port, NULL /* port_num */, &path, NULL, NULL))
  1101. break;
  1102. rctx = OSSL_HTTP_open(host, port, proxy, no_proxy,
  1103. use_ssl, bio, rbio, bio_update_fn, arg,
  1104. buf_size, timeout);
  1105. new_rpath:
  1106. redirection_url = NULL;
  1107. if (rctx != NULL) {
  1108. if (!OSSL_HTTP_set1_request(rctx, path, headers,
  1109. NULL /* content_type */,
  1110. NULL /* req */,
  1111. expected_ct, expect_asn1, max_resp_len,
  1112. -1 /* use same max time (timeout) */,
  1113. 0 /* no keep_alive */)) {
  1114. OSSL_HTTP_REQ_CTX_free(rctx);
  1115. rctx = NULL;
  1116. } else {
  1117. resp = OSSL_HTTP_exchange(rctx, &redirection_url);
  1118. }
  1119. }
  1120. OPENSSL_free(path);
  1121. if (resp == NULL && redirection_url != NULL) {
  1122. if (redirection_ok(++n_redirs, current_url, redirection_url)
  1123. && may_still_retry(max_time, &timeout)) {
  1124. (void)BIO_reset(bio);
  1125. OPENSSL_free(current_url);
  1126. current_url = redirection_url;
  1127. if (*redirection_url == '/') { /* redirection to same server */
  1128. path = OPENSSL_strdup(redirection_url);
  1129. if (path == NULL) {
  1130. OPENSSL_free(host);
  1131. OPENSSL_free(port);
  1132. (void)OSSL_HTTP_close(rctx, 1);
  1133. BIO_free(resp);
  1134. OPENSSL_free(current_url);
  1135. return NULL;
  1136. }
  1137. goto new_rpath;
  1138. }
  1139. OPENSSL_free(host);
  1140. OPENSSL_free(port);
  1141. (void)OSSL_HTTP_close(rctx, 1);
  1142. continue;
  1143. }
  1144. /* if redirection not allowed, ignore it */
  1145. OPENSSL_free(redirection_url);
  1146. }
  1147. OPENSSL_free(host);
  1148. OPENSSL_free(port);
  1149. if (!OSSL_HTTP_close(rctx, resp != NULL)) {
  1150. BIO_free(resp);
  1151. resp = NULL;
  1152. }
  1153. break;
  1154. }
  1155. OPENSSL_free(current_url);
  1156. return resp;
  1157. }
  1158. /* Exchange request and response over a connection managed via |prctx| */
  1159. BIO *OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX **prctx,
  1160. const char *server, const char *port,
  1161. const char *path, int use_ssl,
  1162. const char *proxy, const char *no_proxy,
  1163. BIO *bio, BIO *rbio,
  1164. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  1165. int buf_size, const STACK_OF(CONF_VALUE) *headers,
  1166. const char *content_type, BIO *req,
  1167. const char *expected_ct, int expect_asn1,
  1168. size_t max_resp_len, int timeout, int keep_alive)
  1169. {
  1170. OSSL_HTTP_REQ_CTX *rctx = prctx == NULL ? NULL : *prctx;
  1171. BIO *resp = NULL;
  1172. if (rctx == NULL) {
  1173. rctx = OSSL_HTTP_open(server, port, proxy, no_proxy,
  1174. use_ssl, bio, rbio, bio_update_fn, arg,
  1175. buf_size, timeout);
  1176. timeout = -1; /* Already set during opening the connection */
  1177. }
  1178. if (rctx != NULL) {
  1179. if (OSSL_HTTP_set1_request(rctx, path, headers, content_type, req,
  1180. expected_ct, expect_asn1,
  1181. max_resp_len, timeout, keep_alive))
  1182. resp = OSSL_HTTP_exchange(rctx, NULL);
  1183. if (resp == NULL || !OSSL_HTTP_is_alive(rctx)) {
  1184. if (!OSSL_HTTP_close(rctx, resp != NULL)) {
  1185. BIO_free(resp);
  1186. resp = NULL;
  1187. }
  1188. rctx = NULL;
  1189. }
  1190. }
  1191. if (prctx != NULL)
  1192. *prctx = rctx;
  1193. return resp;
  1194. }
  1195. int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX *rctx, int ok)
  1196. {
  1197. BIO *wbio;
  1198. int ret = 1;
  1199. /* callback can be used to finish TLS session and free its BIO */
  1200. if (rctx != NULL && rctx->upd_fn != NULL) {
  1201. wbio = (*rctx->upd_fn)(rctx->wbio, rctx->upd_arg,
  1202. 0 /* disconnect */, ok);
  1203. ret = wbio != NULL;
  1204. if (ret)
  1205. rctx->wbio = wbio;
  1206. }
  1207. OSSL_HTTP_REQ_CTX_free(rctx);
  1208. return ret;
  1209. }
  1210. /* BASE64 encoder used for encoding basic proxy authentication credentials */
  1211. static char *base64encode(const void *buf, size_t len)
  1212. {
  1213. int i;
  1214. size_t outl;
  1215. char *out;
  1216. /* Calculate size of encoded data */
  1217. outl = (len / 3);
  1218. if (len % 3 > 0)
  1219. outl++;
  1220. outl <<= 2;
  1221. out = OPENSSL_malloc(outl + 1);
  1222. if (out == NULL)
  1223. return 0;
  1224. i = EVP_EncodeBlock((unsigned char *)out, buf, len);
  1225. if (!ossl_assert(0 <= i && (size_t)i <= outl)) {
  1226. OPENSSL_free(out);
  1227. return NULL;
  1228. }
  1229. return out;
  1230. }
  1231. /*
  1232. * Promote the given connection BIO using the CONNECT method for a TLS proxy.
  1233. * This is typically called by an app, so bio_err and prog are used unless NULL
  1234. * to print additional diagnostic information in a user-oriented way.
  1235. */
  1236. int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
  1237. const char *proxyuser, const char *proxypass,
  1238. int timeout, BIO *bio_err, const char *prog)
  1239. {
  1240. #undef BUF_SIZE
  1241. #define BUF_SIZE (8 * 1024)
  1242. char *mbuf = OPENSSL_malloc(BUF_SIZE);
  1243. char *mbufp;
  1244. int read_len = 0;
  1245. int ret = 0;
  1246. BIO *fbio = BIO_new(BIO_f_buffer());
  1247. int rv;
  1248. time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
  1249. if (bio == NULL || server == NULL
  1250. || (bio_err != NULL && prog == NULL)) {
  1251. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  1252. goto end;
  1253. }
  1254. if (port == NULL || *port == '\0')
  1255. port = OSSL_HTTPS_PORT;
  1256. if (mbuf == NULL || fbio == NULL) {
  1257. BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog);
  1258. goto end;
  1259. }
  1260. BIO_push(fbio, bio);
  1261. BIO_printf(fbio, "CONNECT %s:%s "HTTP_1_0"\r\n", server, port);
  1262. /*
  1263. * Workaround for broken proxies which would otherwise close
  1264. * the connection when entering tunnel mode (e.g., Squid 2.6)
  1265. */
  1266. BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n");
  1267. /* Support for basic (base64) proxy authentication */
  1268. if (proxyuser != NULL) {
  1269. size_t len = strlen(proxyuser) + 1;
  1270. char *proxyauth, *proxyauthenc = NULL;
  1271. if (proxypass != NULL)
  1272. len += strlen(proxypass);
  1273. proxyauth = OPENSSL_malloc(len + 1);
  1274. if (proxyauth == NULL)
  1275. goto end;
  1276. if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser,
  1277. proxypass != NULL ? proxypass : "") != (int)len)
  1278. goto proxy_end;
  1279. proxyauthenc = base64encode(proxyauth, len);
  1280. if (proxyauthenc != NULL) {
  1281. BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc);
  1282. OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc));
  1283. }
  1284. proxy_end:
  1285. OPENSSL_clear_free(proxyauth, len);
  1286. if (proxyauthenc == NULL)
  1287. goto end;
  1288. }
  1289. /* Terminate the HTTP CONNECT request */
  1290. BIO_printf(fbio, "\r\n");
  1291. for (;;) {
  1292. if (BIO_flush(fbio) != 0)
  1293. break;
  1294. /* potentially needs to be retried if BIO is non-blocking */
  1295. if (!BIO_should_retry(fbio))
  1296. break;
  1297. }
  1298. for (;;) {
  1299. /* will not actually wait if timeout == 0 */
  1300. rv = BIO_wait(fbio, max_time, 100 /* milliseconds */);
  1301. if (rv <= 0) {
  1302. BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog,
  1303. rv == 0 ? "timed out" : "failed waiting for data");
  1304. goto end;
  1305. }
  1306. /*-
  1307. * The first line is the HTTP response.
  1308. * According to RFC 7230, it is formatted exactly like this:
  1309. * HTTP/d.d ddd reason text\r\n
  1310. */
  1311. read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
  1312. /* the BIO may not block, so we must wait for the 1st line to come in */
  1313. if (read_len < (int)HTTP_LINE1_MINLEN)
  1314. continue;
  1315. /* Check for HTTP/1.x */
  1316. mbufp = mbuf;
  1317. if (!CHECK_AND_SKIP_PREFIX(mbufp, HTTP_PREFIX)) {
  1318. ERR_raise(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR);
  1319. BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n",
  1320. prog);
  1321. /* Wrong protocol, not even HTTP, so stop reading headers */
  1322. goto end;
  1323. }
  1324. if (!HAS_PREFIX(mbufp, HTTP_VERSION_PATT)) {
  1325. ERR_raise(ERR_LIB_HTTP, HTTP_R_RECEIVED_WRONG_HTTP_VERSION);
  1326. BIO_printf(bio_err,
  1327. "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
  1328. prog, (int)HTTP_VERSION_STR_LEN, mbufp);
  1329. goto end;
  1330. }
  1331. mbufp += HTTP_VERSION_STR_LEN;
  1332. /* RFC 7231 4.3.6: any 2xx status code is valid */
  1333. if (!HAS_PREFIX(mbufp, " 2")) {
  1334. if (ossl_isspace(*mbufp))
  1335. mbufp++;
  1336. /* chop any trailing whitespace */
  1337. while (read_len > 0 && ossl_isspace(mbuf[read_len - 1]))
  1338. read_len--;
  1339. mbuf[read_len] = '\0';
  1340. ERR_raise_data(ERR_LIB_HTTP, HTTP_R_CONNECT_FAILURE,
  1341. "reason=%s", mbufp);
  1342. BIO_printf(bio_err, "%s: HTTP CONNECT failed, reason=%s\n",
  1343. prog, mbufp);
  1344. goto end;
  1345. }
  1346. ret = 1;
  1347. break;
  1348. }
  1349. /* Read past all following headers */
  1350. do {
  1351. /*
  1352. * This does not necessarily catch the case when the full
  1353. * HTTP response came in more than a single TCP message.
  1354. */
  1355. read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
  1356. } while (read_len > 2);
  1357. end:
  1358. if (fbio != NULL) {
  1359. (void)BIO_flush(fbio);
  1360. BIO_pop(fbio);
  1361. BIO_free(fbio);
  1362. }
  1363. OPENSSL_free(mbuf);
  1364. return ret;
  1365. #undef BUF_SIZE
  1366. }