http_client.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  1. /*
  2. * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright Siemens AG 2018-2020
  4. *
  5. * Licensed under the Apache License 2.0 (the "License"). You may not use
  6. * this file except in compliance with the License. You can obtain a copy
  7. * in the file LICENSE in the source distribution or at
  8. * https://www.openssl.org/source/license.html
  9. */
  10. #include "e_os.h"
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include "crypto/ctype.h"
  14. #include <string.h>
  15. #include <openssl/asn1.h>
  16. #include <openssl/evp.h>
  17. #include <openssl/err.h>
  18. #include <openssl/httperr.h>
  19. #include <openssl/cmperr.h>
  20. #include <openssl/buffer.h>
  21. #include <openssl/http.h>
  22. #include "internal/sockets.h"
  23. #include "internal/cryptlib.h" /* for ossl_assert() */
  24. #include "http_local.h"
  25. DEFINE_STACK_OF(CONF_VALUE)
  26. #define HTTP_PREFIX "HTTP/"
  27. #define HTTP_VERSION_PATT "1." /* allow 1.x */
  28. #define HTTP_VERSION_STR_LEN 3
  29. #define HTTP_LINE1_MINLEN ((int)strlen(HTTP_PREFIX HTTP_VERSION_PATT "x 200\n"))
  30. #define HTTP_VERSION_MAX_REDIRECTIONS 50
  31. #define HTTP_STATUS_CODE_OK 200
  32. #define HTTP_STATUS_CODE_MOVED_PERMANENTLY 301
  33. #define HTTP_STATUS_CODE_FOUND 302
  34. /* Stateful HTTP request code, supporting blocking and non-blocking I/O */
  35. /* Opaque HTTP request status structure */
  36. struct ossl_http_req_ctx_st {
  37. int state; /* Current I/O state */
  38. unsigned char *iobuf; /* Line buffer */
  39. int iobuflen; /* Line buffer length */
  40. BIO *wbio; /* BIO to send request to */
  41. BIO *rbio; /* BIO to read response from */
  42. BIO *mem; /* Memory BIO response is built into */
  43. int method_GET; /* HTTP method "GET" or "POST" */
  44. const char *expected_ct; /* expected Content-Type, or NULL */
  45. int expect_asn1; /* response must be ASN.1-encoded */
  46. unsigned long resp_len; /* length of response */
  47. unsigned long max_resp_len; /* Maximum length of response */
  48. time_t max_time; /* Maximum end time of the transfer, or 0 */
  49. char *redirection_url; /* Location given with HTTP status 301/302 */
  50. };
  51. #define HTTP_DEFAULT_MAX_LINE_LENGTH (4 * 1024)
  52. #define HTTP_DEFAULT_MAX_RESP_LEN (100 * 1024)
  53. /* HTTP states */
  54. #define OHS_NOREAD 0x1000 /* If set no reading should be performed */
  55. #define OHS_ERROR (0 | OHS_NOREAD) /* Error condition */
  56. #define OHS_FIRSTLINE 1 /* First line being read */
  57. #define OHS_REDIRECT 0xa /* Looking for redirection location */
  58. #define OHS_HEADERS 2 /* MIME headers being read */
  59. #define OHS_ASN1_HEADER 3 /* HTTP initial header (tag+length) being read */
  60. #define OHS_CONTENT 4 /* HTTP content octets being read */
  61. #define OHS_WRITE_INIT (5 | OHS_NOREAD) /* 1st call: ready to start I/O */
  62. #define OHS_WRITE (6 | OHS_NOREAD) /* Request being sent */
  63. #define OHS_FLUSH (7 | OHS_NOREAD) /* Request being flushed */
  64. #define OHS_DONE (8 | OHS_NOREAD) /* Completed */
  65. #define OHS_HTTP_HEADER (9 | OHS_NOREAD) /* Headers set, w/o final \r\n */
  66. OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio,
  67. int method_GET, int maxline,
  68. unsigned long max_resp_len,
  69. int timeout,
  70. const char *expected_content_type,
  71. int expect_asn1)
  72. {
  73. OSSL_HTTP_REQ_CTX *rctx;
  74. if (wbio == NULL || rbio == NULL) {
  75. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  76. return NULL;
  77. }
  78. if ((rctx = OPENSSL_zalloc(sizeof(*rctx))) == NULL)
  79. return NULL;
  80. rctx->state = OHS_ERROR;
  81. rctx->iobuflen = maxline > 0 ? maxline : HTTP_DEFAULT_MAX_LINE_LENGTH;
  82. rctx->iobuf = OPENSSL_malloc(rctx->iobuflen);
  83. rctx->wbio = wbio;
  84. rctx->rbio = rbio;
  85. rctx->mem = BIO_new(BIO_s_mem());
  86. if (rctx->iobuf == NULL || rctx->mem == NULL) {
  87. OSSL_HTTP_REQ_CTX_free(rctx);
  88. return NULL;
  89. }
  90. rctx->method_GET = method_GET;
  91. rctx->expected_ct = expected_content_type;
  92. rctx->expect_asn1 = expect_asn1;
  93. rctx->resp_len = 0;
  94. OSSL_HTTP_REQ_CTX_set_max_response_length(rctx, max_resp_len);
  95. rctx->max_time = timeout > 0 ? time(NULL) + timeout : 0;
  96. return rctx;
  97. }
  98. void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx)
  99. {
  100. if (rctx == NULL)
  101. return;
  102. BIO_free(rctx->mem); /* this may indirectly call ERR_clear_error() */
  103. OPENSSL_free(rctx->iobuf);
  104. OPENSSL_free(rctx);
  105. }
  106. BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(OSSL_HTTP_REQ_CTX *rctx)
  107. {
  108. if (rctx == NULL) {
  109. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  110. return NULL;
  111. }
  112. return rctx->mem;
  113. }
  114. void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx,
  115. unsigned long len)
  116. {
  117. if (rctx == NULL) {
  118. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  119. return;
  120. }
  121. rctx->max_resp_len = len != 0 ? len : HTTP_DEFAULT_MAX_RESP_LEN;
  122. }
  123. /*
  124. * Create HTTP header using given op and path (or "/" in case path is NULL).
  125. * Server name (and port) must be given if and only if plain HTTP proxy is used.
  126. */
  127. int OSSL_HTTP_REQ_CTX_header(OSSL_HTTP_REQ_CTX *rctx, const char *server,
  128. const char *port, const char *path)
  129. {
  130. if (rctx == NULL) {
  131. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  132. return 0;
  133. }
  134. if (BIO_printf(rctx->mem, "%s ", rctx->method_GET ? "GET" : "POST") <= 0)
  135. return 0;
  136. if (server != NULL) { /* HTTP (but not HTTPS) proxy is used */
  137. /*
  138. * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only
  139. * allowed when using a proxy
  140. */
  141. if (BIO_printf(rctx->mem, OSSL_HTTP_PREFIX"%s", server) <= 0)
  142. return 0;
  143. if (port != NULL && BIO_printf(rctx->mem, ":%s", port) <= 0)
  144. return 0;
  145. }
  146. /* Make sure path includes a forward slash */
  147. if (path == NULL)
  148. path = "/";
  149. if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0)
  150. return 0;
  151. if (BIO_printf(rctx->mem, "%s "HTTP_PREFIX"1.0\r\n", path) <= 0)
  152. return 0;
  153. rctx->state = OHS_HTTP_HEADER;
  154. return 1;
  155. }
  156. int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx,
  157. const char *name, const char *value)
  158. {
  159. if (rctx == NULL || name == NULL) {
  160. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  161. return 0;
  162. }
  163. if (BIO_puts(rctx->mem, name) <= 0)
  164. return 0;
  165. if (value != NULL) {
  166. if (BIO_write(rctx->mem, ": ", 2) != 2)
  167. return 0;
  168. if (BIO_puts(rctx->mem, value) <= 0)
  169. return 0;
  170. }
  171. if (BIO_write(rctx->mem, "\r\n", 2) != 2)
  172. return 0;
  173. rctx->state = OHS_HTTP_HEADER;
  174. return 1;
  175. }
  176. static int OSSL_HTTP_REQ_CTX_content(OSSL_HTTP_REQ_CTX *rctx,
  177. const char *content_type, BIO *req_mem)
  178. {
  179. const unsigned char *req;
  180. long req_len;
  181. if (rctx == NULL || req_mem == NULL) {
  182. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  183. return 0;
  184. }
  185. if (content_type != NULL
  186. && BIO_printf(rctx->mem, "Content-Type: %s\r\n", content_type) <= 0)
  187. return 0;
  188. if ((req_len = BIO_get_mem_data(req_mem, &req)) <= 0)
  189. return 0;
  190. rctx->state = OHS_WRITE_INIT;
  191. return BIO_printf(rctx->mem, "Content-Length: %ld\r\n\r\n", req_len) > 0
  192. && BIO_write(rctx->mem, req, req_len) == (int)req_len;
  193. }
  194. BIO *HTTP_asn1_item2bio(const ASN1_ITEM *it, const ASN1_VALUE *val)
  195. {
  196. BIO *res;
  197. if (it == NULL || val == NULL) {
  198. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  199. return NULL;
  200. }
  201. if ((res = BIO_new(BIO_s_mem())) == NULL)
  202. return NULL;
  203. if (ASN1_item_i2d_bio(it, res, val) <= 0) {
  204. BIO_free(res);
  205. res = NULL;
  206. }
  207. return res;
  208. }
  209. int OSSL_HTTP_REQ_CTX_i2d(OSSL_HTTP_REQ_CTX *rctx, const char *content_type,
  210. const ASN1_ITEM *it, ASN1_VALUE *req)
  211. {
  212. BIO *mem;
  213. int res;
  214. if (rctx == NULL || it == NULL || req == NULL) {
  215. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  216. return 0;
  217. }
  218. res = (mem = HTTP_asn1_item2bio(it, req)) != NULL
  219. && OSSL_HTTP_REQ_CTX_content(rctx, content_type, mem);
  220. BIO_free(mem);
  221. return res;
  222. }
  223. static int OSSL_HTTP_REQ_CTX_add1_headers(OSSL_HTTP_REQ_CTX *rctx,
  224. const STACK_OF(CONF_VALUE) *headers,
  225. const char *host)
  226. {
  227. int i;
  228. int add_host = 1;
  229. CONF_VALUE *hdr;
  230. for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
  231. hdr = sk_CONF_VALUE_value(headers, i);
  232. if (add_host && strcasecmp("host", hdr->name) == 0)
  233. add_host = 0;
  234. if (!OSSL_HTTP_REQ_CTX_add1_header(rctx, hdr->name, hdr->value))
  235. return 0;
  236. }
  237. if (add_host && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Host", host))
  238. return 0;
  239. return 1;
  240. }
  241. /*-
  242. * Create OSSL_HTTP_REQ_CTX structure using the values provided.
  243. * If !use_http_proxy then the 'server' and 'port' parameters are ignored.
  244. * If req_mem == NULL then use GET and ignore content_type, else POST.
  245. */
  246. OSSL_HTTP_REQ_CTX *HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int use_http_proxy,
  247. const char *server, const char *port,
  248. const char *path,
  249. const STACK_OF(CONF_VALUE) *headers,
  250. const char *content_type, BIO *req_mem,
  251. int maxline, unsigned long max_resp_len,
  252. int timeout,
  253. const char *expected_content_type,
  254. int expect_asn1)
  255. {
  256. OSSL_HTTP_REQ_CTX *rctx;
  257. if (use_http_proxy && (server == NULL || port == NULL)) {
  258. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  259. return NULL;
  260. }
  261. /* remaining parameters are checked indirectly by the functions called */
  262. if ((rctx = OSSL_HTTP_REQ_CTX_new(wbio, rbio, req_mem == NULL, maxline,
  263. max_resp_len, timeout,
  264. expected_content_type, expect_asn1))
  265. == NULL)
  266. return NULL;
  267. if (OSSL_HTTP_REQ_CTX_header(rctx, use_http_proxy ? server : NULL,
  268. port, path)
  269. && OSSL_HTTP_REQ_CTX_add1_headers(rctx, headers, server)
  270. && (req_mem == NULL
  271. || OSSL_HTTP_REQ_CTX_content(rctx, content_type, req_mem)))
  272. return rctx;
  273. OSSL_HTTP_REQ_CTX_free(rctx);
  274. return NULL;
  275. }
  276. /*
  277. * Parse first HTTP response line. This should be like this: "HTTP/1.0 200 OK".
  278. * We need to obtain the numeric code and (optional) informational message.
  279. */
  280. static int parse_http_line1(char *line)
  281. {
  282. int retcode;
  283. char *code, *reason, *end;
  284. /* Skip to first whitespace (past protocol info) */
  285. for (code = line; *code != '\0' && !ossl_isspace(*code); code++)
  286. continue;
  287. if (*code == '\0') {
  288. HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
  289. return 0;
  290. }
  291. /* Skip past whitespace to start of response code */
  292. while (*code != '\0' && ossl_isspace(*code))
  293. code++;
  294. if (*code == '\0') {
  295. HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
  296. return 0;
  297. }
  298. /* Find end of response code: first whitespace after start of code */
  299. for (reason = code; *reason != '\0' && !ossl_isspace(*reason); reason++)
  300. continue;
  301. if (*reason == '\0') {
  302. HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
  303. return 0;
  304. }
  305. /* Set end of response code and start of message */
  306. *reason++ = '\0';
  307. /* Attempt to parse numeric code */
  308. retcode = strtoul(code, &end, 10);
  309. if (*end != '\0')
  310. return 0;
  311. /* Skip over any leading whitespace in message */
  312. while (*reason != '\0' && ossl_isspace(*reason))
  313. reason++;
  314. if (*reason != '\0') {
  315. /*
  316. * Finally zap any trailing whitespace in message (include CRLF)
  317. */
  318. /* chop any trailing whitespace from reason */
  319. /* We know reason has a non-whitespace character so this is OK */
  320. for (end = reason + strlen(reason) - 1; ossl_isspace(*end); end--)
  321. *end = '\0';
  322. }
  323. switch (retcode) {
  324. case HTTP_STATUS_CODE_OK:
  325. case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
  326. case HTTP_STATUS_CODE_FOUND:
  327. return retcode;
  328. default:
  329. if (retcode < 400)
  330. HTTPerr(0, HTTP_R_STATUS_CODE_UNSUPPORTED);
  331. else
  332. HTTPerr(0, HTTP_R_RECEIVED_ERROR);
  333. if (*reason == '\0')
  334. ERR_add_error_data(2, "Code=", code);
  335. else
  336. ERR_add_error_data(4, "Code=", code, ",Reason=", reason);
  337. return 0;
  338. }
  339. }
  340. static int check_set_resp_len(OSSL_HTTP_REQ_CTX *rctx, unsigned long len)
  341. {
  342. const char *tag = NULL;
  343. unsigned long val = 0;
  344. if (len > rctx->max_resp_len) {
  345. HTTPerr(0, HTTP_R_MAX_RESP_LEN_EXCEEDED);
  346. tag = ",max=";
  347. val = rctx->max_resp_len;
  348. }
  349. if (rctx->resp_len != 0 && rctx->resp_len != len) {
  350. HTTPerr(0, HTTP_R_INCONSISTENT_CONTENT_LENGTH);
  351. tag = ",before=";
  352. val = rctx->resp_len;
  353. }
  354. if (tag != NULL) {
  355. char len_str[32];
  356. char str[32];
  357. BIO_snprintf(len_str, sizeof(len_str), "%lu", len);
  358. BIO_snprintf(str, sizeof(str), "%lu", val);
  359. ERR_add_error_data(4, "length=", len_str, tag, str);
  360. return 0;
  361. }
  362. rctx->resp_len = len;
  363. return 1;
  364. }
  365. /*
  366. * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx.
  367. * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry.
  368. */
  369. int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx)
  370. {
  371. int i;
  372. long n, n_to_send = 0;
  373. unsigned long resp_len;
  374. const unsigned char *p;
  375. char *key, *value, *line_end = NULL;
  376. if (rctx == NULL) {
  377. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  378. return 0;
  379. }
  380. rctx->redirection_url = NULL;
  381. next_io:
  382. if ((rctx->state & OHS_NOREAD) == 0) {
  383. n = BIO_read(rctx->rbio, rctx->iobuf, rctx->iobuflen);
  384. if (n <= 0) {
  385. if (BIO_should_retry(rctx->rbio))
  386. return -1;
  387. return 0;
  388. }
  389. /* Write data to memory BIO */
  390. if (BIO_write(rctx->mem, rctx->iobuf, n) != n)
  391. return 0;
  392. }
  393. switch (rctx->state) {
  394. case OHS_HTTP_HEADER:
  395. /* Last operation was adding headers: need a final \r\n */
  396. if (BIO_write(rctx->mem, "\r\n", 2) != 2) {
  397. rctx->state = OHS_ERROR;
  398. return 0;
  399. }
  400. rctx->state = OHS_WRITE_INIT;
  401. /* fall thru */
  402. case OHS_WRITE_INIT:
  403. n_to_send = BIO_get_mem_data(rctx->mem, NULL);
  404. rctx->state = OHS_WRITE;
  405. /* fall thru */
  406. case OHS_WRITE:
  407. n = BIO_get_mem_data(rctx->mem, &p);
  408. i = BIO_write(rctx->wbio, p + (n - n_to_send), n_to_send);
  409. if (i <= 0) {
  410. if (BIO_should_retry(rctx->wbio))
  411. return -1;
  412. rctx->state = OHS_ERROR;
  413. return 0;
  414. }
  415. n_to_send -= i;
  416. if (n_to_send > 0)
  417. goto next_io;
  418. rctx->state = OHS_FLUSH;
  419. (void)BIO_reset(rctx->mem);
  420. /* fall thru */
  421. case OHS_FLUSH:
  422. i = BIO_flush(rctx->wbio);
  423. if (i > 0) {
  424. rctx->state = OHS_FIRSTLINE;
  425. goto next_io;
  426. }
  427. if (BIO_should_retry(rctx->wbio))
  428. return -1;
  429. rctx->state = OHS_ERROR;
  430. return 0;
  431. case OHS_ERROR:
  432. return 0;
  433. case OHS_FIRSTLINE:
  434. case OHS_HEADERS:
  435. case OHS_REDIRECT:
  436. /* Attempt to read a line in */
  437. next_line:
  438. /*
  439. * Due to strange memory BIO behavior with BIO_gets we have to check
  440. * there's a complete line in there before calling BIO_gets or we'll
  441. * just get a partial read.
  442. */
  443. n = BIO_get_mem_data(rctx->mem, &p);
  444. if (n <= 0 || memchr(p, '\n', n) == 0) {
  445. if (n >= rctx->iobuflen) {
  446. rctx->state = OHS_ERROR;
  447. return 0;
  448. }
  449. goto next_io;
  450. }
  451. n = BIO_gets(rctx->mem, (char *)rctx->iobuf, rctx->iobuflen);
  452. if (n <= 0) {
  453. if (BIO_should_retry(rctx->mem))
  454. goto next_io;
  455. rctx->state = OHS_ERROR;
  456. return 0;
  457. }
  458. /* Don't allow excessive lines */
  459. if (n == rctx->iobuflen) {
  460. HTTPerr(0, HTTP_R_RESPONSE_LINE_TOO_LONG);
  461. rctx->state = OHS_ERROR;
  462. return 0;
  463. }
  464. /* First line */
  465. if (rctx->state == OHS_FIRSTLINE) {
  466. switch (parse_http_line1((char *)rctx->iobuf)) {
  467. case HTTP_STATUS_CODE_OK:
  468. rctx->state = OHS_HEADERS;
  469. goto next_line;
  470. case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
  471. case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */
  472. if (rctx->method_GET) {
  473. rctx->state = OHS_REDIRECT;
  474. goto next_line;
  475. }
  476. HTTPerr(0, HTTP_R_REDIRECTION_NOT_ENABLED);
  477. /* redirection is not supported/recommended for POST */
  478. /* fall through */
  479. default:
  480. rctx->state = OHS_ERROR;
  481. return 0;
  482. }
  483. }
  484. key = (char *)rctx->iobuf;
  485. value = strchr(key, ':');
  486. if (value != NULL) {
  487. *(value++) = '\0';
  488. while (ossl_isspace(*value))
  489. value++;
  490. line_end = strchr(value, '\r');
  491. if (line_end == NULL)
  492. line_end = strchr(value, '\n');
  493. if (line_end != NULL)
  494. *line_end = '\0';
  495. }
  496. if (value != NULL && line_end != NULL) {
  497. if (rctx->state == OHS_REDIRECT
  498. && strcasecmp(key, "Location") == 0) {
  499. rctx->redirection_url = value;
  500. return 0;
  501. }
  502. if (rctx->expected_ct != NULL
  503. && strcasecmp(key, "Content-Type") == 0) {
  504. if (strcasecmp(rctx->expected_ct, value) != 0) {
  505. HTTPerr(0, HTTP_R_UNEXPECTED_CONTENT_TYPE);
  506. ERR_add_error_data(4, "expected=", rctx->expected_ct,
  507. ",actual=", value);
  508. return 0;
  509. }
  510. rctx->expected_ct = NULL; /* content-type has been found */
  511. }
  512. if (strcasecmp(key, "Content-Length") == 0) {
  513. resp_len = strtoul(value, &line_end, 10);
  514. if (line_end == value || *line_end != '\0') {
  515. HTTPerr(0, HTTP_R_ERROR_PARSING_CONTENT_LENGTH);
  516. ERR_add_error_data(2, "input=", value);
  517. return 0;
  518. }
  519. if (!check_set_resp_len(rctx, resp_len))
  520. return 0;
  521. }
  522. }
  523. /* Look for blank line: end of headers */
  524. for (p = rctx->iobuf; *p != '\0'; p++) {
  525. if (*p != '\r' && *p != '\n')
  526. break;
  527. }
  528. if (*p != '\0') /* not end of headers */
  529. goto next_line;
  530. if (rctx->expected_ct != NULL) {
  531. HTTPerr(0, HTTP_R_MISSING_CONTENT_TYPE);
  532. ERR_add_error_data(2, "expected=", rctx->expected_ct);
  533. return 0;
  534. }
  535. if (rctx->state == OHS_REDIRECT) {
  536. /* http status code indicated redirect but there was no Location */
  537. HTTPerr(0, HTTP_R_MISSING_REDIRECT_LOCATION);
  538. return 0;
  539. }
  540. if (!rctx->expect_asn1) {
  541. rctx->state = OHS_CONTENT;
  542. goto content;
  543. }
  544. rctx->state = OHS_ASN1_HEADER;
  545. /* Fall thru */
  546. case OHS_ASN1_HEADER:
  547. /*
  548. * Now reading ASN1 header: can read at least 2 bytes which is enough
  549. * for ASN1 SEQUENCE header and either length field or at least the
  550. * length of the length field.
  551. */
  552. n = BIO_get_mem_data(rctx->mem, &p);
  553. if (n < 2)
  554. goto next_io;
  555. /* Check it is an ASN1 SEQUENCE */
  556. if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
  557. HTTPerr(0, HTTP_R_MISSING_ASN1_ENCODING);
  558. return 0;
  559. }
  560. /* Check out length field */
  561. if ((*p & 0x80) != 0) {
  562. /*
  563. * If MSB set on initial length octet we can now always read 6
  564. * octets: make sure we have them.
  565. */
  566. if (n < 6)
  567. goto next_io;
  568. n = *p & 0x7F;
  569. /* Not NDEF or excessive length */
  570. if (n == 0 || (n > 4)) {
  571. HTTPerr(0, HTTP_R_ERROR_PARSING_ASN1_LENGTH);
  572. return 0;
  573. }
  574. p++;
  575. resp_len = 0;
  576. for (i = 0; i < n; i++) {
  577. resp_len <<= 8;
  578. resp_len |= *p++;
  579. }
  580. resp_len += n + 2;
  581. } else {
  582. resp_len = *p + 2;
  583. }
  584. if (!check_set_resp_len(rctx, resp_len))
  585. return 0;
  586. content:
  587. rctx->state = OHS_CONTENT;
  588. /* Fall thru */
  589. case OHS_CONTENT:
  590. default:
  591. n = BIO_get_mem_data(rctx->mem, NULL);
  592. if (n < (long)rctx->resp_len /* may be 0 if no Content-Type or ASN.1 */)
  593. goto next_io;
  594. rctx->state = OHS_DONE;
  595. return 1;
  596. }
  597. }
  598. #ifndef OPENSSL_NO_SOCK
  599. /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
  600. static BIO *HTTP_new_bio(const char *server /* optionally includes ":port" */,
  601. const char *server_port /* explicit server port */,
  602. const char *proxy /* optionally includes ":port" */)
  603. {
  604. const char *host = server, *host_end;
  605. char host_name[100];
  606. const char *port = server_port;
  607. BIO *cbio;
  608. if (!ossl_assert(server != NULL))
  609. return NULL;
  610. if (proxy != NULL) {
  611. host = proxy;
  612. port = NULL;
  613. }
  614. host_end = strchr(host, '/');
  615. if (host_end != NULL) {
  616. size_t host_len = host_end - host;
  617. if (host_len < sizeof(host_name)) {
  618. /* chop trailing string starting with '/' */
  619. strncpy(host_name, host, host_len);
  620. host_name[host_len] = '\0';
  621. host = host_name;
  622. }
  623. }
  624. cbio = BIO_new_connect(host /* optionally includes ":port" */);
  625. if (cbio == NULL)
  626. goto end;
  627. if (port != NULL)
  628. (void)BIO_set_conn_port(cbio, port);
  629. end:
  630. return cbio;
  631. }
  632. #endif /* OPENSSL_NO_SOCK */
  633. static ASN1_VALUE *BIO_mem_d2i(BIO *mem, const ASN1_ITEM *it)
  634. {
  635. const unsigned char *p;
  636. long len = BIO_get_mem_data(mem, &p);
  637. ASN1_VALUE *resp = ASN1_item_d2i(NULL, &p, len, it);
  638. if (resp == NULL)
  639. HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
  640. return resp;
  641. }
  642. static BIO *OSSL_HTTP_REQ_CTX_transfer(OSSL_HTTP_REQ_CTX *rctx)
  643. {
  644. int sending = 1;
  645. int rv;
  646. if (rctx == NULL) {
  647. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  648. return NULL;
  649. }
  650. for (;;) {
  651. rv = OSSL_HTTP_REQ_CTX_nbio(rctx);
  652. if (rv != -1)
  653. break;
  654. /* BIO_should_retry was true */
  655. sending = 0;
  656. /* will not actually wait if rctx->max_time == 0 */
  657. if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0)
  658. return NULL;
  659. }
  660. if (rv == 0) {
  661. if (rctx->redirection_url == NULL) { /* an error occurred */
  662. if (sending && (rctx->state & OHS_NOREAD) != 0)
  663. HTTPerr(0, HTTP_R_ERROR_SENDING);
  664. else
  665. HTTPerr(0, HTTP_R_ERROR_RECEIVING);
  666. }
  667. return NULL;
  668. }
  669. if (!BIO_up_ref(rctx->mem))
  670. return NULL;
  671. return rctx->mem;
  672. }
  673. /* Exchange ASN.1-encoded request and response via HTTP on (non-)blocking BIO */
  674. ASN1_VALUE *OSSL_HTTP_REQ_CTX_sendreq_d2i(OSSL_HTTP_REQ_CTX *rctx,
  675. const ASN1_ITEM *it)
  676. {
  677. if (rctx == NULL || it == NULL) {
  678. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  679. return NULL;
  680. }
  681. return BIO_mem_d2i(OSSL_HTTP_REQ_CTX_transfer(rctx), it);
  682. }
  683. static int update_timeout(int timeout, time_t start_time)
  684. {
  685. long elapsed_time;
  686. if (timeout == 0)
  687. return 0;
  688. elapsed_time = (long)(time(NULL) - start_time); /* this might overflow */
  689. return timeout <= elapsed_time ? -1 : timeout - elapsed_time;
  690. }
  691. /*-
  692. * Exchange HTTP request and response with the given server.
  693. * If req_mem == NULL then use GET and ignore content_type, else POST.
  694. * The redirection_url output (freed by caller) parameter is used only for GET.
  695. *
  696. * Typically the bio and rbio parameters are NULL and a network BIO is created
  697. * internally for connecting to the given server and port, optionally via a
  698. * proxy and its port, and is then used for exchanging the request and response.
  699. * If bio is given and rbio is NULL then this BIO is used instead.
  700. * If both bio and rbio are given (which may be memory BIOs for instance)
  701. * then no explicit connection is attempted,
  702. * bio is used for writing the request, and rbio for reading the response.
  703. *
  704. * bio_update_fn is an optional BIO connect/disconnect callback function,
  705. * which has the prototype
  706. * BIO *(*OSSL_HTTP_bio_cb_t) (BIO *bio, void *arg, int conn, int detail);
  707. * The callback may modify the HTTP BIO provided in the bio argument,
  708. * whereby it may make use of any custom defined argument 'arg'.
  709. * During connection establishment, just after BIO_do_connect_retry(),
  710. * the callback function is invoked with the 'conn' argument being 1
  711. * 'detail' indicating whether a HTTPS (i.e., TLS) connection is requested.
  712. * On disconnect 'conn' is 0 and 'detail' indicates that no error occurred.
  713. * For instance, on connect the funct may prepend a TLS BIO to implement HTTPS;
  714. * after disconnect it may do some error diagnostics and/or specific cleanup.
  715. * The function should return NULL to indicate failure.
  716. * After disconnect the modified BIO will be deallocated using BIO_free_all().
  717. */
  718. BIO *OSSL_HTTP_transfer(const char *server, const char *port, const char *path,
  719. int use_ssl, const char *proxy, const char *no_proxy,
  720. BIO *bio, BIO *rbio,
  721. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  722. const STACK_OF(CONF_VALUE) *headers,
  723. const char *content_type, BIO *req_mem,
  724. int maxline, unsigned long max_resp_len, int timeout,
  725. const char *expected_ct, int expect_asn1,
  726. char **redirection_url)
  727. {
  728. time_t start_time = timeout > 0 ? time(NULL) : 0;
  729. BIO *cbio; /* = bio if present, used as connection BIO if rbio is NULL */
  730. OSSL_HTTP_REQ_CTX *rctx;
  731. BIO *resp = NULL;
  732. if (redirection_url != NULL)
  733. *redirection_url = NULL; /* do this beforehand to prevent dbl free */
  734. if (use_ssl && bio_update_fn == NULL) {
  735. HTTPerr(0, HTTP_R_TLS_NOT_ENABLED);
  736. return NULL;
  737. }
  738. if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) {
  739. HTTPerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
  740. return NULL;
  741. }
  742. if (bio != NULL) {
  743. cbio = bio;
  744. } else {
  745. #ifndef OPENSSL_NO_SOCK
  746. if (server == NULL) {
  747. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  748. return NULL;
  749. }
  750. if (*port == '\0')
  751. port = NULL;
  752. if (port == NULL && strchr(server, ':') == NULL)
  753. port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
  754. proxy = http_adapt_proxy(proxy, no_proxy, server, use_ssl);
  755. if ((cbio = HTTP_new_bio(server, port, proxy)) == NULL)
  756. return NULL;
  757. #else
  758. HTTPerr(0, HTTP_R_SOCK_NOT_SUPPORTED);
  759. return NULL;
  760. #endif
  761. }
  762. /* remaining parameters are checked indirectly by the functions called */
  763. (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
  764. if (rbio == NULL && BIO_do_connect_retry(cbio, timeout, -1) <= 0)
  765. goto end;
  766. /* now timeout is guaranteed to be >= 0 */
  767. /* callback can be used to wrap or prepend TLS session */
  768. if (bio_update_fn != NULL) {
  769. BIO *orig_bio = cbio;
  770. cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl);
  771. if (cbio == NULL) {
  772. cbio = orig_bio;
  773. goto end;
  774. }
  775. }
  776. rctx = HTTP_REQ_CTX_new(cbio, rbio != NULL ? rbio : cbio,
  777. !use_ssl && proxy != NULL, server, port, path,
  778. headers, content_type, req_mem, maxline,
  779. max_resp_len, update_timeout(timeout, start_time),
  780. expected_ct, expect_asn1);
  781. if (rctx == NULL)
  782. goto end;
  783. resp = OSSL_HTTP_REQ_CTX_transfer(rctx);
  784. if (resp == NULL) {
  785. if (rctx->redirection_url != NULL) {
  786. if (redirection_url == NULL)
  787. HTTPerr(0, HTTP_R_REDIRECTION_NOT_ENABLED);
  788. else
  789. /* may be NULL if out of memory: */
  790. *redirection_url = OPENSSL_strdup(rctx->redirection_url);
  791. } else {
  792. char buf[200];
  793. unsigned long err = ERR_peek_error();
  794. int lib = ERR_GET_LIB(err);
  795. int reason = ERR_GET_REASON(err);
  796. if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP
  797. || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT)
  798. || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR)
  799. #ifndef OPENSSL_NO_CMP
  800. || (lib == ERR_LIB_CMP
  801. && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
  802. #endif
  803. ) {
  804. BIO_snprintf(buf, 200, "server=%s:%s", server, port);
  805. ERR_add_error_data(1, buf);
  806. if (proxy != NULL)
  807. ERR_add_error_data(2, " proxy=", proxy);
  808. if (err == 0) {
  809. BIO_snprintf(buf, 200, " peer has disconnected%s",
  810. use_ssl ? " violating the protocol" :
  811. ", likely because it requires the use of TLS");
  812. ERR_add_error_data(1, buf);
  813. }
  814. }
  815. }
  816. }
  817. OSSL_HTTP_REQ_CTX_free(rctx);
  818. /* callback can be used to clean up TLS session */
  819. if (bio_update_fn != NULL
  820. && (*bio_update_fn)(cbio, arg, 0, resp != NULL) == NULL) {
  821. BIO_free(resp);
  822. resp = NULL;
  823. }
  824. end:
  825. /*
  826. * Use BIO_free_all() because bio_update_fn may prepend or append to cbio.
  827. * This also frees any (e.g., SSL/TLS) BIOs linked with bio and,
  828. * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer.
  829. */
  830. if (bio == NULL) /* cbio was not provided by caller */
  831. BIO_free_all(cbio);
  832. if (resp != NULL)
  833. /* remove any spurious error queue entries by ssl_add_cert_chain() */
  834. (void)ERR_pop_to_mark();
  835. else
  836. (void)ERR_clear_last_mark();
  837. return resp;
  838. }
  839. static int redirection_ok(int n_redir, const char *old_url, const char *new_url)
  840. {
  841. size_t https_len = strlen(OSSL_HTTPS_NAME":");
  842. if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) {
  843. HTTPerr(0, HTTP_R_TOO_MANY_REDIRECTIONS);
  844. return 0;
  845. }
  846. if (*new_url == '/') /* redirection to same server => same protocol */
  847. return 1;
  848. if (strncmp(old_url, OSSL_HTTPS_NAME":", https_len) == 0 &&
  849. strncmp(new_url, OSSL_HTTPS_NAME":", https_len) != 0) {
  850. HTTPerr(0, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP);
  851. return 0;
  852. }
  853. return 1;
  854. }
  855. /* Get data via HTTP from server at given URL, potentially with redirection */
  856. BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy,
  857. BIO *bio, BIO *rbio,
  858. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  859. const STACK_OF(CONF_VALUE) *headers,
  860. int maxline, unsigned long max_resp_len, int timeout,
  861. const char *expected_content_type, int expect_asn1)
  862. {
  863. time_t start_time = timeout > 0 ? time(NULL) : 0;
  864. char *current_url, *redirection_url;
  865. int n_redirs = 0;
  866. char *host;
  867. char *port;
  868. char *path;
  869. int use_ssl;
  870. BIO *resp = NULL;
  871. if (url == NULL) {
  872. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  873. return NULL;
  874. }
  875. if ((current_url = OPENSSL_strdup(url)) == NULL)
  876. return NULL;
  877. for (;;) {
  878. if (!OSSL_HTTP_parse_url(current_url, &host, &port, &path, &use_ssl))
  879. break;
  880. new_rpath:
  881. resp = OSSL_HTTP_transfer(host, port, path, use_ssl, proxy, no_proxy,
  882. bio, rbio,
  883. bio_update_fn, arg, headers, NULL, NULL,
  884. maxline, max_resp_len,
  885. update_timeout(timeout, start_time),
  886. expected_content_type, expect_asn1,
  887. &redirection_url);
  888. OPENSSL_free(path);
  889. if (resp == NULL && redirection_url != NULL) {
  890. if (redirection_ok(++n_redirs, current_url, redirection_url)) {
  891. (void)BIO_reset(bio);
  892. OPENSSL_free(current_url);
  893. current_url = redirection_url;
  894. if (*redirection_url == '/') { /* redirection to same server */
  895. path = OPENSSL_strdup(redirection_url);
  896. goto new_rpath;
  897. }
  898. OPENSSL_free(host);
  899. OPENSSL_free(port);
  900. continue;
  901. }
  902. OPENSSL_free(redirection_url);
  903. }
  904. OPENSSL_free(host);
  905. OPENSSL_free(port);
  906. break;
  907. }
  908. OPENSSL_free(current_url);
  909. return resp;
  910. }
  911. /* Get ASN.1-encoded data via HTTP from server at given URL */
  912. ASN1_VALUE *OSSL_HTTP_get_asn1(const char *url,
  913. const char *proxy, const char *no_proxy,
  914. BIO *bio, BIO *rbio,
  915. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  916. const STACK_OF(CONF_VALUE) *headers,
  917. int maxline, unsigned long max_resp_len,
  918. int timeout, const char *expected_content_type,
  919. const ASN1_ITEM *it)
  920. {
  921. BIO *mem;
  922. ASN1_VALUE *resp = NULL;
  923. if (url == NULL || it == NULL) {
  924. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  925. return NULL;
  926. }
  927. if ((mem = OSSL_HTTP_get(url, proxy, no_proxy, bio, rbio, bio_update_fn,
  928. arg, headers, maxline, max_resp_len, timeout,
  929. expected_content_type, 1 /* expect_asn1 */))
  930. != NULL)
  931. resp = BIO_mem_d2i(mem, it);
  932. BIO_free(mem);
  933. return resp;
  934. }
  935. /* Post ASN.1-encoded request via HTTP to server return ASN.1 response */
  936. ASN1_VALUE *OSSL_HTTP_post_asn1(const char *server, const char *port,
  937. const char *path, int use_ssl,
  938. const char *proxy, const char *no_proxy,
  939. BIO *bio, BIO *rbio,
  940. OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
  941. const STACK_OF(CONF_VALUE) *headers,
  942. const char *content_type,
  943. const ASN1_VALUE *req, const ASN1_ITEM *req_it,
  944. int maxline, unsigned long max_resp_len,
  945. int timeout, const char *expected_ct,
  946. const ASN1_ITEM *rsp_it)
  947. {
  948. BIO *req_mem;
  949. BIO *res_mem;
  950. ASN1_VALUE *resp = NULL;
  951. if (req == NULL) {
  952. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  953. return NULL;
  954. }
  955. /* remaining parameters are checked indirectly */
  956. req_mem = HTTP_asn1_item2bio(req_it, req);
  957. res_mem = OSSL_HTTP_transfer(server, port, path, use_ssl, proxy, no_proxy,
  958. bio, rbio,
  959. bio_update_fn, arg, headers, content_type,
  960. req_mem /* may be NULL */, maxline,
  961. max_resp_len, timeout,
  962. expected_ct, 1 /* expect_asn1 */, NULL);
  963. BIO_free(req_mem);
  964. if (res_mem != NULL)
  965. resp = BIO_mem_d2i(res_mem, rsp_it);
  966. BIO_free(res_mem);
  967. return resp;
  968. }
  969. /* BASE64 encoder used for encoding basic proxy authentication credentials */
  970. static char *base64encode(const void *buf, size_t len)
  971. {
  972. int i;
  973. size_t outl;
  974. char *out;
  975. /* Calculate size of encoded data */
  976. outl = (len / 3);
  977. if (len % 3 > 0)
  978. outl++;
  979. outl <<= 2;
  980. out = OPENSSL_malloc(outl + 1);
  981. if (out == NULL)
  982. return 0;
  983. i = EVP_EncodeBlock((unsigned char *)out, buf, len);
  984. if (!ossl_assert(0 <= i && (size_t)i <= outl)) {
  985. OPENSSL_free(out);
  986. return NULL;
  987. }
  988. return out;
  989. }
  990. /*
  991. * Promote the given connection BIO using the CONNECT method for a TLS proxy.
  992. * This is typically called by an app, so bio_err and prog are used unless NULL
  993. * to print additional diagnostic information in a user-oriented way.
  994. */
  995. int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
  996. const char *proxyuser, const char *proxypass,
  997. int timeout, BIO *bio_err, const char *prog)
  998. {
  999. #undef BUF_SIZE
  1000. #define BUF_SIZE (8 * 1024)
  1001. char *mbuf = OPENSSL_malloc(BUF_SIZE);
  1002. char *mbufp;
  1003. int read_len = 0;
  1004. int ret = 0;
  1005. BIO *fbio = BIO_new(BIO_f_buffer());
  1006. int rv;
  1007. time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
  1008. if (bio == NULL || server == NULL
  1009. || (bio_err != NULL && prog == NULL)) {
  1010. HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
  1011. goto end;
  1012. }
  1013. if (port == NULL || *port == '\0')
  1014. port = OSSL_HTTPS_PORT;
  1015. if (mbuf == NULL || fbio == NULL) {
  1016. BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog);
  1017. goto end;
  1018. }
  1019. BIO_push(fbio, bio);
  1020. BIO_printf(fbio, "CONNECT %s:%s "HTTP_PREFIX"1.0\r\n", server, port);
  1021. /*
  1022. * Workaround for broken proxies which would otherwise close
  1023. * the connection when entering tunnel mode (e.g., Squid 2.6)
  1024. */
  1025. BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n");
  1026. /* Support for basic (base64) proxy authentication */
  1027. if (proxyuser != NULL) {
  1028. size_t len = strlen(proxyuser) + 1;
  1029. char *proxyauth, *proxyauthenc = NULL;
  1030. if (proxypass != NULL)
  1031. len += strlen(proxypass);
  1032. proxyauth = OPENSSL_malloc(len + 1);
  1033. if (proxyauth == NULL)
  1034. goto end;
  1035. if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser,
  1036. proxypass != NULL ? proxypass : "") != (int)len)
  1037. goto proxy_end;
  1038. proxyauthenc = base64encode(proxyauth, len);
  1039. if (proxyauthenc != NULL) {
  1040. BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc);
  1041. OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc));
  1042. }
  1043. proxy_end:
  1044. OPENSSL_clear_free(proxyauth, len);
  1045. if (proxyauthenc == NULL)
  1046. goto end;
  1047. }
  1048. /* Terminate the HTTP CONNECT request */
  1049. BIO_printf(fbio, "\r\n");
  1050. for (;;) {
  1051. if (BIO_flush(fbio) != 0)
  1052. break;
  1053. /* potentially needs to be retried if BIO is non-blocking */
  1054. if (!BIO_should_retry(fbio))
  1055. break;
  1056. }
  1057. for (;;) {
  1058. /* will not actually wait if timeout == 0 */
  1059. rv = BIO_wait(fbio, max_time, 100 /* milliseconds */);
  1060. if (rv <= 0) {
  1061. BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog,
  1062. rv == 0 ? "timed out" : "failed waiting for data");
  1063. goto end;
  1064. }
  1065. /*-
  1066. * The first line is the HTTP response.
  1067. * According to RFC 7230, it is formatted exactly like this:
  1068. * HTTP/d.d ddd Reason text\r\n
  1069. */
  1070. read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
  1071. /* the BIO may not block, so we must wait for the 1st line to come in */
  1072. if (read_len < HTTP_LINE1_MINLEN)
  1073. continue;
  1074. /* RFC 7231 4.3.6: any 2xx status code is valid */
  1075. if (strncmp(mbuf, HTTP_PREFIX, strlen(HTTP_PREFIX)) != 0) {
  1076. HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
  1077. BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n",
  1078. prog);
  1079. /* Wrong protocol, not even HTTP, so stop reading headers */
  1080. goto end;
  1081. }
  1082. mbufp = mbuf + strlen(HTTP_PREFIX);
  1083. if (strncmp(mbufp, HTTP_VERSION_PATT, strlen(HTTP_VERSION_PATT)) != 0) {
  1084. HTTPerr(0, HTTP_R_RECEIVED_WRONG_HTTP_VERSION);
  1085. BIO_printf(bio_err,
  1086. "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
  1087. prog, HTTP_VERSION_STR_LEN, mbufp);
  1088. goto end;
  1089. }
  1090. mbufp += HTTP_VERSION_STR_LEN;
  1091. if (strncmp(mbufp, " 2", strlen(" 2")) != 0) {
  1092. mbufp += 1;
  1093. /* chop any trailing whitespace */
  1094. while (read_len > 0 && ossl_isspace(mbuf[read_len - 1]))
  1095. read_len--;
  1096. mbuf[read_len] = '\0';
  1097. HTTPerr(0, HTTP_R_CONNECT_FAILURE);
  1098. ERR_add_error_data(2, "Reason=", mbufp);
  1099. BIO_printf(bio_err, "%s: HTTP CONNECT failed, Reason=%s\n",
  1100. prog, mbufp);
  1101. goto end;
  1102. }
  1103. ret = 1;
  1104. break;
  1105. }
  1106. /* Read past all following headers */
  1107. do {
  1108. /*
  1109. * TODO: This does not necessarily catch the case when the full
  1110. * HTTP response came in in more than a single TCP message.
  1111. */
  1112. read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
  1113. } while (read_len > 2);
  1114. end:
  1115. if (fbio != NULL) {
  1116. (void)BIO_flush(fbio);
  1117. BIO_pop(fbio);
  1118. BIO_free(fbio);
  1119. }
  1120. OPENSSL_free(mbuf);
  1121. return ret;
  1122. #undef BUF_SIZE
  1123. }