[package] uhttpd: add explicit stdin eof notification for Lua and CGI childs
[openwrt.git] / package / uhttpd / src / uhttpd-lua.c
1 /*
2  * uhttpd - Tiny single-threaded httpd - Lua handler
3  *
4  *   Copyright (C) 2010-2012 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
28         char buffer[UH_LIMIT_MSGHEAD];
29
30         int to = 1;
31         int fd = fileno(stdin);
32         int rlen = 0;
33
34         length = luaL_checknumber(L, 1);
35
36         if ((length > 0) && (length <= sizeof(buffer)))
37         {
38                 /* receive data */
39                 rlen = uh_raw_recv(fd, buffer, length, to);
40
41                 /* data read */
42                 if (rlen > 0)
43                 {
44                         lua_pushnumber(L, rlen);
45                         lua_pushlstring(L, buffer, rlen);
46                         return 2;
47                 }
48
49                 /* eof */
50                 else if (rlen == 0)
51                 {
52                         lua_pushnumber(L, 0);
53                         return 1;
54                 }
55
56                 /* no, timeout and actually no data */
57                 else
58                 {
59                         lua_pushnumber(L, -1);
60                         return 1;
61                 }
62         }
63
64         /* parameter error */
65         lua_pushnumber(L, -2);
66         return 1;
67 }
68
69 static int uh_lua_send_common(lua_State *L, int chunked)
70 {
71         size_t length;
72
73         char chunk[16];
74         const char *buffer;
75
76         int rv;
77         int to = 1;
78         int fd = fileno(stdout);
79         int slen = 0;
80
81         buffer = luaL_checklstring(L, 1, &length);
82
83         if (chunked)
84         {
85                 if (length > 0)
86                 {
87                         snprintf(chunk, sizeof(chunk), "%X\r\n", length);
88
89                         ensure_out(rv = uh_raw_send(fd, chunk, strlen(chunk), to));
90                         slen += rv;
91
92                         ensure_out(rv = uh_raw_send(fd, buffer, length, to));
93                         slen += rv;
94
95                         ensure_out(rv = uh_raw_send(fd, "\r\n", 2, to));
96                         slen += rv;
97                 }
98                 else
99                 {
100                         slen = uh_raw_send(fd, "0\r\n\r\n", 5, to);
101                 }
102         }
103         else
104         {
105                 slen = uh_raw_send(fd, buffer, length, to);
106         }
107
108 out:
109         lua_pushnumber(L, slen);
110         return 1;
111 }
112
113 static int uh_lua_send(lua_State *L)
114 {
115         return uh_lua_send_common(L, 0);
116 }
117
118 static int uh_lua_sendc(lua_State *L)
119 {
120         return uh_lua_send_common(L, 1);
121 }
122
123 static int uh_lua_str2str(lua_State *L, int (*xlate_func) (char *, int, const char *, int))
124 {
125         size_t inlen;
126         int outlen;
127         const char *inbuf;
128         char outbuf[UH_LIMIT_MSGHEAD];
129
130         inbuf = luaL_checklstring(L, 1, &inlen);
131         outlen = (* xlate_func)(outbuf, sizeof(outbuf), inbuf, inlen);
132         if (outlen < 0)
133                 luaL_error(L, "%s on URL-encode codec",
134                                    (outlen==-1) ? "buffer overflow" : "malformed string");
135
136         lua_pushlstring(L, outbuf, outlen);
137         return 1;
138 }
139
140 static int uh_lua_urldecode(lua_State *L)
141 {
142         return uh_lua_str2str( L, uh_urldecode );
143 }
144
145
146 static int uh_lua_urlencode(lua_State *L)
147 {
148         return uh_lua_str2str( L, uh_urlencode );
149 }
150
151
152 lua_State * uh_lua_init(const struct config *conf)
153 {
154         lua_State *L = lua_open();
155         const char *err_str = NULL;
156
157         /* Load standard libaries */
158         luaL_openlibs(L);
159
160         /* build uhttpd api table */
161         lua_newtable(L);
162
163         /* register global send and receive functions */
164         lua_pushcfunction(L, uh_lua_recv);
165         lua_setfield(L, -2, "recv");
166
167         lua_pushcfunction(L, uh_lua_send);
168         lua_setfield(L, -2, "send");
169
170         lua_pushcfunction(L, uh_lua_sendc);
171         lua_setfield(L, -2, "sendc");
172
173         lua_pushcfunction(L, uh_lua_urldecode);
174         lua_setfield(L, -2, "urldecode");
175
176         lua_pushcfunction(L, uh_lua_urlencode);
177         lua_setfield(L, -2, "urlencode");
178
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");
186
187         /* _G.uhttpd = { ... } */
188         lua_setfield(L, LUA_GLOBALSINDEX, "uhttpd");
189
190
191         /* load Lua handler */
192         switch (luaL_loadfile(L, conf->lua_handler))
193         {
194                 case LUA_ERRSYNTAX:
195                         fprintf(stderr,
196                                         "Lua handler contains syntax errors, unable to continue\n");
197                         exit(1);
198
199                 case LUA_ERRMEM:
200                         fprintf(stderr,
201                                         "Lua handler ran out of memory, unable to continue\n");
202                         exit(1);
203
204                 case LUA_ERRFILE:
205                         fprintf(stderr,
206                                         "Lua cannot open the handler script, unable to continue\n");
207                         exit(1);
208
209                 default:
210                         /* compile Lua handler */
211                         switch (lua_pcall(L, 0, 0, 0))
212                         {
213                                 case LUA_ERRRUN:
214                                         err_str = luaL_checkstring(L, -1);
215                                         fprintf(stderr,
216                                                         "Lua handler had runtime error, "
217                                                         "unable to continue\n"
218                                                         "Error: %s\n", err_str);
219                                         exit(1);
220
221                                 case LUA_ERRMEM:
222                                         err_str = luaL_checkstring(L, -1);
223                                         fprintf(stderr,
224                                                         "Lua handler ran out of memory, "
225                                                         "unable to continue\n"
226                                                         "Error: %s\n", err_str);
227                                         exit(1);
228
229                                 default:
230                                         /* test handler function */
231                                         lua_getglobal(L, UH_LUA_CALLBACK);
232
233                                         if (! lua_isfunction(L, -1))
234                                         {
235                                                 fprintf(stderr,
236                                                                 "Lua handler provides no "UH_LUA_CALLBACK"(), "
237                                                                 "unable to continue\n");
238                                                 exit(1);
239                                         }
240
241                                         lua_pop(L, 1);
242                                         break;
243                         }
244
245                         break;
246         }
247
248         return L;
249 }
250
251 static void uh_lua_shutdown(struct uh_lua_state *state)
252 {
253         close(state->rfd);
254         close(state->wfd);
255         free(state);
256 }
257
258 static bool uh_lua_socket_cb(struct client *cl)
259 {
260         int len;
261         char buf[UH_LIMIT_MSGHEAD];
262
263         struct uh_lua_state *state = (struct uh_lua_state *)cl->priv;
264
265         /* there is unread post data waiting */
266         while (state->content_length > 0)
267         {
268                 /* remaining data in http head buffer ... */
269                 if (state->cl->httpbuf.len > 0)
270                 {
271                         len = min(state->content_length, state->cl->httpbuf.len);
272
273                         D("Lua: Child(%d) feed %d HTTP buffer bytes\n",
274                           state->cl->proc.pid, len);
275
276                         memcpy(buf, state->cl->httpbuf.ptr, len);
277
278                         state->cl->httpbuf.len -= len;
279                         state->cl->httpbuf.ptr += len;
280                 }
281
282                 /* read it from socket ... */
283                 else
284                 {
285                         len = uh_tcp_recv(state->cl, buf,
286                                                           min(state->content_length, sizeof(buf)));
287
288                         if ((len < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
289                                 break;
290
291                         D("Lua: Child(%d) feed %d/%d TCP socket bytes\n",
292                           state->cl->proc.pid, len,
293                           min(state->content_length, sizeof(buf)));
294                 }
295
296                 if (len)
297                         state->content_length -= len;
298                 else
299                         state->content_length = 0;
300
301                 /* ... write to Lua process */
302                 len = uh_raw_send(state->wfd, buf, len,
303                                                   cl->server->conf->script_timeout);
304
305                 /* explicit EOF notification for the child */
306                 if (state->content_length <= 0)
307                         close(state->wfd);
308         }
309
310         /* try to read data from child */
311         while ((len = uh_raw_recv(state->rfd, buf, sizeof(buf), -1)) > 0)
312         {
313                 /* pass through buffer to socket */
314                 D("Lua: Child(%d) relaying %d normal bytes\n", state->cl->proc.pid, len);
315                 ensure_out(uh_tcp_send(state->cl, buf, len));
316                 state->data_sent = true;
317         }
318
319         /* child has been marked dead by timeout or child handler, bail out */
320         if (false && cl->dead)
321         {
322                 D("Lua: Child(%d) is marked dead, returning\n", state->cl->proc.pid);
323                 goto out;
324         }
325
326         if ((len == 0) ||
327                 ((errno != EAGAIN) && (errno != EWOULDBLOCK) && (len == -1)))
328         {
329                 D("Lua: Child(%d) presumed dead [%s]\n",
330                   state->cl->proc.pid, strerror(errno));
331
332                 goto out;
333         }
334
335         return true;
336
337 out:
338         if (!state->data_sent)
339         {
340                 if (state->cl->timeout.pending)
341                         uh_http_sendhf(state->cl, 502, "Bad Gateway",
342                                                    "The Lua process did not produce any response\n");
343                 else
344                         uh_http_sendhf(state->cl, 504, "Gateway Timeout",
345                                                    "The Lua process took too long to produce a "
346                                                    "response\n");
347         }
348
349         uh_lua_shutdown(state);
350         return false;
351 }
352
353 bool uh_lua_request(struct client *cl, lua_State *L)
354 {
355         int i;
356         char *query_string;
357         const char *prefix = cl->server->conf->lua_prefix;
358         const char *err_str = NULL;
359
360         int rfd[2] = { 0, 0 };
361         int wfd[2] = { 0, 0 };
362
363         pid_t child;
364
365         struct uh_lua_state *state;
366         struct http_request *req = &cl->request;
367
368         int content_length = cl->httpbuf.len;
369
370
371         /* allocate state */
372         if (!(state = malloc(sizeof(*state))))
373         {
374                 uh_client_error(cl, 500, "Internal Server Error", "Out of memory");
375                 return false;
376         }
377
378         /* spawn pipes for me->child, child->me */
379         if ((pipe(rfd) < 0) || (pipe(wfd) < 0))
380         {
381                 if (rfd[0] > 0) close(rfd[0]);
382                 if (rfd[1] > 0) close(rfd[1]);
383                 if (wfd[0] > 0) close(wfd[0]);
384                 if (wfd[1] > 0) close(wfd[1]);
385
386                 uh_client_error(cl, 500, "Internal Server Error",
387                                                 "Failed to create pipe: %s", strerror(errno));
388
389                 return false;
390         }
391
392
393         switch ((child = fork()))
394         {
395         case -1:
396                 uh_client_error(cl, 500, "Internal Server Error",
397                                                 "Failed to fork child: %s", strerror(errno));
398
399                 return false;
400
401         case 0:
402 #ifdef DEBUG
403                 sleep(atoi(getenv("UHTTPD_SLEEP_ON_FORK") ?: "0"));
404 #endif
405
406                 /* close loose pipe ends */
407                 close(rfd[0]);
408                 close(wfd[1]);
409
410                 /* patch stdout and stdin to pipes */
411                 dup2(rfd[1], 1);
412                 dup2(wfd[0], 0);
413
414                 /* avoid leaking our pipe into child-child processes */
415                 fd_cloexec(rfd[1]);
416                 fd_cloexec(wfd[0]);
417
418                 /* put handler callback on stack */
419                 lua_getglobal(L, UH_LUA_CALLBACK);
420
421                 /* build env table */
422                 lua_newtable(L);
423
424                 /* request method */
425                 switch(req->method)
426                 {
427                         case UH_HTTP_MSG_GET:
428                                 lua_pushstring(L, "GET");
429                                 break;
430
431                         case UH_HTTP_MSG_HEAD:
432                                 lua_pushstring(L, "HEAD");
433                                 break;
434
435                         case UH_HTTP_MSG_POST:
436                                 lua_pushstring(L, "POST");
437                                 break;
438                 }
439
440                 lua_setfield(L, -2, "REQUEST_METHOD");
441
442                 /* request url */
443                 lua_pushstring(L, req->url);
444                 lua_setfield(L, -2, "REQUEST_URI");
445
446                 /* script name */
447                 lua_pushstring(L, cl->server->conf->lua_prefix);
448                 lua_setfield(L, -2, "SCRIPT_NAME");
449
450                 /* query string, path info */
451                 if ((query_string = strchr(req->url, '?')) != NULL)
452                 {
453                         lua_pushstring(L, query_string + 1);
454                         lua_setfield(L, -2, "QUERY_STRING");
455
456                         if ((int)(query_string - req->url) > strlen(prefix))
457                         {
458                                 lua_pushlstring(L,
459                                         &req->url[strlen(prefix)],
460                                         (int)(query_string - req->url) - strlen(prefix)
461                                 );
462
463                                 lua_setfield(L, -2, "PATH_INFO");
464                         }
465                 }
466                 else if (strlen(req->url) > strlen(prefix))
467                 {
468                         lua_pushstring(L, &req->url[strlen(prefix)]);
469                         lua_setfield(L, -2, "PATH_INFO");
470                 }
471
472                 /* http protcol version */
473                 lua_pushnumber(L, floor(req->version * 10) / 10);
474                 lua_setfield(L, -2, "HTTP_VERSION");
475
476                 if (req->version > 1.0)
477                         lua_pushstring(L, "HTTP/1.1");
478                 else
479                         lua_pushstring(L, "HTTP/1.0");
480
481                 lua_setfield(L, -2, "SERVER_PROTOCOL");
482
483
484                 /* address information */
485                 lua_pushstring(L, sa_straddr(&cl->peeraddr));
486                 lua_setfield(L, -2, "REMOTE_ADDR");
487
488                 lua_pushinteger(L, sa_port(&cl->peeraddr));
489                 lua_setfield(L, -2, "REMOTE_PORT");
490
491                 lua_pushstring(L, sa_straddr(&cl->servaddr));
492                 lua_setfield(L, -2, "SERVER_ADDR");
493
494                 lua_pushinteger(L, sa_port(&cl->servaddr));
495                 lua_setfield(L, -2, "SERVER_PORT");
496
497                 /* essential env vars */
498                 foreach_header(i, req->headers)
499                 {
500                         if (!strcasecmp(req->headers[i], "Content-Length"))
501                         {
502                                 content_length = atoi(req->headers[i+1]);
503                         }
504                         else if (!strcasecmp(req->headers[i], "Content-Type"))
505                         {
506                                 lua_pushstring(L, req->headers[i+1]);
507                                 lua_setfield(L, -2, "CONTENT_TYPE");
508                         }
509                 }
510
511                 lua_pushnumber(L, content_length);
512                 lua_setfield(L, -2, "CONTENT_LENGTH");
513
514                 /* misc. headers */
515                 lua_newtable(L);
516
517                 foreach_header(i, req->headers)
518                 {
519                         if( strcasecmp(req->headers[i], "Content-Length") &&
520                                 strcasecmp(req->headers[i], "Content-Type"))
521                         {
522                                 lua_pushstring(L, req->headers[i+1]);
523                                 lua_setfield(L, -2, req->headers[i]);
524                         }
525                 }
526
527                 lua_setfield(L, -2, "headers");
528
529
530                 /* call */
531                 switch (lua_pcall(L, 1, 0, 0))
532                 {
533                         case LUA_ERRMEM:
534                         case LUA_ERRRUN:
535                                 err_str = luaL_checkstring(L, -1);
536
537                                 if (! err_str)
538                                         err_str = "Unknown error";
539
540                                 printf("HTTP/%.1f 500 Internal Server Error\r\n"
541                                            "Connection: close\r\n"
542                                            "Content-Type: text/plain\r\n"
543                                            "Content-Length: %i\r\n\r\n"
544                                            "Lua raised a runtime error:\n  %s\n",
545                                            req->version, 31 + strlen(err_str), err_str);
546
547                                 break;
548
549                         default:
550                                 break;
551                 }
552
553                 close(wfd[0]);
554                 close(rfd[1]);
555                 exit(0);
556
557                 break;
558
559         /* parent; handle I/O relaying */
560         default:
561                 memset(state, 0, sizeof(*state));
562
563                 state->cl = cl;
564                 state->cl->proc.pid = child;
565
566                 /* close unneeded pipe ends */
567                 close(rfd[1]);
568                 close(wfd[0]);
569
570                 D("Lua: Child(%d) created: rfd(%d) wfd(%d)\n", child, rfd[0], wfd[1]);
571
572                 state->content_length = cl->httpbuf.len;
573
574                 /* find content length */
575                 if (req->method == UH_HTTP_MSG_POST)
576                 {
577                         foreach_header(i, req->headers)
578                         {
579                                 if (!strcasecmp(req->headers[i], "Content-Length"))
580                                 {
581                                         state->content_length = atoi(req->headers[i+1]);
582                                         break;
583                                 }
584                         }
585                 }
586
587                 state->rfd = rfd[0];
588                 fd_nonblock(state->rfd);
589
590                 state->wfd = wfd[1];
591                 fd_nonblock(state->wfd);
592
593                 cl->cb = uh_lua_socket_cb;
594                 cl->priv = state;
595
596                 break;
597         }
598
599         return true;
600 }
601
602 void uh_lua_close(lua_State *L)
603 {
604         lua_close(L);
605 }