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 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];
271 /* Connection loss before accept() is routine, ignore silently */
272 if (BIO_do_accept(acbio) <= 0)
275 cbio = BIO_pop(acbio);
284 (void)BIO_get_fd(cbio, &acfd);
289 /* Read the request line. */
290 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
294 if (accept_get && strncmp(reqbuf, "GET ", 4) == 0) {
295 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
296 for (url = reqbuf + 4; *url == ' '; ++url)
299 log_message(prog, LOG_INFO,
300 "Invalid GET -- URL does not begin with '/': %s", url);
305 /* Splice off the HTTP version identifier. */
306 for (end = url; *end != '\0'; end++)
309 if (strncmp(end, " HTTP/1.", 7) != 0) {
310 log_message(prog, LOG_INFO,
311 "Invalid GET -- bad HTTP/version string: %s", end + 1);
317 * Skip "GET / HTTP..." requests often used by load-balancers.
318 * 'url' was incremented above to point to the first byte *after*
319 * the leading slash, so in case 'GET / ' it is now an empty string.
324 len = urldecode(url);
326 log_message(prog, LOG_INFO,
327 "Invalid GET request -- bad URL encoding: %s", url);
330 if ((getbio = BIO_new_mem_buf(url, len)) == NULL
331 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
332 log_message(prog, LOG_ERR,
333 "Could not allocate base64 bio with size = %d", len);
339 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
340 getbio = BIO_push(b64, getbio);
341 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
342 log_message(prog, LOG_INFO,
343 "HTTP request does not start with GET/POST: %s", reqbuf);
344 /* TODO provide better diagnosis in case client tries TLS */
348 /* Read and skip past the headers. */
350 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
352 log_message(prog, LOG_ERR,
353 "Error skipping remaining HTTP headers");
356 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
361 /* Clear alarm before we close the client socket */
366 /* Try to read and parse request */
367 req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL);
369 log_message(prog, LOG_ERR, "Error parsing request");
374 BIO_free_all(getbio);
378 acfd = (int)INVALID_SOCKET;
383 /* assumes that cbio does not do an encoding that changes the output length */
384 int http_server_send_asn1_resp(BIO *cbio, const char *content_type,
385 const ASN1_ITEM *it, const ASN1_VALUE *resp)
387 int ret = BIO_printf(cbio, "HTTP/1.0 200 OK\r\nContent-type: %s\r\n"
388 "Content-Length: %d\r\n\r\n", content_type,
389 ASN1_item_i2d(resp, NULL, it)) > 0
390 && ASN1_item_i2d_bio(it, cbio, resp) > 0;
392 (void)BIO_flush(cbio);