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