http_server.c 16 KB

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