2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
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
10 /* Very basic HTTP server */
12 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
14 * On VMS, you need to define this to get the declaration of fileno(). The
15 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
17 # define _POSIX_C_SOURCE 2
21 #include "http_server.h"
22 #include "internal/sockets.h"
23 #include <openssl/err.h>
24 #include <openssl/trace.h>
25 #include <openssl/rand.h>
30 # if defined(OPENSSL_TANDEM_FLOSS)
31 # include <floss.h(floss_fork)>
35 #define HTTP_PREFIX "HTTP/"
36 #define HTTP_VERSION_PATT "1." /* allow 1.x */
37 #define HTTP_PREFIX_VERSION HTTP_PREFIX""HTTP_VERSION_PATT
38 #define HTTP_1_0 HTTP_PREFIX_VERSION"0" /* "HTTP/1.0" */
39 #define HTTP_VERSION_STR " "HTTP_PREFIX_VERSION
41 #define log_HTTP(prog, level, text) \
42 trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, "%s", text)
43 #define log_HTTP1(prog, level, fmt, arg) \
44 trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, arg)
45 #define log_HTTP2(prog, level, fmt, arg1, arg2) \
46 trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, arg1, arg2)
47 #define log_HTTP3(prog, level, fmt, a1, a2, a3) \
48 trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, a1, a2, a3)
51 int n_responders = 0; /* run multiple responder processes, set by ocsp.c */
52 int acfd = (int)INVALID_SOCKET;
54 void socket_timeout(int signum)
56 if (acfd != (int)INVALID_SOCKET)
57 (void)shutdown(acfd, SHUT_RD);
60 static void killall(int ret, pid_t *kidpids)
64 for (i = 0; i < n_responders; ++i)
66 (void)kill(kidpids[i], SIGTERM);
67 OPENSSL_free(kidpids);
72 static int termsig = 0;
74 static void noteterm(int sig)
80 * Loop spawning up to `multi` child processes, only child processes return
81 * from this function. The parent process loops until receiving a termination
82 * signal, kills extant children and exits without returning.
84 void spawn_loop(const char *prog)
86 pid_t *kidpids = NULL;
91 openlog(prog, LOG_PID, LOG_DAEMON);
94 log_HTTP1(prog, LOG_CRIT,
95 "error detaching from parent process group: %s",
99 kidpids = app_malloc(n_responders * sizeof(*kidpids), "child PID array");
100 for (i = 0; i < n_responders; ++i)
103 signal(SIGINT, noteterm);
104 signal(SIGTERM, noteterm);
106 while (termsig == 0) {
110 * Wait for a child to replace when we're at the limit.
111 * Slow down if a child exited abnormally or waitpid() < 0
113 while (termsig == 0 && procs >= n_responders) {
114 if ((fpid = waitpid(-1, &status, 0)) > 0) {
115 for (i = 0; i < procs; ++i) {
116 if (kidpids[i] == fpid) {
122 if (i >= n_responders) {
123 log_HTTP1(prog, LOG_CRIT,
124 "internal error: no matching child slot for pid: %ld",
129 if (WIFEXITED(status)) {
130 log_HTTP2(prog, LOG_WARNING,
131 "child process: %ld, exit status: %d",
132 (long)fpid, WEXITSTATUS(status));
133 } else if (WIFSIGNALED(status)) {
137 if (WCOREDUMP(status))
138 dumped = " (core dumped)";
140 log_HTTP3(prog, LOG_WARNING,
141 "child process: %ld, term signal %d%s",
142 (long)fpid, WTERMSIG(status), dumped);
147 } else if (errno != EINTR) {
148 log_HTTP1(prog, LOG_CRIT,
149 "waitpid() failed: %s", strerror(errno));
156 switch (fpid = fork()) {
158 /* System critically low on memory, pause and try again later */
162 OPENSSL_free(kidpids);
163 signal(SIGINT, SIG_DFL);
164 signal(SIGTERM, SIG_DFL);
167 if (RAND_poll() <= 0) {
168 log_HTTP(prog, LOG_CRIT, "RAND_poll() failed");
172 default: /* parent */
173 for (i = 0; i < n_responders; ++i) {
174 if (kidpids[i] == 0) {
180 if (i >= n_responders) {
181 log_HTTP(prog, LOG_CRIT,
182 "internal error: no free child slots");
189 /* The loop above can only break on termsig */
190 log_HTTP1(prog, LOG_INFO, "terminating on signal: %d", termsig);
195 #ifndef OPENSSL_NO_SOCK
196 BIO *http_server_init(const char *prog, const char *port, int verb)
198 BIO *acbio = NULL, *bufbio;
202 if (verb >= 0 && !log_set_verbosity(prog, verb))
204 bufbio = BIO_new(BIO_f_buffer());
207 acbio = BIO_new(BIO_s_accept());
209 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
210 || BIO_set_accept_port(acbio, port /* may be "0" */) < 0) {
211 log_HTTP(prog, LOG_ERR, "error setting up accept BIO");
215 BIO_set_accept_bios(acbio, bufbio);
217 if (BIO_do_accept(acbio) <= 0) {
218 log_HTTP1(prog, LOG_ERR, "error setting accept on port %s", port);
222 /* Report back what address and port are used */
223 BIO_get_fd(acbio, &asock);
224 port_num = report_server_accept(bio_out, asock, 1, 1);
226 log_HTTP(prog, LOG_ERR, "error printing ACCEPT string");
233 ERR_print_errors(bio_err);
240 * Decode %xx URL-decoding in-place. Ignores malformed sequences.
242 static int urldecode(char *p)
244 unsigned char *out = (unsigned char *)p;
245 unsigned char *save = out;
250 } else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
251 /* Don't check, can't fail because of ixdigit() call. */
252 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
253 | OPENSSL_hexchar2int(p[2]);
260 return (int)(out - save);
263 /* if *pcbio != NULL, continue given connected session, else accept new */
264 /* if found_keep_alive != NULL, return this way connection persistence state */
265 int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq,
266 char **ppath, BIO **pcbio, BIO *acbio,
267 int *found_keep_alive,
268 const char *prog, int accept_get, int timeout)
270 BIO *cbio = *pcbio, *getbio = NULL, *b64 = NULL;
272 char reqbuf[2048], inbuf[2048];
273 char *meth, *url, *end;
284 get_sock_info_address(BIO_get_fd(acbio, NULL), NULL, &port);
286 log_HTTP(prog, LOG_ERR, "cannot get port listening on");
289 log_HTTP1(prog, LOG_DEBUG,
290 "awaiting new connection on port %s ...", port);
293 if (BIO_do_accept(acbio) <= 0)
294 /* Connection loss before accept() is routine, ignore silently */
297 *pcbio = cbio = BIO_pop(acbio);
299 log_HTTP(prog, LOG_DEBUG, "awaiting next request ...");
302 /* Cannot call http_server_send_status(..., cbio, ...) */
309 (void)BIO_get_fd(cbio, &acfd);
314 /* Read the request line. */
315 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
320 log_HTTP(prog, LOG_WARNING, "request line read error");
321 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
325 if (((end = strchr(reqbuf, '\r')) != NULL && end[1] == '\n')
326 || (end = strchr(reqbuf, '\n')) != NULL)
328 if (log_get_verbosity() < LOG_TRACE)
329 trace_log_message(-1, prog, LOG_INFO,
330 "received request, 1st line: %s", reqbuf);
331 log_HTTP(prog, LOG_TRACE, "received request header:");
332 log_HTTP1(prog, LOG_TRACE, "%s", reqbuf);
334 log_HTTP(prog, LOG_WARNING,
335 "cannot parse HTTP header: missing end of line");
336 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
341 if ((accept_get && CHECK_AND_SKIP_PREFIX(url, "GET "))
342 || CHECK_AND_SKIP_PREFIX(url, "POST ")) {
344 /* Expecting (GET|POST) {sp} /URL {sp} HTTP/1.x */
349 log_HTTP2(prog, LOG_WARNING,
350 "invalid %s -- URL does not begin with '/': %s",
352 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
357 /* Splice off the HTTP version identifier. */
358 for (end = url; *end != '\0'; end++)
361 if (!HAS_PREFIX(end, HTTP_VERSION_STR)) {
362 log_HTTP2(prog, LOG_WARNING,
363 "invalid %s -- bad HTTP/version string: %s",
365 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
369 /* above HTTP 1.0, connection persistence is the default */
370 if (found_keep_alive != NULL)
371 *found_keep_alive = end[sizeof(HTTP_VERSION_STR) - 1] > '0';
374 * Skip "GET / HTTP..." requests often used by load-balancers.
375 * 'url' was incremented above to point to the first byte *after*
376 * the leading slash, so in case 'GET / ' it is now an empty string.
378 if (strlen(meth) == 3 && url[0] == '\0') {
379 (void)http_server_send_status(prog, cbio, 200, "OK");
383 len = urldecode(url);
385 log_HTTP2(prog, LOG_WARNING,
386 "invalid %s request -- bad URL encoding: %s", meth, url);
387 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
390 if (strlen(meth) == 3) { /* GET */
391 if ((getbio = BIO_new_mem_buf(url, len)) == NULL
392 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
393 log_HTTP1(prog, LOG_ERR,
394 "could not allocate base64 bio with size = %d", len);
397 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
398 getbio = BIO_push(b64, getbio);
401 log_HTTP2(prog, LOG_WARNING,
402 "HTTP request does not begin with %sPOST: %s",
403 accept_get ? "GET or " : "", reqbuf);
404 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
408 /* chop any further/duplicate leading or trailing '/' */
411 while (end >= url + 2 && end[-2] == '/' && end[-1] == '/')
415 /* Read and skip past the headers. */
419 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
421 log_HTTP(prog, LOG_WARNING, "error reading HTTP header");
422 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
426 if (((end = strchr(inbuf, '\r')) != NULL && end[1] == '\n')
427 || (end = strchr(inbuf, '\n')) != NULL)
429 log_HTTP1(prog, LOG_TRACE, "%s", *inbuf == '\0' ?
430 " " /* workaround for "" getting ignored */ : inbuf);
432 log_HTTP(prog, LOG_WARNING,
433 "error parsing HTTP header: missing end of line");
434 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
438 if (inbuf[0] == '\0')
442 value = strchr(key, ':');
444 log_HTTP(prog, LOG_WARNING,
445 "error parsing HTTP header: missing ':'");
446 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
450 while (*value == ' ')
452 /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
453 if (found_keep_alive != NULL
454 && OPENSSL_strcasecmp(key, "Connection") == 0) {
455 if (OPENSSL_strcasecmp(value, "keep-alive") == 0)
456 *found_keep_alive = 1;
457 else if (OPENSSL_strcasecmp(value, "close") == 0)
458 *found_keep_alive = 0;
463 /* Clear alarm before we close the client socket */
468 /* Try to read and parse request */
469 req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL);
471 log_HTTP(prog, LOG_WARNING,
472 "error parsing DER-encoded request content");
473 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
474 } else if (ppath != NULL && (*ppath = OPENSSL_strdup(url)) == NULL) {
475 log_HTTP1(prog, LOG_ERR,
476 "out of memory allocating %zu bytes", strlen(url) + 1);
477 ASN1_item_free(req, it);
484 BIO_free_all(getbio);
488 acfd = (int)INVALID_SOCKET;
493 (void)http_server_send_status(prog, cbio, 500, "Internal Server Error");
495 OPENSSL_free(*ppath);
504 /* assumes that cbio does not do an encoding that changes the output length */
505 int http_server_send_asn1_resp(const char *prog, BIO *cbio, int keep_alive,
506 const char *content_type,
507 const ASN1_ITEM *it, const ASN1_VALUE *resp)
510 int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" 200 OK\r\n%s"
511 "Content-type: %s\r\n"
512 "Content-Length: %d\r\n",
513 keep_alive ? "Connection: keep-alive\r\n" : "",
515 ASN1_item_i2d(resp, NULL, it));
517 if (ret < 0 || (size_t)ret >= sizeof(buf))
519 if (log_get_verbosity() < LOG_TRACE && (p = strchr(buf, '\r')) != NULL)
520 trace_log_message(-1, prog, LOG_INFO,
521 "sending response, 1st line: %.*s", (int)(p - buf),
523 log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
525 ret = BIO_printf(cbio, "%s\r\n", buf) > 0
526 && ASN1_item_i2d_bio(it, cbio, resp) > 0;
528 (void)BIO_flush(cbio);
532 int http_server_send_status(const char *prog, BIO *cbio,
533 int status, const char *reason)
536 int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" %d %s\r\n\r\n",
537 /* This implicitly cancels keep-alive */
540 if (ret < 0 || (size_t)ret >= sizeof(buf))
542 log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
544 ret = BIO_printf(cbio, "%s\r\n", buf) > 0;
545 (void)BIO_flush(cbio);