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
)
134 static bool uh_cgi_socket_cb(struct client
*cl
)
136 int i
, len
, blen
, hdroff
;
137 char buf
[UH_LIMIT_MSGHEAD
];
139 struct uh_cgi_state
*state
= (struct uh_cgi_state
*)cl
->priv
;
140 struct http_response
*res
= &cl
->response
;
141 struct http_request
*req
= &cl
->request
;
143 /* there is unread post data waiting */
144 while (state
->content_length
> 0)
146 /* remaining data in http head buffer ... */
147 if (cl
->httpbuf
.len
> 0)
149 len
= min(state
->content_length
, cl
->httpbuf
.len
);
151 D("CGI: Child(%d) feed %d HTTP buffer bytes\n", cl
->proc
.pid
, len
);
153 memcpy(buf
, cl
->httpbuf
.ptr
, len
);
155 cl
->httpbuf
.len
-= len
;
156 cl
->httpbuf
.ptr
+=len
;
159 /* read it from socket ... */
162 len
= uh_tcp_recv(cl
, buf
,
163 min(state
->content_length
, sizeof(buf
)));
165 if ((len
< 0) && ((errno
== EAGAIN
) || (errno
== EWOULDBLOCK
)))
168 D("CGI: Child(%d) feed %d/%d TCP socket bytes\n",
169 cl
->proc
.pid
, len
, min(state
->content_length
, sizeof(buf
)));
173 state
->content_length
-= len
;
175 state
->content_length
= 0;
177 /* ... write to CGI process */
178 len
= uh_raw_send(cl
->wpipe
.fd
, buf
, len
,
179 cl
->server
->conf
->script_timeout
);
181 /* explicit EOF notification for the child */
182 if (state
->content_length
<= 0)
183 uh_ufd_remove(&cl
->wpipe
);
186 /* try to read data from child */
187 while ((len
= uh_raw_recv(cl
->rpipe
.fd
, buf
, state
->header_sent
188 ? sizeof(buf
) : state
->httpbuf
.len
, -1)) > 0)
190 /* we have not pushed out headers yet, parse input */
191 if (!state
->header_sent
)
193 /* try to parse header ... */
194 memcpy(state
->httpbuf
.ptr
, buf
, len
);
195 state
->httpbuf
.len
-= len
;
196 state
->httpbuf
.ptr
+= len
;
198 blen
= state
->httpbuf
.ptr
- state
->httpbuf
.buf
;
200 if (uh_cgi_header_parse(res
, state
->httpbuf
.buf
, blen
, &hdroff
))
203 ensure_out(uh_http_sendf(cl
, NULL
,
204 "HTTP/%.1f %03d %s\r\n"
205 "Connection: close\r\n",
206 req
->version
, res
->statuscode
, res
->statusmsg
));
208 /* add Content-Type if no Location or Content-Type */
209 if (!uh_cgi_header_lookup(res
, "Location") &&
210 !uh_cgi_header_lookup(res
, "Content-Type"))
212 ensure_out(uh_http_send(cl
, NULL
,
213 "Content-Type: text/plain\r\n", -1));
216 /* if request was HTTP 1.1 we'll respond chunked */
217 if ((req
->version
> 1.0) &&
218 !uh_cgi_header_lookup(res
, "Transfer-Encoding"))
220 ensure_out(uh_http_send(cl
, NULL
,
221 "Transfer-Encoding: chunked\r\n", -1));
224 /* write headers from CGI program */
225 foreach_header(i
, res
->headers
)
227 ensure_out(uh_http_sendf(cl
, NULL
, "%s: %s\r\n",
228 res
->headers
[i
], res
->headers
[i
+1]));
231 /* terminate header */
232 ensure_out(uh_http_send(cl
, NULL
, "\r\n", -1));
234 state
->header_sent
= true;
236 /* push out remaining head buffer */
239 D("CGI: Child(%d) relaying %d rest bytes\n",
240 cl
->proc
.pid
, blen
- hdroff
);
242 ensure_out(uh_http_send(cl
, req
,
243 state
->httpbuf
.buf
+ hdroff
,
248 /* ... failed and head buffer exceeded */
249 else if (!state
->httpbuf
.len
)
251 /* I would do this ...
253 * uh_cgi_error_500(cl, req,
254 * "The CGI program generated an "
255 * "invalid response:\n\n");
257 * ... but in order to stay as compatible as possible,
258 * treat whatever we got as text/plain response and
259 * build the required headers here.
262 ensure_out(uh_http_sendf(cl
, NULL
,
263 "HTTP/%.1f 200 OK\r\n"
264 "Content-Type: text/plain\r\n"
266 req
->version
, (req
->version
> 1.0)
267 ? "Transfer-Encoding: chunked\r\n" : ""
270 state
->header_sent
= true;
272 D("CGI: Child(%d) relaying %d invalid bytes\n",
275 ensure_out(uh_http_send(cl
, req
, buf
, len
));
280 /* headers complete, pass through buffer to socket */
281 D("CGI: Child(%d) relaying %d normal bytes\n", cl
->proc
.pid
, len
);
282 ensure_out(uh_http_send(cl
, req
, buf
, len
));
286 /* got EOF or read error from child */
288 ((errno
!= EAGAIN
) && (errno
!= EWOULDBLOCK
) && (len
== -1)))
290 D("CGI: Child(%d) presumed dead [%s]\n", cl
->proc
.pid
, strerror(errno
));
298 if (!state
->header_sent
)
300 if (cl
->timeout
.pending
)
301 uh_http_sendhf(cl
, 502, "Bad Gateway",
302 "The CGI process did not produce any response\n");
304 uh_http_sendhf(cl
, 504, "Gateway Timeout",
305 "The CGI process took too long to produce a "
310 uh_http_send(cl
, req
, "", 0);
313 uh_cgi_shutdown(state
);
317 bool uh_cgi_request(struct client
*cl
, struct path_info
*pi
,
318 struct interpreter
*ip
)
322 int rfd
[2] = { 0, 0 };
323 int wfd
[2] = { 0, 0 };
327 struct uh_cgi_state
*state
;
328 struct http_request
*req
= &cl
->request
;
331 if (!(state
= malloc(sizeof(*state
))))
333 uh_http_sendhf(cl
, 500, "Internal Server Error", "Out of memory");
337 /* spawn pipes for me->child, child->me */
338 if ((pipe(rfd
) < 0) || (pipe(wfd
) < 0))
340 if (rfd
[0] > 0) close(rfd
[0]);
341 if (rfd
[1] > 0) close(rfd
[1]);
342 if (wfd
[0] > 0) close(wfd
[0]);
343 if (wfd
[1] > 0) close(wfd
[1]);
345 uh_http_sendhf(cl
, 500, "Internal Server Error",
346 "Failed to create pipe: %s\n", strerror(errno
));
351 /* fork off child process */
352 switch ((child
= fork()))
356 uh_http_sendhf(cl
, 500, "Internal Server Error",
357 "Failed to fork child: %s\n", strerror(errno
));
364 sleep(atoi(getenv("UHTTPD_SLEEP_ON_FORK") ?: "0"));
367 /* do not leak parent epoll descriptor */
370 /* close loose pipe ends */
374 /* patch stdout and stdin to pipes */
378 /* avoid leaking our pipe into child-child processes */
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
))
386 /* build environment */
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);
397 setenv("HTTPS", "on", 1);
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);
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);
415 setenv("PATH_INFO", pi
->info
, 1);
417 /* REDIRECT_STATUS, php-cgi wants it */
418 switch (req
->redirect_status
)
421 setenv("REDIRECT_STATUS", "404", 1);
425 setenv("REDIRECT_STATUS", "200", 1);
430 if (req
->version
> 1.0)
431 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
433 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
438 case UH_HTTP_MSG_GET
:
439 setenv("REQUEST_METHOD", "GET", 1);
442 case UH_HTTP_MSG_HEAD
:
443 setenv("REQUEST_METHOD", "HEAD", 1);
446 case UH_HTTP_MSG_POST
:
447 setenv("REQUEST_METHOD", "POST", 1);
452 setenv("REQUEST_URI", req
->url
, 1);
456 setenv("REMOTE_USER", req
->realm
->user
, 1);
458 /* request message headers */
459 foreach_header(i
, req
->headers
)
461 if (!strcasecmp(req
->headers
[i
], "Accept"))
462 setenv("HTTP_ACCEPT", req
->headers
[i
+1], 1);
464 else if (!strcasecmp(req
->headers
[i
], "Accept-Charset"))
465 setenv("HTTP_ACCEPT_CHARSET", req
->headers
[i
+1], 1);
467 else if (!strcasecmp(req
->headers
[i
], "Accept-Encoding"))
468 setenv("HTTP_ACCEPT_ENCODING", req
->headers
[i
+1], 1);
470 else if (!strcasecmp(req
->headers
[i
], "Accept-Language"))
471 setenv("HTTP_ACCEPT_LANGUAGE", req
->headers
[i
+1], 1);
473 else if (!strcasecmp(req
->headers
[i
], "Authorization"))
474 setenv("HTTP_AUTHORIZATION", req
->headers
[i
+1], 1);
476 else if (!strcasecmp(req
->headers
[i
], "Connection"))
477 setenv("HTTP_CONNECTION", req
->headers
[i
+1], 1);
479 else if (!strcasecmp(req
->headers
[i
], "Cookie"))
480 setenv("HTTP_COOKIE", req
->headers
[i
+1], 1);
482 else if (!strcasecmp(req
->headers
[i
], "Host"))
483 setenv("HTTP_HOST", req
->headers
[i
+1], 1);
485 else if (!strcasecmp(req
->headers
[i
], "Referer"))
486 setenv("HTTP_REFERER", req
->headers
[i
+1], 1);
488 else if (!strcasecmp(req
->headers
[i
], "User-Agent"))
489 setenv("HTTP_USER_AGENT", req
->headers
[i
+1], 1);
491 else if (!strcasecmp(req
->headers
[i
], "Content-Type"))
492 setenv("CONTENT_TYPE", req
->headers
[i
+1], 1);
494 else if (!strcasecmp(req
->headers
[i
], "Content-Length"))
495 setenv("CONTENT_LENGTH", req
->headers
[i
+1], 1);
499 /* execute child code ... */
504 execl(ip
->path
, ip
->path
, pi
->phys
, NULL
);
506 execl(pi
->phys
, pi
->phys
, NULL
);
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
));
517 printf("Status: 403 Forbidden\r\n\r\n"
518 "Access to this resource is forbidden\n");
527 /* parent; handle I/O relaying */
529 memset(state
, 0, sizeof(*state
));
531 cl
->rpipe
.fd
= rfd
[0];
532 cl
->wpipe
.fd
= wfd
[1];
533 cl
->proc
.pid
= child
;
535 /* make pipe non-blocking */
536 fd_nonblock(cl
->rpipe
.fd
);
537 fd_nonblock(cl
->wpipe
.fd
);
539 /* close unneeded pipe ends */
543 D("CGI: Child(%d) created: rfd(%d) wfd(%d)\n", child
, rfd
[0], wfd
[1]);
545 state
->httpbuf
.ptr
= state
->httpbuf
.buf
;
546 state
->httpbuf
.len
= sizeof(state
->httpbuf
.buf
);
548 state
->content_length
= cl
->httpbuf
.len
;
550 /* find content length */
551 if (req
->method
== UH_HTTP_MSG_POST
)
553 foreach_header(i
, req
->headers
)
555 if (!strcasecmp(req
->headers
[i
], "Content-Length"))
557 state
->content_length
= atoi(req
->headers
[i
+1]);
563 cl
->cb
= uh_cgi_socket_cb
;