http_server.c 17 KB

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