2 * uhttpd - Tiny single-threaded httpd - CGI handler
4 * Copyright (C) 2010 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
< len
; 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
) && (&bufptr
[1] != 0) )
83 res
.statusmsg
= &bufptr
[1];
87 res
.headers
[hdrcount
++] = hdrname
;
88 res
.headers
[hdrcount
++] = bufptr
;
108 static char * uh_cgi_header_lookup(struct http_response
*res
, const char *hdrname
)
112 foreach_header(i
, res
->headers
)
114 if( ! strcasecmp(res
->headers
[i
], hdrname
) )
115 return res
->headers
[i
+1];
121 static int uh_cgi_error_500(struct client
*cl
, struct http_request
*req
, const char *message
)
123 if( uh_http_sendf(cl
, NULL
,
124 "HTTP/%.1f 500 Internal Server Error\r\n"
125 "Content-Type: text/plain\r\n%s\r\n",
128 ? "Transfer-Encoding: chunked\r\n" : ""
131 return uh_http_send(cl
, req
, message
, -1);
138 void uh_cgi_request(struct client
*cl
, struct http_request
*req
, struct path_info
*pi
)
140 int i
, hdroff
, bufoff
;
144 int content_length
= 0;
147 int rfd
[2] = { 0, 0 };
148 int wfd
[2] = { 0, 0 };
150 char buf
[UH_LIMIT_MSGHEAD
];
151 char hdr
[UH_LIMIT_MSGHEAD
];
159 struct timeval timeout
;
160 struct http_response
*res
;
163 /* spawn pipes for me->child, child->me */
164 if( (pipe(rfd
) < 0) || (pipe(wfd
) < 0) )
166 uh_http_sendhf(cl
, 500, "Internal Server Error",
167 "Failed to create pipe: %s", strerror(errno
));
169 if( rfd
[0] > 0 ) close(rfd
[0]);
170 if( rfd
[1] > 0 ) close(rfd
[1]);
171 if( wfd
[0] > 0 ) close(wfd
[0]);
172 if( wfd
[1] > 0 ) close(wfd
[1]);
177 /* fork off child process */
178 switch( (child
= fork()) )
182 uh_http_sendhf(cl
, 500, "Internal Server Error",
183 "Failed to fork child: %s", strerror(errno
));
188 /* restore SIGTERM */
190 sa
.sa_handler
= SIG_DFL
;
191 sigemptyset(&sa
.sa_mask
);
192 sigaction(SIGTERM
, &sa
, NULL
);
194 /* close loose pipe ends */
198 /* patch stdout and stdin to pipes */
202 /* check for regular, world-executable file */
203 if( (pi
->stat
.st_mode
& S_IFREG
) &&
204 (pi
->stat
.st_mode
& S_IXOTH
)
206 /* build environment */
209 /* common information */
210 setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
211 setenv("SERVER_SOFTWARE", "uHTTPd", 1);
212 setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
217 setenv("HTTPS", "on", 1);
221 setenv("SERVER_NAME", sa_straddr(&cl
->servaddr
), 1);
222 setenv("SERVER_ADDR", sa_straddr(&cl
->servaddr
), 1);
223 setenv("SERVER_PORT", sa_strport(&cl
->servaddr
), 1);
224 setenv("REMOTE_HOST", sa_straddr(&cl
->peeraddr
), 1);
225 setenv("REMOTE_ADDR", sa_straddr(&cl
->peeraddr
), 1);
226 setenv("REMOTE_PORT", sa_strport(&cl
->peeraddr
), 1);
228 /* path information */
229 setenv("SCRIPT_NAME", pi
->name
, 1);
230 setenv("SCRIPT_FILENAME", pi
->phys
, 1);
231 setenv("DOCUMENT_ROOT", pi
->root
, 1);
232 setenv("QUERY_STRING", pi
->query
? pi
->query
: "", 1);
235 setenv("PATH_INFO", pi
->info
, 1);
239 if( req
->version
> 1.0 )
240 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
242 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
245 switch( req
->method
)
247 case UH_HTTP_MSG_GET
:
248 setenv("REQUEST_METHOD", "GET", 1);
251 case UH_HTTP_MSG_HEAD
:
252 setenv("REQUEST_METHOD", "HEAD", 1);
255 case UH_HTTP_MSG_POST
:
256 setenv("REQUEST_METHOD", "POST", 1);
261 setenv("REQUEST_URI", req
->url
, 1);
265 setenv("REMOTE_USER", req
->realm
->user
, 1);
267 /* request message headers */
268 foreach_header(i
, req
->headers
)
270 if( ! strcasecmp(req
->headers
[i
], "Accept") )
271 setenv("HTTP_ACCEPT", req
->headers
[i
+1], 1);
273 else if( ! strcasecmp(req
->headers
[i
], "Accept-Charset") )
274 setenv("HTTP_ACCEPT_CHARSET", req
->headers
[i
+1], 1);
276 else if( ! strcasecmp(req
->headers
[i
], "Accept-Encoding") )
277 setenv("HTTP_ACCEPT_ENCODING", req
->headers
[i
+1], 1);
279 else if( ! strcasecmp(req
->headers
[i
], "Accept-Language") )
280 setenv("HTTP_ACCEPT_LANGUAGE", req
->headers
[i
+1], 1);
282 else if( ! strcasecmp(req
->headers
[i
], "Authorization") )
283 setenv("HTTP_AUTHORIZATION", req
->headers
[i
+1], 1);
285 else if( ! strcasecmp(req
->headers
[i
], "Connection") )
286 setenv("HTTP_CONNECTION", req
->headers
[i
+1], 1);
288 else if( ! strcasecmp(req
->headers
[i
], "Cookie") )
289 setenv("HTTP_COOKIE", req
->headers
[i
+1], 1);
291 else if( ! strcasecmp(req
->headers
[i
], "Host") )
292 setenv("HTTP_HOST", req
->headers
[i
+1], 1);
294 else if( ! strcasecmp(req
->headers
[i
], "Referer") )
295 setenv("HTTP_REFERER", req
->headers
[i
+1], 1);
297 else if( ! strcasecmp(req
->headers
[i
], "User-Agent") )
298 setenv("HTTP_USER_AGENT", req
->headers
[i
+1], 1);
300 else if( ! strcasecmp(req
->headers
[i
], "Content-Type") )
301 setenv("CONTENT_TYPE", req
->headers
[i
+1], 1);
303 else if( ! strcasecmp(req
->headers
[i
], "Content-Length") )
304 setenv("CONTENT_LENGTH", req
->headers
[i
+1], 1);
308 /* execute child code ... */
309 if( chdir(pi
->root
) )
312 execl(pi
->phys
, pi
->phys
, NULL
);
314 /* in case it fails ... */
316 "Status: 500 Internal Server Error\r\n\r\n"
317 "Unable to launch the requested CGI program:\n"
319 pi
->phys
, strerror(errno
)
327 "Status: 403 Forbidden\r\n\r\n"
328 "Access to this resource is forbidden\n"
338 /* parent; handle I/O relaying */
340 /* close unneeded pipe ends */
345 fd_max
= max(rfd
[0], wfd
[1]) + 1;
347 /* find content length */
348 if( req
->method
== UH_HTTP_MSG_POST
)
350 foreach_header(i
, req
->headers
)
352 if( ! strcasecmp(req
->headers
[i
], "Content-Length") )
354 content_length
= atoi(req
->headers
[i
+1]);
361 memset(hdr
, 0, sizeof(hdr
));
363 timeout
.tv_sec
= cl
->server
->conf
->script_timeout
;
367 do { if( x < 0 ) goto out; } while(0)
369 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
375 FD_SET(rfd
[0], &reader
);
376 FD_SET(wfd
[1], &writer
);
378 /* wait until we can read or write or both */
379 if( select_intr(fd_max
, &reader
,
380 (content_length
> -1) ? &writer
: NULL
, NULL
,
381 (header_sent
< 1) ? &timeout
: NULL
) > 0
383 /* ready to write to cgi program */
384 if( FD_ISSET(wfd
[1], &writer
) )
386 /* there is unread post data waiting */
387 if( content_length
> 0 )
389 /* read it from socket ... */
390 if( (buflen
= uh_tcp_recv(cl
, buf
, min(content_length
, sizeof(buf
)))) > 0 )
392 /* ... and write it to child's stdin */
393 if( write(wfd
[1], buf
, buflen
) < 0 )
396 content_length
-= buflen
;
399 /* unexpected eof! */
402 if( write(wfd
[1], "", 0) < 0 )
409 /* there is no more post data, close pipe to child's stdin */
410 else if( content_length
> -1 )
417 /* ready to read from cgi program */
418 if( FD_ISSET(rfd
[0], &reader
) )
420 /* read data from child ... */
421 if( (buflen
= read(rfd
[0], buf
, sizeof(buf
))) > 0 )
423 /* we have not pushed out headers yet, parse input */
426 /* head buffer not full and no end yet */
427 if( hdrlen
< sizeof(hdr
) )
429 bufoff
= min(buflen
, sizeof(hdr
) - hdrlen
);
430 memcpy(&hdr
[hdrlen
], buf
, bufoff
);
439 /* try to parse header ... */
440 if( (res
= uh_cgi_header_parse(hdr
, hdrlen
, &hdroff
)) != NULL
)
443 ensure(uh_http_sendf(cl
, NULL
,
444 "HTTP/%.1f %03d %s\r\n"
445 "Connection: close\r\n",
446 req
->version
, res
->statuscode
,
449 /* add Content-Type if no Location or Content-Type */
450 if( !uh_cgi_header_lookup(res
, "Location") &&
451 !uh_cgi_header_lookup(res
, "Content-Type")
453 ensure(uh_http_send(cl
, NULL
,
454 "Content-Type: text/plain\r\n", -1));
457 /* if request was HTTP 1.1 we'll respond chunked */
458 if( (req
->version
> 1.0) &&
459 !uh_cgi_header_lookup(res
, "Transfer-Encoding")
461 ensure(uh_http_send(cl
, NULL
,
462 "Transfer-Encoding: chunked\r\n", -1));
465 /* write headers from CGI program */
466 foreach_header(i
, res
->headers
)
468 ensure(uh_http_sendf(cl
, NULL
, "%s: %s\r\n",
469 res
->headers
[i
], res
->headers
[i
+1]));
472 /* terminate header */
473 ensure(uh_http_send(cl
, NULL
, "\r\n", -1));
475 /* push out remaining head buffer */
476 if( hdroff
< hdrlen
)
477 ensure(uh_http_send(cl
, req
, &hdr
[hdroff
], hdrlen
- hdroff
));
480 /* ... failed and head buffer exceeded */
481 else if( hdrlen
>= sizeof(hdr
) )
483 ensure(uh_cgi_error_500(cl
, req
,
484 "The CGI program generated an invalid response:\n\n"));
486 ensure(uh_http_send(cl
, req
, hdr
, hdrlen
));
489 /* ... failed but free buffer space, try again */
495 /* push out remaining read buffer */
496 if( bufoff
< buflen
)
497 ensure(uh_http_send(cl
, req
, &buf
[bufoff
], buflen
- bufoff
));
504 /* headers complete, pass through buffer to socket */
505 ensure(uh_http_send(cl
, req
, buf
, buflen
));
508 /* looks like eof from child */
511 /* cgi script did not output useful stuff at all */
514 /* I would do this ...
516 * uh_cgi_error_500(cl, req,
517 * "The CGI program generated an "
518 * "invalid response:\n\n");
520 * ... but in order to stay as compatible as possible,
521 * treat whatever we got as text/plain response and
522 * build the required headers here.
525 ensure(uh_http_sendf(cl
, NULL
,
526 "HTTP/%.1f 200 OK\r\n"
527 "Content-Type: text/plain\r\n"
529 req
->version
, (req
->version
> 1.0)
530 ? "Transfer-Encoding: chunked\r\n" : ""
533 ensure(uh_http_send(cl
, req
, hdr
, hdrlen
));
536 /* send final chunk if we're in chunked transfer mode */
537 ensure(uh_http_send(cl
, req
, "", 0));
543 /* timeout exceeded or interrupted by SIGCHLD */
546 if( (errno
!= EINTR
) && ! header_sent
)
548 ensure(uh_http_sendhf(cl
, 504, "Gateway Timeout",
549 "The CGI script took too long to produce "
553 /* send final chunk if we're in chunked transfer mode */
554 ensure(uh_http_send(cl
, req
, "", 0));
564 if( !kill(child
, 0) )
566 kill(child
, SIGTERM
);
567 waitpid(child
, NULL
, 0);
This page took 0.075029 seconds and 5 git commands to generate.