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