http_client.c 53 KB

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