uhttpd: deliver SIGTERM to child when parent leaves I/O loop
[project/luci.git] / contrib / 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(struct client *cl, struct http_request *req, struct path_info *pi)
139 {
140         int i, hdroff, bufoff;
141         int hdrlen = 0;
142         int buflen = 0;
143         int fd_max = 0;
144         int content_length = 0;
145         int header_sent = 0;
146
147         int rfd[2] = { 0, 0 };
148         int wfd[2] = { 0, 0 };
149
150         char buf[UH_LIMIT_MSGHEAD];
151         char hdr[UH_LIMIT_MSGHEAD];
152
153         pid_t child;
154
155         fd_set reader;
156         fd_set writer;
157
158         struct timeval timeout;
159         struct http_response *res;
160
161
162         /* spawn pipes for me->child, child->me */
163         if( (pipe(rfd) < 0) || (pipe(wfd) < 0) )
164         {
165                 uh_http_sendhf(cl, 500, "Internal Server Error",
166                         "Failed to create pipe: %s", strerror(errno));
167
168                 if( rfd[0] > 0 ) close(rfd[0]);
169                 if( rfd[1] > 0 ) close(rfd[1]);
170                 if( wfd[0] > 0 ) close(wfd[0]);
171                 if( wfd[1] > 0 ) close(wfd[1]);
172
173                 return;
174         }
175
176         /* fork off child process */
177         switch( (child = fork()) )
178         {
179                 /* oops */
180                 case -1:
181                         uh_http_sendhf(cl, 500, "Internal Server Error",
182                                 "Failed to fork child: %s", strerror(errno));
183                         return;
184
185                 /* exec child */
186                 case 0:
187                         /* child */
188                         close(rfd[0]);
189                         close(wfd[1]);
190
191                         /* patch stdout and stdin to pipes */
192                         dup2(rfd[1], 1);
193                         dup2(wfd[0], 0);
194
195                         /* check for regular, world-executable file */
196                         if( (pi->stat.st_mode & S_IFREG) &&
197                             (pi->stat.st_mode & S_IXOTH)
198                         ) {
199                                 /* build environment */
200                                 clearenv();
201
202                                 /* common information */
203                                 setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
204                                 setenv("SERVER_SOFTWARE", "uHTTPd", 1);
205                                 setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
206
207 #ifdef HAVE_TLS
208                                 /* https? */
209                                 if( cl->tls )
210                                         setenv("HTTPS", "on", 1);
211 #endif
212
213                                 /* addresses */
214                                 setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
215                                 setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
216                                 setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
217                                 setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
218                                 setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
219                                 setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
220
221                                 /* path information */
222                                 setenv("SCRIPT_NAME", pi->name, 1);
223                                 setenv("SCRIPT_FILENAME", pi->phys, 1);
224                                 setenv("DOCUMENT_ROOT", pi->root, 1);
225                                 setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
226
227                                 if( pi->info )
228                                         setenv("PATH_INFO", pi->info, 1);
229
230
231                                 /* http version */
232                                 if( req->version > 1.0 )
233                                         setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
234                                 else
235                                         setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
236
237                                 /* request method */
238                                 switch( req->method )
239                                 {
240                                         case UH_HTTP_MSG_GET:
241                                                 setenv("REQUEST_METHOD", "GET", 1);
242                                                 break;
243
244                                         case UH_HTTP_MSG_HEAD:
245                                                 setenv("REQUEST_METHOD", "HEAD", 1);
246                                                 break;
247
248                                         case UH_HTTP_MSG_POST:
249                                                 setenv("REQUEST_METHOD", "POST", 1);
250                                                 break;
251                                 }
252
253                                 /* request url */
254                                 setenv("REQUEST_URI", req->url, 1);
255
256                                 /* remote user */
257                                 if( req->realm )
258                                         setenv("REMOTE_USER", req->realm->user, 1);
259
260                                 /* request message headers */
261                                 foreach_header(i, req->headers)
262                                 {
263                                         if( ! strcasecmp(req->headers[i], "Accept") )
264                                                 setenv("HTTP_ACCEPT", req->headers[i+1], 1);
265
266                                         else if( ! strcasecmp(req->headers[i], "Accept-Charset") )
267                                                 setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
268
269                                         else if( ! strcasecmp(req->headers[i], "Accept-Encoding") )
270                                                 setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
271
272                                         else if( ! strcasecmp(req->headers[i], "Accept-Language") )
273                                                 setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
274
275                                         else if( ! strcasecmp(req->headers[i], "Authorization") )
276                                                 setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
277
278                                         else if( ! strcasecmp(req->headers[i], "Connection") )
279                                                 setenv("HTTP_CONNECTION", req->headers[i+1], 1);
280
281                                         else if( ! strcasecmp(req->headers[i], "Cookie") )
282                                                 setenv("HTTP_COOKIE", req->headers[i+1], 1);
283
284                                         else if( ! strcasecmp(req->headers[i], "Host") )
285                                                 setenv("HTTP_HOST", req->headers[i+1], 1);
286
287                                         else if( ! strcasecmp(req->headers[i], "Referer") )
288                                                 setenv("HTTP_REFERER", req->headers[i+1], 1);
289
290                                         else if( ! strcasecmp(req->headers[i], "User-Agent") )
291                                                 setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
292
293                                         else if( ! strcasecmp(req->headers[i], "Content-Type") )
294                                                 setenv("CONTENT_TYPE", req->headers[i+1], 1);
295
296                                         else if( ! strcasecmp(req->headers[i], "Content-Length") )
297                                                 setenv("CONTENT_LENGTH", req->headers[i+1], 1);
298                                 }
299
300
301                                 /* execute child code ... */
302                                 if( chdir(pi->root) )
303                                         perror("chdir()");
304
305                                 execl(pi->phys, pi->phys, NULL);
306
307                                 /* in case it fails ... */
308                                 printf(
309                                         "Status: 500 Internal Server Error\r\n\r\n"
310                                         "Unable to launch the requested CGI program:\n"
311                                         "  %s: %s\n",
312                                                 pi->phys, strerror(errno)
313                                 );
314                         }
315
316                         /* 403 */
317                         else
318                         {
319                                 printf(
320                                         "Status: 403 Forbidden\r\n\r\n"
321                                         "Access to this resource is forbidden\n"
322                                 );
323                         }
324
325                         close(wfd[0]);
326                         close(rfd[1]);
327                         exit(0);
328
329                         break;
330
331                 /* parent; handle I/O relaying */
332                 default:
333                         /* close unneeded pipe ends */
334                         close(rfd[1]);
335                         close(wfd[0]);
336
337                         /* max watch fd */
338                         fd_max = max(rfd[0], wfd[1]) + 1;
339
340                         /* find content length */
341                         if( req->method == UH_HTTP_MSG_POST )
342                         {
343                                 foreach_header(i, req->headers)
344                                 {
345                                         if( ! strcasecmp(req->headers[i], "Content-Length") )
346                                         {
347                                                 content_length = atoi(req->headers[i+1]);
348                                                 break;
349                                         }
350                                 }
351                         }
352
353
354                         memset(hdr, 0, sizeof(hdr));
355
356 #define ensure(x) \
357         do { if( x < 0 ) goto out; } while(0)
358
359                         /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
360                         while( 1 )
361                         {
362                                 FD_ZERO(&reader);
363                                 FD_ZERO(&writer);
364
365                                 FD_SET(rfd[0], &reader);
366                                 FD_SET(wfd[1], &writer);
367
368                                 timeout.tv_sec = 15;
369                                 timeout.tv_usec = 0;
370
371                                 /* wait until we can read or write or both */
372                                 if( select(fd_max, &reader, (content_length > -1) ? &writer : NULL, NULL, &timeout) > 0 )
373                                 {
374                                         /* ready to write to cgi program */
375                                         if( FD_ISSET(wfd[1], &writer) )
376                                         {
377                                                 /* there is unread post data waiting */
378                                                 if( content_length > 0 )
379                                                 {
380                                                         /* read it from socket ... */
381                                                         if( (buflen = uh_tcp_recv(cl, buf, min(content_length, sizeof(buf)))) > 0 )
382                                                         {
383                                                                 /* ... and write it to child's stdin */
384                                                                 if( write(wfd[1], buf, buflen) < 0 )
385                                                                         perror("write()");
386
387                                                                 content_length -= buflen;
388                                                         }
389
390                                                         /* unexpected eof! */
391                                                         else
392                                                         {
393                                                                 if( write(wfd[1], "", 0) < 0 )
394                                                                         perror("write()");
395
396                                                                 content_length = 0;
397                                                         }
398                                                 }
399
400                                                 /* there is no more post data, close pipe to child's stdin */
401                                                 else if( content_length > -1 )
402                                                 {
403                                                         close(wfd[1]);
404                                                         content_length = -1;
405                                                 }
406                                         }
407
408                                         /* ready to read from cgi program */
409                                         if( FD_ISSET(rfd[0], &reader) )
410                                         {
411                                                 /* read data from child ... */
412                                                 if( (buflen = read(rfd[0], buf, sizeof(buf))) > 0 )
413                                                 {
414                                                         /* we have not pushed out headers yet, parse input */
415                                                         if( ! header_sent )
416                                                         {
417                                                                 /* head buffer not full and no end yet */
418                                                                 if( hdrlen < sizeof(hdr) )
419                                                                 {
420                                                                         bufoff = min(buflen, sizeof(hdr) - hdrlen);
421                                                                         memcpy(&hdr[hdrlen], buf, bufoff);
422                                                                         hdrlen += bufoff;
423                                                                 }
424                                                                 else
425                                                                 {
426                                                                         bufoff = 0;
427                                                                 }
428
429
430                                                                 /* try to parse header ... */
431                                                                 if( (res = uh_cgi_header_parse(hdr, hdrlen, &hdroff)) != NULL )
432                                                                 {
433                                                                         /* write status */
434                                                                         ensure(uh_http_sendf(cl, NULL,
435                                                                                 "HTTP/%.1f %03d %s\r\n"
436                                                                                 "Connection: close\r\n",
437                                                                                 req->version, res->statuscode,
438                                                                                 res->statusmsg));
439
440                                                                         /* add Content-Type if no Location or Content-Type */
441                                                                         if( !uh_cgi_header_lookup(res, "Location") &&
442                                                                             !uh_cgi_header_lookup(res, "Content-Type")
443                                                                         ) {
444                                                                                 ensure(uh_http_send(cl, NULL,
445                                                                                         "Content-Type: text/plain\r\n", -1));
446                                                                         }
447
448                                                                         /* if request was HTTP 1.1 we'll respond chunked */
449                                                                         if( (req->version > 1.0) &&
450                                                                             !uh_cgi_header_lookup(res, "Transfer-Encoding")
451                                                                         ) {
452                                                                                 ensure(uh_http_send(cl, NULL,
453                                                                                         "Transfer-Encoding: chunked\r\n", -1));
454                                                                         }
455
456                                                                         /* write headers from CGI program */
457                                                                         foreach_header(i, res->headers)
458                                                                         {
459                                                                                 ensure(uh_http_sendf(cl, NULL, "%s: %s\r\n",
460                                                                                         res->headers[i], res->headers[i+1]));
461                                                                         }
462
463                                                                         /* terminate header */
464                                                                         ensure(uh_http_send(cl, NULL, "\r\n", -1));
465
466                                                                         /* push out remaining head buffer */
467                                                                         if( hdroff < hdrlen )
468                                                                                 ensure(uh_http_send(cl, req, &hdr[hdroff], hdrlen - hdroff));
469                                                                 }
470
471                                                                 /* ... failed and head buffer exceeded */
472                                                                 else if( hdrlen >= sizeof(hdr) )
473                                                                 {
474                                                                         ensure(uh_cgi_error_500(cl, req,
475                                                                                 "The CGI program generated an invalid response:\n\n"));
476
477                                                                         ensure(uh_http_send(cl, req, hdr, hdrlen));
478                                                                 }
479
480                                                                 /* ... failed but free buffer space, try again */
481                                                                 else
482                                                                 {
483                                                                         continue;
484                                                                 }
485
486                                                                 /* push out remaining read buffer */
487                                                                 if( bufoff < buflen )
488                                                                         ensure(uh_http_send(cl, req, &buf[bufoff], buflen - bufoff));
489
490                                                                 header_sent = 1;
491                                                                 continue;
492                                                         }
493
494
495                                                         /* headers complete, pass through buffer to socket */
496                                                         ensure(uh_http_send(cl, req, buf, buflen));
497                                                 }
498
499                                                 /* looks like eof from child */
500                                                 else
501                                                 {
502                                                         /* cgi script did not output useful stuff at all */
503                                                         if( ! header_sent )
504                                                         {
505                                                                 /* I would do this ...
506                                                                  *
507                                                                  *    uh_cgi_error_500(cl, req,
508                                                                  *        "The CGI program generated an "
509                                                                  *        "invalid response:\n\n");
510                                                                  *
511                                                                  * ... but in order to stay as compatible as possible,
512                                                                  * treat whatever we got as text/plain response and
513                                                                  * build the required headers here.
514                                                                  */
515
516                                                                 ensure(uh_http_sendf(cl, NULL,
517                                                                         "HTTP/%.1f 200 OK\r\n"
518                                                                         "Content-Type: text/plain\r\n"
519                                                                         "%s\r\n",
520                                                                                 req->version, (req->version > 1.0)
521                                                                                         ? "Transfer-Encoding: chunked\r\n" : ""
522                                                                 ));
523
524                                                                 ensure(uh_http_send(cl, req, hdr, hdrlen));
525                                                         }
526
527                                                         /* send final chunk if we're in chunked transfer mode */
528                                                         ensure(uh_http_send(cl, req, "", 0));
529                                                         break;
530                                                 }
531                                         }
532                                 }
533
534                                 /* no activity for 15 seconds... looks dead */
535                                 else
536                                 {
537                                         ensure(uh_http_sendhf(cl, 504, "Gateway Timeout",
538                                                 "The CGI script took too long to produce a response"));
539
540                                         break;
541                                 }
542                         }
543
544                 out:
545                         close(rfd[0]);
546                         close(wfd[1]);
547
548                         if( !kill(child, 0) )
549                                 kill(child, SIGTERM);
550
551                         break;
552         }
553 }
554