http_server.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /*
  2. * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /* Very basic HTTP server */
  10. #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
  11. /*
  12. * On VMS, you need to define this to get the declaration of fileno(). The
  13. * value 2 is to make sure no function defined in POSIX-2 is left undefined.
  14. */
  15. # define _POSIX_C_SOURCE 2
  16. #endif
  17. #include <ctype.h>
  18. #include "http_server.h"
  19. #include "internal/sockets.h"
  20. #include <openssl/err.h>
  21. #include <openssl/trace.h>
  22. #include <openssl/rand.h>
  23. #include "s_apps.h"
  24. #include "log.h"
  25. #if defined(__TANDEM)
  26. # if defined(OPENSSL_TANDEM_FLOSS)
  27. # include <floss.h(floss_fork)>
  28. # endif
  29. #endif
  30. #define HTTP_PREFIX "HTTP/"
  31. #define HTTP_VERSION_PATT "1." /* allow 1.x */
  32. #define HTTP_PREFIX_VERSION HTTP_PREFIX""HTTP_VERSION_PATT
  33. #define HTTP_1_0 HTTP_PREFIX_VERSION"0" /* "HTTP/1.0" */
  34. #define HTTP_VERSION_STR " "HTTP_PREFIX_VERSION
  35. #define log_HTTP(prog, level, text) \
  36. trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, "%s", text)
  37. #define log_HTTP1(prog, level, fmt, arg) \
  38. trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, arg)
  39. #define log_HTTP2(prog, level, fmt, arg1, arg2) \
  40. trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, arg1, arg2)
  41. #define log_HTTP3(prog, level, fmt, a1, a2, a3) \
  42. trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, a1, a2, a3)
  43. #ifdef HTTP_DAEMON
  44. int n_responders = 0; /* run multiple responder processes, set by ocsp.c */
  45. int acfd = (int)INVALID_SOCKET;
  46. void socket_timeout(int signum)
  47. {
  48. if (acfd != (int)INVALID_SOCKET)
  49. (void)shutdown(acfd, SHUT_RD);
  50. }
  51. static void killall(int ret, pid_t *kidpids)
  52. {
  53. int i;
  54. for (i = 0; i < n_responders; ++i)
  55. if (kidpids[i] != 0)
  56. (void)kill(kidpids[i], SIGTERM);
  57. OPENSSL_free(kidpids);
  58. OSSL_sleep(1000);
  59. exit(ret);
  60. }
  61. static int termsig = 0;
  62. static void noteterm(int sig)
  63. {
  64. termsig = sig;
  65. }
  66. /*
  67. * Loop spawning up to `multi` child processes, only child processes return
  68. * from this function. The parent process loops until receiving a termination
  69. * signal, kills extant children and exits without returning.
  70. */
  71. void spawn_loop(const char *prog)
  72. {
  73. pid_t *kidpids = NULL;
  74. int status;
  75. int procs = 0;
  76. int i;
  77. openlog(prog, LOG_PID, LOG_DAEMON);
  78. if (setpgid(0, 0)) {
  79. log_HTTP1(prog, LOG_CRIT,
  80. "error detaching from parent process group: %s",
  81. strerror(errno));
  82. exit(1);
  83. }
  84. kidpids = app_malloc(n_responders * sizeof(*kidpids), "child PID array");
  85. for (i = 0; i < n_responders; ++i)
  86. kidpids[i] = 0;
  87. signal(SIGINT, noteterm);
  88. signal(SIGTERM, noteterm);
  89. while (termsig == 0) {
  90. pid_t fpid;
  91. /*
  92. * Wait for a child to replace when we're at the limit.
  93. * Slow down if a child exited abnormally or waitpid() < 0
  94. */
  95. while (termsig == 0 && procs >= n_responders) {
  96. if ((fpid = waitpid(-1, &status, 0)) > 0) {
  97. for (i = 0; i < procs; ++i) {
  98. if (kidpids[i] == fpid) {
  99. kidpids[i] = 0;
  100. --procs;
  101. break;
  102. }
  103. }
  104. if (i >= n_responders) {
  105. log_HTTP1(prog, LOG_CRIT,
  106. "internal error: no matching child slot for pid: %ld",
  107. (long)fpid);
  108. killall(1, kidpids);
  109. }
  110. if (status != 0) {
  111. if (WIFEXITED(status)) {
  112. log_HTTP2(prog, LOG_WARNING,
  113. "child process: %ld, exit status: %d",
  114. (long)fpid, WEXITSTATUS(status));
  115. } else if (WIFSIGNALED(status)) {
  116. char *dumped = "";
  117. # ifdef WCOREDUMP
  118. if (WCOREDUMP(status))
  119. dumped = " (core dumped)";
  120. # endif
  121. log_HTTP3(prog, LOG_WARNING,
  122. "child process: %ld, term signal %d%s",
  123. (long)fpid, WTERMSIG(status), dumped);
  124. }
  125. OSSL_sleep(1000);
  126. }
  127. break;
  128. } else if (errno != EINTR) {
  129. log_HTTP1(prog, LOG_CRIT,
  130. "waitpid() failed: %s", strerror(errno));
  131. killall(1, kidpids);
  132. }
  133. }
  134. if (termsig)
  135. break;
  136. switch (fpid = fork()) {
  137. case -1: /* error */
  138. /* System critically low on memory, pause and try again later */
  139. OSSL_sleep(30000);
  140. break;
  141. case 0: /* child */
  142. OPENSSL_free(kidpids);
  143. signal(SIGINT, SIG_DFL);
  144. signal(SIGTERM, SIG_DFL);
  145. if (termsig)
  146. _exit(0);
  147. if (RAND_poll() <= 0) {
  148. log_HTTP(prog, LOG_CRIT, "RAND_poll() failed");
  149. _exit(1);
  150. }
  151. return;
  152. default: /* parent */
  153. for (i = 0; i < n_responders; ++i) {
  154. if (kidpids[i] == 0) {
  155. kidpids[i] = fpid;
  156. procs++;
  157. break;
  158. }
  159. }
  160. if (i >= n_responders) {
  161. log_HTTP(prog, LOG_CRIT,
  162. "internal error: no free child slots");
  163. killall(1, kidpids);
  164. }
  165. break;
  166. }
  167. }
  168. /* The loop above can only break on termsig */
  169. log_HTTP1(prog, LOG_INFO, "terminating on signal: %d", termsig);
  170. killall(0, kidpids);
  171. }
  172. #endif
  173. #ifndef OPENSSL_NO_SOCK
  174. BIO *http_server_init(const char *prog, const char *port, int verb)
  175. {
  176. BIO *acbio = NULL, *bufbio;
  177. int asock;
  178. int port_num;
  179. char name[40];
  180. snprintf(name, sizeof(name), "*:%s", port); /* port may be "0" */
  181. if (verb >= 0 && !log_set_verbosity(prog, verb))
  182. return NULL;
  183. bufbio = BIO_new(BIO_f_buffer());
  184. if (bufbio == NULL)
  185. goto err;
  186. acbio = BIO_new(BIO_s_accept());
  187. if (acbio == NULL
  188. || BIO_set_accept_ip_family(acbio, BIO_FAMILY_IPANY) <= 0 /* IPv4/6 */
  189. || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) <= 0
  190. || BIO_set_accept_name(acbio, name) <= 0) {
  191. log_HTTP(prog, LOG_ERR, "error setting up accept BIO");
  192. goto err;
  193. }
  194. BIO_set_accept_bios(acbio, bufbio);
  195. bufbio = NULL;
  196. if (BIO_do_accept(acbio) <= 0) {
  197. log_HTTP1(prog, LOG_ERR, "error setting accept on port %s", port);
  198. goto err;
  199. }
  200. /* Report back what address and port are used */
  201. BIO_get_fd(acbio, &asock);
  202. port_num = report_server_accept(bio_out, asock, 1, 1);
  203. if (port_num == 0) {
  204. log_HTTP(prog, LOG_ERR, "error printing ACCEPT string");
  205. goto err;
  206. }
  207. return acbio;
  208. err:
  209. ERR_print_errors(bio_err);
  210. BIO_free_all(acbio);
  211. BIO_free(bufbio);
  212. return NULL;
  213. }
  214. /*
  215. * Decode %xx URL-decoding in-place. Ignores malformed sequences.
  216. */
  217. static int urldecode(char *p)
  218. {
  219. unsigned char *out = (unsigned char *)p;
  220. unsigned char *save = out;
  221. for (; *p; p++) {
  222. if (*p != '%') {
  223. *out++ = *p;
  224. } else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
  225. /* Don't check, can't fail because of ixdigit() call. */
  226. *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
  227. | OPENSSL_hexchar2int(p[2]);
  228. p += 2;
  229. } else {
  230. return -1;
  231. }
  232. }
  233. *out = '\0';
  234. return (int)(out - save);
  235. }
  236. /* if *pcbio != NULL, continue given connected session, else accept new */
  237. /* if found_keep_alive != NULL, return this way connection persistence state */
  238. int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq,
  239. char **ppath, BIO **pcbio, BIO *acbio,
  240. int *found_keep_alive,
  241. const char *prog, int accept_get, int timeout)
  242. {
  243. BIO *cbio = *pcbio, *getbio = NULL, *b64 = NULL;
  244. int len;
  245. char reqbuf[2048], inbuf[2048];
  246. char *meth, *url, *end;
  247. ASN1_VALUE *req;
  248. int ret = 0;
  249. *preq = NULL;
  250. if (ppath != NULL)
  251. *ppath = NULL;
  252. if (cbio == NULL) {
  253. char *port;
  254. get_sock_info_address(BIO_get_fd(acbio, NULL), NULL, &port);
  255. if (port == NULL) {
  256. log_HTTP(prog, LOG_ERR, "cannot get port listening on");
  257. goto fatal;
  258. }
  259. log_HTTP1(prog, LOG_DEBUG,
  260. "awaiting new connection on port %s ...", port);
  261. OPENSSL_free(port);
  262. if (BIO_do_accept(acbio) <= 0)
  263. /* Connection loss before accept() is routine, ignore silently */
  264. return ret;
  265. *pcbio = cbio = BIO_pop(acbio);
  266. } else {
  267. log_HTTP(prog, LOG_DEBUG, "awaiting next request ...");
  268. }
  269. if (cbio == NULL) {
  270. /* Cannot call http_server_send_status(..., cbio, ...) */
  271. ret = -1;
  272. goto out;
  273. }
  274. # ifdef HTTP_DAEMON
  275. if (timeout > 0) {
  276. (void)BIO_get_fd(cbio, &acfd);
  277. alarm(timeout);
  278. }
  279. # endif
  280. /* Read the request line. */
  281. len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
  282. if (len == 0)
  283. return ret;
  284. ret = 1;
  285. if (len < 0) {
  286. log_HTTP(prog, LOG_WARNING, "request line read error");
  287. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  288. goto out;
  289. }
  290. if (((end = strchr(reqbuf, '\r')) != NULL && end[1] == '\n')
  291. || (end = strchr(reqbuf, '\n')) != NULL)
  292. *end = '\0';
  293. if (log_get_verbosity() < LOG_TRACE)
  294. trace_log_message(-1, prog, LOG_INFO,
  295. "received request, 1st line: %s", reqbuf);
  296. log_HTTP(prog, LOG_TRACE, "received request header:");
  297. log_HTTP1(prog, LOG_TRACE, "%s", reqbuf);
  298. if (end == NULL) {
  299. log_HTTP(prog, LOG_WARNING,
  300. "cannot parse HTTP header: missing end of line");
  301. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  302. goto out;
  303. }
  304. url = meth = reqbuf;
  305. if ((accept_get && CHECK_AND_SKIP_PREFIX(url, "GET "))
  306. || CHECK_AND_SKIP_PREFIX(url, "POST ")) {
  307. /* Expecting (GET|POST) {sp} /URL {sp} HTTP/1.x */
  308. url[-1] = '\0';
  309. while (*url == ' ')
  310. url++;
  311. if (*url != '/') {
  312. log_HTTP2(prog, LOG_WARNING,
  313. "invalid %s -- URL does not begin with '/': %s",
  314. meth, url);
  315. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  316. goto out;
  317. }
  318. url++;
  319. /* Splice off the HTTP version identifier. */
  320. for (end = url; *end != '\0'; end++)
  321. if (*end == ' ')
  322. break;
  323. if (!HAS_PREFIX(end, HTTP_VERSION_STR)) {
  324. log_HTTP2(prog, LOG_WARNING,
  325. "invalid %s -- bad HTTP/version string: %s",
  326. meth, end + 1);
  327. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  328. goto out;
  329. }
  330. *end = '\0';
  331. /* above HTTP 1.0, connection persistence is the default */
  332. if (found_keep_alive != NULL)
  333. *found_keep_alive = end[sizeof(HTTP_VERSION_STR) - 1] > '0';
  334. /*-
  335. * Skip "GET / HTTP..." requests often used by load-balancers.
  336. * 'url' was incremented above to point to the first byte *after*
  337. * the leading slash, so in case 'GET / ' it is now an empty string.
  338. */
  339. if (strlen(meth) == 3 && url[0] == '\0') {
  340. (void)http_server_send_status(prog, cbio, 200, "OK");
  341. goto out;
  342. }
  343. len = urldecode(url);
  344. if (len < 0) {
  345. log_HTTP2(prog, LOG_WARNING,
  346. "invalid %s request -- bad URL encoding: %s", meth, url);
  347. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  348. goto out;
  349. }
  350. if (strlen(meth) == 3) { /* GET */
  351. if ((getbio = BIO_new_mem_buf(url, len)) == NULL
  352. || (b64 = BIO_new(BIO_f_base64())) == NULL) {
  353. log_HTTP1(prog, LOG_ERR,
  354. "could not allocate base64 bio with size = %d", len);
  355. goto fatal;
  356. }
  357. BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
  358. getbio = BIO_push(b64, getbio);
  359. }
  360. } else {
  361. log_HTTP2(prog, LOG_WARNING,
  362. "HTTP request does not begin with %sPOST: %s",
  363. accept_get ? "GET or " : "", reqbuf);
  364. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  365. goto out;
  366. }
  367. /* chop any further/duplicate leading or trailing '/' */
  368. while (*url == '/')
  369. url++;
  370. while (end >= url + 2 && end[-2] == '/' && end[-1] == '/')
  371. end--;
  372. *end = '\0';
  373. /* Read and skip past the headers. */
  374. for (;;) {
  375. char *key, *value;
  376. len = BIO_gets(cbio, inbuf, sizeof(inbuf));
  377. if (len <= 0) {
  378. log_HTTP(prog, LOG_WARNING, "error reading HTTP header");
  379. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  380. goto out;
  381. }
  382. if (((end = strchr(inbuf, '\r')) != NULL && end[1] == '\n')
  383. || (end = strchr(inbuf, '\n')) != NULL)
  384. *end = '\0';
  385. log_HTTP1(prog, LOG_TRACE, "%s", *inbuf == '\0' ?
  386. " " /* workaround for "" getting ignored */ : inbuf);
  387. if (end == NULL) {
  388. log_HTTP(prog, LOG_WARNING,
  389. "error parsing HTTP header: missing end of line");
  390. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  391. goto out;
  392. }
  393. if (inbuf[0] == '\0')
  394. break;
  395. key = inbuf;
  396. value = strchr(key, ':');
  397. if (value == NULL) {
  398. log_HTTP(prog, LOG_WARNING,
  399. "error parsing HTTP header: missing ':'");
  400. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  401. goto out;
  402. }
  403. *(value++) = '\0';
  404. while (*value == ' ')
  405. value++;
  406. /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
  407. if (found_keep_alive != NULL
  408. && OPENSSL_strcasecmp(key, "Connection") == 0) {
  409. if (OPENSSL_strcasecmp(value, "keep-alive") == 0)
  410. *found_keep_alive = 1;
  411. else if (OPENSSL_strcasecmp(value, "close") == 0)
  412. *found_keep_alive = 0;
  413. }
  414. }
  415. # ifdef HTTP_DAEMON
  416. /* Clear alarm before we close the client socket */
  417. alarm(0);
  418. timeout = 0;
  419. # endif
  420. /* Try to read and parse request */
  421. req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL);
  422. if (req == NULL) {
  423. log_HTTP(prog, LOG_WARNING,
  424. "error parsing DER-encoded request content");
  425. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  426. } else if (ppath != NULL && (*ppath = OPENSSL_strdup(url)) == NULL) {
  427. log_HTTP1(prog, LOG_ERR,
  428. "out of memory allocating %zu bytes", strlen(url) + 1);
  429. ASN1_item_free(req, it);
  430. goto fatal;
  431. }
  432. *preq = req;
  433. out:
  434. BIO_free_all(getbio);
  435. # ifdef HTTP_DAEMON
  436. if (timeout > 0)
  437. alarm(0);
  438. acfd = (int)INVALID_SOCKET;
  439. # endif
  440. return ret;
  441. fatal:
  442. (void)http_server_send_status(prog, cbio, 500, "Internal Server Error");
  443. if (ppath != NULL) {
  444. OPENSSL_free(*ppath);
  445. *ppath = NULL;
  446. }
  447. BIO_free_all(cbio);
  448. *pcbio = NULL;
  449. ret = -1;
  450. goto out;
  451. }
  452. /* assumes that cbio does not do an encoding that changes the output length */
  453. int http_server_send_asn1_resp(const char *prog, BIO *cbio, int keep_alive,
  454. const char *content_type,
  455. const ASN1_ITEM *it, const ASN1_VALUE *resp)
  456. {
  457. char buf[200], *p;
  458. int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" 200 OK\r\n%s"
  459. "Content-type: %s\r\n"
  460. "Content-Length: %d\r\n",
  461. keep_alive ? "Connection: keep-alive\r\n" : "",
  462. content_type,
  463. ASN1_item_i2d(resp, NULL, it));
  464. if (ret < 0 || (size_t)ret >= sizeof(buf))
  465. return 0;
  466. if (log_get_verbosity() < LOG_TRACE && (p = strchr(buf, '\r')) != NULL)
  467. trace_log_message(-1, prog, LOG_INFO,
  468. "sending response, 1st line: %.*s", (int)(p - buf),
  469. buf);
  470. log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
  471. ret = BIO_printf(cbio, "%s\r\n", buf) > 0
  472. && ASN1_item_i2d_bio(it, cbio, resp) > 0;
  473. (void)BIO_flush(cbio);
  474. return ret;
  475. }
  476. int http_server_send_status(const char *prog, BIO *cbio,
  477. int status, const char *reason)
  478. {
  479. char buf[200];
  480. int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" %d %s\r\n\r\n",
  481. /* This implicitly cancels keep-alive */
  482. status, reason);
  483. if (ret < 0 || (size_t)ret >= sizeof(buf))
  484. return 0;
  485. log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
  486. ret = BIO_printf(cbio, "%s\r\n", buf) > 0;
  487. (void)BIO_flush(cbio);
  488. return ret;
  489. }
  490. #endif