]> git.ipfire.org Git - thirdparty/openssl.git/blob - apps/lib/http_server.c
str[n]casecmp => OPENSSL_strncasecmp
[thirdparty/openssl.git] / apps / lib / http_server.c
1 /*
2 * Copyright 1995-2021 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 <ctype.h>
21 #include "http_server.h"
22 #include "internal/sockets.h"
23 #include <openssl/err.h>
24 #include <openssl/rand.h>
25 #include "s_apps.h"
26
27 #if defined(__TANDEM)
28 # if defined(OPENSSL_TANDEM_FLOSS)
29 # include <floss.h(floss_fork)>
30 # endif
31 #endif
32
33 static int verbosity = LOG_INFO;
34
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
40
41 #ifdef HTTP_DAEMON
42
43 int multi = 0; /* run multiple responder processes */
44 int acfd = (int) INVALID_SOCKET;
45
46 static int print_syslog(const char *str, size_t len, void *levPtr)
47 {
48 int level = *(int *)levPtr;
49 int ilen = len > MAXERRLEN ? MAXERRLEN : len;
50
51 syslog(level, "%.*s", ilen, str);
52
53 return ilen;
54 }
55 #endif
56
57 void log_message(const char *prog, int level, const char *fmt, ...)
58 {
59 va_list ap;
60
61 if (verbosity < level)
62 return;
63
64 va_start(ap, fmt);
65 #ifdef HTTP_DAEMON
66 if (multi) {
67 char buf[1024];
68
69 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0)
70 syslog(level, "%s", buf);
71 if (level <= LOG_ERR)
72 ERR_print_errors_cb(print_syslog, &level);
73 } else
74 #endif
75 {
76 BIO_printf(bio_err, "%s: ", prog);
77 BIO_vprintf(bio_err, fmt, ap);
78 BIO_printf(bio_err, "\n");
79 (void)BIO_flush(bio_err);
80 }
81 va_end(ap);
82 }
83
84 #ifdef HTTP_DAEMON
85 void socket_timeout(int signum)
86 {
87 if (acfd != (int)INVALID_SOCKET)
88 (void)shutdown(acfd, SHUT_RD);
89 }
90
91 static void killall(int ret, pid_t *kidpids)
92 {
93 int i;
94
95 for (i = 0; i < multi; ++i)
96 if (kidpids[i] != 0)
97 (void)kill(kidpids[i], SIGTERM);
98 OPENSSL_free(kidpids);
99 ossl_sleep(1000);
100 exit(ret);
101 }
102
103 static int termsig = 0;
104
105 static void noteterm(int sig)
106 {
107 termsig = sig;
108 }
109
110 /*
111 * Loop spawning up to `multi` child processes, only child processes return
112 * from this function. The parent process loops until receiving a termination
113 * signal, kills extant children and exits without returning.
114 */
115 void spawn_loop(const char *prog)
116 {
117 pid_t *kidpids = NULL;
118 int status;
119 int procs = 0;
120 int i;
121
122 openlog(prog, LOG_PID, LOG_DAEMON);
123
124 if (setpgid(0, 0)) {
125 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
126 strerror(errno));
127 exit(1);
128 }
129 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
130 for (i = 0; i < multi; ++i)
131 kidpids[i] = 0;
132
133 signal(SIGINT, noteterm);
134 signal(SIGTERM, noteterm);
135
136 while (termsig == 0) {
137 pid_t fpid;
138
139 /*
140 * Wait for a child to replace when we're at the limit.
141 * Slow down if a child exited abnormally or waitpid() < 0
142 */
143 while (termsig == 0 && procs >= multi) {
144 if ((fpid = waitpid(-1, &status, 0)) > 0) {
145 for (i = 0; i < procs; ++i) {
146 if (kidpids[i] == fpid) {
147 kidpids[i] = 0;
148 --procs;
149 break;
150 }
151 }
152 if (i >= multi) {
153 syslog(LOG_ERR, "fatal: internal error: "
154 "no matching child slot for pid: %ld",
155 (long) fpid);
156 killall(1, kidpids);
157 }
158 if (status != 0) {
159 if (WIFEXITED(status))
160 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
161 (long)fpid, WEXITSTATUS(status));
162 else if (WIFSIGNALED(status))
163 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
164 (long)fpid, WTERMSIG(status),
165 # ifdef WCOREDUMP
166 WCOREDUMP(status) ? " (core dumped)" :
167 # endif
168 "");
169 ossl_sleep(1000);
170 }
171 break;
172 } else if (errno != EINTR) {
173 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
174 killall(1, kidpids);
175 }
176 }
177 if (termsig)
178 break;
179
180 switch (fpid = fork()) {
181 case -1: /* error */
182 /* System critically low on memory, pause and try again later */
183 ossl_sleep(30000);
184 break;
185 case 0: /* child */
186 OPENSSL_free(kidpids);
187 signal(SIGINT, SIG_DFL);
188 signal(SIGTERM, SIG_DFL);
189 if (termsig)
190 _exit(0);
191 if (RAND_poll() <= 0) {
192 syslog(LOG_ERR, "fatal: RAND_poll() failed");
193 _exit(1);
194 }
195 return;
196 default: /* parent */
197 for (i = 0; i < multi; ++i) {
198 if (kidpids[i] == 0) {
199 kidpids[i] = fpid;
200 procs++;
201 break;
202 }
203 }
204 if (i >= multi) {
205 syslog(LOG_ERR, "fatal: internal error: no free child slots");
206 killall(1, kidpids);
207 }
208 break;
209 }
210 }
211
212 /* The loop above can only break on termsig */
213 syslog(LOG_INFO, "terminating on signal: %d", termsig);
214 killall(0, kidpids);
215 }
216 #endif
217
218 #ifndef OPENSSL_NO_SOCK
219 BIO *http_server_init(const char *prog, const char *port, int verb)
220 {
221 BIO *acbio = NULL, *bufbio;
222 int asock;
223 int port_num;
224
225 if (verb >= 0) {
226 if (verb > LOG_TRACE) {
227 log_message(prog, LOG_ERR,
228 "Logging verbosity level %d too high", verb);
229 return NULL;
230 }
231 verbosity = verb;
232 }
233 bufbio = BIO_new(BIO_f_buffer());
234 if (bufbio == NULL)
235 goto err;
236 acbio = BIO_new(BIO_s_accept());
237 if (acbio == NULL
238 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
239 || BIO_set_accept_port(acbio, port /* may be "0" */) < 0) {
240 log_message(prog, LOG_ERR, "Error setting up accept BIO");
241 goto err;
242 }
243
244 BIO_set_accept_bios(acbio, bufbio);
245 bufbio = NULL;
246 if (BIO_do_accept(acbio) <= 0) {
247 log_message(prog, LOG_ERR, "Error starting accept");
248 goto err;
249 }
250
251 /* Report back what address and port are used */
252 BIO_get_fd(acbio, &asock);
253 port_num = report_server_accept(bio_out, asock, 1, 1);
254 if (port_num == 0) {
255 log_message(prog, LOG_ERR, "Error printing ACCEPT string");
256 goto err;
257 }
258
259 return acbio;
260
261 err:
262 BIO_free_all(acbio);
263 BIO_free(bufbio);
264 return NULL;
265 }
266
267 /*
268 * Decode %xx URL-decoding in-place. Ignores malformed sequences.
269 */
270 static int urldecode(char *p)
271 {
272 unsigned char *out = (unsigned char *)p;
273 unsigned char *save = out;
274
275 for (; *p; p++) {
276 if (*p != '%') {
277 *out++ = *p;
278 } else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
279 /* Don't check, can't fail because of ixdigit() call. */
280 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
281 | OPENSSL_hexchar2int(p[2]);
282 p += 2;
283 } else {
284 return -1;
285 }
286 }
287 *out = '\0';
288 return (int)(out - save);
289 }
290
291 /* if *pcbio != NULL, continue given connected session, else accept new */
292 /* if found_keep_alive != NULL, return this way connection persistence state */
293 int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq,
294 char **ppath, BIO **pcbio, BIO *acbio,
295 int *found_keep_alive,
296 const char *prog, int accept_get, int timeout)
297 {
298 BIO *cbio = *pcbio, *getbio = NULL, *b64 = NULL;
299 int len;
300 char reqbuf[2048], inbuf[2048];
301 char *meth, *url, *end;
302 ASN1_VALUE *req;
303 int ret = 0;
304
305 *preq = NULL;
306 if (ppath != NULL)
307 *ppath = NULL;
308
309 if (cbio == NULL) {
310 char *port;
311
312 get_sock_info_address(BIO_get_fd(acbio, NULL), NULL, &port);
313 if (port == NULL) {
314 log_message(prog, LOG_ERR, "Cannot get port listening on");
315 goto fatal;
316 }
317 log_message(prog, LOG_DEBUG,
318 "Awaiting new connection on port %s ...", port);
319 OPENSSL_free(port);
320
321 if (BIO_do_accept(acbio) <= 0)
322 /* Connection loss before accept() is routine, ignore silently */
323 return ret;
324
325 *pcbio = cbio = BIO_pop(acbio);
326 } else {
327 log_message(prog, LOG_DEBUG, "Awaiting next request ...");
328 }
329 if (cbio == NULL) {
330 /* Cannot call http_server_send_status(cbio, ...) */
331 ret = -1;
332 goto out;
333 }
334
335 # ifdef HTTP_DAEMON
336 if (timeout > 0) {
337 (void)BIO_get_fd(cbio, &acfd);
338 alarm(timeout);
339 }
340 # endif
341
342 /* Read the request line. */
343 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
344 if (len == 0)
345 return ret;
346 ret = 1;
347 if (len < 0) {
348 log_message(prog, LOG_WARNING, "Request line read error");
349 (void)http_server_send_status(cbio, 400, "Bad Request");
350 goto out;
351 }
352 if ((end = strchr(reqbuf, '\r')) != NULL
353 || (end = strchr(reqbuf, '\n')) != NULL)
354 *end = '\0';
355 log_message(prog, LOG_INFO, "Received request, 1st line: %s", reqbuf);
356
357 url = meth = reqbuf;
358 if ((accept_get && CHECK_AND_SKIP_PREFIX(url, "GET "))
359 || CHECK_AND_SKIP_PREFIX(url, "POST ")) {
360
361 /* Expecting (GET|POST) {sp} /URL {sp} HTTP/1.x */
362 url[-1] = '\0';
363 while (*url == ' ')
364 url++;
365 if (*url != '/') {
366 log_message(prog, LOG_WARNING,
367 "Invalid %s -- URL does not begin with '/': %s",
368 meth, url);
369 (void)http_server_send_status(cbio, 400, "Bad Request");
370 goto out;
371 }
372 url++;
373
374 /* Splice off the HTTP version identifier. */
375 for (end = url; *end != '\0'; end++)
376 if (*end == ' ')
377 break;
378 if (!HAS_PREFIX(end, HTTP_VERSION_STR)) {
379 log_message(prog, LOG_WARNING,
380 "Invalid %s -- bad HTTP/version string: %s",
381 meth, end + 1);
382 (void)http_server_send_status(cbio, 400, "Bad Request");
383 goto out;
384 }
385 *end = '\0';
386 /* above HTTP 1.0, connection persistence is the default */
387 if (found_keep_alive != NULL)
388 *found_keep_alive = end[sizeof(HTTP_VERSION_STR) - 1] > '0';
389
390 /*-
391 * Skip "GET / HTTP..." requests often used by load-balancers.
392 * 'url' was incremented above to point to the first byte *after*
393 * the leading slash, so in case 'GET / ' it is now an empty string.
394 */
395 if (strlen(meth) == 3 && url[0] == '\0') {
396 (void)http_server_send_status(cbio, 200, "OK");
397 goto out;
398 }
399
400 len = urldecode(url);
401 if (len < 0) {
402 log_message(prog, LOG_WARNING,
403 "Invalid %s request -- bad URL encoding: %s",
404 meth, url);
405 (void)http_server_send_status(cbio, 400, "Bad Request");
406 goto out;
407 }
408 if (strlen(meth) == 3) { /* GET */
409 if ((getbio = BIO_new_mem_buf(url, len)) == NULL
410 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
411 log_message(prog, LOG_ERR,
412 "Could not allocate base64 bio with size = %d",
413 len);
414 goto fatal;
415 }
416 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
417 getbio = BIO_push(b64, getbio);
418 }
419 } else {
420 log_message(prog, LOG_WARNING,
421 "HTTP request does not begin with %sPOST: %s",
422 accept_get ? "GET or " : "", reqbuf);
423 (void)http_server_send_status(cbio, 400, "Bad Request");
424 goto out;
425 }
426
427 /* chop any further/duplicate leading or trailing '/' */
428 while (*url == '/')
429 url++;
430 while (end >= url + 2 && end[-2] == '/' && end[-1] == '/')
431 end--;
432 *end = '\0';
433
434 /* Read and skip past the headers. */
435 for (;;) {
436 char *key, *value, *line_end = NULL;
437
438 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
439 if (len <= 0) {
440 log_message(prog, LOG_WARNING, "Error reading HTTP header");
441 (void)http_server_send_status(cbio, 400, "Bad Request");
442 goto out;
443 }
444
445 if (inbuf[0] == '\r' || inbuf[0] == '\n')
446 break;
447
448 key = inbuf;
449 value = strchr(key, ':');
450 if (value == NULL) {
451 log_message(prog, LOG_WARNING,
452 "Error parsing HTTP header: missing ':'");
453 (void)http_server_send_status(cbio, 400, "Bad Request");
454 goto out;
455 }
456 *(value++) = '\0';
457 while (*value == ' ')
458 value++;
459 line_end = strchr(value, '\r');
460 if (line_end == NULL) {
461 line_end = strchr(value, '\n');
462 if (line_end == NULL) {
463 log_message(prog, LOG_WARNING,
464 "Error parsing HTTP header: missing end of line");
465 (void)http_server_send_status(cbio, 400, "Bad Request");
466 goto out;
467 }
468 }
469 *line_end = '\0';
470 /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
471 if (found_keep_alive != NULL
472 && OPENSSL_strcasecmp(key, "Connection") == 0) {
473 if (OPENSSL_strcasecmp(value, "keep-alive") == 0)
474 *found_keep_alive = 1;
475 else if (OPENSSL_strcasecmp(value, "close") == 0)
476 *found_keep_alive = 0;
477 }
478 }
479
480 # ifdef HTTP_DAEMON
481 /* Clear alarm before we close the client socket */
482 alarm(0);
483 timeout = 0;
484 # endif
485
486 /* Try to read and parse request */
487 req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL);
488 if (req == NULL) {
489 log_message(prog, LOG_WARNING,
490 "Error parsing DER-encoded request content");
491 (void)http_server_send_status(cbio, 400, "Bad Request");
492 } else if (ppath != NULL && (*ppath = OPENSSL_strdup(url)) == NULL) {
493 log_message(prog, LOG_ERR,
494 "Out of memory allocating %zu bytes", strlen(url) + 1);
495 ASN1_item_free(req, it);
496 goto fatal;
497 }
498
499 *preq = req;
500
501 out:
502 BIO_free_all(getbio);
503 # ifdef HTTP_DAEMON
504 if (timeout > 0)
505 alarm(0);
506 acfd = (int)INVALID_SOCKET;
507 # endif
508 return ret;
509
510 fatal:
511 (void)http_server_send_status(cbio, 500, "Internal Server Error");
512 if (ppath != NULL) {
513 OPENSSL_free(*ppath);
514 *ppath = NULL;
515 }
516 BIO_free_all(cbio);
517 *pcbio = NULL;
518 ret = -1;
519 goto out;
520 }
521
522 /* assumes that cbio does not do an encoding that changes the output length */
523 int http_server_send_asn1_resp(BIO *cbio, int keep_alive,
524 const char *content_type,
525 const ASN1_ITEM *it, const ASN1_VALUE *resp)
526 {
527 int ret = BIO_printf(cbio, HTTP_1_0" 200 OK\r\n%s"
528 "Content-type: %s\r\n"
529 "Content-Length: %d\r\n\r\n",
530 keep_alive ? "Connection: keep-alive\r\n" : "",
531 content_type,
532 ASN1_item_i2d(resp, NULL, it)) > 0
533 && ASN1_item_i2d_bio(it, cbio, resp) > 0;
534
535 (void)BIO_flush(cbio);
536 return ret;
537 }
538
539 int http_server_send_status(BIO *cbio, int status, const char *reason)
540 {
541 int ret = BIO_printf(cbio, HTTP_1_0" %d %s\r\n\r\n",
542 /* This implicitly cancels keep-alive */
543 status, reason) > 0;
544
545 (void)BIO_flush(cbio);
546 return ret;
547 }
548 #endif