SSLDaemon.pm untested

filter: Statementstmt 0.0% 0 / 366 Branchbran 0.0% 0 / 182 Conditioncond 0.0% 0 / 66 MC/DCmcdc 0.0% 0 / 38 Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 711 CC 92 SCAR 65.8
CC
92
Cov
0%
get_request
1980.0
send_response
182.0
_need_more
72.0
CRAP 717.1
1 # $Id: SSLDaemon.pm,v 1.1 2012-09-20 13:39:13 ubuntu Exp $
2 #
3  
4 use strict;
5  
6 package WSRF::SSLDaemon;
7  
8 =head1 NAME
9  
10 SSLDaemon - a simple https server class
11  
12 =head1 SYNOPSIS
13  
14 use SSLDaemon;
15 use HTTP::Status;
16  
17 my $d = HTTP::Daemon->new || die;
18 print "Please contact me at: <URL:", $d->url, ">\n";
19 while (my $c = $d->accept) {
20 while (my $r = $c->get_request) {
21 if ($r->method eq 'GET' and $r->url->path eq "/xyzzy") {
22 # remember, this is *not* recommened practice :-)
23 $c->send_file_response("/etc/passwd");
24 } else {
25 $c->send_error(RC_FORBIDDEN)
26 }
27 }
28 $c->close;
29 undef($c);
30 }
31  
32 =head1 DESCRIPTION
33  
34 Instances of the I<HTTP::Daemon> class are HTTP/1.1 servers that
35 listen on a socket for incoming requests. The I<HTTP::Daemon> is a
36 sub-class of I<IO::Socket::INET>, so you can perform socket operations
37 directly on it too.
38  
39 The accept() method will return when a connection from a client is
40 available. In a scalar context the returned value will be a reference
41 to a object of the I<HTTP::Daemon::ClientConn> class which is another
42 I<IO::Socket::INET> subclass. In a list context a two-element array
43 is returned containing the new I<HTTP::Daemon::ClientConn> reference
44 and the peer address; the list will be empty upon failure. Calling
45 the get_request() method on the I<HTTP::Daemon::ClientConn> object
46 will read data from the client and return an I<HTTP::Request> object
47 reference.
48  
49 This HTTP daemon does not fork(2) for you. Your application, i.e. the
50 user of the I<HTTP::Daemon> is reponsible for forking if that is
51 desirable. Also note that the user is responsible for generating
52 responses that conform to the HTTP/1.1 protocol. The
53 I<HTTP::Daemon::ClientConn> class provides some methods that make this easier.
54  
55 =head1 METHODS
56  
57 The following is a list of methods that are new (or enhanced) relative
58 to the I<IO::Socket::INET> base class.
59  
60 =over 4
61  
62 =cut
63  
64  
65 use vars qw($VERSION @ISA $PROTO $DEBUG);
66  
67 $VERSION = sprintf("%d.%02d", q$Revision: 1.1 $ =~ /(\d+)\.(\d+)/);
68  
69 use IO::Socket::INET qw(AF_INET INADDR_ANY inet_ntoa);
70 use IO::Socket::SSL qw(debug4);
71 @ISA=qw(IO::Socket::SSL);
72  
73 $PROTO = "HTTP/1.1";
74  
75 =item $d = new HTTP::Daemon
76  
77 The constructor takes the same parameters as the
78 I<IO::Socket::INET> constructor. It can also be called without specifying
79 any parameters. The daemon will then set up a listen queue of 5
80 connections and allocate some random port number. A server that wants
81 to bind to some specific address on the standard HTTP port will be
82 constructed like this:
83  
84 $d = new Daemon
85 LocalAddr => 'www.someplace.com',
86 LocalPort => 80;
87  
88 =cut
89 sub new
90 {
91 my($class, %args) = @_;
92 $args{Listen} ||= 5;
93 $args{Proto} ||= 'tcp';
94 return $class->SUPER::new(%args);
95 }
96  
97  
98 =item $c = $d->accept([$pkg])
99  
100 This method is the same as I<IO::Socket::accept> but returns an
101 I<HTTP::Daemon::ClientConn> reference by default. It returns undef if
102 you specify a timeout and no connection is made within that time. In
103 a scalar context the returned value will be a reference to a object of
104 the I<HTTP::Daemon::ClientConn> class which is another
105 I<IO::Socket::INET> subclass. In a list context a two-element array
106 is returned containing the new I<HTTP::Daemon::ClientConn> reference
107 and the peer address; the list will be empty upon failure.
108  
109  
110 =cut
111  
112 sub accept
113 {
114 my $self = shift;
115 my $pkg = shift || "SSLDaemon::ClientConn";
116 my ($sock, $peer) = $self->SUPER::accept($pkg);
117 if ($sock) {
118 ${*$sock}{'httpd_daemon'} = $self;
119 return wantarray ? ($sock, $peer) : $sock;
120 } else {
121 return;
122 }
123 }
124  
125  
126 =item $d->url
127  
128 Returns a URL string that can be used to access the server root.
129  
130 =cut
131  
132 sub url
133 {
134 my $self = shift;
135 my $url = "https://";
136 my $addr = $self->sockaddr;
137 if ($addr eq INADDR_ANY) {
138 require Sys::Hostname;
139 $url .= lc Sys::Hostname::hostname();
140 }
141 else {
142 $url .= gethostbyaddr($addr, AF_INET) || inet_ntoa($addr);
143 }
144 my $port = $self->sockport;
145 $url .= ":$port" if $port != 80;
146 $url .= "/";
147 $url;
148 }
149  
150  
151 =item $d->product_tokens
152  
153 Returns the name that this server will use to identify itself. This
154 is the string that is sent with the I<Server> response header. The
155 main reason to have this method is that subclasses can override it if
156 they want to use another product name.
157  
158 =cut
159  
160 sub product_tokens
161 {
162 "libwww-perl-daemon/$SSLDaemon::VERSION";
163 }
164  
165  
166 package SSLDaemon::ClientConn;
167  
168 use vars qw(@ISA $DEBUG);
169 use IO::Socket ();
170 @ISA=qw(IO::Socket::SSL);
171 *DEBUG = \$SSLDaemon::DEBUG;
172  
173 use HTTP::Request ();
174 use HTTP::Response ();
175 use HTTP::Status;
176 use HTTP::Date qw(time2str);
177 use LWP::MediaTypes qw(guess_media_type);
178 use Carp ();
179  
180 my $CRLF = "\015\012"; # "\r\n" is not portable
181 my $HTTP_1_0 = _http_version("HTTP/1.0");
182 my $HTTP_1_1 = _http_version("HTTP/1.1");
183  
184 =back
185  
186 The I<SSLDaemon::ClientConn> is also a I<IO::Socket::INET>
187 subclass. Instances of this class are returned by the accept() method
188 of I<HTTP::Daemon>. The following additional methods are
189 provided:
190  
191 =over 4
192  
193 =item $c->get_request([$headers_only])
194  
195 Read data from the client and turn it into an
196 I<HTTP::Request> object which is then returned. It returns C<undef>
197 if reading of the request fails. If it fails, then the
198 I<HTTP::Daemon::ClientConn> object ($c) should be discarded, and you
199 should not call this method again. The $c->reason method might give
200 you some information about why $c->get_request returned C<undef>.
201  
202 The $c->get_request method supports HTTP/1.1 request content bodies,
203 including I<chunked> transfer encoding with footer and self delimiting
204 I<multipart/*> content types.
205  
206 The $c->get_request method will normally not return until the whole
207 request has been received from the client. This might not be what you
208 want if the request is an upload of a multi-mega-byte file (and with
209 chunked transfer encoding HTTP can even support infinite request
210 messages - uploading live audio for instance). If you pass a TRUE
211 value as the $headers_only argument, then $c->get_request will return
212 immediately after parsing the request headers and you are responsible
213 for reading the rest of the request content. If you are going to
214 call $c->get_request again on the same connection you better read the
215 correct number of bytes.
216  
217 =cut
218 ####### I/O subroutines ########################
219 sub generic_read {
220 my ($self, $read_func, undef, $length, $offset) = @_;
221 my $ssl = $self->_get_ssl_object || return;
222  
223 #print "Calling read_func....$read_func for $length\n";
224 #my $data = $read_func->($ssl, $length);
225 my $data = Net::SSLeay::read($ssl, $length);
226 #print "Called read_func...\n";
227 return $self->error("SSL read error") unless (defined($data) && length($data));
228  
229 my $buffer=\$_[2];
230 $length = length($data);
231 $$buffer ||= '';
232 $offset ||= 0;
233 if ($offset > length($$buffer)) {
234 $$buffer.="\0" x ($offset-length($$buffer)); #mimic behavior of read
235 }
236  
237 substr($$buffer, $offset, length($$buffer), $data);
238 return $length;
239 }
240  
241  
242  
243  
244  
245 sub get_request
246 {
247 my($self, $only_headers) = @_;
248 if (${*$self}{'httpd_nomore'}) {
249 $self->reason("No more requests from this connection");
250 return;
251 }
252  
253 $self->reason("");
254 my $buf = ${*$self}{'httpd_rbuf'};
255 $buf = "" unless defined $buf;
256  
257 #print "Blocking= ".$self->blocking."\n";
258  
259 my $timeout = $ {*$self}{'io_socket_timeout'};
260 my $fdset = "";
261 vec($fdset, $self->fileno, 1) = 1;
262 local($_);
263  
264 #print "Connection Acepted From:\n";
265 #my $cert = $self->dump_peer_certificate();
266 #print $cert;
267 #my($DN,$issuer) = split( /\n/, $cert);
268 #$DN =~ s/Subject Name: //o;
269 #$issuer =~ s/Issuer Name: //o;
270
271 #$ENV{SSL_CLIENT_DN} = $DN;
272 #$ENV{SSL_CLIENT_ISSUER} = $issuer;
273  
274 READ_HEADER:
275 while (1) {
276 # loop until we have the whole header in $buf
277 $buf =~ s/^(?:\015?\012)+//; # ignore leading blank lines
278 if ($buf =~ /\012/) { # potential, has at least one line
279 if ($buf =~ /^\w+[^\012]+HTTP\/\d+\.\d+\015?\012/) {
280 if ($buf =~ /\015?\012\015?\012/) {
281 last READ_HEADER; # we have it
282 } elsif (length($buf) > 16*1024) {
283 $self->send_error(413); # REQUEST_ENTITY_TOO_LARGE
284 $self->reason("Very long header");
285 return;
286 }
287 } else {
288 last READ_HEADER; # HTTP/0.9 client
289 }
290 } elsif (length($buf) > 16*1024) {
291 $self->send_error(414); # REQUEST_URI_TOO_LARGE
292 $self->reason("Very long first line");
293 return;
294 }
295 print STDERR "Need more data for complete header\n" if $DEBUG;
296 return unless $self->_need_more($buf, $timeout, $fdset);
297 }
298 if ($buf !~ s/^(\S+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012//) {
299 ${*$self}{'httpd_client_proto'} = _http_version("HTTP/1.0");
300 $self->send_error(400); # BAD_REQUEST
301 $self->reason("Bad request line: $buf");
302 return;
303 }
304 my $method = $1;
305 my $uri = $2;
306 my $proto = $3 || "HTTP/0.9";
307 $uri = "http://$uri" if $method eq "CONNECT";
308 $uri = $HTTP::URI_CLASS->new($uri, $self->daemon->url);
309 my $r = HTTP::Request->new($method, $uri);
310 $r->protocol($proto);
311 ${*$self}{'httpd_client_proto'} = $proto = _http_version($proto);
312  
313 if ($proto >= $HTTP_1_0) {
314 # we expect to find some headers
315 my($key, $val);
316 HEADER:
317 while ($buf =~ s/^([^\012]*)\012//) {
318 $_ = $1;
319 s/\015$//;
320 if (/^([\w\-]+)\s*:\s*(.*)/) {
321 $r->push_header($key, $val) if $key;
322 ($key, $val) = ($1, $2);
323 } elsif (/^\s+(.*)/) {
324 $val .= " $1";
325 } else {
326 last HEADER;
327 }
328 }
329 $r->push_header($key, $val) if $key;
330 }
331  
332 my $conn = $r->header('Connection');
333 if ($proto >= $HTTP_1_1) {
334 ${*$self}{'httpd_nomore'}++ if $conn && lc($conn) =~ /\bclose\b/;
335 } else {
336 ${*$self}{'httpd_nomore'}++ unless $conn &&
337 lc($conn) =~ /\bkeep-alive\b/;
338 }
339  
340 if ($only_headers) {
341 ${*$self}{'httpd_rbuf'} = $buf;
342 return $r;
343 }
344  
345 # Find out how much content to read
346 my $te = $r->header('Transfer-Encoding');
347 my $ct = $r->header('Content-Type');
348 my $len = $r->header('Content-Length');
349  
350 if ($te && lc($te) eq 'chunked') {
351 # Handle chunked transfer encoding
352 my $body = "";
353 CHUNK:
354 while (1) {
355 print STDERR "Chunked\n" if $DEBUG;
356 if ($buf =~ s/^([^\012]*)\012//) {
357 my $chunk_head = $1;
358 unless ($chunk_head =~ /^([0-9A-Fa-f]+)/) {
359 $self->send_error(400);
360 $self->reason("Bad chunk header $chunk_head");
361 return;
362 }
363 my $size = hex($1);
364 last CHUNK if $size == 0;
365  
366 my $missing = $size - length($buf) + 2; # 2=CRLF at chunk end
367 # must read until we have a complete chunk
368 while ($missing > 0) {
369 print STDERR "Need $missing more bytes\n" if $DEBUG;
370 my $n = $self->_need_more($buf, $timeout, $fdset);
371 return unless $n;
372 $missing -= $n;
373 }
374 $body .= substr($buf, 0, $size);
375 substr($buf, 0, $size+2) = '';
376  
377 } else {
378 # need more data in order to have a complete chunk header
379 return unless $self->_need_more($buf, $timeout, $fdset);
380 }
381 }
382 $r->content($body);
383  
384 # pretend it was a normal entity body
385 $r->remove_header('Transfer-Encoding');
386 $r->header('Content-Length', length($body));
387  
388 my($key, $val);
389 FOOTER:
390 while (1) {
391 if ($buf !~ /\012/) {
392 # need at least one line to look at
393 return unless $self->_need_more($buf, $timeout, $fdset);
394 } else {
395 $buf =~ s/^([^\012]*)\012//;
396 $_ = $1;
397 s/\015$//;
398 if (/^([\w\-]+)\s*:\s*(.*)/) {
399 $r->push_header($key, $val) if $key;
400 ($key, $val) = ($1, $2);
401 } elsif (/^\s+(.*)/) {
402 $val .= " $1";
403 } elsif (!length) {
404 last FOOTER;
405 } else {
406 $self->reason("Bad footer syntax");
407 return;
408 }
409 }
410 }
411 $r->push_header($key, $val) if $key;
412  
413 } elsif ($te) {
414 $self->send_error(501); # Unknown transfer encoding
415 $self->reason("Unknown transfer encoding '$te'");
416 return;
417  
418 } elsif ($ct && lc($ct) =~ m/^multipart\/\w+\s*;.*boundary\s*=\s*(\w+)/) {
419 # Handle multipart content type
420 my $boundary = "$CRLF--$1--$CRLF";
421 my $index;
422 while (1) {
423 $index = index($buf, $boundary);
424 last if $index >= 0;
425 # end marker not yet found
426 return unless $self->_need_more($buf, $timeout, $fdset);
427 }
428 $index += length($boundary);
429 $r->content(substr($buf, 0, $index));
430 substr($buf, 0, $index) = '';
431  
432 } elsif ($len) {
433 # Plain body specified by "Content-Length"
434 my $missing = $len - length($buf);
435 while ($missing > 0) {
436 print "Need $missing more bytes of content\n" if $DEBUG;
437 my $n = $self->_need_more($buf, $timeout, $fdset);
438 return unless $n;
439 $missing -= $n;
440 }
441 if (length($buf) > $len) {
442 $r->content(substr($buf,0,$len));
443 substr($buf, 0, $len) = '';
444 } else {
445 $r->content($buf);
446 $buf='';
447 }
448 }
449 ${*$self}{'httpd_rbuf'} = $buf;
450  
451 $r;
452 }
453  
454 sub _need_more
455 {
456 my $self = shift;
457 #my($buf,$timeout,$fdset) = @_;
458 if ($_[1]) {
459 my($timeout, $fdset) = @_[1,2];
460 print STDERR "select(,,,$timeout)\n" if $DEBUG;
461 my $n = select($fdset,undef,undef,$timeout);
462 unless ($n) {
463 $self->reason(defined($n) ? "Timeout" : "select: $!");
464 return;
465 }
466 }
467 print STDERR "sysread()\n" if $DEBUG;
468 my $n = sysread($self, $_[0], 2048, length($_[0]));
469 $self->reason(defined($n) ? "Client closed" : "sysread: $!") unless $n;
470 $n;
471 }
472  
473 =item $c->read_buffer([$new_value])
474  
475 Bytes read by $c->get_request, but not used are placed in the I<read
476 buffer>. The next time $c->get_request is called it will consume the
477 bytes in this buffer before reading more data from the network
478 connection itself. The read buffer is invalid after $c->get_request
479 has returned an undefined value.
480  
481 If you handle the reading of the request content yourself you need to
482 empty this buffer before you read more and you need to place
483 unconsumed bytes here. You also need this buffer if you implement
484 services like I<101 Switching Protocols>.
485  
486 This method always return the old buffer content and can optionally
487 replace the buffer content if you pass it an argument.
488  
489 =cut
490  
491 sub read_buffer
492 {
493 my $self = shift;
494 my $old = ${*$self}{'httpd_rbuf'};
495 if (@_) {
496 ${*$self}{'httpd_rbuf'} = shift;
497 }
498 $old;
499 }
500  
501  
502 =item $c->reason
503  
504 When $c->get_request returns C<undef> you can obtain a short string
505 describing why it happened by calling $c->reason.
506  
507 =cut
508  
509 sub reason
510 {
511 my $self = shift;
512 my $old = ${*$self}{'httpd_reason'};
513 if (@_) {
514 ${*$self}{'httpd_reason'} = shift;
515 }
516 $old;
517 }
518  
519  
520 =item $c->proto_ge($proto)
521  
522 Return TRUE if the client announced a protocol with version number
523 greater or equal to the given argument. The $proto argument can be a
524 string like "HTTP/1.1" or just "1.1".
525  
526 =cut
527  
528 sub proto_ge
529 {
530 my $self = shift;
531 ${*$self}{'httpd_client_proto'} >= _http_version(shift);
532 }
533  
534 sub _http_version
535 {
536 local($_) = shift;
537 return 0 unless m,^(?:HTTP/)?(\d+)\.(\d+)$,i;
538 $1 * 1000 + $2;
539 }
540  
541 =item $c->antique_client
542  
543 Return TRUE if the client speaks the HTTP/0.9 protocol. No status
544 code and no headers should be returned to such a client. This should
545 be the same as !$c->proto_ge("HTTP/1.0").
546  
547 =cut
548  
549 sub antique_client
550 {
551 my $self = shift;
552 ${*$self}{'httpd_client_proto'} < $HTTP_1_0;
553 }
554  
555  
556 =item $c->force_last_request
557  
558 Make sure that $c->get_request will not try to read more requests off
559 this connection. If you generate a response that is not self
560 delimiting, then you should signal this fact by calling this method.
561  
562 This attribute is turned on automatically if the client announces
563 protocol HTTP/1.0 or worse and does not include a "Connection:
564 Keep-Alive" header. It is also turned on automatically when HTTP/1.1
565 or better clients send the "Connection: close" request header.
566  
567 =cut
568  
569 sub force_last_request
570 {
571 my $self = shift;
572 ${*$self}{'httpd_nomore'}++;
573 }
574  
575  
576 =item $c->send_status_line( [$code, [$mess, [$proto]]] )
577  
578 Send the status line back to the client. If $code is omitted 200 is
579 assumed. If $mess is omitted, then a message corresponding to $code
580 is inserted. If $proto is missing the content of the
581 $HTTP::Daemon::PROTO variable is used.
582  
583 =cut
584  
585 sub send_status_line
586 {
587 my($self, $status, $message, $proto) = @_;
588 return if $self->antique_client;
589 $status ||= RC_OK;
590 $message ||= status_message($status) || "";
591 $proto ||= $SSLDaemon::PROTO || "HTTP/1.1";
592 print $self "$proto $status $message$CRLF";
593 }
594  
595 =item $c->send_crlf
596  
597 Send the CRLF sequence to the client.
598  
599 =cut
600  
601  
602 sub send_crlf
603 {
604 my $self = shift;
605 print $self $CRLF;
606 }
607  
608  
609 =item $c->send_basic_header( [$code, [$mess, [$proto]]] )
610  
611 Send the status line and the "Date:" and "Server:" headers back to
612 the client. This header is assumed to be continued and does not end
613 with an empty CRLF line.
614  
615 =cut
616  
617 sub send_basic_header
618 {
619 my $self = shift;
620 return if $self->antique_client;
621 $self->send_status_line(@_);
622 print $self "Date: ", time2str(time), $CRLF;
623 my $product = $self->daemon->product_tokens;
624 print $self "Server: $product$CRLF" if $product;
625 }
626  
627  
628 =item $c->send_response( [$res] )
629  
630 Write a I<HTTP::Response> object to the
631 client as a response. We try hard to make sure that the response is
632 self delimiting so that the connection can stay persistent for further
633 request/response exchanges.
634  
635 The content attribute of the I<HTTP::Response> object can be a normal
636 string or a subroutine reference. If it is a subroutine, then
637 whatever this callback routine returns is written back to the
638 client as the response content. The routine will be called until it
639 return an undefined or empty value. If the client is HTTP/1.1 aware
640 then we will use chunked transfer encoding for the response.
641  
642 =cut
643  
644 sub send_response
645 {
646 my $self = shift;
647 my $res = shift;
648 if (!ref $res) {
649 $res ||= RC_OK;
650 $res = HTTP::Response->new($res, @_);
651 }
652 my $content = $res->content;
653 my $chunked;
654 unless ($self->antique_client) {
655 my $code = $res->code;
656 $self->send_basic_header($code, $res->message, $res->protocol);
657 if ($code =~ /^(1\d\d|[23]04)$/) {
658 # make sure content is empty
659 $res->remove_header("Content-Length");
660 $content = "";
661 } elsif ($res->request && $res->request->method eq "HEAD") {
662 # probably OK
663 } elsif (ref($content) eq "CODE") {
664 if ($self->proto_ge("HTTP/1.1")) {
665 $res->push_header("Transfer-Encoding" => "chunked");
666 $chunked++;
667 } else {
668 $self->force_last_request;
669 }
670 } elsif (length($content)) {
671 $res->header("Content-Length" => length($content));
672 } else {
673 $self->force_last_request;
674 }
675 print $self $res->headers_as_string($CRLF);
676 print $self $CRLF; # separates headers and content
677 }
678 if (ref($content) eq "CODE") {
679 while (1) {
680 my $chunk = &$content();
681 last unless defined($chunk) && length($chunk);
682 if ($chunked) {
683 printf $self "%x%s%s%s", length($chunk), $CRLF, $chunk, $CRLF;
684 } else {
685 print $self $chunk;
686 }
687 }
688 print $self "0$CRLF$CRLF" if $chunked; # no trailers either
689 } elsif (length $content) {
690 print $self $content;
691 }
692 }
693  
694  
695 =item $c->send_redirect( $loc, [$code, [$entity_body]] )
696  
697 Send a redirect response back to the client. The location ($loc) can
698 be an absolute or relative URL. The $code must be one the redirect
699 status codes, and defaults to "301 Moved Permanently"
700  
701 =cut
702  
703 sub send_redirect
704 {
705 my($self, $loc, $status, $content) = @_;
706 $status ||= RC_MOVED_PERMANENTLY;
707 Carp::croak("Status '$status' is not redirect") unless is_redirect($status);
708 $self->send_basic_header($status);
709 my $base = $self->daemon->url;
710 $loc = $HTTP::URI_CLASS->new($loc, $base) unless ref($loc);
711 $loc = $loc->abs($base);
712 print $self "Location: $loc$CRLF";
713 if ($content) {
714 my $ct = $content =~ /^\s*</ ? "text/html" : "text/plain";
715 print $self "Content-Type: $ct$CRLF";
716 }
717 print $self $CRLF;
718 print $self $content if $content;
719 $self->force_last_request; # no use keeping the connection open
720 }
721  
722  
723 =item $c->send_error( [$code, [$error_message]] )
724  
725 Send an error response back to the client. If the $code is missing a
726 "Bad Request" error is reported. The $error_message is a string that
727 is incorporated in the body of the HTML entity body.
728  
729 =cut
730  
731 sub send_error
732 {
733 my($self, $status, $error) = @_;
734 $status ||= RC_BAD_REQUEST;
735 Carp::croak("Status '$status' is not an error") unless is_error($status);
736 my $mess = status_message($status);
737 $error ||= "";
738 $mess = <<EOT;
739 <title>$status $mess</title>
740 <h1>$status $mess</h1>
741 $error
742 EOT
743 unless ($self->antique_client) {
744 $self->send_basic_header($status);
745 print $self "Content-Type: text/html$CRLF";
746 print $self "Content-Length: " . length($mess) . $CRLF;
747 print $self $CRLF;
748 }
749 print $self $mess;
750 $status;
751 }
752  
753  
754 =item $c->send_file_response($filename)
755  
756 Send back a response with the specified $filename as content. If the
757 file is a directory we try to generate an HTML index of it.
758  
759 =cut
760  
761 sub send_file_response
762 {
763 my($self, $file) = @_;
764 if (-d $file) {
765 $self->send_dir($file);
766 } elsif (-f _) {
767 # plain file
768 local(*F);
769 sysopen(F, $file, 0) or
770 return $self->send_error(RC_FORBIDDEN);
771 binmode(F);
772 my($ct,$ce) = guess_media_type($file);
773 my($size,$mtime) = (stat _)[7,9];
774 unless ($self->antique_client) {
775 $self->send_basic_header;
776 print $self "Content-Type: $ct$CRLF";
777 print $self "Content-Encoding: $ce$CRLF" if $ce;
778 print $self "Content-Length: $size$CRLF" if $size;
779 print $self "Last-Modified: ", time2str($mtime), "$CRLF" if $mtime;
780 print $self $CRLF;
781 }
782 $self->send_file(\*F);
783 return RC_OK;
784 } else {
785 $self->send_error(RC_NOT_FOUND);
786 }
787 }
788  
789  
790 sub send_dir
791 {
792 my($self, $dir) = @_;
793 $self->send_error(RC_NOT_FOUND) unless -d $dir;
794 $self->send_error(RC_NOT_IMPLEMENTED);
795 }
796  
797  
798 =item $c->send_file($fd);
799  
800 Copy the file to the client. The file can be a string (which
801 will be interpreted as a filename) or a reference to an I<IO::Handle>
802 or glob.
803  
804 =cut
805  
806 sub send_file
807 {
808 my($self, $file) = @_;
809 my $opened = 0;
810 if (!ref($file)) {
811 local(*F);
812 open(F, $file) || return undef;
813 binmode(F);
814 $file = \*F;
815 $opened++;
816 }
817 my $cnt = 0;
818 my $buf = "";
819 my $n;
820 while ($n = sysread($file, $buf, 8*1024)) {
821 last if !$n;
822 $cnt += $n;
823 print $self $buf;
824 }
825 close($file) if $opened;
826 $cnt;
827 }
828  
829  
830 =item $c->daemon
831  
832 Return a reference to the corresponding I<HTTP::Daemon> object.
833  
834 =cut
835  
836 sub daemon
837 {
838 my $self = shift;
839 ${*$self}{'httpd_daemon'};
840 }
841  
842 =back
843  
844 =head1 SEE ALSO
845  
846 RFC 2068
847  
848 L<IO::Socket::INET>, L<Apache>
849  
850 =head1 COPYRIGHT
851  
852 Copyright 1996-2001, Gisle Aas
853  
854 This library is free software; you can redistribute it and/or
855 modify it under the same terms as Perl itself.
856  
857 =cut
858  
859 1;