2 * uhttpd - Tiny single-threaded httpd - CGI handler
4 * Copyright (C) 2010-2011 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"
23 static struct http_response
* uh_cgi_header_parse(char *buf
, int len
, int *off
)
30 static struct http_response res
;
33 if (((bufptr
= strfind(buf
, len
, "\r\n\r\n", 4)) != NULL
) ||
34 ((bufptr
= strfind(buf
, len
, "\n\n", 2)) != NULL
))
36 *off
= (int)(bufptr
- buf
) + ((bufptr
[0] == '\r') ? 4 : 2);
38 memset(&res
, 0, sizeof(res
));
45 for (pos
= 0; pos
< *off
; pos
++)
47 if (!hdrname
&& (buf
[pos
] == ':'))
51 if ((pos
< len
) && (buf
[pos
] == ' '))
61 else if ((buf
[pos
] == '\r') || (buf
[pos
] == '\n'))
68 if ((pos
< len
) && (buf
[pos
] == '\n'))
73 if ((hdrcount
+ 1) < array_size(res
.headers
))
75 if (!strcasecmp(hdrname
, "Status"))
77 res
.statuscode
= atoi(bufptr
);
79 if (res
.statuscode
< 100)
82 if (((bufptr
= strchr(bufptr
, ' ')) != NULL
) &&
85 res
.statusmsg
= &bufptr
[1];
90 res
.headers
[hdrcount
++] = hdrname
;
91 res
.headers
[hdrcount
++] = bufptr
;
111 static char * uh_cgi_header_lookup(struct http_response
*res
,
116 foreach_header(i
, res
->headers
)
118 if (!strcasecmp(res
->headers
[i
], hdrname
))
119 return res
->headers
[i
+1];
125 static int uh_cgi_error_500(struct client
*cl
, struct http_request
*req
,
128 if (uh_http_sendf(cl
, NULL
,
129 "HTTP/%.1f 500 Internal Server Error\r\n"
130 "Content-Type: text/plain\r\n%s\r\n",
133 ? "Transfer-Encoding: chunked\r\n" : "") >= 0)
135 return uh_http_send(cl
, req
, message
, -1);
142 void uh_cgi_request(struct client
*cl
, struct http_request
*req
,
143 struct path_info
*pi
, struct interpreter
*ip
)
145 int i
, hdroff
, bufoff
, rv
;
149 int content_length
= 0;
152 int rfd
[2] = { 0, 0 };
153 int wfd
[2] = { 0, 0 };
155 char buf
[UH_LIMIT_MSGHEAD
];
156 char hdr
[UH_LIMIT_MSGHEAD
];
166 struct timeval timeout
;
167 struct http_response
*res
;
170 /* spawn pipes for me->child, child->me */
171 if ((pipe(rfd
) < 0) || (pipe(wfd
) < 0))
173 uh_http_sendhf(cl
, 500, "Internal Server Error",
174 "Failed to create pipe: %s", strerror(errno
));
176 if (rfd
[0] > 0) close(rfd
[0]);
177 if (rfd
[1] > 0) close(rfd
[1]);
178 if (wfd
[0] > 0) close(wfd
[0]);
179 if (wfd
[1] > 0) close(wfd
[1]);
184 /* fork off child process */
185 switch ((child
= fork()))
189 uh_http_sendhf(cl
, 500, "Internal Server Error",
190 "Failed to fork child: %s", strerror(errno
));
195 /* unblock signals */
197 sigprocmask(SIG_SETMASK
, &ss
, NULL
);
199 /* restore SIGTERM */
201 sa
.sa_handler
= SIG_DFL
;
202 sigemptyset(&sa
.sa_mask
);
203 sigaction(SIGTERM
, &sa
, NULL
);
205 /* close loose pipe ends */
209 /* patch stdout and stdin to pipes */
213 /* avoid leaking our pipe into child-child processes */
217 /* check for regular, world-executable file _or_ interpreter */
218 if (((pi
->stat
.st_mode
& S_IFREG
) &&
219 (pi
->stat
.st_mode
& S_IXOTH
)) || (ip
!= NULL
))
221 /* build environment */
224 /* common information */
225 setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
226 setenv("SERVER_SOFTWARE", "uHTTPd", 1);
227 setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
232 setenv("HTTPS", "on", 1);
236 setenv("SERVER_NAME", sa_straddr(&cl
->servaddr
), 1);
237 setenv("SERVER_ADDR", sa_straddr(&cl
->servaddr
), 1);
238 setenv("SERVER_PORT", sa_strport(&cl
->servaddr
), 1);
239 setenv("REMOTE_HOST", sa_straddr(&cl
->peeraddr
), 1);
240 setenv("REMOTE_ADDR", sa_straddr(&cl
->peeraddr
), 1);
241 setenv("REMOTE_PORT", sa_strport(&cl
->peeraddr
), 1);
243 /* path information */
244 setenv("SCRIPT_NAME", pi
->name
, 1);
245 setenv("SCRIPT_FILENAME", pi
->phys
, 1);
246 setenv("DOCUMENT_ROOT", pi
->root
, 1);
247 setenv("QUERY_STRING", pi
->query
? pi
->query
: "", 1);
250 setenv("PATH_INFO", pi
->info
, 1);
252 /* REDIRECT_STATUS, php-cgi wants it */
253 switch (req
->redirect_status
)
256 setenv("REDIRECT_STATUS", "404", 1);
260 setenv("REDIRECT_STATUS", "200", 1);
265 if (req
->version
> 1.0)
266 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
268 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
273 case UH_HTTP_MSG_GET
:
274 setenv("REQUEST_METHOD", "GET", 1);
277 case UH_HTTP_MSG_HEAD
:
278 setenv("REQUEST_METHOD", "HEAD", 1);
281 case UH_HTTP_MSG_POST
:
282 setenv("REQUEST_METHOD", "POST", 1);
287 setenv("REQUEST_URI", req
->url
, 1);
291 setenv("REMOTE_USER", req
->realm
->user
, 1);
293 /* request message headers */
294 foreach_header(i
, req
->headers
)
296 if (!strcasecmp(req
->headers
[i
], "Accept"))
297 setenv("HTTP_ACCEPT", req
->headers
[i
+1], 1);
299 else if (!strcasecmp(req
->headers
[i
], "Accept-Charset"))
300 setenv("HTTP_ACCEPT_CHARSET", req
->headers
[i
+1], 1);
302 else if (!strcasecmp(req
->headers
[i
], "Accept-Encoding"))
303 setenv("HTTP_ACCEPT_ENCODING", req
->headers
[i
+1], 1);
305 else if (!strcasecmp(req
->headers
[i
], "Accept-Language"))
306 setenv("HTTP_ACCEPT_LANGUAGE", req
->headers
[i
+1], 1);
308 else if (!strcasecmp(req
->headers
[i
], "Authorization"))
309 setenv("HTTP_AUTHORIZATION", req
->headers
[i
+1], 1);
311 else if (!strcasecmp(req
->headers
[i
], "Connection"))
312 setenv("HTTP_CONNECTION", req
->headers
[i
+1], 1);
314 else if (!strcasecmp(req
->headers
[i
], "Cookie"))
315 setenv("HTTP_COOKIE", req
->headers
[i
+1], 1);
317 else if (!strcasecmp(req
->headers
[i
], "Host"))
318 setenv("HTTP_HOST", req
->headers
[i
+1], 1);
320 else if (!strcasecmp(req
->headers
[i
], "Referer"))
321 setenv("HTTP_REFERER", req
->headers
[i
+1], 1);
323 else if (!strcasecmp(req
->headers
[i
], "User-Agent"))
324 setenv("HTTP_USER_AGENT", req
->headers
[i
+1], 1);
326 else if (!strcasecmp(req
->headers
[i
], "Content-Type"))
327 setenv("CONTENT_TYPE", req
->headers
[i
+1], 1);
329 else if (!strcasecmp(req
->headers
[i
], "Content-Length"))
330 setenv("CONTENT_LENGTH", req
->headers
[i
+1], 1);
334 /* execute child code ... */
339 execl(ip
->path
, ip
->path
, pi
->phys
, NULL
);
341 execl(pi
->phys
, pi
->phys
, NULL
);
343 /* in case it fails ... */
344 printf("Status: 500 Internal Server Error\r\n\r\n"
345 "Unable to launch the requested CGI program:\n"
347 ip
? ip
->path
: pi
->phys
, strerror(errno
));
353 printf("Status: 403 Forbidden\r\n\r\n"
354 "Access to this resource is forbidden\n");
363 /* parent; handle I/O relaying */
365 /* close unneeded pipe ends */
370 fd_max
= max(rfd
[0], wfd
[1]) + 1;
372 /* find content length */
373 if (req
->method
== UH_HTTP_MSG_POST
)
375 foreach_header(i
, req
->headers
)
377 if (!strcasecmp(req
->headers
[i
], "Content-Length"))
379 content_length
= atoi(req
->headers
[i
+1]);
386 memset(hdr
, 0, sizeof(hdr
));
388 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
394 FD_SET(rfd
[0], &reader
);
395 FD_SET(wfd
[1], &writer
);
397 timeout
.tv_sec
= (header_sent
< 1) ? cl
->server
->conf
->script_timeout
: 3;
400 ensure_out(rv
= select_intr(fd_max
, &reader
,
401 (content_length
> -1)
408 ensure_out(kill(child
, 0));
411 /* wait until we can read or write or both */
414 /* ready to write to cgi program */
415 if (FD_ISSET(wfd
[1], &writer
))
417 /* there is unread post data waiting */
418 if (content_length
> 0)
420 /* read it from socket ... */
421 ensure_out(buflen
= uh_tcp_recv(cl
, buf
,
422 min(content_length
, sizeof(buf
))));
426 /* ... and write it to child's stdin */
427 if (write(wfd
[1], buf
, buflen
) < 0)
430 content_length
-= buflen
;
433 /* unexpected eof! */
436 if (write(wfd
[1], "", 0) < 0)
443 /* there is no more post data, close pipe to child's stdin */
444 else if (content_length
> -1)
451 /* ready to read from cgi program */
452 if (FD_ISSET(rfd
[0], &reader
))
454 /* read data from child ... */
455 if ((buflen
= read(rfd
[0], buf
, sizeof(buf
))) > 0)
457 /* we have not pushed out headers yet, parse input */
460 /* head buffer not full and no end yet */
461 if (hdrlen
< sizeof(hdr
))
463 bufoff
= min(buflen
, sizeof(hdr
) - hdrlen
);
464 memcpy(&hdr
[hdrlen
], buf
, bufoff
);
473 /* try to parse header ... */
474 if ((res
= uh_cgi_header_parse(hdr
, hdrlen
, &hdroff
)) != NULL
)
477 ensure_out(uh_http_sendf(cl
, NULL
,
478 "HTTP/%.1f %03d %s\r\n"
479 "Connection: close\r\n",
480 req
->version
, res
->statuscode
,
483 /* add Content-Type if no Location or Content-Type */
484 if( !uh_cgi_header_lookup(res
, "Location") &&
485 !uh_cgi_header_lookup(res
, "Content-Type")
487 ensure_out(uh_http_send(cl
, NULL
,
488 "Content-Type: text/plain\r\n", -1));
491 /* if request was HTTP 1.1 we'll respond chunked */
492 if( (req
->version
> 1.0) &&
493 !uh_cgi_header_lookup(res
, "Transfer-Encoding")
495 ensure_out(uh_http_send(cl
, NULL
,
496 "Transfer-Encoding: chunked\r\n", -1));
499 /* write headers from CGI program */
500 foreach_header(i
, res
->headers
)
502 ensure_out(uh_http_sendf(cl
, NULL
, "%s: %s\r\n",
503 res
->headers
[i
], res
->headers
[i
+1]));
506 /* terminate header */
507 ensure_out(uh_http_send(cl
, NULL
, "\r\n", -1));
509 /* push out remaining head buffer */
511 ensure_out(uh_http_send(cl
, req
, &hdr
[hdroff
], hdrlen
- hdroff
));
514 /* ... failed and head buffer exceeded */
515 else if (hdrlen
>= sizeof(hdr
))
517 ensure_out(uh_cgi_error_500(cl
, req
,
518 "The CGI program generated an invalid response:\n\n"));
520 ensure_out(uh_http_send(cl
, req
, hdr
, hdrlen
));
523 /* ... failed but free buffer space, try again */
529 /* push out remaining read buffer */
531 ensure_out(uh_http_send(cl
, req
, &buf
[bufoff
], buflen
- bufoff
));
538 /* headers complete, pass through buffer to socket */
539 ensure_out(uh_http_send(cl
, req
, buf
, buflen
));
542 /* looks like eof from child */
545 /* cgi script did not output useful stuff at all */
548 /* I would do this ...
550 * uh_cgi_error_500(cl, req,
551 * "The CGI program generated an "
552 * "invalid response:\n\n");
554 * ... but in order to stay as compatible as possible,
555 * treat whatever we got as text/plain response and
556 * build the required headers here.
559 ensure_out(uh_http_sendf(cl
, NULL
,
560 "HTTP/%.1f 200 OK\r\n"
561 "Content-Type: text/plain\r\n"
563 req
->version
, (req
->version
> 1.0)
564 ? "Transfer-Encoding: chunked\r\n" : ""
567 ensure_out(uh_http_send(cl
, req
, hdr
, hdrlen
));
570 /* send final chunk if we're in chunked transfer mode */
571 ensure_out(uh_http_send(cl
, req
, "", 0));
577 /* timeout exceeded or interrupted by SIGCHLD */
580 if ((errno
!= EINTR
) && ! header_sent
)
582 ensure_out(uh_http_sendhf(cl
, 504, "Gateway Timeout",
583 "The CGI script took too long to produce "
587 /* send final chunk if we're in chunked transfer mode */
588 ensure_out(uh_http_send(cl
, req
, "", 0));
600 kill(child
, SIGTERM
);
601 waitpid(child
, NULL
, 0);