[package] uhttpd: unblock signals in CGI childs, solves hanging ssh logout after...
[openwrt/svn-archive/archive.git] / package / uhttpd / src / uhttpd-cgi.c
1 /*
2 * uhttpd - Tiny single-threaded httpd - CGI handler
3 *
4 * Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "uhttpd.h"
20 #include "uhttpd-utils.h"
21 #include "uhttpd-cgi.h"
22
23 static struct http_response * uh_cgi_header_parse(char *buf, int len, int *off)
24 {
25 char *bufptr = NULL;
26 char *hdrname = NULL;
27 int hdrcount = 0;
28 int pos = 0;
29
30 static struct http_response res;
31
32
33 if( ((bufptr = strfind(buf, len, "\r\n\r\n", 4)) != NULL) ||
34 ((bufptr = strfind(buf, len, "\n\n", 2)) != NULL)
35 ) {
36 *off = (int)(bufptr - buf) + ((bufptr[0] == '\r') ? 4 : 2);
37
38 memset(&res, 0, sizeof(res));
39
40 res.statuscode = 200;
41 res.statusmsg = "OK";
42
43 bufptr = &buf[0];
44
45 for( pos = 0; pos < len; pos++ )
46 {
47 if( !hdrname && (buf[pos] == ':') )
48 {
49 buf[pos++] = 0;
50
51 if( (pos < len) && (buf[pos] == ' ') )
52 pos++;
53
54 if( pos < len )
55 {
56 hdrname = bufptr;
57 bufptr = &buf[pos];
58 }
59 }
60
61 else if( (buf[pos] == '\r') || (buf[pos] == '\n') )
62 {
63 buf[pos++] = 0;
64
65 if( ! hdrname )
66 break;
67
68 if( (pos < len) && (buf[pos] == '\n') )
69 pos++;
70
71 if( pos <= len )
72 {
73 if( (hdrcount + 1) < array_size(res.headers) )
74 {
75 if( ! strcasecmp(hdrname, "Status") )
76 {
77 res.statuscode = atoi(bufptr);
78
79 if( res.statuscode < 100 )
80 res.statuscode = 200;
81
82 if( ((bufptr = strchr(bufptr, ' ')) != NULL) && (&bufptr[1] != 0) )
83 res.statusmsg = &bufptr[1];
84 }
85 else
86 {
87 res.headers[hdrcount++] = hdrname;
88 res.headers[hdrcount++] = bufptr;
89 }
90
91 bufptr = &buf[pos];
92 hdrname = NULL;
93 }
94 else
95 {
96 return NULL;
97 }
98 }
99 }
100 }
101
102 return &res;
103 }
104
105 return NULL;
106 }
107
108 static char * uh_cgi_header_lookup(struct http_response *res, const char *hdrname)
109 {
110 int i;
111
112 foreach_header(i, res->headers)
113 {
114 if( ! strcasecmp(res->headers[i], hdrname) )
115 return res->headers[i+1];
116 }
117
118 return NULL;
119 }
120
121 static int uh_cgi_error_500(struct client *cl, struct http_request *req, const char *message)
122 {
123 if( uh_http_sendf(cl, NULL,
124 "HTTP/%.1f 500 Internal Server Error\r\n"
125 "Content-Type: text/plain\r\n%s\r\n",
126 req->version,
127 (req->version > 1.0)
128 ? "Transfer-Encoding: chunked\r\n" : ""
129 ) >= 0
130 ) {
131 return uh_http_send(cl, req, message, -1);
132 }
133
134 return -1;
135 }
136
137
138 void uh_cgi_request(
139 struct client *cl, struct http_request *req,
140 struct path_info *pi, struct interpreter *ip
141 ) {
142 int i, hdroff, bufoff, rv;
143 int hdrlen = 0;
144 int buflen = 0;
145 int fd_max = 0;
146 int content_length = 0;
147 int header_sent = 0;
148
149 int rfd[2] = { 0, 0 };
150 int wfd[2] = { 0, 0 };
151
152 char buf[UH_LIMIT_MSGHEAD];
153 char hdr[UH_LIMIT_MSGHEAD];
154
155 pid_t child;
156
157 fd_set reader;
158 fd_set writer;
159
160 sigset_t ss;
161
162 struct sigaction sa;
163 struct timeval timeout;
164 struct http_response *res;
165
166
167 /* spawn pipes for me->child, child->me */
168 if( (pipe(rfd) < 0) || (pipe(wfd) < 0) )
169 {
170 uh_http_sendhf(cl, 500, "Internal Server Error",
171 "Failed to create pipe: %s", strerror(errno));
172
173 if( rfd[0] > 0 ) close(rfd[0]);
174 if( rfd[1] > 0 ) close(rfd[1]);
175 if( wfd[0] > 0 ) close(wfd[0]);
176 if( wfd[1] > 0 ) close(wfd[1]);
177
178 return;
179 }
180
181 /* fork off child process */
182 switch( (child = fork()) )
183 {
184 /* oops */
185 case -1:
186 uh_http_sendhf(cl, 500, "Internal Server Error",
187 "Failed to fork child: %s", strerror(errno));
188 return;
189
190 /* exec child */
191 case 0:
192 /* unblock signals */
193 sigemptyset(&ss);
194 sigprocmask(SIG_SETMASK, &ss, NULL);
195
196 /* restore SIGTERM */
197 sa.sa_flags = 0;
198 sa.sa_handler = SIG_DFL;
199 sigemptyset(&sa.sa_mask);
200 sigaction(SIGTERM, &sa, NULL);
201
202 /* close loose pipe ends */
203 close(rfd[0]);
204 close(wfd[1]);
205
206 /* patch stdout and stdin to pipes */
207 dup2(rfd[1], 1);
208 dup2(wfd[0], 0);
209
210 /* avoid leaking our pipe into child-child processes */
211 fd_cloexec(rfd[1]);
212 fd_cloexec(wfd[0]);
213
214 /* check for regular, world-executable file _or_ interpreter */
215 if( ((pi->stat.st_mode & S_IFREG) &&
216 (pi->stat.st_mode & S_IXOTH)) || (ip != NULL)
217 ) {
218 /* build environment */
219 clearenv();
220
221 /* common information */
222 setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
223 setenv("SERVER_SOFTWARE", "uHTTPd", 1);
224 setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
225
226 #ifdef HAVE_TLS
227 /* https? */
228 if( cl->tls )
229 setenv("HTTPS", "on", 1);
230 #endif
231
232 /* addresses */
233 setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
234 setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
235 setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
236 setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
237 setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
238 setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
239
240 /* path information */
241 setenv("SCRIPT_NAME", pi->name, 1);
242 setenv("SCRIPT_FILENAME", pi->phys, 1);
243 setenv("DOCUMENT_ROOT", pi->root, 1);
244 setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
245
246 if( pi->info )
247 setenv("PATH_INFO", pi->info, 1);
248
249 /* REDIRECT_STATUS, php-cgi wants it */
250 switch( req->redirect_status )
251 {
252 case 404:
253 setenv("REDIRECT_STATUS", "404", 1);
254 break;
255
256 default:
257 setenv("REDIRECT_STATUS", "200", 1);
258 break;
259 }
260
261 /* http version */
262 if( req->version > 1.0 )
263 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
264 else
265 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
266
267 /* request method */
268 switch( req->method )
269 {
270 case UH_HTTP_MSG_GET:
271 setenv("REQUEST_METHOD", "GET", 1);
272 break;
273
274 case UH_HTTP_MSG_HEAD:
275 setenv("REQUEST_METHOD", "HEAD", 1);
276 break;
277
278 case UH_HTTP_MSG_POST:
279 setenv("REQUEST_METHOD", "POST", 1);
280 break;
281 }
282
283 /* request url */
284 setenv("REQUEST_URI", req->url, 1);
285
286 /* remote user */
287 if( req->realm )
288 setenv("REMOTE_USER", req->realm->user, 1);
289
290 /* request message headers */
291 foreach_header(i, req->headers)
292 {
293 if( ! strcasecmp(req->headers[i], "Accept") )
294 setenv("HTTP_ACCEPT", req->headers[i+1], 1);
295
296 else if( ! strcasecmp(req->headers[i], "Accept-Charset") )
297 setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
298
299 else if( ! strcasecmp(req->headers[i], "Accept-Encoding") )
300 setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
301
302 else if( ! strcasecmp(req->headers[i], "Accept-Language") )
303 setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
304
305 else if( ! strcasecmp(req->headers[i], "Authorization") )
306 setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
307
308 else if( ! strcasecmp(req->headers[i], "Connection") )
309 setenv("HTTP_CONNECTION", req->headers[i+1], 1);
310
311 else if( ! strcasecmp(req->headers[i], "Cookie") )
312 setenv("HTTP_COOKIE", req->headers[i+1], 1);
313
314 else if( ! strcasecmp(req->headers[i], "Host") )
315 setenv("HTTP_HOST", req->headers[i+1], 1);
316
317 else if( ! strcasecmp(req->headers[i], "Referer") )
318 setenv("HTTP_REFERER", req->headers[i+1], 1);
319
320 else if( ! strcasecmp(req->headers[i], "User-Agent") )
321 setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
322
323 else if( ! strcasecmp(req->headers[i], "Content-Type") )
324 setenv("CONTENT_TYPE", req->headers[i+1], 1);
325
326 else if( ! strcasecmp(req->headers[i], "Content-Length") )
327 setenv("CONTENT_LENGTH", req->headers[i+1], 1);
328 }
329
330
331 /* execute child code ... */
332 if( chdir(pi->root) )
333 perror("chdir()");
334
335 if( ip != NULL )
336 execl(ip->path, ip->path, pi->phys, NULL);
337 else
338 execl(pi->phys, pi->phys, NULL);
339
340 /* in case it fails ... */
341 printf(
342 "Status: 500 Internal Server Error\r\n\r\n"
343 "Unable to launch the requested CGI program:\n"
344 " %s: %s\n",
345 ip ? ip->path : pi->phys, strerror(errno)
346 );
347 }
348
349 /* 403 */
350 else
351 {
352 printf(
353 "Status: 403 Forbidden\r\n\r\n"
354 "Access to this resource is forbidden\n"
355 );
356 }
357
358 close(wfd[0]);
359 close(rfd[1]);
360 exit(0);
361
362 break;
363
364 /* parent; handle I/O relaying */
365 default:
366 /* close unneeded pipe ends */
367 close(rfd[1]);
368 close(wfd[0]);
369
370 /* max watch fd */
371 fd_max = max(rfd[0], wfd[1]) + 1;
372
373 /* find content length */
374 if( req->method == UH_HTTP_MSG_POST )
375 {
376 foreach_header(i, req->headers)
377 {
378 if( ! strcasecmp(req->headers[i], "Content-Length") )
379 {
380 content_length = atoi(req->headers[i+1]);
381 break;
382 }
383 }
384 }
385
386
387 memset(hdr, 0, sizeof(hdr));
388
389 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
390 while( 1 )
391 {
392 FD_ZERO(&reader);
393 FD_ZERO(&writer);
394
395 FD_SET(rfd[0], &reader);
396 FD_SET(wfd[1], &writer);
397
398 timeout.tv_sec = (header_sent < 1) ? cl->server->conf->script_timeout : 3;
399 timeout.tv_usec = 0;
400
401 ensure_out(rv = select_intr(fd_max, &reader,
402 (content_length > -1) ? &writer : NULL, NULL, &timeout));
403
404 /* timeout */
405 if( rv == 0 )
406 {
407 ensure_out(kill(child, 0));
408 }
409
410 /* wait until we can read or write or both */
411 else if( rv > 0 )
412 {
413 /* ready to write to cgi program */
414 if( FD_ISSET(wfd[1], &writer) )
415 {
416 /* there is unread post data waiting */
417 if( content_length > 0 )
418 {
419 /* read it from socket ... */
420 ensure_out(buflen = uh_tcp_recv(cl, buf,
421 min(content_length, sizeof(buf))));
422
423 if( buflen > 0 )
424 {
425 /* ... and write it to child's stdin */
426 if( write(wfd[1], buf, buflen) < 0 )
427 perror("write()");
428
429 content_length -= buflen;
430 }
431
432 /* unexpected eof! */
433 else
434 {
435 if( write(wfd[1], "", 0) < 0 )
436 perror("write()");
437
438 content_length = 0;
439 }
440 }
441
442 /* there is no more post data, close pipe to child's stdin */
443 else if( content_length > -1 )
444 {
445 close(wfd[1]);
446 content_length = -1;
447 }
448 }
449
450 /* ready to read from cgi program */
451 if( FD_ISSET(rfd[0], &reader) )
452 {
453 /* read data from child ... */
454 if( (buflen = read(rfd[0], buf, sizeof(buf))) > 0 )
455 {
456 /* we have not pushed out headers yet, parse input */
457 if( ! header_sent )
458 {
459 /* head buffer not full and no end yet */
460 if( hdrlen < sizeof(hdr) )
461 {
462 bufoff = min(buflen, sizeof(hdr) - hdrlen);
463 memcpy(&hdr[hdrlen], buf, bufoff);
464 hdrlen += bufoff;
465 }
466 else
467 {
468 bufoff = 0;
469 }
470
471
472 /* try to parse header ... */
473 if( (res = uh_cgi_header_parse(hdr, hdrlen, &hdroff)) != NULL )
474 {
475 /* write status */
476 ensure_out(uh_http_sendf(cl, NULL,
477 "HTTP/%.1f %03d %s\r\n"
478 "Connection: close\r\n",
479 req->version, res->statuscode,
480 res->statusmsg));
481
482 /* add Content-Type if no Location or Content-Type */
483 if( !uh_cgi_header_lookup(res, "Location") &&
484 !uh_cgi_header_lookup(res, "Content-Type")
485 ) {
486 ensure_out(uh_http_send(cl, NULL,
487 "Content-Type: text/plain\r\n", -1));
488 }
489
490 /* if request was HTTP 1.1 we'll respond chunked */
491 if( (req->version > 1.0) &&
492 !uh_cgi_header_lookup(res, "Transfer-Encoding")
493 ) {
494 ensure_out(uh_http_send(cl, NULL,
495 "Transfer-Encoding: chunked\r\n", -1));
496 }
497
498 /* write headers from CGI program */
499 foreach_header(i, res->headers)
500 {
501 ensure_out(uh_http_sendf(cl, NULL, "%s: %s\r\n",
502 res->headers[i], res->headers[i+1]));
503 }
504
505 /* terminate header */
506 ensure_out(uh_http_send(cl, NULL, "\r\n", -1));
507
508 /* push out remaining head buffer */
509 if( hdroff < hdrlen )
510 ensure_out(uh_http_send(cl, req, &hdr[hdroff], hdrlen - hdroff));
511 }
512
513 /* ... failed and head buffer exceeded */
514 else if( hdrlen >= sizeof(hdr) )
515 {
516 ensure_out(uh_cgi_error_500(cl, req,
517 "The CGI program generated an invalid response:\n\n"));
518
519 ensure_out(uh_http_send(cl, req, hdr, hdrlen));
520 }
521
522 /* ... failed but free buffer space, try again */
523 else
524 {
525 continue;
526 }
527
528 /* push out remaining read buffer */
529 if( bufoff < buflen )
530 ensure_out(uh_http_send(cl, req, &buf[bufoff], buflen - bufoff));
531
532 header_sent = 1;
533 continue;
534 }
535
536
537 /* headers complete, pass through buffer to socket */
538 ensure_out(uh_http_send(cl, req, buf, buflen));
539 }
540
541 /* looks like eof from child */
542 else
543 {
544 /* cgi script did not output useful stuff at all */
545 if( ! header_sent )
546 {
547 /* I would do this ...
548 *
549 * uh_cgi_error_500(cl, req,
550 * "The CGI program generated an "
551 * "invalid response:\n\n");
552 *
553 * ... but in order to stay as compatible as possible,
554 * treat whatever we got as text/plain response and
555 * build the required headers here.
556 */
557
558 ensure_out(uh_http_sendf(cl, NULL,
559 "HTTP/%.1f 200 OK\r\n"
560 "Content-Type: text/plain\r\n"
561 "%s\r\n",
562 req->version, (req->version > 1.0)
563 ? "Transfer-Encoding: chunked\r\n" : ""
564 ));
565
566 ensure_out(uh_http_send(cl, req, hdr, hdrlen));
567 }
568
569 /* send final chunk if we're in chunked transfer mode */
570 ensure_out(uh_http_send(cl, req, "", 0));
571 break;
572 }
573 }
574 }
575
576 /* timeout exceeded or interrupted by SIGCHLD */
577 else
578 {
579 if( (errno != EINTR) && ! header_sent )
580 {
581 ensure_out(uh_http_sendhf(cl, 504, "Gateway Timeout",
582 "The CGI script took too long to produce "
583 "a response"));
584 }
585
586 /* send final chunk if we're in chunked transfer mode */
587 ensure_out(uh_http_send(cl, req, "", 0));
588
589 break;
590 }
591 }
592
593 out:
594 close(rfd[0]);
595 close(wfd[1]);
596
597 if( !kill(child, 0) )
598 {
599 kill(child, SIGTERM);
600 waitpid(child, NULL, 0);
601 }
602
603 break;
604 }
605 }
606