c1e749043864507a449f9b5047e62864a3bd07d7
[openwrt/openwrt.git] / package / uhttpd / src / uhttpd-lua.c
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
24 static 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
69 static 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
101 static int uh_lua_send(lua_State *L)
102 {
103 return uh_lua_send_common(L, 0);
104 }
105
106 static int uh_lua_sendc(lua_State *L)
107 {
108 return uh_lua_send_common(L, 1);
109 }
110
111 static 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
125 lua_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
212 void uh_lua_request(struct client *cl, struct http_request *req, lua_State *L)
213 {
214 int i, data_sent;
215 int content_length = 0;
216 int buflen = 0;
217 int fd_max = 0;
218 char *query_string;
219 const char *prefix = cl->server->conf->lua_prefix;
220 const char *err_str = NULL;
221
222 int rfd[2] = { 0, 0 };
223 int wfd[2] = { 0, 0 };
224
225 char buf[UH_LIMIT_MSGHEAD];
226
227 pid_t child;
228
229 fd_set reader;
230 fd_set writer;
231
232 struct sigaction sa;
233 struct timeval timeout;
234
235
236 /* spawn pipes for me->child, child->me */
237 if( (pipe(rfd) < 0) || (pipe(wfd) < 0) )
238 {
239 uh_http_sendhf(cl, 500, "Internal Server Error",
240 "Failed to create pipe: %s", strerror(errno));
241
242 if( rfd[0] > 0 ) close(rfd[0]);
243 if( rfd[1] > 0 ) close(rfd[1]);
244 if( wfd[0] > 0 ) close(wfd[0]);
245 if( wfd[1] > 0 ) close(wfd[1]);
246
247 return;
248 }
249
250
251 switch( (child = fork()) )
252 {
253 case -1:
254 uh_http_sendhf(cl, 500, "Internal Server Error",
255 "Failed to fork child: %s", strerror(errno));
256 break;
257
258 case 0:
259 /* restore SIGTERM */
260 sa.sa_flags = 0;
261 sa.sa_handler = SIG_DFL;
262 sigemptyset(&sa.sa_mask);
263 sigaction(SIGTERM, &sa, NULL);
264
265 /* close loose pipe ends */
266 close(rfd[0]);
267 close(wfd[1]);
268
269 /* patch stdout and stdin to pipes */
270 dup2(rfd[1], 1);
271 dup2(wfd[0], 0);
272
273 /* put handler callback on stack */
274 lua_getglobal(L, UH_LUA_CALLBACK);
275
276 /* build env table */
277 lua_newtable(L);
278
279 /* request method */
280 switch(req->method)
281 {
282 case UH_HTTP_MSG_GET:
283 lua_pushstring(L, "GET");
284 break;
285
286 case UH_HTTP_MSG_HEAD:
287 lua_pushstring(L, "HEAD");
288 break;
289
290 case UH_HTTP_MSG_POST:
291 lua_pushstring(L, "POST");
292 break;
293 }
294
295 lua_setfield(L, -2, "REQUEST_METHOD");
296
297 /* request url */
298 lua_pushstring(L, req->url);
299 lua_setfield(L, -2, "REQUEST_URI");
300
301 /* script name */
302 lua_pushstring(L, cl->server->conf->lua_prefix);
303 lua_setfield(L, -2, "SCRIPT_NAME");
304
305 /* query string, path info */
306 if( (query_string = strchr(req->url, '?')) != NULL )
307 {
308 lua_pushstring(L, query_string + 1);
309 lua_setfield(L, -2, "QUERY_STRING");
310
311 if( (int)(query_string - req->url) > strlen(prefix) )
312 {
313 lua_pushlstring(L,
314 &req->url[strlen(prefix)],
315 (int)(query_string - req->url) - strlen(prefix)
316 );
317
318 lua_setfield(L, -2, "PATH_INFO");
319 }
320 }
321 else if( strlen(req->url) > strlen(prefix) )
322 {
323 lua_pushstring(L, &req->url[strlen(prefix)]);
324 lua_setfield(L, -2, "PATH_INFO");
325 }
326
327 /* http protcol version */
328 lua_pushnumber(L, floor(req->version * 10) / 10);
329 lua_setfield(L, -2, "HTTP_VERSION");
330
331 if( req->version > 1.0 )
332 lua_pushstring(L, "HTTP/1.1");
333 else
334 lua_pushstring(L, "HTTP/1.0");
335
336 lua_setfield(L, -2, "SERVER_PROTOCOL");
337
338
339 /* address information */
340 lua_pushstring(L, sa_straddr(&cl->peeraddr));
341 lua_setfield(L, -2, "REMOTE_ADDR");
342
343 lua_pushinteger(L, sa_port(&cl->peeraddr));
344 lua_setfield(L, -2, "REMOTE_PORT");
345
346 lua_pushstring(L, sa_straddr(&cl->servaddr));
347 lua_setfield(L, -2, "SERVER_ADDR");
348
349 lua_pushinteger(L, sa_port(&cl->servaddr));
350 lua_setfield(L, -2, "SERVER_PORT");
351
352 /* essential env vars */
353 foreach_header(i, req->headers)
354 {
355 if( !strcasecmp(req->headers[i], "Content-Length") )
356 {
357 lua_pushnumber(L, atoi(req->headers[i+1]));
358 lua_setfield(L, -2, "CONTENT_LENGTH");
359 }
360 else if( !strcasecmp(req->headers[i], "Content-Type") )
361 {
362 lua_pushstring(L, req->headers[i+1]);
363 lua_setfield(L, -2, "CONTENT_TYPE");
364 }
365 }
366
367 /* misc. headers */
368 lua_newtable(L);
369
370 foreach_header(i, req->headers)
371 {
372 if( strcasecmp(req->headers[i], "Content-Length") &&
373 strcasecmp(req->headers[i], "Content-Type")
374 ) {
375 lua_pushstring(L, req->headers[i+1]);
376 lua_setfield(L, -2, req->headers[i]);
377 }
378 }
379
380 lua_setfield(L, -2, "headers");
381
382
383 /* call */
384 switch( lua_pcall(L, 1, 0, 0) )
385 {
386 case LUA_ERRMEM:
387 case LUA_ERRRUN:
388 err_str = luaL_checkstring(L, -1);
389
390 if( ! err_str )
391 err_str = "Unknown error";
392
393 printf(
394 "HTTP/%.1f 500 Internal Server Error\r\n"
395 "Connection: close\r\n"
396 "Content-Type: text/plain\r\n"
397 "Content-Length: %i\r\n\r\n"
398 "Lua raised a runtime error:\n %s\n",
399 req->version, 31 + strlen(err_str), err_str
400 );
401
402 break;
403
404 default:
405 break;
406 }
407
408 close(wfd[0]);
409 close(rfd[1]);
410 exit(0);
411
412 break;
413
414 /* parent; handle I/O relaying */
415 default:
416 /* close unneeded pipe ends */
417 close(rfd[1]);
418 close(wfd[0]);
419
420 /* max watch fd */
421 fd_max = max(rfd[0], wfd[1]) + 1;
422
423 /* find content length */
424 if( req->method == UH_HTTP_MSG_POST )
425 {
426 foreach_header(i, req->headers)
427 {
428 if( ! strcasecmp(req->headers[i], "Content-Length") )
429 {
430 content_length = atoi(req->headers[i+1]);
431 break;
432 }
433 }
434 }
435
436
437 #define ensure(x) \
438 do { if( x < 0 ) goto out; } while(0)
439
440 data_sent = 0;
441
442 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
443 while( 1 )
444 {
445 FD_ZERO(&reader);
446 FD_ZERO(&writer);
447
448 FD_SET(rfd[0], &reader);
449 FD_SET(wfd[1], &writer);
450
451 timeout.tv_sec = cl->server->conf->script_timeout;
452 timeout.tv_usec = 0;
453
454 /* wait until we can read or write or both */
455 if( select(fd_max, &reader, (content_length > -1) ? &writer : NULL, NULL, &timeout) > 0 )
456 {
457 /* ready to write to Lua child */
458 if( FD_ISSET(wfd[1], &writer) )
459 {
460 /* there is unread post data waiting */
461 if( content_length > 0 )
462 {
463 /* read it from socket ... */
464 if( (buflen = uh_tcp_recv(cl, buf, min(content_length, sizeof(buf)))) > 0 )
465 {
466 /* ... and write it to child's stdin */
467 if( write(wfd[1], buf, buflen) < 0 )
468 perror("write()");
469
470 content_length -= buflen;
471 }
472
473 /* unexpected eof! */
474 else
475 {
476 if( write(wfd[1], "", 0) < 0 )
477 perror("write()");
478
479 content_length = 0;
480 }
481 }
482
483 /* there is no more post data, close pipe to child's stdin */
484 else if( content_length > -1 )
485 {
486 close(wfd[1]);
487 content_length = -1;
488 }
489 }
490
491 /* ready to read from Lua child */
492 if( FD_ISSET(rfd[0], &reader) )
493 {
494 /* read data from child ... */
495 if( (buflen = read(rfd[0], buf, sizeof(buf))) > 0 )
496 {
497 /* pass through buffer to socket */
498 ensure(uh_tcp_send(cl, buf, buflen));
499 data_sent = 1;
500 }
501
502 /* looks like eof from child */
503 else
504 {
505 /* error? */
506 if( ! data_sent )
507 uh_http_sendhf(cl, 500, "Internal Server Error",
508 "The Lua child did not produce any response");
509
510 break;
511 }
512 }
513 }
514
515 /* timeout exceeded or interrupted by SIGCHLD */
516 else
517 {
518 if( (errno != EINTR) && ! data_sent )
519 {
520 ensure(uh_http_sendhf(cl, 504, "Gateway Timeout",
521 "The Lua script took too long to produce "
522 "a response"));
523 }
524
525 break;
526 }
527 }
528
529 out:
530 close(rfd[0]);
531 close(wfd[1]);
532
533 if( !kill(child, 0) )
534 kill(child, SIGTERM);
535
536 break;
537 }
538 }
539
540 void uh_lua_close(lua_State *L)
541 {
542 lua_close(L);
543 }
544
545