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