Root/package/uhttpd/src/uhttpd-cgi.c

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

Archive Download this file



interactive