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 struct config
*conf
)
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 /* Pass the document-root to the Lua handler by placing it in
168 ** uhttpd.docroot. It could alternatively be placed in env.DOCUMENT_ROOT
169 ** which would more closely resemble the CGI protocol; but would mean that
170 ** it is not available at the time when the handler-chunk is loaded but
171 ** rather not until the handler is called, without any code savings. */
172 lua_pushstring(L
, conf
->docroot
);
173 lua_setfield(L
, -2, "docroot");
175 /* _G.uhttpd = { ... } */
176 lua_setfield(L
, LUA_GLOBALSINDEX
, "uhttpd");
179 /* load Lua handler */
180 switch (luaL_loadfile(L
, conf
->lua_handler
))
184 "Lua handler contains syntax errors, unable to continue\n");
189 "Lua handler ran out of memory, unable to continue\n");
194 "Lua cannot open the handler script, unable to continue\n");
198 /* compile Lua handler */
199 switch (lua_pcall(L
, 0, 0, 0))
202 err_str
= luaL_checkstring(L
, -1);
204 "Lua handler had runtime error, unable to continue\n"
205 "Error: %s\n", err_str
210 err_str
= luaL_checkstring(L
, -1);
212 "Lua handler ran out of memory, unable to continue\n"
213 "Error: %s\n", err_str
218 /* test handler function */
219 lua_getglobal(L
, UH_LUA_CALLBACK
);
221 if (! lua_isfunction(L
, -1))
224 "Lua handler provides no " UH_LUA_CALLBACK
"(), unable to continue\n");
238 void uh_lua_request(struct client
*cl
, struct http_request
*req
, lua_State
*L
)
241 int content_length
= 0;
245 const char *prefix
= cl
->server
->conf
->lua_prefix
;
246 const char *err_str
= NULL
;
248 int rfd
[2] = { 0, 0 };
249 int wfd
[2] = { 0, 0 };
251 char buf
[UH_LIMIT_MSGHEAD
];
259 struct timeval timeout
;
262 /* spawn pipes for me->child, child->me */
263 if ((pipe(rfd
) < 0) || (pipe(wfd
) < 0))
265 uh_http_sendhf(cl
, 500, "Internal Server Error",
266 "Failed to create pipe: %s", strerror(errno
));
268 if (rfd
[0] > 0) close(rfd
[0]);
269 if (rfd
[1] > 0) close(rfd
[1]);
270 if (wfd
[0] > 0) close(wfd
[0]);
271 if (wfd
[1] > 0) close(wfd
[1]);
277 switch ((child
= fork()))
280 uh_http_sendhf(cl
, 500, "Internal Server Error",
281 "Failed to fork child: %s", strerror(errno
));
285 /* restore SIGTERM */
287 sa
.sa_handler
= SIG_DFL
;
288 sigemptyset(&sa
.sa_mask
);
289 sigaction(SIGTERM
, &sa
, NULL
);
291 /* close loose pipe ends */
295 /* patch stdout and stdin to pipes */
299 /* put handler callback on stack */
300 lua_getglobal(L
, UH_LUA_CALLBACK
);
302 /* build env table */
308 case UH_HTTP_MSG_GET
:
309 lua_pushstring(L
, "GET");
312 case UH_HTTP_MSG_HEAD
:
313 lua_pushstring(L
, "HEAD");
316 case UH_HTTP_MSG_POST
:
317 lua_pushstring(L
, "POST");
321 lua_setfield(L
, -2, "REQUEST_METHOD");
324 lua_pushstring(L
, req
->url
);
325 lua_setfield(L
, -2, "REQUEST_URI");
328 lua_pushstring(L
, cl
->server
->conf
->lua_prefix
);
329 lua_setfield(L
, -2, "SCRIPT_NAME");
331 /* query string, path info */
332 if ((query_string
= strchr(req
->url
, '?')) != NULL
)
334 lua_pushstring(L
, query_string
+ 1);
335 lua_setfield(L
, -2, "QUERY_STRING");
337 if ((int)(query_string
- req
->url
) > strlen(prefix
))
340 &req
->url
[strlen(prefix
)],
341 (int)(query_string
- req
->url
) - strlen(prefix
)
344 lua_setfield(L
, -2, "PATH_INFO");
347 else if (strlen(req
->url
) > strlen(prefix
))
349 lua_pushstring(L
, &req
->url
[strlen(prefix
)]);
350 lua_setfield(L
, -2, "PATH_INFO");
353 /* http protcol version */
354 lua_pushnumber(L
, floor(req
->version
* 10) / 10);
355 lua_setfield(L
, -2, "HTTP_VERSION");
357 if (req
->version
> 1.0)
358 lua_pushstring(L
, "HTTP/1.1");
360 lua_pushstring(L
, "HTTP/1.0");
362 lua_setfield(L
, -2, "SERVER_PROTOCOL");
365 /* address information */
366 lua_pushstring(L
, sa_straddr(&cl
->peeraddr
));
367 lua_setfield(L
, -2, "REMOTE_ADDR");
369 lua_pushinteger(L
, sa_port(&cl
->peeraddr
));
370 lua_setfield(L
, -2, "REMOTE_PORT");
372 lua_pushstring(L
, sa_straddr(&cl
->servaddr
));
373 lua_setfield(L
, -2, "SERVER_ADDR");
375 lua_pushinteger(L
, sa_port(&cl
->servaddr
));
376 lua_setfield(L
, -2, "SERVER_PORT");
378 /* essential env vars */
379 foreach_header(i
, req
->headers
)
381 if (!strcasecmp(req
->headers
[i
], "Content-Length"))
383 lua_pushnumber(L
, atoi(req
->headers
[i
+1]));
384 lua_setfield(L
, -2, "CONTENT_LENGTH");
386 else if (!strcasecmp(req
->headers
[i
], "Content-Type"))
388 lua_pushstring(L
, req
->headers
[i
+1]);
389 lua_setfield(L
, -2, "CONTENT_TYPE");
396 foreach_header(i
, req
->headers
)
398 if( strcasecmp(req
->headers
[i
], "Content-Length") &&
399 strcasecmp(req
->headers
[i
], "Content-Type")
401 lua_pushstring(L
, req
->headers
[i
+1]);
402 lua_setfield(L
, -2, req
->headers
[i
]);
406 lua_setfield(L
, -2, "headers");
410 switch (lua_pcall(L
, 1, 0, 0))
414 err_str
= luaL_checkstring(L
, -1);
417 err_str
= "Unknown error";
420 "HTTP/%.1f 500 Internal Server Error\r\n"
421 "Connection: close\r\n"
422 "Content-Type: text/plain\r\n"
423 "Content-Length: %i\r\n\r\n"
424 "Lua raised a runtime error:\n %s\n",
425 req
->version
, 31 + strlen(err_str
), err_str
440 /* parent; handle I/O relaying */
442 /* close unneeded pipe ends */
447 fd_max
= max(rfd
[0], wfd
[1]) + 1;
449 /* find content length */
450 if (req
->method
== UH_HTTP_MSG_POST
)
452 foreach_header(i
, req
->headers
)
454 if (! strcasecmp(req
->headers
[i
], "Content-Length"))
456 content_length
= atoi(req
->headers
[i
+1]);
464 do { if (x < 0) goto out; } while(0)
468 timeout
.tv_sec
= cl
->server
->conf
->script_timeout
;
471 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
477 FD_SET(rfd
[0], &reader
);
478 FD_SET(wfd
[1], &writer
);
480 /* wait until we can read or write or both */
481 if (select_intr(fd_max
, &reader
,
482 (content_length
> -1) ? &writer
: NULL
,
484 (data_sent
< 1) ? &timeout
: NULL
) > 0)
486 /* ready to write to Lua child */
487 if (FD_ISSET(wfd
[1], &writer
))
489 /* there is unread post data waiting */
490 if (content_length
> 0)
492 /* read it from socket ... */
493 if ((buflen
= uh_tcp_recv(cl
, buf
, min(content_length
, sizeof(buf
)))) > 0)
495 /* ... and write it to child's stdin */
496 if (write(wfd
[1], buf
, buflen
) < 0)
499 content_length
-= buflen
;
502 /* unexpected eof! */
505 if (write(wfd
[1], "", 0) < 0)
512 /* there is no more post data, close pipe to child's stdin */
513 else if (content_length
> -1)
520 /* ready to read from Lua child */
521 if (FD_ISSET(rfd
[0], &reader
))
523 /* read data from child ... */
524 if ((buflen
= read(rfd
[0], buf
, sizeof(buf
))) > 0)
526 /* pass through buffer to socket */
527 ensure(uh_tcp_send(cl
, buf
, buflen
));
531 /* looks like eof from child */
536 uh_http_sendhf(cl
, 500, "Internal Server Error",
537 "The Lua child did not produce any response");
544 /* timeout exceeded or interrupted by SIGCHLD */
547 if ((errno
!= EINTR
) && ! data_sent
)
549 ensure(uh_http_sendhf(cl
, 504, "Gateway Timeout",
550 "The Lua script took too long to produce "
564 kill(child
, SIGTERM
);
565 waitpid(child
, NULL
, 0);
572 void uh_lua_close(lua_State
*L
)