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

Archive Download this file



interactive