2 * uhttpd - Tiny single-threaded httpd - Lua handler
4 * Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include "uhttpd-utils.h"
21 #include "uhttpd-lua.h"
24 static int uh_lua_recv(lua_State
*L
)
27 char buffer
[UH_LIMIT_MSGHEAD
];
30 struct timeval timeout
;
32 length
= luaL_checknumber(L
, 1);
34 if( (length
> 0) && (length
<= sizeof(buffer
)) )
37 FD_SET(fileno(stdin
), &reader
);
41 timeout
.tv_usec
= 100000;
43 /* check whether fd is readable */
44 if( select(fileno(stdin
) + 1, &reader
, NULL
, NULL
, &timeout
) > 0 )
47 rlen
= read(fileno(stdin
), buffer
, length
);
48 lua_pushnumber(L
, rlen
);
52 lua_pushlstring(L
, buffer
, rlen
);
59 /* no, timeout and actually no data */
60 lua_pushnumber(L
, -2);
65 lua_pushnumber(L
, -3);
69 static int uh_lua_send_common(lua_State
*L
, int chunked
)
76 buffer
= luaL_checklstring(L
, 1, &length
);
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);
89 slen
= write(fileno(stdout
), "0\r\n\r\n", 5);
94 slen
= write(fileno(stdout
), buffer
, length
);
97 lua_pushnumber(L
, slen
);
101 static int uh_lua_send(lua_State
*L
)
103 return uh_lua_send_common(L
, 0);
106 static int uh_lua_sendc(lua_State
*L
)
108 return uh_lua_send_common(L
, 1);
111 static int uh_lua_str2str(lua_State
*L
, int (*xlate_func
) (char *, int, const char *, int))
116 char outbuf
[UH_LIMIT_MSGHEAD
];
118 inbuf
= luaL_checklstring(L
, 1, &inlen
);
119 outlen
= (* xlate_func
)(outbuf
, sizeof(outbuf
), inbuf
, inlen
);
121 luaL_error( L
, "%s on URL-encode codec",
122 (outlen
==-1) ? "buffer overflow" : "malformed string" );
124 lua_pushlstring(L
, outbuf
, outlen
);
128 static int uh_lua_urldecode(lua_State
*L
)
130 return uh_lua_str2str( L
, uh_urldecode
);
134 static int uh_lua_urlencode(lua_State
*L
)
136 return uh_lua_str2str( L
, uh_urlencode
);
140 lua_State
* uh_lua_init(const char *handler
)
142 lua_State
*L
= lua_open();
143 const char *err_str
= NULL
;
145 /* Load standard libaries */
148 /* build uhttpd api table */
151 /* register global send and receive functions */
152 lua_pushcfunction(L
, uh_lua_recv
);
153 lua_setfield(L
, -2, "recv");
155 lua_pushcfunction(L
, uh_lua_send
);
156 lua_setfield(L
, -2, "send");
158 lua_pushcfunction(L
, uh_lua_sendc
);
159 lua_setfield(L
, -2, "sendc");
161 lua_pushcfunction(L
, uh_lua_urldecode
);
162 lua_setfield(L
, -2, "urldecode");
164 lua_pushcfunction(L
, uh_lua_urlencode
);
165 lua_setfield(L
, -2, "urlencode");
167 /* _G.uhttpd = { ... } */
168 lua_setfield(L
, LUA_GLOBALSINDEX
, "uhttpd");
171 /* load Lua handler */
172 switch( luaL_loadfile(L
, handler
) )
176 "Lua handler contains syntax errors, unable to continue\n");
181 "Lua handler ran out of memory, unable to continue\n");
186 "Lua cannot open the handler script, unable to continue\n");
190 /* compile Lua handler */
191 switch( lua_pcall(L
, 0, 0, 0) )
194 err_str
= luaL_checkstring(L
, -1);
196 "Lua handler had runtime error, unable to continue\n"
197 "Error: %s\n", err_str
202 err_str
= luaL_checkstring(L
, -1);
204 "Lua handler ran out of memory, unable to continue\n"
205 "Error: %s\n", err_str
210 /* test handler function */
211 lua_getglobal(L
, UH_LUA_CALLBACK
);
213 if( ! lua_isfunction(L
, -1) )
216 "Lua handler provides no " UH_LUA_CALLBACK
"(), unable to continue\n");
230 void uh_lua_request(struct client
*cl
, struct http_request
*req
, lua_State
*L
)
233 int content_length
= 0;
237 const char *prefix
= cl
->server
->conf
->lua_prefix
;
238 const char *err_str
= NULL
;
240 int rfd
[2] = { 0, 0 };
241 int wfd
[2] = { 0, 0 };
243 char buf
[UH_LIMIT_MSGHEAD
];
251 struct timeval timeout
;
254 /* spawn pipes for me->child, child->me */
255 if( (pipe(rfd
) < 0) || (pipe(wfd
) < 0) )
257 uh_http_sendhf(cl
, 500, "Internal Server Error",
258 "Failed to create pipe: %s", strerror(errno
));
260 if( rfd
[0] > 0 ) close(rfd
[0]);
261 if( rfd
[1] > 0 ) close(rfd
[1]);
262 if( wfd
[0] > 0 ) close(wfd
[0]);
263 if( wfd
[1] > 0 ) close(wfd
[1]);
269 switch( (child
= fork()) )
272 uh_http_sendhf(cl
, 500, "Internal Server Error",
273 "Failed to fork child: %s", strerror(errno
));
277 /* restore SIGTERM */
279 sa
.sa_handler
= SIG_DFL
;
280 sigemptyset(&sa
.sa_mask
);
281 sigaction(SIGTERM
, &sa
, NULL
);
283 /* close loose pipe ends */
287 /* patch stdout and stdin to pipes */
291 /* put handler callback on stack */
292 lua_getglobal(L
, UH_LUA_CALLBACK
);
294 /* build env table */
300 case UH_HTTP_MSG_GET
:
301 lua_pushstring(L
, "GET");
304 case UH_HTTP_MSG_HEAD
:
305 lua_pushstring(L
, "HEAD");
308 case UH_HTTP_MSG_POST
:
309 lua_pushstring(L
, "POST");
313 lua_setfield(L
, -2, "REQUEST_METHOD");
316 lua_pushstring(L
, req
->url
);
317 lua_setfield(L
, -2, "REQUEST_URI");
320 lua_pushstring(L
, cl
->server
->conf
->lua_prefix
);
321 lua_setfield(L
, -2, "SCRIPT_NAME");
323 /* query string, path info */
324 if( (query_string
= strchr(req
->url
, '?')) != NULL
)
326 lua_pushstring(L
, query_string
+ 1);
327 lua_setfield(L
, -2, "QUERY_STRING");
329 if( (int)(query_string
- req
->url
) > strlen(prefix
) )
332 &req
->url
[strlen(prefix
)],
333 (int)(query_string
- req
->url
) - strlen(prefix
)
336 lua_setfield(L
, -2, "PATH_INFO");
339 else if( strlen(req
->url
) > strlen(prefix
) )
341 lua_pushstring(L
, &req
->url
[strlen(prefix
)]);
342 lua_setfield(L
, -2, "PATH_INFO");
345 /* http protcol version */
346 lua_pushnumber(L
, floor(req
->version
* 10) / 10);
347 lua_setfield(L
, -2, "HTTP_VERSION");
349 if( req
->version
> 1.0 )
350 lua_pushstring(L
, "HTTP/1.1");
352 lua_pushstring(L
, "HTTP/1.0");
354 lua_setfield(L
, -2, "SERVER_PROTOCOL");
357 /* address information */
358 lua_pushstring(L
, sa_straddr(&cl
->peeraddr
));
359 lua_setfield(L
, -2, "REMOTE_ADDR");
361 lua_pushinteger(L
, sa_port(&cl
->peeraddr
));
362 lua_setfield(L
, -2, "REMOTE_PORT");
364 lua_pushstring(L
, sa_straddr(&cl
->servaddr
));
365 lua_setfield(L
, -2, "SERVER_ADDR");
367 lua_pushinteger(L
, sa_port(&cl
->servaddr
));
368 lua_setfield(L
, -2, "SERVER_PORT");
370 /* essential env vars */
371 foreach_header(i
, req
->headers
)
373 if( !strcasecmp(req
->headers
[i
], "Content-Length") )
375 lua_pushnumber(L
, atoi(req
->headers
[i
+1]));
376 lua_setfield(L
, -2, "CONTENT_LENGTH");
378 else if( !strcasecmp(req
->headers
[i
], "Content-Type") )
380 lua_pushstring(L
, req
->headers
[i
+1]);
381 lua_setfield(L
, -2, "CONTENT_TYPE");
388 foreach_header(i
, req
->headers
)
390 if( strcasecmp(req
->headers
[i
], "Content-Length") &&
391 strcasecmp(req
->headers
[i
], "Content-Type")
393 lua_pushstring(L
, req
->headers
[i
+1]);
394 lua_setfield(L
, -2, req
->headers
[i
]);
398 lua_setfield(L
, -2, "headers");
402 switch( lua_pcall(L
, 1, 0, 0) )
406 err_str
= luaL_checkstring(L
, -1);
409 err_str
= "Unknown error";
412 "HTTP/%.1f 500 Internal Server Error\r\n"
413 "Connection: close\r\n"
414 "Content-Type: text/plain\r\n"
415 "Content-Length: %i\r\n\r\n"
416 "Lua raised a runtime error:\n %s\n",
417 req
->version
, 31 + strlen(err_str
), err_str
432 /* parent; handle I/O relaying */
434 /* close unneeded pipe ends */
439 fd_max
= max(rfd
[0], wfd
[1]) + 1;
441 /* find content length */
442 if( req
->method
== UH_HTTP_MSG_POST
)
444 foreach_header(i
, req
->headers
)
446 if( ! strcasecmp(req
->headers
[i
], "Content-Length") )
448 content_length
= atoi(req
->headers
[i
+1]);
456 do { if( x < 0 ) goto out; } while(0)
460 timeout
.tv_sec
= cl
->server
->conf
->script_timeout
;
463 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
469 FD_SET(rfd
[0], &reader
);
470 FD_SET(wfd
[1], &writer
);
472 /* wait until we can read or write or both */
473 if( select_intr(fd_max
, &reader
,
474 (content_length
> -1) ? &writer
: NULL
, NULL
,
475 (data_sent
< 1) ? &timeout
: NULL
) > 0
477 /* ready to write to Lua child */
478 if( FD_ISSET(wfd
[1], &writer
) )
480 /* there is unread post data waiting */
481 if( content_length
> 0 )
483 /* read it from socket ... */
484 if( (buflen
= uh_tcp_recv(cl
, buf
, min(content_length
, sizeof(buf
)))) > 0 )
486 /* ... and write it to child's stdin */
487 if( write(wfd
[1], buf
, buflen
) < 0 )
490 content_length
-= buflen
;
493 /* unexpected eof! */
496 if( write(wfd
[1], "", 0) < 0 )
503 /* there is no more post data, close pipe to child's stdin */
504 else if( content_length
> -1 )
511 /* ready to read from Lua child */
512 if( FD_ISSET(rfd
[0], &reader
) )
514 /* read data from child ... */
515 if( (buflen
= read(rfd
[0], buf
, sizeof(buf
))) > 0 )
517 /* pass through buffer to socket */
518 ensure(uh_tcp_send(cl
, buf
, buflen
));
522 /* looks like eof from child */
527 uh_http_sendhf(cl
, 500, "Internal Server Error",
528 "The Lua child did not produce any response");
535 /* timeout exceeded or interrupted by SIGCHLD */
538 if( (errno
!= EINTR
) && ! data_sent
)
540 ensure(uh_http_sendhf(cl
, 504, "Gateway Timeout",
541 "The Lua script took too long to produce "
553 if( !kill(child
, 0) )
555 kill(child
, SIGTERM
);
556 waitpid(child
, NULL
, 0);
563 void uh_lua_close(lua_State
*L
)