http_server.c 17 KB

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