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