http_client.c 41 KB

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