2 * uhttpd - Tiny single-threaded httpd - Lua handler
4 * Copyright (C) 2010-2012 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
)
28 char buffer
[UH_LIMIT_MSGHEAD
];
31 int fd
= fileno(stdin
);
34 length
= luaL_checknumber(L
, 1);
36 if ((length
> 0) && (length
<= sizeof(buffer
)))
39 rlen
= uh_raw_recv(fd
, buffer
, length
, to
);
44 lua_pushnumber(L
, rlen
);
45 lua_pushlstring(L
, buffer
, rlen
);
56 /* no, timeout and actually no data */
59 lua_pushnumber(L
, -1);
65 lua_pushnumber(L
, -2);
69 static int uh_lua_send_common(lua_State
*L
, int chunked
)
78 int fd
= fileno(stdout
);
81 buffer
= luaL_checklstring(L
, 1, &length
);
87 snprintf(chunk
, sizeof(chunk
), "%X\r\n", length
);
89 ensure_out(rv
= uh_raw_send(fd
, chunk
, strlen(chunk
), to
));
92 ensure_out(rv
= uh_raw_send(fd
, buffer
, length
, to
));
95 ensure_out(rv
= uh_raw_send(fd
, "\r\n", 2, to
));
100 slen
= uh_raw_send(fd
, "0\r\n\r\n", 5, to
);
105 slen
= uh_raw_send(fd
, buffer
, length
, to
);
109 lua_pushnumber(L
, slen
);
113 static int uh_lua_send(lua_State
*L
)
115 return uh_lua_send_common(L
, 0);
118 static int uh_lua_sendc(lua_State
*L
)
120 return uh_lua_send_common(L
, 1);
123 static int uh_lua_str2str(lua_State
*L
, int (*xlate_func
) (char *, int, const char *, int))
128 char outbuf
[UH_LIMIT_MSGHEAD
];
130 inbuf
= luaL_checklstring(L
, 1, &inlen
);
131 outlen
= (* xlate_func
)(outbuf
, sizeof(outbuf
), inbuf
, inlen
);
133 luaL_error(L
, "%s on URL-encode codec",
134 (outlen
==-1) ? "buffer overflow" : "malformed string");
136 lua_pushlstring(L
, outbuf
, outlen
);
140 static int uh_lua_urldecode(lua_State
*L
)
142 return uh_lua_str2str( L
, uh_urldecode
);
146 static int uh_lua_urlencode(lua_State
*L
)
148 return uh_lua_str2str( L
, uh_urlencode
);
152 lua_State
* uh_lua_init(const struct config
*conf
)
154 lua_State
*L
= lua_open();
155 const char *err_str
= NULL
;
157 /* Load standard libaries */
160 /* build uhttpd api table */
163 /* register global send and receive functions */
164 lua_pushcfunction(L
, uh_lua_recv
);
165 lua_setfield(L
, -2, "recv");
167 lua_pushcfunction(L
, uh_lua_send
);
168 lua_setfield(L
, -2, "send");
170 lua_pushcfunction(L
, uh_lua_sendc
);
171 lua_setfield(L
, -2, "sendc");
173 lua_pushcfunction(L
, uh_lua_urldecode
);
174 lua_setfield(L
, -2, "urldecode");
176 lua_pushcfunction(L
, uh_lua_urlencode
);
177 lua_setfield(L
, -2, "urlencode");
179 /* Pass the document-root to the Lua handler by placing it in
180 ** uhttpd.docroot. It could alternatively be placed in env.DOCUMENT_ROOT
181 ** which would more closely resemble the CGI protocol; but would mean that
182 ** it is not available at the time when the handler-chunk is loaded but
183 ** rather not until the handler is called, without any code savings. */
184 lua_pushstring(L
, conf
->docroot
);
185 lua_setfield(L
, -2, "docroot");
187 /* _G.uhttpd = { ... } */
188 lua_setfield(L
, LUA_GLOBALSINDEX
, "uhttpd");
191 /* load Lua handler */
192 switch (luaL_loadfile(L
, conf
->lua_handler
))
196 "Lua handler contains syntax errors, unable to continue\n");
201 "Lua handler ran out of memory, unable to continue\n");
206 "Lua cannot open the handler script, unable to continue\n");
210 /* compile Lua handler */
211 switch (lua_pcall(L
, 0, 0, 0))
214 err_str
= luaL_checkstring(L
, -1);
216 "Lua handler had runtime error, "
217 "unable to continue\n"
218 "Error: %s\n", err_str
);
222 err_str
= luaL_checkstring(L
, -1);
224 "Lua handler ran out of memory, "
225 "unable to continue\n"
226 "Error: %s\n", err_str
);
230 /* test handler function */
231 lua_getglobal(L
, UH_LUA_CALLBACK
);
233 if (! lua_isfunction(L
, -1))
236 "Lua handler provides no "UH_LUA_CALLBACK
"(), "
237 "unable to continue\n");
251 static void uh_lua_shutdown(struct uh_lua_state
*state
)
256 static bool uh_lua_socket_cb(struct client
*cl
)
259 char buf
[UH_LIMIT_MSGHEAD
];
261 struct uh_lua_state
*state
= (struct uh_lua_state
*)cl
->priv
;
263 /* there is unread post data waiting */
264 while (state
->content_length
> 0)
266 /* remaining data in http head buffer ... */
267 if (cl
->httpbuf
.len
> 0)
269 len
= min(state
->content_length
, cl
->httpbuf
.len
);
271 D("Lua: Child(%d) feed %d HTTP buffer bytes\n", cl
->proc
.pid
, len
);
273 memcpy(buf
, cl
->httpbuf
.ptr
, len
);
275 cl
->httpbuf
.len
-= len
;
276 cl
->httpbuf
.ptr
+= len
;
279 /* read it from socket ... */
282 len
= uh_tcp_recv(cl
, buf
, min(state
->content_length
, sizeof(buf
)));
284 if ((len
< 0) && ((errno
== EAGAIN
) || (errno
== EWOULDBLOCK
)))
287 D("Lua: Child(%d) feed %d/%d TCP socket bytes\n",
288 cl
->proc
.pid
, len
, min(state
->content_length
, sizeof(buf
)));
292 state
->content_length
-= len
;
294 state
->content_length
= 0;
296 /* ... write to Lua process */
297 len
= uh_raw_send(cl
->wpipe
.fd
, buf
, len
,
298 cl
->server
->conf
->script_timeout
);
300 /* explicit EOF notification for the child */
301 if (state
->content_length
<= 0)
302 uh_ufd_remove(&cl
->wpipe
);
305 /* try to read data from child */
306 while ((len
= uh_raw_recv(cl
->rpipe
.fd
, buf
, sizeof(buf
), -1)) > 0)
308 /* pass through buffer to socket */
309 D("Lua: Child(%d) relaying %d normal bytes\n", cl
->proc
.pid
, len
);
310 ensure_out(uh_tcp_send(cl
, buf
, len
));
311 state
->data_sent
= true;
314 /* got EOF or read error from child */
316 ((errno
!= EAGAIN
) && (errno
!= EWOULDBLOCK
) && (len
== -1)))
318 D("Lua: Child(%d) presumed dead [%s]\n",
319 cl
->proc
.pid
, strerror(errno
));
327 if (!state
->data_sent
)
329 if (cl
->timeout
.pending
)
330 uh_http_sendhf(cl
, 502, "Bad Gateway",
331 "The Lua process did not produce any response\n");
333 uh_http_sendhf(cl
, 504, "Gateway Timeout",
334 "The Lua process took too long to produce a "
338 uh_lua_shutdown(state
);
342 bool uh_lua_request(struct client
*cl
, lua_State
*L
)
346 const char *prefix
= cl
->server
->conf
->lua_prefix
;
347 const char *err_str
= NULL
;
349 int rfd
[2] = { 0, 0 };
350 int wfd
[2] = { 0, 0 };
354 struct uh_lua_state
*state
;
355 struct http_request
*req
= &cl
->request
;
357 int content_length
= cl
->httpbuf
.len
;
361 if (!(state
= malloc(sizeof(*state
))))
363 uh_client_error(cl
, 500, "Internal Server Error", "Out of memory");
367 /* spawn pipes for me->child, child->me */
368 if ((pipe(rfd
) < 0) || (pipe(wfd
) < 0))
370 if (rfd
[0] > 0) close(rfd
[0]);
371 if (rfd
[1] > 0) close(rfd
[1]);
372 if (wfd
[0] > 0) close(wfd
[0]);
373 if (wfd
[1] > 0) close(wfd
[1]);
375 uh_client_error(cl
, 500, "Internal Server Error",
376 "Failed to create pipe: %s", strerror(errno
));
382 switch ((child
= fork()))
385 uh_client_error(cl
, 500, "Internal Server Error",
386 "Failed to fork child: %s", strerror(errno
));
392 sleep(atoi(getenv("UHTTPD_SLEEP_ON_FORK") ?: "0"));
395 /* do not leak parent epoll descriptor */
398 /* close loose pipe ends */
402 /* patch stdout and stdin to pipes */
406 /* avoid leaking our pipe into child-child processes */
410 /* put handler callback on stack */
411 lua_getglobal(L
, UH_LUA_CALLBACK
);
413 /* build env table */
419 case UH_HTTP_MSG_GET
:
420 lua_pushstring(L
, "GET");
423 case UH_HTTP_MSG_HEAD
:
424 lua_pushstring(L
, "HEAD");
427 case UH_HTTP_MSG_POST
:
428 lua_pushstring(L
, "POST");
432 lua_setfield(L
, -2, "REQUEST_METHOD");
435 lua_pushstring(L
, req
->url
);
436 lua_setfield(L
, -2, "REQUEST_URI");
439 lua_pushstring(L
, cl
->server
->conf
->lua_prefix
);
440 lua_setfield(L
, -2, "SCRIPT_NAME");
442 /* query string, path info */
443 if ((query_string
= strchr(req
->url
, '?')) != NULL
)
445 lua_pushstring(L
, query_string
+ 1);
446 lua_setfield(L
, -2, "QUERY_STRING");
448 if ((int)(query_string
- req
->url
) > strlen(prefix
))
451 &req
->url
[strlen(prefix
)],
452 (int)(query_string
- req
->url
) - strlen(prefix
)
455 lua_setfield(L
, -2, "PATH_INFO");
458 else if (strlen(req
->url
) > strlen(prefix
))
460 lua_pushstring(L
, &req
->url
[strlen(prefix
)]);
461 lua_setfield(L
, -2, "PATH_INFO");
464 /* http protcol version */
465 lua_pushnumber(L
, floor(req
->version
* 10) / 10);
466 lua_setfield(L
, -2, "HTTP_VERSION");
468 if (req
->version
> 1.0)
469 lua_pushstring(L
, "HTTP/1.1");
471 lua_pushstring(L
, "HTTP/1.0");
473 lua_setfield(L
, -2, "SERVER_PROTOCOL");
476 /* address information */
477 lua_pushstring(L
, sa_straddr(&cl
->peeraddr
));
478 lua_setfield(L
, -2, "REMOTE_ADDR");
480 lua_pushinteger(L
, sa_port(&cl
->peeraddr
));
481 lua_setfield(L
, -2, "REMOTE_PORT");
483 lua_pushstring(L
, sa_straddr(&cl
->servaddr
));
484 lua_setfield(L
, -2, "SERVER_ADDR");
486 lua_pushinteger(L
, sa_port(&cl
->servaddr
));
487 lua_setfield(L
, -2, "SERVER_PORT");
489 /* essential env vars */
490 foreach_header(i
, req
->headers
)
492 if (!strcasecmp(req
->headers
[i
], "Content-Length"))
494 content_length
= atoi(req
->headers
[i
+1]);
496 else if (!strcasecmp(req
->headers
[i
], "Content-Type"))
498 lua_pushstring(L
, req
->headers
[i
+1]);
499 lua_setfield(L
, -2, "CONTENT_TYPE");
503 lua_pushnumber(L
, content_length
);
504 lua_setfield(L
, -2, "CONTENT_LENGTH");
509 foreach_header(i
, req
->headers
)
511 if( strcasecmp(req
->headers
[i
], "Content-Length") &&
512 strcasecmp(req
->headers
[i
], "Content-Type"))
514 lua_pushstring(L
, req
->headers
[i
+1]);
515 lua_setfield(L
, -2, req
->headers
[i
]);
519 lua_setfield(L
, -2, "headers");
523 switch (lua_pcall(L
, 1, 0, 0))
527 err_str
= luaL_checkstring(L
, -1);
530 err_str
= "Unknown error";
532 printf("HTTP/%.1f 500 Internal Server Error\r\n"
533 "Connection: close\r\n"
534 "Content-Type: text/plain\r\n"
535 "Content-Length: %i\r\n\r\n"
536 "Lua raised a runtime error:\n %s\n",
537 req
->version
, 31 + strlen(err_str
), err_str
);
551 /* parent; handle I/O relaying */
553 memset(state
, 0, sizeof(*state
));
555 cl
->rpipe
.fd
= rfd
[0];
556 cl
->wpipe
.fd
= wfd
[1];
557 cl
->proc
.pid
= child
;
559 /* make pipe non-blocking */
560 fd_nonblock(cl
->rpipe
.fd
);
561 fd_nonblock(cl
->wpipe
.fd
);
563 /* close unneeded pipe ends */
567 D("Lua: Child(%d) created: rfd(%d) wfd(%d)\n", child
, rfd
[0], wfd
[1]);
569 state
->content_length
= cl
->httpbuf
.len
;
571 /* find content length */
572 if (req
->method
== UH_HTTP_MSG_POST
)
574 foreach_header(i
, req
->headers
)
576 if (!strcasecmp(req
->headers
[i
], "Content-Length"))
578 state
->content_length
= atoi(req
->headers
[i
+1]);
584 cl
->cb
= uh_lua_socket_cb
;
593 void uh_lua_close(lua_State
*L
)