[package] uhttpd:
[openwrt/svn-archive/archive.git] / package / uhttpd / src / uhttpd-cgi.c
1 /*
2 * uhttpd - Tiny single-threaded httpd - CGI 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-cgi.h"
22
23
24 static bool
25 uh_cgi_header_parse(struct http_response *res, char *buf, int len, int *off)
26 {
27 char *bufptr = NULL;
28 char *hdrname = NULL;
29 int hdrcount = 0;
30 int pos = 0;
31
32 if (((bufptr = strfind(buf, len, "\r\n\r\n", 4)) != NULL) ||
33 ((bufptr = strfind(buf, len, "\n\n", 2)) != NULL))
34 {
35 *off = (int)(bufptr - buf) + ((bufptr[0] == '\r') ? 4 : 2);
36
37 memset(res, 0, sizeof(*res));
38
39 res->statuscode = 200;
40 res->statusmsg = "OK";
41
42 bufptr = &buf[0];
43
44 for (pos = 0; pos < *off; pos++)
45 {
46 if (!hdrname && (buf[pos] == ':'))
47 {
48 buf[pos++] = 0;
49
50 if ((pos < len) && (buf[pos] == ' '))
51 pos++;
52
53 if (pos < len)
54 {
55 hdrname = bufptr;
56 bufptr = &buf[pos];
57 }
58 }
59
60 else if ((buf[pos] == '\r') || (buf[pos] == '\n'))
61 {
62 if (! hdrname)
63 break;
64
65 buf[pos++] = 0;
66
67 if ((pos < len) && (buf[pos] == '\n'))
68 pos++;
69
70 if (pos <= len)
71 {
72 if ((hdrcount+1) < array_size(res->headers))
73 {
74 if (!strcasecmp(hdrname, "Status"))
75 {
76 res->statuscode = atoi(bufptr);
77
78 if (res->statuscode < 100)
79 res->statuscode = 200;
80
81 if (((bufptr = strchr(bufptr, ' ')) != NULL) &&
82 (&bufptr[1] != 0))
83 {
84 res->statusmsg = &bufptr[1];
85 }
86
87 D("CGI: HTTP/1.x %03d %s\n",
88 res->statuscode, res->statusmsg);
89 }
90 else
91 {
92 D("CGI: HTTP: %s: %s\n", hdrname, bufptr);
93
94 res->headers[hdrcount++] = hdrname;
95 res->headers[hdrcount++] = bufptr;
96 }
97
98 bufptr = &buf[pos];
99 hdrname = NULL;
100 }
101 else
102 {
103 return false;
104 }
105 }
106 }
107 }
108
109 return true;
110 }
111
112 return false;
113 }
114
115 static char * uh_cgi_header_lookup(struct http_response *res,
116 const char *hdrname)
117 {
118 int i;
119
120 foreach_header(i, res->headers)
121 {
122 if (!strcasecmp(res->headers[i], hdrname))
123 return res->headers[i+1];
124 }
125
126 return NULL;
127 }
128
129 static void uh_cgi_shutdown(struct uh_cgi_state *state)
130 {
131 close(state->rfd);
132 close(state->wfd);
133 free(state);
134 }
135
136 static bool uh_cgi_socket_cb(struct client *cl)
137 {
138 int i, len, hdroff;
139 char buf[UH_LIMIT_MSGHEAD];
140
141 struct uh_cgi_state *state = (struct uh_cgi_state *)cl->priv;
142 struct http_response *res = &state->cl->response;
143 struct http_request *req = &state->cl->request;
144
145 /* there is unread post data waiting */
146 while (state->content_length > 0)
147 {
148 /* remaining data in http head buffer ... */
149 if (state->cl->httpbuf.len > 0)
150 {
151 len = min(state->content_length, state->cl->httpbuf.len);
152
153 D("CGI: Child(%d) feed %d HTTP buffer bytes\n",
154 state->cl->proc.pid, len);
155
156 memcpy(buf, state->cl->httpbuf.ptr, len);
157
158 state->cl->httpbuf.len -= len;
159 state->cl->httpbuf.ptr +=len;
160 }
161
162 /* read it from socket ... */
163 else
164 {
165 len = uh_tcp_recv(state->cl, buf,
166 min(state->content_length, sizeof(buf)));
167
168 if ((len < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
169 break;
170
171 D("CGI: Child(%d) feed %d/%d TCP socket bytes\n",
172 state->cl->proc.pid, len,
173 min(state->content_length, sizeof(buf)));
174 }
175
176 if (len)
177 state->content_length -= len;
178 else
179 state->content_length = 0;
180
181 /* ... write to CGI process */
182 len = uh_raw_send(state->wfd, buf, len,
183 cl->server->conf->script_timeout);
184 }
185
186 /* try to read data from child */
187 while ((len = uh_raw_recv(state->rfd, buf, sizeof(buf), -1)) > 0)
188 {
189 /* we have not pushed out headers yet, parse input */
190 if (!state->header_sent)
191 {
192 /* try to parse header ... */
193 memcpy(state->httpbuf, buf, len);
194
195 if (uh_cgi_header_parse(res, state->httpbuf, len, &hdroff))
196 {
197 /* write status */
198 ensure_out(uh_http_sendf(state->cl, NULL,
199 "HTTP/%.1f %03d %s\r\n"
200 "Connection: close\r\n",
201 req->version, res->statuscode, res->statusmsg));
202
203 /* add Content-Type if no Location or Content-Type */
204 if (!uh_cgi_header_lookup(res, "Location") &&
205 !uh_cgi_header_lookup(res, "Content-Type"))
206 {
207 ensure_out(uh_http_send(state->cl, NULL,
208 "Content-Type: text/plain\r\n", -1));
209 }
210
211 /* if request was HTTP 1.1 we'll respond chunked */
212 if ((req->version > 1.0) &&
213 !uh_cgi_header_lookup(res, "Transfer-Encoding"))
214 {
215 ensure_out(uh_http_send(state->cl, NULL,
216 "Transfer-Encoding: chunked\r\n", -1));
217 }
218
219 /* write headers from CGI program */
220 foreach_header(i, res->headers)
221 {
222 ensure_out(uh_http_sendf(state->cl, NULL, "%s: %s\r\n",
223 res->headers[i], res->headers[i+1]));
224 }
225
226 /* terminate header */
227 ensure_out(uh_http_send(state->cl, NULL, "\r\n", -1));
228
229 state->header_sent = true;
230
231 /* push out remaining head buffer */
232 if (hdroff < len)
233 {
234 D("CGI: Child(%d) relaying %d rest bytes\n",
235 state->cl->proc.pid, len - hdroff);
236
237 ensure_out(uh_http_send(state->cl, req,
238 &buf[hdroff], len - hdroff));
239 }
240 }
241
242 /* ... failed and head buffer exceeded */
243 else
244 {
245 /* I would do this ...
246 *
247 * uh_cgi_error_500(cl, req,
248 * "The CGI program generated an "
249 * "invalid response:\n\n");
250 *
251 * ... but in order to stay as compatible as possible,
252 * treat whatever we got as text/plain response and
253 * build the required headers here.
254 */
255
256 ensure_out(uh_http_sendf(state->cl, NULL,
257 "HTTP/%.1f 200 OK\r\n"
258 "Content-Type: text/plain\r\n"
259 "%s\r\n",
260 req->version, (req->version > 1.0)
261 ? "Transfer-Encoding: chunked\r\n" : ""
262 ));
263
264 state->header_sent = true;
265
266 D("CGI: Child(%d) relaying %d invalid bytes\n",
267 state->cl->proc.pid, len);
268
269 ensure_out(uh_http_send(state->cl, req, buf, len));
270 }
271 }
272 else
273 {
274 /* headers complete, pass through buffer to socket */
275 D("CGI: Child(%d) relaying %d normal bytes\n",
276 state->cl->proc.pid, len);
277
278 ensure_out(uh_http_send(state->cl, req, buf, len));
279 }
280 }
281
282 /* child has been marked dead by timeout or child handler, bail out */
283 if (false && cl->dead)
284 {
285 D("CGI: Child(%d) is marked dead, returning\n", state->cl->proc.pid);
286 goto out;
287 }
288
289 if ((len == 0) ||
290 ((errno != EAGAIN) && (errno != EWOULDBLOCK) && (len == -1)))
291 {
292 D("CGI: Child(%d) presumed dead [%s]\n",
293 state->cl->proc.pid, strerror(errno));
294
295 goto out;
296 }
297
298 return true;
299
300 out:
301 if (!state->header_sent)
302 {
303 if (state->cl->timeout.pending)
304 uh_http_sendhf(state->cl, 502, "Bad Gateway",
305 "The CGI process did not produce any response\n");
306 else
307 uh_http_sendhf(state->cl, 504, "Gateway Timeout",
308 "The CGI process took too long to produce a "
309 "response\n");
310 }
311 else
312 {
313 uh_http_send(state->cl, req, "", 0);
314 }
315
316 uh_cgi_shutdown(state);
317 return false;
318 }
319
320 bool uh_cgi_request(struct client *cl, struct path_info *pi,
321 struct interpreter *ip)
322 {
323 int i;
324
325 int rfd[2] = { 0, 0 };
326 int wfd[2] = { 0, 0 };
327
328 pid_t child;
329
330 struct uh_cgi_state *state;
331 struct http_request *req = &cl->request;
332
333 /* allocate state */
334 if (!(state = malloc(sizeof(*state))))
335 {
336 uh_http_sendhf(cl, 500, "Internal Server Error", "Out of memory");
337 return false;
338 }
339
340 /* spawn pipes for me->child, child->me */
341 if ((pipe(rfd) < 0) || (pipe(wfd) < 0))
342 {
343 if (rfd[0] > 0) close(rfd[0]);
344 if (rfd[1] > 0) close(rfd[1]);
345 if (wfd[0] > 0) close(wfd[0]);
346 if (wfd[1] > 0) close(wfd[1]);
347
348 uh_http_sendhf(cl, 500, "Internal Server Error",
349 "Failed to create pipe: %s\n", strerror(errno));
350
351 return false;
352 }
353
354 /* fork off child process */
355 switch ((child = fork()))
356 {
357 /* oops */
358 case -1:
359 uh_http_sendhf(cl, 500, "Internal Server Error",
360 "Failed to fork child: %s\n", strerror(errno));
361
362 return false;
363
364 /* exec child */
365 case 0:
366 #ifdef DEBUG
367 sleep(atoi(getenv("UHTTPD_SLEEP_ON_FORK") ?: "0"));
368 #endif
369
370 /* close loose pipe ends */
371 close(rfd[0]);
372 close(wfd[1]);
373
374 /* patch stdout and stdin to pipes */
375 dup2(rfd[1], 1);
376 dup2(wfd[0], 0);
377
378 /* avoid leaking our pipe into child-child processes */
379 fd_cloexec(rfd[1]);
380 fd_cloexec(wfd[0]);
381
382 /* check for regular, world-executable file _or_ interpreter */
383 if (((pi->stat.st_mode & S_IFREG) &&
384 (pi->stat.st_mode & S_IXOTH)) || (ip != NULL))
385 {
386 /* build environment */
387 clearenv();
388
389 /* common information */
390 setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
391 setenv("SERVER_SOFTWARE", "uHTTPd", 1);
392 setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
393
394 #ifdef HAVE_TLS
395 /* https? */
396 if (cl->tls)
397 setenv("HTTPS", "on", 1);
398 #endif
399
400 /* addresses */
401 setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
402 setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
403 setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
404 setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
405 setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
406 setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
407
408 /* path information */
409 setenv("SCRIPT_NAME", pi->name, 1);
410 setenv("SCRIPT_FILENAME", pi->phys, 1);
411 setenv("DOCUMENT_ROOT", pi->root, 1);
412 setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
413
414 if (pi->info)
415 setenv("PATH_INFO", pi->info, 1);
416
417 /* REDIRECT_STATUS, php-cgi wants it */
418 switch (req->redirect_status)
419 {
420 case 404:
421 setenv("REDIRECT_STATUS", "404", 1);
422 break;
423
424 default:
425 setenv("REDIRECT_STATUS", "200", 1);
426 break;
427 }
428
429 /* http version */
430 if (req->version > 1.0)
431 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
432 else
433 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
434
435 /* request method */
436 switch (req->method)
437 {
438 case UH_HTTP_MSG_GET:
439 setenv("REQUEST_METHOD", "GET", 1);
440 break;
441
442 case UH_HTTP_MSG_HEAD:
443 setenv("REQUEST_METHOD", "HEAD", 1);
444 break;
445
446 case UH_HTTP_MSG_POST:
447 setenv("REQUEST_METHOD", "POST", 1);
448 break;
449 }
450
451 /* request url */
452 setenv("REQUEST_URI", req->url, 1);
453
454 /* remote user */
455 if (req->realm)
456 setenv("REMOTE_USER", req->realm->user, 1);
457
458 /* request message headers */
459 foreach_header(i, req->headers)
460 {
461 if (!strcasecmp(req->headers[i], "Accept"))
462 setenv("HTTP_ACCEPT", req->headers[i+1], 1);
463
464 else if (!strcasecmp(req->headers[i], "Accept-Charset"))
465 setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
466
467 else if (!strcasecmp(req->headers[i], "Accept-Encoding"))
468 setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
469
470 else if (!strcasecmp(req->headers[i], "Accept-Language"))
471 setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
472
473 else if (!strcasecmp(req->headers[i], "Authorization"))
474 setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
475
476 else if (!strcasecmp(req->headers[i], "Connection"))
477 setenv("HTTP_CONNECTION", req->headers[i+1], 1);
478
479 else if (!strcasecmp(req->headers[i], "Cookie"))
480 setenv("HTTP_COOKIE", req->headers[i+1], 1);
481
482 else if (!strcasecmp(req->headers[i], "Host"))
483 setenv("HTTP_HOST", req->headers[i+1], 1);
484
485 else if (!strcasecmp(req->headers[i], "Referer"))
486 setenv("HTTP_REFERER", req->headers[i+1], 1);
487
488 else if (!strcasecmp(req->headers[i], "User-Agent"))
489 setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
490
491 else if (!strcasecmp(req->headers[i], "Content-Type"))
492 setenv("CONTENT_TYPE", req->headers[i+1], 1);
493
494 else if (!strcasecmp(req->headers[i], "Content-Length"))
495 setenv("CONTENT_LENGTH", req->headers[i+1], 1);
496 }
497
498
499 /* execute child code ... */
500 if (chdir(pi->root))
501 perror("chdir()");
502
503 if (ip != NULL)
504 execl(ip->path, ip->path, pi->phys, NULL);
505 else
506 execl(pi->phys, pi->phys, NULL);
507
508 /* in case it fails ... */
509 printf("Status: 500 Internal Server Error\r\n\r\n"
510 "Unable to launch the requested CGI program:\n"
511 " %s: %s\n", ip ? ip->path : pi->phys, strerror(errno));
512 }
513
514 /* 403 */
515 else
516 {
517 printf("Status: 403 Forbidden\r\n\r\n"
518 "Access to this resource is forbidden\n");
519 }
520
521 close(wfd[0]);
522 close(rfd[1]);
523 exit(0);
524
525 break;
526
527 /* parent; handle I/O relaying */
528 default:
529 memset(state, 0, sizeof(*state));
530
531 state->cl = cl;
532 state->cl->proc.pid = child;
533
534 /* close unneeded pipe ends */
535 close(rfd[1]);
536 close(wfd[0]);
537
538 D("CGI: Child(%d) created: rfd(%d) wfd(%d)\n", child, rfd[0], wfd[1]);
539
540 state->content_length = cl->httpbuf.len;
541
542 /* find content length */
543 if (req->method == UH_HTTP_MSG_POST)
544 {
545 foreach_header(i, req->headers)
546 {
547 if (!strcasecmp(req->headers[i], "Content-Length"))
548 {
549 state->content_length = atoi(req->headers[i+1]);
550 break;
551 }
552 }
553 }
554
555 state->rfd = rfd[0];
556 fd_nonblock(state->rfd);
557
558 state->wfd = wfd[1];
559 fd_nonblock(state->wfd);
560
561 cl->cb = uh_cgi_socket_cb;
562 cl->priv = state;
563
564 break;
565 }
566
567 return true;
568 }