root/luci/trunk/contrib/package/uhttpd/src/uhttpd-lua.c @ 5901

Revision 5901, 10.9 KB (checked in by jow, 3 years ago)

uhttpd: make Lua handler more CGI like and fork child away

Line 
1/*
2 * uhttpd - Tiny single-threaded httpd - Lua 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-lua.h"
22
23
24static int uh_lua_recv(lua_State *L)
25{
26    size_t length;
27    char buffer[UH_LIMIT_MSGHEAD];
28    ssize_t rlen = 0;
29    fd_set reader;
30    struct timeval timeout;
31
32    length = luaL_checknumber(L, 1);
33
34    if( (length > 0) && (length <= sizeof(buffer)) )
35    {
36        FD_ZERO(&reader);
37        FD_SET(fileno(stdin), &reader);
38
39        /* fail after 0.1s */
40        timeout.tv_sec  = 0;
41        timeout.tv_usec = 100000;
42
43        /* check whether fd is readable */
44        if( select(fileno(stdin) + 1, &reader, NULL, NULL, &timeout) > 0 )
45        {
46            /* receive data */
47            rlen = read(fileno(stdin), buffer, length);
48            lua_pushnumber(L, rlen);
49
50            if( rlen > 0 )
51            {
52                lua_pushlstring(L, buffer, rlen);
53                return 2;
54            }
55
56            return 1;
57        }
58
59        /* no, timeout and actually no data */
60        lua_pushnumber(L, -2);
61        return 1;
62    }
63
64    /* parameter error */
65    lua_pushnumber(L, -3);
66    return 1;
67}
68
69static int uh_lua_send_common(lua_State *L, int chunked)
70{
71    size_t length;
72    const char *buffer;
73    char chunk[16];
74    ssize_t slen = 0;
75
76    buffer = luaL_checklstring(L, 1, &length);
77
78    if( chunked )
79    {
80        if( length > 0 )
81        {
82            snprintf(chunk, sizeof(chunk), "%X\r\n", length);
83            slen =  write(fileno(stdout), chunk, strlen(chunk));
84            slen += write(fileno(stdout), buffer, length);
85            slen += write(fileno(stdout), "\r\n", 2);
86        }
87        else
88        {
89            slen = write(fileno(stdout), "0\r\n\r\n", 5);
90        }
91    }
92    else
93    {
94        slen = write(fileno(stdout), buffer, length);
95    }
96
97    lua_pushnumber(L, slen);
98    return 1;
99}
100
101static int uh_lua_send(lua_State *L)
102{
103    return uh_lua_send_common(L, 0);
104}
105
106static int uh_lua_sendc(lua_State *L)
107{
108    return uh_lua_send_common(L, 1);
109}
110
111static int uh_lua_urldecode(lua_State *L)
112{
113    size_t inlen, outlen;
114    const char *inbuf;
115    char outbuf[UH_LIMIT_MSGHEAD];
116
117    inbuf = luaL_checklstring(L, 1, &inlen);
118    outlen = uh_urldecode(outbuf, sizeof(outbuf), inbuf, inlen);
119
120    lua_pushlstring(L, outbuf, outlen);
121    return 1;
122}
123
124
125lua_State * uh_lua_init(const char *handler)
126{
127    lua_State *L = lua_open();
128    const char *err_str = NULL;
129
130    /* Load standard libaries */
131    luaL_openlibs(L);
132
133    /* build uhttpd api table */
134    lua_newtable(L);
135
136    /* register global send and receive functions */
137    lua_pushcfunction(L, uh_lua_recv);
138    lua_setfield(L, -2, "recv");
139
140    lua_pushcfunction(L, uh_lua_send);
141    lua_setfield(L, -2, "send");
142
143    lua_pushcfunction(L, uh_lua_sendc);
144    lua_setfield(L, -2, "sendc");
145
146    lua_pushcfunction(L, uh_lua_urldecode);
147    lua_setfield(L, -2, "urldecode");
148
149    /* _G.uhttpd = { ... } */
150    lua_setfield(L, LUA_GLOBALSINDEX, "uhttpd");
151
152
153    /* load Lua handler */
154    switch( luaL_loadfile(L, handler) )
155    {
156        case LUA_ERRSYNTAX:
157            fprintf(stderr,
158                "Lua handler contains syntax errors, unable to continue\n");
159            exit(1);
160
161        case LUA_ERRMEM:
162            fprintf(stderr,
163                "Lua handler ran out of memory, unable to continue\n");
164            exit(1);
165
166        case LUA_ERRFILE:
167            fprintf(stderr,
168                "Lua cannot open the handler script, unable to continue\n");
169            exit(1);
170
171        default:
172            /* compile Lua handler */
173            switch( lua_pcall(L, 0, 0, 0) )
174            {
175                case LUA_ERRRUN:
176                    err_str = luaL_checkstring(L, -1);
177                    fprintf(stderr,
178                        "Lua handler had runtime error, unable to continue\n"
179                        "Error: %s\n", err_str
180                    );
181                    exit(1);
182
183                case LUA_ERRMEM:
184                    err_str = luaL_checkstring(L, -1);
185                    fprintf(stderr,
186                        "Lua handler ran out of memory, unable to continue\n"
187                        "Error: %s\n", err_str
188                    );
189                    exit(1);
190
191                default:
192                    /* test handler function */
193                    lua_getglobal(L, UH_LUA_CALLBACK);
194
195                    if( ! lua_isfunction(L, -1) )
196                    {
197                        fprintf(stderr,
198                            "Lua handler provides no " UH_LUA_CALLBACK "(), unable to continue\n");
199                        exit(1);
200                    }
201
202                    lua_pop(L, 1);
203                    break;
204            }
205
206            break;
207    }
208
209    return L;
210}
211
212void uh_lua_request(struct client *cl, struct http_request *req, lua_State *L)
213{
214    pid_t pid;
215
216    int i, data_sent;
217    int content_length = 0;
218    int buflen = 0;
219    int fd_max = 0;
220    char *query_string;
221    const char *prefix = cl->server->conf->lua_prefix;
222    const char *err_str = NULL;
223
224    int rfd[2] = { 0, 0 };
225    int wfd[2] = { 0, 0 };
226
227    char buf[UH_LIMIT_MSGHEAD];
228
229    fd_set reader;
230    fd_set writer;
231
232    struct timeval timeout;
233
234
235    /* spawn pipes for me->child, child->me */
236    if( (pipe(rfd) < 0) || (pipe(wfd) < 0) )
237    {
238        uh_http_sendhf(cl, 500, "Internal Server Error",
239            "Failed to create pipe: %s", strerror(errno));
240
241        if( rfd[0] > 0 ) close(rfd[0]);
242        if( rfd[1] > 0 ) close(rfd[1]);
243        if( wfd[0] > 0 ) close(wfd[0]);
244        if( wfd[1] > 0 ) close(wfd[1]);
245
246        return;
247    }
248
249
250    switch( (pid = fork()) )
251    {
252        case -1:
253            uh_http_sendhf(cl, 500, "Internal Server Error",
254                "Failed to fork child: %s", strerror(errno));
255            break;
256
257        case 0:
258            /* child */
259            close(rfd[0]);
260            close(wfd[1]);
261
262            /* patch stdout and stdin to pipes */
263            dup2(rfd[1], 1);
264            dup2(wfd[0], 0);
265
266            /* put handler callback on stack */
267            lua_getglobal(L, UH_LUA_CALLBACK);
268
269            /* build env table */
270            lua_newtable(L);
271
272            /* request method */
273            switch(req->method)
274            {
275                case UH_HTTP_MSG_GET:
276                    lua_pushstring(L, "GET");
277                    break;
278
279                case UH_HTTP_MSG_HEAD:
280                    lua_pushstring(L, "HEAD");
281                    break;
282
283                case UH_HTTP_MSG_POST:
284                    lua_pushstring(L, "POST");
285                    break;
286            }
287
288            lua_setfield(L, -2, "REQUEST_METHOD");
289
290            /* request url */
291            lua_pushstring(L, req->url);
292            lua_setfield(L, -2, "REQUEST_URI");
293
294            /* script name */
295            lua_pushstring(L, cl->server->conf->lua_prefix);
296            lua_setfield(L, -2, "SCRIPT_NAME");
297
298            /* query string, path info */
299            if( (query_string = strchr(req->url, '?')) != NULL )
300            {
301                lua_pushstring(L, query_string + 1);
302                lua_setfield(L, -2, "QUERY_STRING");
303
304                if( (int)(query_string - req->url) > strlen(prefix) )
305                {
306                    lua_pushlstring(L,
307                        &req->url[strlen(prefix)],
308                        (int)(query_string - req->url) - strlen(prefix)
309                    );
310
311                    lua_setfield(L, -2, "PATH_INFO");
312                }
313            }
314            else if( strlen(req->url) > strlen(prefix) )
315            {
316                lua_pushstring(L, &req->url[strlen(prefix)]);
317                lua_setfield(L, -2, "PATH_INFO");
318            }
319
320            /* http protcol version */
321            lua_pushnumber(L, floor(req->version * 10) / 10);
322            lua_setfield(L, -2, "HTTP_VERSION");
323
324            if( req->version > 1.0 )
325                lua_pushstring(L, "HTTP/1.1");
326            else
327                lua_pushstring(L, "HTTP/1.0");
328
329            lua_setfield(L, -2, "SERVER_PROTOCOL");
330
331
332            /* address information */
333            lua_pushstring(L, sa_straddr(&cl->peeraddr));
334            lua_setfield(L, -2, "REMOTE_ADDR");
335
336            lua_pushinteger(L, sa_port(&cl->peeraddr));
337            lua_setfield(L, -2, "REMOTE_PORT");
338
339            lua_pushstring(L, sa_straddr(&cl->servaddr));
340            lua_setfield(L, -2, "SERVER_ADDR");
341
342            lua_pushinteger(L, sa_port(&cl->servaddr));
343            lua_setfield(L, -2, "SERVER_PORT");
344
345            /* essential env vars */
346            foreach_header(i, req->headers)
347            {
348                if( !strcasecmp(req->headers[i], "Content-Length") )
349                {
350                    lua_pushnumber(L, atoi(req->headers[i+1]));
351                    lua_setfield(L, -2, "CONTENT_LENGTH");
352                }
353                else if( !strcasecmp(req->headers[i], "Content-Type") )
354                {
355                    lua_pushstring(L, req->headers[i+1]);
356                    lua_setfield(L, -2, "CONTENT_TYPE");
357                }
358            }
359
360            /* misc. headers */
361            lua_newtable(L);
362
363            foreach_header(i, req->headers)
364            {
365                if( strcasecmp(req->headers[i], "Content-Length") &&
366                    strcasecmp(req->headers[i], "Content-Type")
367                ) {
368                    lua_pushstring(L, req->headers[i+1]);
369                    lua_setfield(L, -2, req->headers[i]);
370                }
371            }
372
373            lua_setfield(L, -2, "headers");
374
375
376            /* call */
377            switch( lua_pcall(L, 1, 0, 0) )
378            {
379                case LUA_ERRMEM:
380                case LUA_ERRRUN:
381                    err_str = luaL_checkstring(L, -1);
382
383                    if( ! err_str )
384                        err_str = "Unknown error";
385
386                    printf(
387                        "HTTP/%.1f 500 Internal Server Error\r\n"
388                        "Connection: close\r\n"
389                        "Content-Type: text/plain\r\n"
390                        "Content-Length: %i\r\n\r\n"
391                        "Lua raised a runtime error:\n  %s\n",
392                            req->version, 31 + strlen(err_str), err_str
393                    );
394
395                    break;
396
397                default:
398                    break;
399            }
400
401            close(wfd[0]);
402            close(rfd[1]);
403            exit(0);
404
405            break;
406
407        /* parent; handle I/O relaying */
408        default:
409            /* close unneeded pipe ends */
410            close(rfd[1]);
411            close(wfd[0]);
412
413            /* max watch fd */
414            fd_max = max(rfd[0], wfd[1]) + 1;
415
416            /* find content length */
417            if( req->method == UH_HTTP_MSG_POST )
418            {
419                foreach_header(i, req->headers)
420                {
421                    if( ! strcasecmp(req->headers[i], "Content-Length") )
422                    {
423                        content_length = atoi(req->headers[i+1]);
424                        break;
425                    }
426                }
427            }
428
429
430#define ensure(x) \
431    do { if( x < 0 ) goto out; } while(0)
432
433            data_sent = 0;
434
435            /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
436            while( 1 )
437            {
438                FD_ZERO(&reader);
439                FD_ZERO(&writer);
440
441                FD_SET(rfd[0], &reader);
442                FD_SET(wfd[1], &writer);
443
444                timeout.tv_sec = 15;
445                timeout.tv_usec = 0;
446
447                /* wait until we can read or write or both */
448                if( select(fd_max, &reader, (content_length > -1) ? &writer : NULL, NULL, &timeout) > 0 )
449                {
450                    /* ready to write to Lua child */
451                    if( FD_ISSET(wfd[1], &writer) )
452                    {
453                        /* there is unread post data waiting */
454                        if( content_length > 0 )
455                        {
456                            /* read it from socket ... */
457                            if( (buflen = uh_tcp_recv(cl, buf, min(content_length, sizeof(buf)))) > 0 )
458                            {
459                                /* ... and write it to child's stdin */
460                                if( write(wfd[1], buf, buflen) < 0 )
461                                    perror("write()");
462
463                                content_length -= buflen;
464                            }
465
466                            /* unexpected eof! */
467                            else
468                            {
469                                if( write(wfd[1], "", 0) < 0 )
470                                    perror("write()");
471
472                                content_length = 0;
473                            }
474                        }
475
476                        /* there is no more post data, close pipe to child's stdin */
477                        else if( content_length > -1 )
478                        {
479                            close(wfd[1]);
480                            content_length = -1;
481                        }
482                    }
483
484                    /* ready to read from Lua child */
485                    if( FD_ISSET(rfd[0], &reader) )
486                    {
487                        /* read data from child ... */
488                        if( (buflen = read(rfd[0], buf, sizeof(buf))) > 0 )
489                        {
490                            /* pass through buffer to socket */
491                            ensure(uh_tcp_send(cl, buf, buflen));
492                            data_sent = 1;
493                        }
494
495                        /* looks like eof from child */
496                        else
497                        {
498                            /* error? */
499                            if( ! data_sent )
500                                uh_http_sendhf(cl, 500, "Internal Server Error",
501                                    "The Lua child did not produce any response");
502
503                            break;
504                        }
505                    }
506                }
507
508                /* no activity for 15 seconds... looks dead */
509                else
510                {
511                    ensure(uh_http_sendhf(cl, 504, "Gateway Timeout",
512                        "The Lua handler took too long to produce a response"));
513
514                    break;
515                }
516            }
517
518        out:
519            close(rfd[0]);
520            close(wfd[1]);
521
522            break;
523    }
524}
525
Note: See TracBrowser for help on using the browser.