[package] uhttpd: do not subscribe to epoll write events
[openwrt.git] / package / uhttpd / src / uhttpd-cgi.c
1 /*
2  * uhttpd - Tiny single-threaded httpd - CGI handler
3  *
4  *   Copyright (C) 2010-2012 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
24 static bool
25 uh_cgi_header_parse(struct http_response *res, char *buf, int len, int *off)
26 {
27         char *bufptr = NULL;
28         char *hdrname = NULL;
29         int hdrcount = 0;
30         int pos = 0;
31
32         if (((bufptr = strfind(buf, len, "\r\n\r\n", 4)) != NULL) ||
33             ((bufptr = strfind(buf, len, "\n\n", 2)) != NULL))
34         {
35                 *off = (int)(bufptr - buf) + ((bufptr[0] == '\r') ? 4 : 2);
36
37                 memset(res, 0, sizeof(*res));
38
39                 res->statuscode = 200;
40                 res->statusmsg  = "OK";
41
42                 bufptr = &buf[0];
43
44                 for (pos = 0; pos < *off; pos++)
45                 {
46                         if (!hdrname && (buf[pos] == ':'))
47                         {
48                                 buf[pos++] = 0;
49
50                                 if ((pos < len) && (buf[pos] == ' '))
51                                         pos++;
52
53                                 if (pos < len)
54                                 {
55                                         hdrname = bufptr;
56                                         bufptr = &buf[pos];
57                                 }
58                         }
59
60                         else if ((buf[pos] == '\r') || (buf[pos] == '\n'))
61                         {
62                                 if (! hdrname)
63                                         break;
64
65                                 buf[pos++] = 0;
66
67                                 if ((pos < len) && (buf[pos] == '\n'))
68                                         pos++;
69
70                                 if (pos <= len)
71                                 {
72                                         if ((hdrcount+1) < array_size(res->headers))
73                                         {
74                                                 if (!strcasecmp(hdrname, "Status"))
75                                                 {
76                                                         res->statuscode = atoi(bufptr);
77
78                                                         if (res->statuscode < 100)
79                                                                 res->statuscode = 200;
80
81                                                         if (((bufptr = strchr(bufptr, ' ')) != NULL) &&
82                                                                 (&bufptr[1] != 0))
83                                                         {
84                                                                 res->statusmsg = &bufptr[1];
85                                                         }
86
87                                                         D("CGI: HTTP/1.x %03d %s\n",
88                                                           res->statuscode, res->statusmsg);
89                                                 }
90                                                 else
91                                                 {
92                                                         D("CGI: HTTP: %s: %s\n", hdrname, bufptr);
93
94                                                         res->headers[hdrcount++] = hdrname;
95                                                         res->headers[hdrcount++] = bufptr;
96                                                 }
97
98                                                 bufptr = &buf[pos];
99                                                 hdrname = NULL;
100                                         }
101                                         else
102                                         {
103                                                 return false;
104                                         }
105                                 }
106                         }
107                 }
108
109                 return true;
110         }
111
112         return false;
113 }
114
115 static char * uh_cgi_header_lookup(struct http_response *res,
116                                                                    const char *hdrname)
117 {
118         int i;
119
120         foreach_header(i, res->headers)
121         {
122                 if (!strcasecmp(res->headers[i], hdrname))
123                         return res->headers[i+1];
124         }
125
126         return NULL;
127 }
128
129 static void uh_cgi_shutdown(struct uh_cgi_state *state)
130 {
131         close(state->rfd);
132         close(state->wfd);
133         free(state);
134 }
135
136 static bool uh_cgi_socket_cb(struct client *cl)
137 {
138         int i, len, hdroff;
139         char buf[UH_LIMIT_MSGHEAD];
140
141         struct uh_cgi_state *state = (struct uh_cgi_state *)cl->priv;
142         struct http_response *res = &state->cl->response;
143         struct http_request *req = &state->cl->request;
144
145         /* there is unread post data waiting */
146         while (state->content_length > 0)
147         {
148                 /* remaining data in http head buffer ... */
149                 if (state->cl->httpbuf.len > 0)
150                 {
151                         len = min(state->content_length, state->cl->httpbuf.len);
152
153                         D("CGI: Child(%d) feed %d HTTP buffer bytes\n",
154                           state->cl->proc.pid, len);
155
156                         memcpy(buf, state->cl->httpbuf.ptr, len);
157
158                         state->cl->httpbuf.len -= len;
159                         state->cl->httpbuf.ptr +=len;
160                 }
161
162                 /* read it from socket ... */
163                 else
164                 {
165                         len = uh_tcp_recv(state->cl, buf,
166                                                           min(state->content_length, sizeof(buf)));
167
168                         if ((len < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
169                                 break;
170
171                         D("CGI: Child(%d) feed %d/%d TCP socket bytes\n",
172                           state->cl->proc.pid, len,
173                           min(state->content_length, sizeof(buf)));
174                 }
175
176                 if (len)
177                         state->content_length -= len;
178                 else
179                         state->content_length = 0;
180
181                 /* ... write to CGI process */
182                 len = uh_raw_send(state->wfd, buf, len,
183                                                   cl->server->conf->script_timeout);
184
185                 /* explicit EOF notification for the child */
186                 if (state->content_length <= 0)
187                         close(state->wfd);
188         }
189
190         /* try to read data from child */
191         while ((len = uh_raw_recv(state->rfd, buf, sizeof(buf), -1)) > 0)
192         {
193                 /* we have not pushed out headers yet, parse input */
194                 if (!state->header_sent)
195                 {
196                         /* try to parse header ... */
197                         memcpy(state->httpbuf, buf, len);
198
199                         if (uh_cgi_header_parse(res, state->httpbuf, len, &hdroff))
200                         {
201                                 /* write status */
202                                 ensure_out(uh_http_sendf(state->cl, NULL,
203                                         "HTTP/%.1f %03d %s\r\n"
204                                         "Connection: close\r\n",
205                                         req->version, res->statuscode, res->statusmsg));
206
207                                 /* add Content-Type if no Location or Content-Type */
208                                 if (!uh_cgi_header_lookup(res, "Location") &&
209                                         !uh_cgi_header_lookup(res, "Content-Type"))
210                                 {
211                                         ensure_out(uh_http_send(state->cl, NULL,
212                                                 "Content-Type: text/plain\r\n", -1));
213                                 }
214
215                                 /* if request was HTTP 1.1 we'll respond chunked */
216                                 if ((req->version > 1.0) &&
217                                         !uh_cgi_header_lookup(res, "Transfer-Encoding"))
218                                 {
219                                         ensure_out(uh_http_send(state->cl, NULL,
220                                                 "Transfer-Encoding: chunked\r\n", -1));
221                                 }
222
223                                 /* write headers from CGI program */
224                                 foreach_header(i, res->headers)
225                                 {
226                                         ensure_out(uh_http_sendf(state->cl, NULL, "%s: %s\r\n",
227                                                 res->headers[i], res->headers[i+1]));
228                                 }
229
230                                 /* terminate header */
231                                 ensure_out(uh_http_send(state->cl, NULL, "\r\n", -1));
232
233                                 state->header_sent = true;
234
235                                 /* push out remaining head buffer */
236                                 if (hdroff < len)
237                                 {
238                                         D("CGI: Child(%d) relaying %d rest bytes\n",
239                                           state->cl->proc.pid, len - hdroff);
240
241                                         ensure_out(uh_http_send(state->cl, req,
242                                                                                         &buf[hdroff], len - hdroff));
243                                 }
244                         }
245
246                         /* ... failed and head buffer exceeded */
247                         else
248                         {
249                                 /* I would do this ...
250                                  *
251                                  *    uh_cgi_error_500(cl, req,
252                                  *        "The CGI program generated an "
253                                  *        "invalid response:\n\n");
254                                  *
255                                  * ... but in order to stay as compatible as possible,
256                                  * treat whatever we got as text/plain response and
257                                  * build the required headers here.
258                                  */
259
260                                 ensure_out(uh_http_sendf(state->cl, NULL,
261                                                                                  "HTTP/%.1f 200 OK\r\n"
262                                                                                  "Content-Type: text/plain\r\n"
263                                                                                  "%s\r\n",
264                                                                                  req->version, (req->version > 1.0)
265                                                                                  ? "Transfer-Encoding: chunked\r\n" : ""
266                                 ));
267
268                                 state->header_sent = true;
269
270                                 D("CGI: Child(%d) relaying %d invalid bytes\n",
271                                   state->cl->proc.pid, len);
272
273                                 ensure_out(uh_http_send(state->cl, req, buf, len));
274                         }
275                 }
276                 else
277                 {
278                         /* headers complete, pass through buffer to socket */
279                         D("CGI: Child(%d) relaying %d normal bytes\n",
280                           state->cl->proc.pid, len);
281
282                         ensure_out(uh_http_send(state->cl, req, buf, len));
283                 }
284         }
285
286         /* got EOF or read error from child */
287         if ((len == 0) ||
288                 ((errno != EAGAIN) && (errno != EWOULDBLOCK) && (len == -1)))
289         {
290                 D("CGI: Child(%d) presumed dead [%s]\n",
291                   state->cl->proc.pid, strerror(errno));
292
293                 goto out;
294         }
295
296         return true;
297
298 out:
299         if (!state->header_sent)
300         {
301                 if (state->cl->timeout.pending)
302                         uh_http_sendhf(state->cl, 502, "Bad Gateway",
303                                                    "The CGI process did not produce any response\n");
304                 else
305                         uh_http_sendhf(state->cl, 504, "Gateway Timeout",
306                                                    "The CGI process took too long to produce a "
307                                                    "response\n");
308         }
309         else
310         {
311                 uh_http_send(state->cl, req, "", 0);
312         }
313
314         uh_cgi_shutdown(state);
315         return false;
316 }
317
318 bool uh_cgi_request(struct client *cl, struct path_info *pi,
319                                         struct interpreter *ip)
320 {
321         int i;
322
323         int rfd[2] = { 0, 0 };
324         int wfd[2] = { 0, 0 };
325
326         pid_t child;
327
328         struct uh_cgi_state *state;
329         struct http_request *req = &cl->request;
330
331         /* allocate state */
332         if (!(state = malloc(sizeof(*state))))
333         {
334                 uh_http_sendhf(cl, 500, "Internal Server Error", "Out of memory");
335                 return false;
336         }
337
338         /* spawn pipes for me->child, child->me */
339         if ((pipe(rfd) < 0) || (pipe(wfd) < 0))
340         {
341                 if (rfd[0] > 0) close(rfd[0]);
342                 if (rfd[1] > 0) close(rfd[1]);
343                 if (wfd[0] > 0) close(wfd[0]);
344                 if (wfd[1] > 0) close(wfd[1]);
345
346                 uh_http_sendhf(cl, 500, "Internal Server Error",
347                                                 "Failed to create pipe: %s\n", strerror(errno));
348
349                 return false;
350         }
351
352         /* fork off child process */
353         switch ((child = fork()))
354         {
355         /* oops */
356         case -1:
357                 uh_http_sendhf(cl, 500, "Internal Server Error",
358                                                 "Failed to fork child: %s\n", strerror(errno));
359
360                 return false;
361
362         /* exec child */
363         case 0:
364 #ifdef DEBUG
365                 sleep(atoi(getenv("UHTTPD_SLEEP_ON_FORK") ?: "0"));
366 #endif
367
368                 /* do not leak parent epoll descriptor */
369                 uloop_done();
370
371                 /* close loose pipe ends */
372                 close(rfd[0]);
373                 close(wfd[1]);
374
375                 /* patch stdout and stdin to pipes */
376                 dup2(rfd[1], 1);
377                 dup2(wfd[0], 0);
378
379                 /* avoid leaking our pipe into child-child processes */
380                 fd_cloexec(rfd[1]);
381                 fd_cloexec(wfd[0]);
382
383                 /* check for regular, world-executable file _or_ interpreter */
384                 if (((pi->stat.st_mode & S_IFREG) &&
385                          (pi->stat.st_mode & S_IXOTH)) || (ip != NULL))
386                 {
387                         /* build environment */
388                         clearenv();
389
390                         /* common information */
391                         setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
392                         setenv("SERVER_SOFTWARE", "uHTTPd", 1);
393                         setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
394
395 #ifdef HAVE_TLS
396                         /* https? */
397                         if (cl->tls)
398                                 setenv("HTTPS", "on", 1);
399 #endif
400
401                         /* addresses */
402                         setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
403                         setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
404                         setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
405                         setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
406                         setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
407                         setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
408
409                         /* path information */
410                         setenv("SCRIPT_NAME", pi->name, 1);
411                         setenv("SCRIPT_FILENAME", pi->phys, 1);
412                         setenv("DOCUMENT_ROOT", pi->root, 1);
413                         setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
414
415                         if (pi->info)
416                                 setenv("PATH_INFO", pi->info, 1);
417
418                         /* REDIRECT_STATUS, php-cgi wants it */
419                         switch (req->redirect_status)
420                         {
421                                 case 404:
422                                         setenv("REDIRECT_STATUS", "404", 1);
423                                         break;
424
425                                 default:
426                                         setenv("REDIRECT_STATUS", "200", 1);
427                                         break;
428                         }
429
430                         /* http version */
431                         if (req->version > 1.0)
432                                 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
433                         else
434                                 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
435
436                         /* request method */
437                         switch (req->method)
438                         {
439                                 case UH_HTTP_MSG_GET:
440                                         setenv("REQUEST_METHOD", "GET", 1);
441                                         break;
442
443                                 case UH_HTTP_MSG_HEAD:
444                                         setenv("REQUEST_METHOD", "HEAD", 1);
445                                         break;
446
447                                 case UH_HTTP_MSG_POST:
448                                         setenv("REQUEST_METHOD", "POST", 1);
449                                         break;
450                         }
451
452                         /* request url */
453                         setenv("REQUEST_URI", req->url, 1);
454
455                         /* remote user */
456                         if (req->realm)
457                                 setenv("REMOTE_USER", req->realm->user, 1);
458
459                         /* request message headers */
460                         foreach_header(i, req->headers)
461                         {
462                                 if (!strcasecmp(req->headers[i], "Accept"))
463                                         setenv("HTTP_ACCEPT", req->headers[i+1], 1);
464
465                                 else if (!strcasecmp(req->headers[i], "Accept-Charset"))
466                                         setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
467
468                                 else if (!strcasecmp(req->headers[i], "Accept-Encoding"))
469                                         setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
470
471                                 else if (!strcasecmp(req->headers[i], "Accept-Language"))
472                                         setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
473
474                                 else if (!strcasecmp(req->headers[i], "Authorization"))
475                                         setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
476
477                                 else if (!strcasecmp(req->headers[i], "Connection"))
478                                         setenv("HTTP_CONNECTION", req->headers[i+1], 1);
479
480                                 else if (!strcasecmp(req->headers[i], "Cookie"))
481                                         setenv("HTTP_COOKIE", req->headers[i+1], 1);
482
483                                 else if (!strcasecmp(req->headers[i], "Host"))
484                                         setenv("HTTP_HOST", req->headers[i+1], 1);
485
486                                 else if (!strcasecmp(req->headers[i], "Referer"))
487                                         setenv("HTTP_REFERER", req->headers[i+1], 1);
488
489                                 else if (!strcasecmp(req->headers[i], "User-Agent"))
490                                         setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
491
492                                 else if (!strcasecmp(req->headers[i], "Content-Type"))
493                                         setenv("CONTENT_TYPE", req->headers[i+1], 1);
494
495                                 else if (!strcasecmp(req->headers[i], "Content-Length"))
496                                         setenv("CONTENT_LENGTH", req->headers[i+1], 1);
497                         }
498
499
500                         /* execute child code ... */
501                         if (chdir(pi->root))
502                                 perror("chdir()");
503
504                         if (ip != NULL)
505                                 execl(ip->path, ip->path, pi->phys, NULL);
506                         else
507                                 execl(pi->phys, pi->phys, NULL);
508
509                         /* in case it fails ... */
510                         printf("Status: 500 Internal Server Error\r\n\r\n"
511                                    "Unable to launch the requested CGI program:\n"
512                                    "  %s: %s\n", ip ? ip->path : pi->phys, strerror(errno));
513                 }
514
515                 /* 403 */
516                 else
517                 {
518                         printf("Status: 403 Forbidden\r\n\r\n"
519                                    "Access to this resource is forbidden\n");
520                 }
521
522                 close(wfd[0]);
523                 close(rfd[1]);
524                 exit(0);
525
526                 break;
527
528         /* parent; handle I/O relaying */
529         default:
530                 memset(state, 0, sizeof(*state));
531
532                 state->cl = cl;
533                 state->cl->pipe.fd = rfd[0];
534                 state->cl->proc.pid = child;
535
536                 /* close unneeded pipe ends */
537                 close(rfd[1]);
538                 close(wfd[0]);
539
540                 D("CGI: Child(%d) created: rfd(%d) wfd(%d)\n", child, rfd[0], wfd[1]);
541
542                 state->content_length = cl->httpbuf.len;
543
544                 /* find content length */
545                 if (req->method == UH_HTTP_MSG_POST)
546                 {
547                         foreach_header(i, req->headers)
548                         {
549                                 if (!strcasecmp(req->headers[i], "Content-Length"))
550                                 {
551                                         state->content_length = atoi(req->headers[i+1]);
552                                         break;
553                                 }
554                         }
555                 }
556
557                 state->rfd = rfd[0];
558                 fd_nonblock(state->rfd);
559
560                 state->wfd = wfd[1];
561                 fd_nonblock(state->wfd);
562
563                 cl->cb = uh_cgi_socket_cb;
564                 cl->priv = state;
565
566                 break;
567         }
568
569         return true;
570 }