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_urldecode(lua_State
*L
)
113 size_t inlen
, outlen
;
115 char outbuf
[UH_LIMIT_MSGHEAD
];
117 inbuf
= luaL_checklstring(L
, 1, &inlen
);
118 outlen
= uh_urldecode(outbuf
, sizeof(outbuf
), inbuf
, inlen
);
120 lua_pushlstring(L
, outbuf
, outlen
);
125 lua_State
* uh_lua_init(const char *handler
)
127 lua_State
*L
= lua_open();
128 const char *err_str
= NULL
;
130 /* Load standard libaries */
133 /* build uhttpd api table */
136 /* register global send and receive functions */
137 lua_pushcfunction(L
, uh_lua_recv
);
138 lua_setfield(L
, -2, "recv");
140 lua_pushcfunction(L
, uh_lua_send
);
141 lua_setfield(L
, -2, "send");
143 lua_pushcfunction(L
, uh_lua_sendc
);
144 lua_setfield(L
, -2, "sendc");
146 lua_pushcfunction(L
, uh_lua_urldecode
);
147 lua_setfield(L
, -2, "urldecode");
149 /* _G.uhttpd = { ... } */
150 lua_setfield(L
, LUA_GLOBALSINDEX
, "uhttpd");
153 /* load Lua handler */
154 switch( luaL_loadfile(L
, handler
) )
158 "Lua handler contains syntax errors, unable to continue\n");
163 "Lua handler ran out of memory, unable to continue\n");
168 "Lua cannot open the handler script, unable to continue\n");
172 /* compile Lua handler */
173 switch( lua_pcall(L
, 0, 0, 0) )
176 err_str
= luaL_checkstring(L
, -1);
178 "Lua handler had runtime error, unable to continue\n"
179 "Error: %s\n", err_str
184 err_str
= luaL_checkstring(L
, -1);
186 "Lua handler ran out of memory, unable to continue\n"
187 "Error: %s\n", err_str
192 /* test handler function */
193 lua_getglobal(L
, UH_LUA_CALLBACK
);
195 if( ! lua_isfunction(L
, -1) )
198 "Lua handler provides no " UH_LUA_CALLBACK
"(), unable to continue\n");
212 void uh_lua_request(struct client
*cl
, struct http_request
*req
, lua_State
*L
)
217 int content_length
= 0;
221 const char *prefix
= cl
->server
->conf
->lua_prefix
;
222 const char *err_str
= NULL
;
224 int rfd
[2] = { 0, 0 };
225 int wfd
[2] = { 0, 0 };
227 char buf
[UH_LIMIT_MSGHEAD
];
232 struct timeval timeout
;
235 /* spawn pipes for me->child, child->me */
236 if( (pipe(rfd
) < 0) || (pipe(wfd
) < 0) )
238 uh_http_sendhf(cl
, 500, "Internal Server Error",
239 "Failed to create pipe: %s", strerror(errno
));
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]);
250 switch( (pid
= fork()) )
253 uh_http_sendhf(cl
, 500, "Internal Server Error",
254 "Failed to fork child: %s", strerror(errno
));
262 /* patch stdout and stdin to pipes */
266 /* put handler callback on stack */
267 lua_getglobal(L
, UH_LUA_CALLBACK
);
269 /* build env table */
275 case UH_HTTP_MSG_GET
:
276 lua_pushstring(L
, "GET");
279 case UH_HTTP_MSG_HEAD
:
280 lua_pushstring(L
, "HEAD");
283 case UH_HTTP_MSG_POST
:
284 lua_pushstring(L
, "POST");
288 lua_setfield(L
, -2, "REQUEST_METHOD");
291 lua_pushstring(L
, req
->url
);
292 lua_setfield(L
, -2, "REQUEST_URI");
295 lua_pushstring(L
, cl
->server
->conf
->lua_prefix
);
296 lua_setfield(L
, -2, "SCRIPT_NAME");
298 /* query string, path info */
299 if( (query_string
= strchr(req
->url
, '?')) != NULL
)
301 lua_pushstring(L
, query_string
+ 1);
302 lua_setfield(L
, -2, "QUERY_STRING");
304 if( (int)(query_string
- req
->url
) > strlen(prefix
) )
307 &req
->url
[strlen(prefix
)],
308 (int)(query_string
- req
->url
) - strlen(prefix
)
311 lua_setfield(L
, -2, "PATH_INFO");
314 else if( strlen(req
->url
) > strlen(prefix
) )
316 lua_pushstring(L
, &req
->url
[strlen(prefix
)]);
317 lua_setfield(L
, -2, "PATH_INFO");
320 /* http protcol version */
321 lua_pushnumber(L
, floor(req
->version
* 10) / 10);
322 lua_setfield(L
, -2, "HTTP_VERSION");
324 if( req
->version
> 1.0 )
325 lua_pushstring(L
, "HTTP/1.1");
327 lua_pushstring(L
, "HTTP/1.0");
329 lua_setfield(L
, -2, "SERVER_PROTOCOL");
332 /* address information */
333 lua_pushstring(L
, sa_straddr(&cl
->peeraddr
));
334 lua_setfield(L
, -2, "REMOTE_ADDR");
336 lua_pushinteger(L
, sa_port(&cl
->peeraddr
));
337 lua_setfield(L
, -2, "REMOTE_PORT");
339 lua_pushstring(L
, sa_straddr(&cl
->servaddr
));
340 lua_setfield(L
, -2, "SERVER_ADDR");
342 lua_pushinteger(L
, sa_port(&cl
->servaddr
));
343 lua_setfield(L
, -2, "SERVER_PORT");
345 /* essential env vars */
346 foreach_header(i
, req
->headers
)
348 if( !strcasecmp(req
->headers
[i
], "Content-Length") )
350 lua_pushnumber(L
, atoi(req
->headers
[i
+1]));
351 lua_setfield(L
, -2, "CONTENT_LENGTH");
353 else if( !strcasecmp(req
->headers
[i
], "Content-Type") )
355 lua_pushstring(L
, req
->headers
[i
+1]);
356 lua_setfield(L
, -2, "CONTENT_TYPE");
363 foreach_header(i
, req
->headers
)
365 if( strcasecmp(req
->headers
[i
], "Content-Length") &&
366 strcasecmp(req
->headers
[i
], "Content-Type")
368 lua_pushstring(L
, req
->headers
[i
+1]);
369 lua_setfield(L
, -2, req
->headers
[i
]);
373 lua_setfield(L
, -2, "headers");
377 switch( lua_pcall(L
, 1, 0, 0) )
381 err_str
= luaL_checkstring(L
, -1);
384 err_str
= "Unknown error";
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
407 /* parent; handle I/O relaying */
409 /* close unneeded pipe ends */
414 fd_max
= max(rfd
[0], wfd
[1]) + 1;
416 /* find content length */
417 if( req
->method
== UH_HTTP_MSG_POST
)
419 foreach_header(i
, req
->headers
)
421 if( ! strcasecmp(req
->headers
[i
], "Content-Length") )
423 content_length
= atoi(req
->headers
[i
+1]);
431 do { if( x < 0 ) goto out; } while(0)
435 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
441 FD_SET(rfd
[0], &reader
);
442 FD_SET(wfd
[1], &writer
);
447 /* wait until we can read or write or both */
448 if( select(fd_max
, &reader
, (content_length
> -1) ? &writer
: NULL
, NULL
, &timeout
) > 0 )
450 /* ready to write to Lua child */
451 if( FD_ISSET(wfd
[1], &writer
) )
453 /* there is unread post data waiting */
454 if( content_length
> 0 )
456 /* read it from socket ... */
457 if( (buflen
= uh_tcp_recv(cl
, buf
, min(content_length
, sizeof(buf
)))) > 0 )
459 /* ... and write it to child's stdin */
460 if( write(wfd
[1], buf
, buflen
) < 0 )
463 content_length
-= buflen
;
466 /* unexpected eof! */
469 if( write(wfd
[1], "", 0) < 0 )
476 /* there is no more post data, close pipe to child's stdin */
477 else if( content_length
> -1 )
484 /* ready to read from Lua child */
485 if( FD_ISSET(rfd
[0], &reader
) )
487 /* read data from child ... */
488 if( (buflen
= read(rfd
[0], buf
, sizeof(buf
))) > 0 )
490 /* pass through buffer to socket */
491 ensure(uh_tcp_send(cl
, buf
, buflen
));
495 /* looks like eof from child */
500 uh_http_sendhf(cl
, 500, "Internal Server Error",
501 "The Lua child did not produce any response");
508 /* no activity for 15 seconds... looks dead */
511 ensure(uh_http_sendhf(cl
, 504, "Gateway Timeout",
512 "The Lua handler took too long to produce a response"));