2 * uhttpd - Tiny single-threaded httpd - CGI 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-cgi.h"
25 uh_cgi_header_parse(struct http_response *res, char *buf, int len, int *off)
32 if (((bufptr = strfind(buf, len, "\r\n\r\n", 4)) != NULL) ||
33 ((bufptr = strfind(buf, len, "\n\n", 2)) != NULL))
35 *off = (int)(bufptr - buf) + ((bufptr[0] == '\r') ? 4 : 2);
37 memset(res, 0, sizeof(*res));
39 res->statuscode = 200;
40 res->statusmsg = "OK";
44 for (pos = 0; pos < *off; pos++)
46 if (!hdrname && (buf[pos] == ':'))
50 if ((pos < len) && (buf[pos] == ' '))
60 else if ((buf[pos] == '\r') || (buf[pos] == '\n'))
67 if ((pos < len) && (buf[pos] == '\n'))
72 if ((hdrcount+1) < array_size(res->headers))
74 if (!strcasecmp(hdrname, "Status"))
76 res->statuscode = atoi(bufptr);
78 if (res->statuscode < 100)
79 res->statuscode = 200;
81 if (((bufptr = strchr(bufptr, ' ')) != NULL) &&
84 res->statusmsg = &bufptr[1];
87 D("CGI: HTTP/1.x %03d %s\n",
88 res->statuscode, res->statusmsg);
92 D("CGI: HTTP: %s: %s\n", hdrname, bufptr);
94 res->headers[hdrcount++] = hdrname;
95 res->headers[hdrcount++] = bufptr;
115 static char * uh_cgi_header_lookup(struct http_response *res,
120 foreach_header(i, res->headers)
122 if (!strcasecmp(res->headers[i], hdrname))
123 return res->headers[i+1];
129 static void uh_cgi_shutdown(struct uh_cgi_state *state)
136 static bool uh_cgi_socket_cb(struct client *cl)
139 char buf[UH_LIMIT_MSGHEAD];
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;
145 /* there is unread post data waiting */
146 while (state->content_length > 0)
148 /* remaining data in http head buffer ... */
149 if (state->cl->httpbuf.len > 0)
151 len = min(state->content_length, state->cl->httpbuf.len);
153 D("CGI: Child(%d) feed %d HTTP buffer bytes\n",
154 state->cl->proc.pid, len);
156 memcpy(buf, state->cl->httpbuf.ptr, len);
158 state->cl->httpbuf.len -= len;
159 state->cl->httpbuf.ptr +=len;
162 /* read it from socket ... */
165 len = uh_tcp_recv(state->cl, buf,
166 min(state->content_length, sizeof(buf)));
168 if ((len < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
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)));
177 state->content_length -= len;
179 state->content_length = 0;
181 /* ... write to CGI process */
182 len = uh_raw_send(state->wfd, buf, len,
183 cl->server->conf->script_timeout);
185 /* explicit EOF notification for the child */
186 if (state->content_length <= 0)
190 /* try to read data from child */
191 while ((len = uh_raw_recv(state->rfd, buf, sizeof(buf), -1)) > 0)
193 /* we have not pushed out headers yet, parse input */
194 if (!state->header_sent)
196 /* try to parse header ... */
197 memcpy(state->httpbuf, buf, len);
199 if (uh_cgi_header_parse(res, state->httpbuf, len, &hdroff))
202 ensure_out(uh_http_sendf(state->cl, NULL,
203 "HTTP/%.1f %03d %s\r\n"
204 "Connection: close\r\n",
205 req->version, res->statuscode, res->statusmsg));
207 /* add Content-Type if no Location or Content-Type */
208 if (!uh_cgi_header_lookup(res, "Location") &&
209 !uh_cgi_header_lookup(res, "Content-Type"))
211 ensure_out(uh_http_send(state->cl, NULL,
212 "Content-Type: text/plain\r\n", -1));
215 /* if request was HTTP 1.1 we'll respond chunked */
216 if ((req->version > 1.0) &&
217 !uh_cgi_header_lookup(res, "Transfer-Encoding"))
219 ensure_out(uh_http_send(state->cl, NULL,
220 "Transfer-Encoding: chunked\r\n", -1));
223 /* write headers from CGI program */
224 foreach_header(i, res->headers)
226 ensure_out(uh_http_sendf(state->cl, NULL, "%s: %s\r\n",
227 res->headers[i], res->headers[i+1]));
230 /* terminate header */
231 ensure_out(uh_http_send(state->cl, NULL, "\r\n", -1));
233 state->header_sent = true;
235 /* push out remaining head buffer */
238 D("CGI: Child(%d) relaying %d rest bytes\n",
239 state->cl->proc.pid, len - hdroff);
241 ensure_out(uh_http_send(state->cl, req,
242 &buf[hdroff], len - hdroff));
246 /* ... failed and head buffer exceeded */
249 /* I would do this ...
251 * uh_cgi_error_500(cl, req,
252 * "The CGI program generated an "
253 * "invalid response:\n\n");
255 * ... but in order to stay as compatible as possible,
256 * treat whatever we got as text/plain response and
257 * build the required headers here.
260 ensure_out(uh_http_sendf(state->cl, NULL,
261 "HTTP/%.1f 200 OK\r\n"
262 "Content-Type: text/plain\r\n"
264 req->version, (req->version > 1.0)
265 ? "Transfer-Encoding: chunked\r\n" : ""
268 state->header_sent = true;
270 D("CGI: Child(%d) relaying %d invalid bytes\n",
271 state->cl->proc.pid, len);
273 ensure_out(uh_http_send(state->cl, req, buf, len));
278 /* headers complete, pass through buffer to socket */
279 D("CGI: Child(%d) relaying %d normal bytes\n",
280 state->cl->proc.pid, len);
282 ensure_out(uh_http_send(state->cl, req, buf, len));
286 /* child has been marked dead by timeout or child handler, bail out */
287 if (false && cl->dead)
289 D("CGI: Child(%d) is marked dead, returning\n", state->cl->proc.pid);
294 ((errno != EAGAIN) && (errno != EWOULDBLOCK) && (len == -1)))
296 D("CGI: Child(%d) presumed dead [%s]\n",
297 state->cl->proc.pid, strerror(errno));
305 if (!state->header_sent)
307 if (state->cl->timeout.pending)
308 uh_http_sendhf(state->cl, 502, "Bad Gateway",
309 "The CGI process did not produce any response\n");
311 uh_http_sendhf(state->cl, 504, "Gateway Timeout",
312 "The CGI process took too long to produce a "
317 uh_http_send(state->cl, req, "", 0);
320 uh_cgi_shutdown(state);
324 bool uh_cgi_request(struct client *cl, struct path_info *pi,
325 struct interpreter *ip)
329 int rfd[2] = { 0, 0 };
330 int wfd[2] = { 0, 0 };
334 struct uh_cgi_state *state;
335 struct http_request *req = &cl->request;
338 if (!(state = malloc(sizeof(*state))))
340 uh_http_sendhf(cl, 500, "Internal Server Error", "Out of memory");
344 /* spawn pipes for me->child, child->me */
345 if ((pipe(rfd) < 0) || (pipe(wfd) < 0))
347 if (rfd[0] > 0) close(rfd[0]);
348 if (rfd[1] > 0) close(rfd[1]);
349 if (wfd[0] > 0) close(wfd[0]);
350 if (wfd[1] > 0) close(wfd[1]);
352 uh_http_sendhf(cl, 500, "Internal Server Error",
353 "Failed to create pipe: %s\n", strerror(errno));
358 /* fork off child process */
359 switch ((child = fork()))
363 uh_http_sendhf(cl, 500, "Internal Server Error",
364 "Failed to fork child: %s\n", strerror(errno));
371 sleep(atoi(getenv("UHTTPD_SLEEP_ON_FORK") ?: "0"));
374 /* close loose pipe ends */
378 /* patch stdout and stdin to pipes */
382 /* avoid leaking our pipe into child-child processes */
386 /* check for regular, world-executable file _or_ interpreter */
387 if (((pi->stat.st_mode & S_IFREG) &&
388 (pi->stat.st_mode & S_IXOTH)) || (ip != NULL))
390 /* build environment */
393 /* common information */
394 setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
395 setenv("SERVER_SOFTWARE", "uHTTPd", 1);
396 setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
401 setenv("HTTPS", "on", 1);
405 setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
406 setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
407 setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
408 setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
409 setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
410 setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
412 /* path information */
413 setenv("SCRIPT_NAME", pi->name, 1);
414 setenv("SCRIPT_FILENAME", pi->phys, 1);
415 setenv("DOCUMENT_ROOT", pi->root, 1);
416 setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
419 setenv("PATH_INFO", pi->info, 1);
421 /* REDIRECT_STATUS, php-cgi wants it */
422 switch (req->redirect_status)
425 setenv("REDIRECT_STATUS", "404", 1);
429 setenv("REDIRECT_STATUS", "200", 1);
434 if (req->version > 1.0)
435 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
437 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
442 case UH_HTTP_MSG_GET:
443 setenv("REQUEST_METHOD", "GET", 1);
446 case UH_HTTP_MSG_HEAD:
447 setenv("REQUEST_METHOD", "HEAD", 1);
450 case UH_HTTP_MSG_POST:
451 setenv("REQUEST_METHOD", "POST", 1);
456 setenv("REQUEST_URI", req->url, 1);
460 setenv("REMOTE_USER", req->realm->user, 1);
462 /* request message headers */
463 foreach_header(i, req->headers)
465 if (!strcasecmp(req->headers[i], "Accept"))
466 setenv("HTTP_ACCEPT", req->headers[i+1], 1);
468 else if (!strcasecmp(req->headers[i], "Accept-Charset"))
469 setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
471 else if (!strcasecmp(req->headers[i], "Accept-Encoding"))
472 setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
474 else if (!strcasecmp(req->headers[i], "Accept-Language"))
475 setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
477 else if (!strcasecmp(req->headers[i], "Authorization"))
478 setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
480 else if (!strcasecmp(req->headers[i], "Connection"))
481 setenv("HTTP_CONNECTION", req->headers[i+1], 1);
483 else if (!strcasecmp(req->headers[i], "Cookie"))
484 setenv("HTTP_COOKIE", req->headers[i+1], 1);
486 else if (!strcasecmp(req->headers[i], "Host"))
487 setenv("HTTP_HOST", req->headers[i+1], 1);
489 else if (!strcasecmp(req->headers[i], "Referer"))
490 setenv("HTTP_REFERER", req->headers[i+1], 1);
492 else if (!strcasecmp(req->headers[i], "User-Agent"))
493 setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
495 else if (!strcasecmp(req->headers[i], "Content-Type"))
496 setenv("CONTENT_TYPE", req->headers[i+1], 1);
498 else if (!strcasecmp(req->headers[i], "Content-Length"))
499 setenv("CONTENT_LENGTH", req->headers[i+1], 1);
503 /* execute child code ... */
508 execl(ip->path, ip->path, pi->phys, NULL);
510 execl(pi->phys, pi->phys, NULL);
512 /* in case it fails ... */
513 printf("Status: 500 Internal Server Error\r\n\r\n"
514 "Unable to launch the requested CGI program:\n"
515 " %s: %s\n", ip ? ip->path : pi->phys, strerror(errno));
521 printf("Status: 403 Forbidden\r\n\r\n"
522 "Access to this resource is forbidden\n");
531 /* parent; handle I/O relaying */
533 memset(state, 0, sizeof(*state));
536 state->cl->proc.pid = child;
538 /* close unneeded pipe ends */
542 D("CGI: Child(%d) created: rfd(%d) wfd(%d)\n", child, rfd[0], wfd[1]);
544 state->content_length = cl->httpbuf.len;
546 /* find content length */
547 if (req->method == UH_HTTP_MSG_POST)
549 foreach_header(i, req->headers)
551 if (!strcasecmp(req->headers[i], "Content-Length"))
553 state->content_length = atoi(req->headers[i+1]);
560 fd_nonblock(state->rfd);
563 fd_nonblock(state->wfd);
565 cl->cb = uh_cgi_socket_cb;