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