http_server.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
  189. || BIO_set_accept_name(acbio, name) < 0) {
  190. log_HTTP(prog, LOG_ERR, "error setting up accept BIO");
  191. goto err;
  192. }
  193. BIO_set_accept_bios(acbio, bufbio);
  194. bufbio = NULL;
  195. if (BIO_do_accept(acbio) <= 0) {
  196. log_HTTP1(prog, LOG_ERR, "error setting accept on port %s", port);
  197. goto err;
  198. }
  199. /* Report back what address and port are used */
  200. BIO_get_fd(acbio, &asock);
  201. port_num = report_server_accept(bio_out, asock, 1, 1);
  202. if (port_num == 0) {
  203. log_HTTP(prog, LOG_ERR, "error printing ACCEPT string");
  204. goto err;
  205. }
  206. return acbio;
  207. err:
  208. ERR_print_errors(bio_err);
  209. BIO_free_all(acbio);
  210. BIO_free(bufbio);
  211. return NULL;
  212. }
  213. /*
  214. * Decode %xx URL-decoding in-place. Ignores malformed sequences.
  215. */
  216. static int urldecode(char *p)
  217. {
  218. unsigned char *out = (unsigned char *)p;
  219. unsigned char *save = out;
  220. for (; *p; p++) {
  221. if (*p != '%') {
  222. *out++ = *p;
  223. } else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
  224. /* Don't check, can't fail because of ixdigit() call. */
  225. *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
  226. | OPENSSL_hexchar2int(p[2]);
  227. p += 2;
  228. } else {
  229. return -1;
  230. }
  231. }
  232. *out = '\0';
  233. return (int)(out - save);
  234. }
  235. /* if *pcbio != NULL, continue given connected session, else accept new */
  236. /* if found_keep_alive != NULL, return this way connection persistence state */
  237. int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq,
  238. char **ppath, BIO **pcbio, BIO *acbio,
  239. int *found_keep_alive,
  240. const char *prog, int accept_get, int timeout)
  241. {
  242. BIO *cbio = *pcbio, *getbio = NULL, *b64 = NULL;
  243. int len;
  244. char reqbuf[2048], inbuf[2048];
  245. char *meth, *url, *end;
  246. ASN1_VALUE *req;
  247. int ret = 0;
  248. *preq = NULL;
  249. if (ppath != NULL)
  250. *ppath = NULL;
  251. if (cbio == NULL) {
  252. char *port;
  253. get_sock_info_address(BIO_get_fd(acbio, NULL), NULL, &port);
  254. if (port == NULL) {
  255. log_HTTP(prog, LOG_ERR, "cannot get port listening on");
  256. goto fatal;
  257. }
  258. log_HTTP1(prog, LOG_DEBUG,
  259. "awaiting new connection on port %s ...", port);
  260. OPENSSL_free(port);
  261. if (BIO_do_accept(acbio) <= 0)
  262. /* Connection loss before accept() is routine, ignore silently */
  263. return ret;
  264. *pcbio = cbio = BIO_pop(acbio);
  265. } else {
  266. log_HTTP(prog, LOG_DEBUG, "awaiting next request ...");
  267. }
  268. if (cbio == NULL) {
  269. /* Cannot call http_server_send_status(..., cbio, ...) */
  270. ret = -1;
  271. goto out;
  272. }
  273. # ifdef HTTP_DAEMON
  274. if (timeout > 0) {
  275. (void)BIO_get_fd(cbio, &acfd);
  276. alarm(timeout);
  277. }
  278. # endif
  279. /* Read the request line. */
  280. len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
  281. if (len == 0)
  282. return ret;
  283. ret = 1;
  284. if (len < 0) {
  285. log_HTTP(prog, LOG_WARNING, "request line read error");
  286. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  287. goto out;
  288. }
  289. if (((end = strchr(reqbuf, '\r')) != NULL && end[1] == '\n')
  290. || (end = strchr(reqbuf, '\n')) != NULL)
  291. *end = '\0';
  292. if (log_get_verbosity() < LOG_TRACE)
  293. trace_log_message(-1, prog, LOG_INFO,
  294. "received request, 1st line: %s", reqbuf);
  295. log_HTTP(prog, LOG_TRACE, "received request header:");
  296. log_HTTP1(prog, LOG_TRACE, "%s", reqbuf);
  297. if (end == NULL) {
  298. log_HTTP(prog, LOG_WARNING,
  299. "cannot parse HTTP header: missing end of line");
  300. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  301. goto out;
  302. }
  303. url = meth = reqbuf;
  304. if ((accept_get && CHECK_AND_SKIP_PREFIX(url, "GET "))
  305. || CHECK_AND_SKIP_PREFIX(url, "POST ")) {
  306. /* Expecting (GET|POST) {sp} /URL {sp} HTTP/1.x */
  307. url[-1] = '\0';
  308. while (*url == ' ')
  309. url++;
  310. if (*url != '/') {
  311. log_HTTP2(prog, LOG_WARNING,
  312. "invalid %s -- URL does not begin with '/': %s",
  313. meth, url);
  314. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  315. goto out;
  316. }
  317. url++;
  318. /* Splice off the HTTP version identifier. */
  319. for (end = url; *end != '\0'; end++)
  320. if (*end == ' ')
  321. break;
  322. if (!HAS_PREFIX(end, HTTP_VERSION_STR)) {
  323. log_HTTP2(prog, LOG_WARNING,
  324. "invalid %s -- bad HTTP/version string: %s",
  325. meth, end + 1);
  326. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  327. goto out;
  328. }
  329. *end = '\0';
  330. /* above HTTP 1.0, connection persistence is the default */
  331. if (found_keep_alive != NULL)
  332. *found_keep_alive = end[sizeof(HTTP_VERSION_STR) - 1] > '0';
  333. /*-
  334. * Skip "GET / HTTP..." requests often used by load-balancers.
  335. * 'url' was incremented above to point to the first byte *after*
  336. * the leading slash, so in case 'GET / ' it is now an empty string.
  337. */
  338. if (strlen(meth) == 3 && url[0] == '\0') {
  339. (void)http_server_send_status(prog, cbio, 200, "OK");
  340. goto out;
  341. }
  342. len = urldecode(url);
  343. if (len < 0) {
  344. log_HTTP2(prog, LOG_WARNING,
  345. "invalid %s request -- bad URL encoding: %s", meth, url);
  346. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  347. goto out;
  348. }
  349. if (strlen(meth) == 3) { /* GET */
  350. if ((getbio = BIO_new_mem_buf(url, len)) == NULL
  351. || (b64 = BIO_new(BIO_f_base64())) == NULL) {
  352. log_HTTP1(prog, LOG_ERR,
  353. "could not allocate base64 bio with size = %d", len);
  354. goto fatal;
  355. }
  356. BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
  357. getbio = BIO_push(b64, getbio);
  358. }
  359. } else {
  360. log_HTTP2(prog, LOG_WARNING,
  361. "HTTP request does not begin with %sPOST: %s",
  362. accept_get ? "GET or " : "", reqbuf);
  363. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  364. goto out;
  365. }
  366. /* chop any further/duplicate leading or trailing '/' */
  367. while (*url == '/')
  368. url++;
  369. while (end >= url + 2 && end[-2] == '/' && end[-1] == '/')
  370. end--;
  371. *end = '\0';
  372. /* Read and skip past the headers. */
  373. for (;;) {
  374. char *key, *value;
  375. len = BIO_gets(cbio, inbuf, sizeof(inbuf));
  376. if (len <= 0) {
  377. log_HTTP(prog, LOG_WARNING, "error reading HTTP header");
  378. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  379. goto out;
  380. }
  381. if (((end = strchr(inbuf, '\r')) != NULL && end[1] == '\n')
  382. || (end = strchr(inbuf, '\n')) != NULL)
  383. *end = '\0';
  384. log_HTTP1(prog, LOG_TRACE, "%s", *inbuf == '\0' ?
  385. " " /* workaround for "" getting ignored */ : inbuf);
  386. if (end == NULL) {
  387. log_HTTP(prog, LOG_WARNING,
  388. "error parsing HTTP header: missing end of line");
  389. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  390. goto out;
  391. }
  392. if (inbuf[0] == '\0')
  393. break;
  394. key = inbuf;
  395. value = strchr(key, ':');
  396. if (value == NULL) {
  397. log_HTTP(prog, LOG_WARNING,
  398. "error parsing HTTP header: missing ':'");
  399. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  400. goto out;
  401. }
  402. *(value++) = '\0';
  403. while (*value == ' ')
  404. value++;
  405. /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
  406. if (found_keep_alive != NULL
  407. && OPENSSL_strcasecmp(key, "Connection") == 0) {
  408. if (OPENSSL_strcasecmp(value, "keep-alive") == 0)
  409. *found_keep_alive = 1;
  410. else if (OPENSSL_strcasecmp(value, "close") == 0)
  411. *found_keep_alive = 0;
  412. }
  413. }
  414. # ifdef HTTP_DAEMON
  415. /* Clear alarm before we close the client socket */
  416. alarm(0);
  417. timeout = 0;
  418. # endif
  419. /* Try to read and parse request */
  420. req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL);
  421. if (req == NULL) {
  422. log_HTTP(prog, LOG_WARNING,
  423. "error parsing DER-encoded request content");
  424. (void)http_server_send_status(prog, cbio, 400, "Bad Request");
  425. } else if (ppath != NULL && (*ppath = OPENSSL_strdup(url)) == NULL) {
  426. log_HTTP1(prog, LOG_ERR,
  427. "out of memory allocating %zu bytes", strlen(url) + 1);
  428. ASN1_item_free(req, it);
  429. goto fatal;
  430. }
  431. *preq = req;
  432. out:
  433. BIO_free_all(getbio);
  434. # ifdef HTTP_DAEMON
  435. if (timeout > 0)
  436. alarm(0);
  437. acfd = (int)INVALID_SOCKET;
  438. # endif
  439. return ret;
  440. fatal:
  441. (void)http_server_send_status(prog, cbio, 500, "Internal Server Error");
  442. if (ppath != NULL) {
  443. OPENSSL_free(*ppath);
  444. *ppath = NULL;
  445. }
  446. BIO_free_all(cbio);
  447. *pcbio = NULL;
  448. ret = -1;
  449. goto out;
  450. }
  451. /* assumes that cbio does not do an encoding that changes the output length */
  452. int http_server_send_asn1_resp(const char *prog, BIO *cbio, int keep_alive,
  453. const char *content_type,
  454. const ASN1_ITEM *it, const ASN1_VALUE *resp)
  455. {
  456. char buf[200], *p;
  457. int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" 200 OK\r\n%s"
  458. "Content-type: %s\r\n"
  459. "Content-Length: %d\r\n",
  460. keep_alive ? "Connection: keep-alive\r\n" : "",
  461. content_type,
  462. ASN1_item_i2d(resp, NULL, it));
  463. if (ret < 0 || (size_t)ret >= sizeof(buf))
  464. return 0;
  465. if (log_get_verbosity() < LOG_TRACE && (p = strchr(buf, '\r')) != NULL)
  466. trace_log_message(-1, prog, LOG_INFO,
  467. "sending response, 1st line: %.*s", (int)(p - buf),
  468. buf);
  469. log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
  470. ret = BIO_printf(cbio, "%s\r\n", buf) > 0
  471. && ASN1_item_i2d_bio(it, cbio, resp) > 0;
  472. (void)BIO_flush(cbio);
  473. return ret;
  474. }
  475. int http_server_send_status(const char *prog, BIO *cbio,
  476. int status, const char *reason)
  477. {
  478. char buf[200];
  479. int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" %d %s\r\n\r\n",
  480. /* This implicitly cancels keep-alive */
  481. status, reason);
  482. if (ret < 0 || (size_t)ret >= sizeof(buf))
  483. return 0;
  484. log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
  485. ret = BIO_printf(cbio, "%s\r\n", buf) > 0;
  486. (void)BIO_flush(cbio);
  487. return ret;
  488. }
  489. #endif