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