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