2 * Copyright 1995-2020 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
22 #include "http_server.h"
23 #include "internal/sockets.h"
24 #include <openssl/err.h>
25 #include <openssl/rand.h>
27 int multi = 0; /* run multiple responder processes */
30 int acfd = (int) INVALID_SOCKET;
34 static int print_syslog(const char *str, size_t len, void *levPtr)
36 int level = *(int *)levPtr;
37 int ilen = len > MAXERRLEN ? MAXERRLEN : len;
39 syslog(level, "%.*s", ilen, str);
45 void log_message(const char *prog, int level, const char *fmt, ...)
54 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0)
55 syslog(level, "%s", buf);
57 ERR_print_errors_cb(print_syslog, &level);
61 BIO_printf(bio_err, "%s: ", prog);
62 BIO_vprintf(bio_err, fmt, ap);
63 BIO_printf(bio_err, "\n");
69 void socket_timeout(int signum)
71 if (acfd != (int)INVALID_SOCKET)
72 (void)shutdown(acfd, SHUT_RD);
75 static void killall(int ret, pid_t *kidpids)
79 for (i = 0; i < multi; ++i)
81 (void)kill(kidpids[i], SIGTERM);
82 OPENSSL_free(kidpids);
87 static int termsig = 0;
89 static void noteterm(int sig)
95 * Loop spawning up to `multi` child processes, only child processes return
96 * from this function. The parent process loops until receiving a termination
97 * signal, kills extant children and exits without returning.
99 void spawn_loop(const char *prog)
101 pid_t *kidpids = NULL;
106 openlog(prog, LOG_PID, LOG_DAEMON);
109 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
113 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
114 for (i = 0; i < multi; ++i)
117 signal(SIGINT, noteterm);
118 signal(SIGTERM, noteterm);
120 while (termsig == 0) {
124 * Wait for a child to replace when we're at the limit.
125 * Slow down if a child exited abnormally or waitpid() < 0
127 while (termsig == 0 && procs >= multi) {
128 if ((fpid = waitpid(-1, &status, 0)) > 0) {
129 for (i = 0; i < procs; ++i) {
130 if (kidpids[i] == fpid) {
137 syslog(LOG_ERR, "fatal: internal error: "
138 "no matching child slot for pid: %ld",
143 if (WIFEXITED(status))
144 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
145 (long)fpid, WEXITSTATUS(status));
146 else if (WIFSIGNALED(status))
147 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
148 (long)fpid, WTERMSIG(status),
150 WCOREDUMP(status) ? " (core dumped)" :
156 } else if (errno != EINTR) {
157 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
164 switch (fpid = fork()) {
166 /* System critically low on memory, pause and try again later */
170 OPENSSL_free(kidpids);
171 signal(SIGINT, SIG_DFL);
172 signal(SIGTERM, SIG_DFL);
175 if (RAND_poll() <= 0) {
176 syslog(LOG_ERR, "fatal: RAND_poll() failed");
180 default: /* parent */
181 for (i = 0; i < multi; ++i) {
182 if (kidpids[i] == 0) {
189 syslog(LOG_ERR, "fatal: internal error: no free child slots");
196 /* The loop above can only break on termsig */
197 syslog(LOG_INFO, "terminating on signal: %d", termsig);
202 #ifndef OPENSSL_NO_SOCK
203 BIO *http_server_init_bio(const char *prog, const char *port)
205 BIO *acbio = NULL, *bufbio;
207 bufbio = BIO_new(BIO_f_buffer());
210 acbio = BIO_new(BIO_s_accept());
212 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
213 || BIO_set_accept_port(acbio, port) < 0) {
214 log_message(prog, LOG_ERR, "Error setting up accept BIO");
218 BIO_set_accept_bios(acbio, bufbio);
220 if (BIO_do_accept(acbio) <= 0) {
221 log_message(prog, LOG_ERR, "Error starting accept");
234 * Decode %xx URL-decoding in-place. Ignores malformed sequences.
236 static int urldecode(char *p)
238 unsigned char *out = (unsigned char *)p;
239 unsigned char *save = out;
244 } else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
245 /* Don't check, can't fail because of ixdigit() call. */
246 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
247 | OPENSSL_hexchar2int(p[2]);
254 return (int)(out - save);
257 int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq,
258 char **ppath, BIO **pcbio, BIO *acbio,
259 const char *prog, int accept_get, int timeout)
261 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
263 char reqbuf[2048], inbuf[2048];
264 char *meth, *url, *end;
273 /* Connection loss before accept() is routine, ignore silently */
274 if (BIO_do_accept(acbio) <= 0)
277 cbio = BIO_pop(acbio);
280 /* Cannot call http_server_send_status(cbio, ...) */
287 (void)BIO_get_fd(cbio, &acfd);
292 /* Read the request line. */
293 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
295 log_message(prog, LOG_INFO,
296 "Request line read error or empty request");
297 (void)http_server_send_status(cbio, 400, "Bad Request");
303 if ((accept_get && strncmp(meth, "GET ", 4) == 0)
304 || (url++, strncmp(meth, "POST ", 5) == 0)) {
305 /* Expecting (GET|POST) {sp} /URL {sp} HTTP/1.x */
310 log_message(prog, LOG_INFO,
311 "Invalid %s -- URL does not begin with '/': %s",
313 (void)http_server_send_status(cbio, 400, "Bad Request");
318 /* Splice off the HTTP version identifier. */
319 for (end = url; *end != '\0'; end++)
322 if (strncmp(end, " HTTP/1.", 7) != 0) {
323 log_message(prog, LOG_INFO,
324 "Invalid %s -- bad HTTP/version string: %s",
326 (void)http_server_send_status(cbio, 400, "Bad Request");
332 * Skip "GET / HTTP..." requests often used by load-balancers.
333 * 'url' was incremented above to point to the first byte *after*
334 * the leading slash, so in case 'GET / ' it is now an empty string.
336 if (strlen(meth) == 3 && url[0] == '\0') {
337 (void)http_server_send_status(cbio, 200, "OK");
341 len = urldecode(url);
343 log_message(prog, LOG_INFO,
344 "Invalid %s request -- bad URL encoding: %s",
346 (void)http_server_send_status(cbio, 400, "Bad Request");
349 if (strlen(meth) == 3) { /* GET */
350 if ((getbio = BIO_new_mem_buf(url, len)) == NULL
351 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
352 log_message(prog, LOG_ERR,
353 "Could not allocate base64 bio with size = %d",
357 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
358 getbio = BIO_push(b64, getbio);
361 log_message(prog, LOG_INFO,
362 "HTTP request does not start with GET/POST: %s", reqbuf);
363 /* TODO provide better diagnosis in case client tries TLS */
364 (void)http_server_send_status(cbio, 400, "Bad Request");
368 /* chop any further/duplicate leading or trailing '/' */
371 while (end >= url + 2 && end[-2] == '/' && end[-1] == '/')
375 /* Read and skip past the headers. */
377 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
379 log_message(prog, LOG_ERR,
380 "Error skipping remaining HTTP headers");
381 (void)http_server_send_status(cbio, 400, "Bad Request");
384 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
389 /* Clear alarm before we close the client socket */
394 /* Try to read and parse request */
395 req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL);
397 log_message(prog, LOG_ERR, "Error parsing request");
398 } else if (ppath != NULL && (*ppath = OPENSSL_strdup(url)) == NULL) {
399 log_message(prog, LOG_ERR,
400 "Out of memory allocating %zu bytes", strlen(url) + 1);
401 ASN1_item_free(req, it);
408 BIO_free_all(getbio);
412 acfd = (int)INVALID_SOCKET;
417 (void)http_server_send_status(cbio, 500, "Internal Server Error");
419 OPENSSL_free(*ppath);
428 /* assumes that cbio does not do an encoding that changes the output length */
429 int http_server_send_asn1_resp(BIO *cbio, const char *content_type,
430 const ASN1_ITEM *it, const ASN1_VALUE *resp)
432 int ret = BIO_printf(cbio, "HTTP/1.0 200 OK\r\nContent-type: %s\r\n"
433 "Content-Length: %d\r\n\r\n", content_type,
434 ASN1_item_i2d(resp, NULL, it)) > 0
435 && ASN1_item_i2d_bio(it, cbio, resp) > 0;
437 (void)BIO_flush(cbio);
441 int http_server_send_status(BIO *cbio, int status, const char *reason)
443 int ret = BIO_printf(cbio, "HTTP/1.0 %d %s\r\n\r\n", status, reason) > 0;
445 (void)BIO_flush(cbio);