2 * Copyright 1995-2023 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>
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
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)
45 int n_responders = 0; /* run multiple responder processes, set by ocsp.c */
46 int acfd = (int)INVALID_SOCKET;
48 void socket_timeout(int signum)
50 if (acfd != (int)INVALID_SOCKET)
51 (void)shutdown(acfd, SHUT_RD);
54 static void killall(int ret, pid_t *kidpids)
58 for (i = 0; i < n_responders; ++i)
60 (void)kill(kidpids[i], SIGTERM);
61 OPENSSL_free(kidpids);
66 static int termsig = 0;
68 static void noteterm(int sig)
74 * Loop spawning up to `multi` child processes, only child processes return
75 * from this function. The parent process loops until receiving a termination
76 * signal, kills extant children and exits without returning.
78 void spawn_loop(const char *prog)
80 pid_t *kidpids = NULL;
85 openlog(prog, LOG_PID, LOG_DAEMON);
88 log_HTTP1(prog, LOG_CRIT,
89 "error detaching from parent process group: %s",
93 kidpids = app_malloc(n_responders * sizeof(*kidpids), "child PID array");
94 for (i = 0; i < n_responders; ++i)
97 signal(SIGINT, noteterm);
98 signal(SIGTERM, noteterm);
100 while (termsig == 0) {
104 * Wait for a child to replace when we're at the limit.
105 * Slow down if a child exited abnormally or waitpid() < 0
107 while (termsig == 0 && procs >= n_responders) {
108 if ((fpid = waitpid(-1, &status, 0)) > 0) {
109 for (i = 0; i < procs; ++i) {
110 if (kidpids[i] == fpid) {
116 if (i >= n_responders) {
117 log_HTTP1(prog, LOG_CRIT,
118 "internal error: no matching child slot for pid: %ld",
123 if (WIFEXITED(status)) {
124 log_HTTP2(prog, LOG_WARNING,
125 "child process: %ld, exit status: %d",
126 (long)fpid, WEXITSTATUS(status));
127 } else if (WIFSIGNALED(status)) {
131 if (WCOREDUMP(status))
132 dumped = " (core dumped)";
134 log_HTTP3(prog, LOG_WARNING,
135 "child process: %ld, term signal %d%s",
136 (long)fpid, WTERMSIG(status), dumped);
141 } else if (errno != EINTR) {
142 log_HTTP1(prog, LOG_CRIT,
143 "waitpid() failed: %s", strerror(errno));
150 switch (fpid = fork()) {
152 /* System critically low on memory, pause and try again later */
156 OPENSSL_free(kidpids);
157 signal(SIGINT, SIG_DFL);
158 signal(SIGTERM, SIG_DFL);
161 if (RAND_poll() <= 0) {
162 log_HTTP(prog, LOG_CRIT, "RAND_poll() failed");
166 default: /* parent */
167 for (i = 0; i < n_responders; ++i) {
168 if (kidpids[i] == 0) {
174 if (i >= n_responders) {
175 log_HTTP(prog, LOG_CRIT,
176 "internal error: no free child slots");
183 /* The loop above can only break on termsig */
184 log_HTTP1(prog, LOG_INFO, "terminating on signal: %d", termsig);
189 #ifndef OPENSSL_NO_SOCK
190 BIO *http_server_init(const char *prog, const char *port, int verb)
192 BIO *acbio = NULL, *bufbio;
197 BIO_snprintf(name, sizeof(name), "*:%s", port); /* port may be "0" */
198 if (verb >= 0 && !log_set_verbosity(prog, verb))
200 bufbio = BIO_new(BIO_f_buffer());
203 acbio = BIO_new(BIO_s_accept());
205 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
206 || BIO_set_accept_name(acbio, name) < 0) {
207 log_HTTP(prog, LOG_ERR, "error setting up accept BIO");
211 BIO_set_accept_bios(acbio, bufbio);
213 if (BIO_do_accept(acbio) <= 0) {
214 log_HTTP1(prog, LOG_ERR, "error setting accept on port %s", port);
218 /* Report back what address and port are used */
219 BIO_get_fd(acbio, &asock);
220 port_num = report_server_accept(bio_out, asock, 1, 1);
222 log_HTTP(prog, LOG_ERR, "error printing ACCEPT string");
229 ERR_print_errors(bio_err);
236 * Decode %xx URL-decoding in-place. Ignores malformed sequences.
238 static int urldecode(char *p)
240 unsigned char *out = (unsigned char *)p;
241 unsigned char *save = out;
246 } else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
247 /* Don't check, can't fail because of ixdigit() call. */
248 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
249 | OPENSSL_hexchar2int(p[2]);
256 return (int)(out - save);
259 /* if *pcbio != NULL, continue given connected session, else accept new */
260 /* if found_keep_alive != NULL, return this way connection persistence state */
261 int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq,
262 char **ppath, BIO **pcbio, BIO *acbio,
263 int *found_keep_alive,
264 const char *prog, int accept_get, int timeout)
266 BIO *cbio = *pcbio, *getbio = NULL, *b64 = NULL;
268 char reqbuf[2048], inbuf[2048];
269 char *meth, *url, *end;
280 get_sock_info_address(BIO_get_fd(acbio, NULL), NULL, &port);
282 log_HTTP(prog, LOG_ERR, "cannot get port listening on");
285 log_HTTP1(prog, LOG_DEBUG,
286 "awaiting new connection on port %s ...", port);
289 if (BIO_do_accept(acbio) <= 0)
290 /* Connection loss before accept() is routine, ignore silently */
293 *pcbio = cbio = BIO_pop(acbio);
295 log_HTTP(prog, LOG_DEBUG, "awaiting next request ...");
298 /* Cannot call http_server_send_status(..., cbio, ...) */
305 (void)BIO_get_fd(cbio, &acfd);
310 /* Read the request line. */
311 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
316 log_HTTP(prog, LOG_WARNING, "request line read error");
317 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
321 if (((end = strchr(reqbuf, '\r')) != NULL && end[1] == '\n')
322 || (end = strchr(reqbuf, '\n')) != NULL)
324 if (log_get_verbosity() < LOG_TRACE)
325 trace_log_message(-1, prog, LOG_INFO,
326 "received request, 1st line: %s", reqbuf);
327 log_HTTP(prog, LOG_TRACE, "received request header:");
328 log_HTTP1(prog, LOG_TRACE, "%s", reqbuf);
330 log_HTTP(prog, LOG_WARNING,
331 "cannot parse HTTP header: missing end of line");
332 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
337 if ((accept_get && CHECK_AND_SKIP_PREFIX(url, "GET "))
338 || CHECK_AND_SKIP_PREFIX(url, "POST ")) {
340 /* Expecting (GET|POST) {sp} /URL {sp} HTTP/1.x */
345 log_HTTP2(prog, LOG_WARNING,
346 "invalid %s -- URL does not begin with '/': %s",
348 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
353 /* Splice off the HTTP version identifier. */
354 for (end = url; *end != '\0'; end++)
357 if (!HAS_PREFIX(end, HTTP_VERSION_STR)) {
358 log_HTTP2(prog, LOG_WARNING,
359 "invalid %s -- bad HTTP/version string: %s",
361 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
365 /* above HTTP 1.0, connection persistence is the default */
366 if (found_keep_alive != NULL)
367 *found_keep_alive = end[sizeof(HTTP_VERSION_STR) - 1] > '0';
370 * Skip "GET / HTTP..." requests often used by load-balancers.
371 * 'url' was incremented above to point to the first byte *after*
372 * the leading slash, so in case 'GET / ' it is now an empty string.
374 if (strlen(meth) == 3 && url[0] == '\0') {
375 (void)http_server_send_status(prog, cbio, 200, "OK");
379 len = urldecode(url);
381 log_HTTP2(prog, LOG_WARNING,
382 "invalid %s request -- bad URL encoding: %s", meth, url);
383 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
386 if (strlen(meth) == 3) { /* GET */
387 if ((getbio = BIO_new_mem_buf(url, len)) == NULL
388 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
389 log_HTTP1(prog, LOG_ERR,
390 "could not allocate base64 bio with size = %d", len);
393 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
394 getbio = BIO_push(b64, getbio);
397 log_HTTP2(prog, LOG_WARNING,
398 "HTTP request does not begin with %sPOST: %s",
399 accept_get ? "GET or " : "", reqbuf);
400 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
404 /* chop any further/duplicate leading or trailing '/' */
407 while (end >= url + 2 && end[-2] == '/' && end[-1] == '/')
411 /* Read and skip past the headers. */
415 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
417 log_HTTP(prog, LOG_WARNING, "error reading HTTP header");
418 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
422 if (((end = strchr(inbuf, '\r')) != NULL && end[1] == '\n')
423 || (end = strchr(inbuf, '\n')) != NULL)
425 log_HTTP1(prog, LOG_TRACE, "%s", *inbuf == '\0' ?
426 " " /* workaround for "" getting ignored */ : inbuf);
428 log_HTTP(prog, LOG_WARNING,
429 "error parsing HTTP header: missing end of line");
430 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
434 if (inbuf[0] == '\0')
438 value = strchr(key, ':');
440 log_HTTP(prog, LOG_WARNING,
441 "error parsing HTTP header: missing ':'");
442 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
446 while (*value == ' ')
448 /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
449 if (found_keep_alive != NULL
450 && OPENSSL_strcasecmp(key, "Connection") == 0) {
451 if (OPENSSL_strcasecmp(value, "keep-alive") == 0)
452 *found_keep_alive = 1;
453 else if (OPENSSL_strcasecmp(value, "close") == 0)
454 *found_keep_alive = 0;
459 /* Clear alarm before we close the client socket */
464 /* Try to read and parse request */
465 req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL);
467 log_HTTP(prog, LOG_WARNING,
468 "error parsing DER-encoded request content");
469 (void)http_server_send_status(prog, cbio, 400, "Bad Request");
470 } else if (ppath != NULL && (*ppath = OPENSSL_strdup(url)) == NULL) {
471 log_HTTP1(prog, LOG_ERR,
472 "out of memory allocating %zu bytes", strlen(url) + 1);
473 ASN1_item_free(req, it);
480 BIO_free_all(getbio);
484 acfd = (int)INVALID_SOCKET;
489 (void)http_server_send_status(prog, cbio, 500, "Internal Server Error");
491 OPENSSL_free(*ppath);
500 /* assumes that cbio does not do an encoding that changes the output length */
501 int http_server_send_asn1_resp(const char *prog, BIO *cbio, int keep_alive,
502 const char *content_type,
503 const ASN1_ITEM *it, const ASN1_VALUE *resp)
506 int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" 200 OK\r\n%s"
507 "Content-type: %s\r\n"
508 "Content-Length: %d\r\n",
509 keep_alive ? "Connection: keep-alive\r\n" : "",
511 ASN1_item_i2d(resp, NULL, it));
513 if (ret < 0 || (size_t)ret >= sizeof(buf))
515 if (log_get_verbosity() < LOG_TRACE && (p = strchr(buf, '\r')) != NULL)
516 trace_log_message(-1, prog, LOG_INFO,
517 "sending response, 1st line: %.*s", (int)(p - buf),
519 log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
521 ret = BIO_printf(cbio, "%s\r\n", buf) > 0
522 && ASN1_item_i2d_bio(it, cbio, resp) > 0;
524 (void)BIO_flush(cbio);
528 int http_server_send_status(const char *prog, BIO *cbio,
529 int status, const char *reason)
532 int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" %d %s\r\n\r\n",
533 /* This implicitly cancels keep-alive */
536 if (ret < 0 || (size_t)ret >= sizeof(buf))
538 log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
540 ret = BIO_printf(cbio, "%s\r\n", buf) > 0;
541 (void)BIO_flush(cbio);