root/trunk/lib/Perlbal/ClientHTTPBase.pm @ 704

Revision 704, 27.1 kB (checked in by marksmith, 2 years ago)

* don't enforce lowercase extensions (OS is probably case sensitive,

even though you are likely to shoot yourself in the foot if you start
using case sensitive extensions...)

* remove ADD in favor of SET, otherwise we will break people's config

files if they define a type we later add to the base class

* fix comments to reflect reality

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1######################################################################
2# Common HTTP functionality for ClientProxy and ClientHTTP
3# possible states:
4#   reading_headers (initial state, then follows one of two paths)
5#     wait_backend, backend_req_sent, wait_res, xfer_res, draining_res
6#     wait_stat, wait_open, xfer_disk
7# both paths can then go into persist_wait, which means they're waiting
8# for another request from the user
9#
10# Copyright 2004, Danga Interactive, Inc.
11# Copyright 2005-2007, Six Apart, Ltd.
12
13package Perlbal::ClientHTTPBase;
14use strict;
15use warnings;
16no  warnings qw(deprecated);
17
18use Sys::Syscall;
19use base "Perlbal::Socket";
20use HTTP::Date ();
21use fields ('service',             # Perlbal::Service object
22            'replacement_uri',     # URI to send instead of the one requested; this is used
23                                   # to instruct _serve_request to send an index file instead
24                                   # of trying to serve a directory and failing
25            'scratch',             # extra storage; plugins can use it if they want
26
27            # reproxy support
28            'reproxy_file',        # filename the backend told us to start opening
29            'reproxy_file_size',   # size of file, once we stat() it
30            'reproxy_fh',          # if needed, IO::Handle of fd
31            'reproxy_file_offset', # how much we've sent from the file.
32
33            'post_sendfile_cb',    # subref to run after we're done sendfile'ing the current file
34
35            'requests',            # number of requests this object has performed for the user
36
37            # service selector parent
38            'selector_svc',        # the original service from which we came
39            );
40
41use Fcntl ':mode';
42use Errno qw( EPIPE ECONNRESET );
43use POSIX ();
44
45# hard-code defaults can be changed with MIME management command
46our $MimeType = {qw(
47                    css  text/css
48                    doc  application/msword
49                    gif  image/gif
50                    htm  text/html
51                    html text/html
52                    jpg  image/jpeg
53                    js   application/x-javascript
54                    mp3  audio/mpeg
55                    mpg  video/mpeg
56                    pdf  application/pdf
57                    png  image/png
58                    tif   image/tiff
59                    tiff  image/tiff
60                    torrent  application/x-bittorrent
61                    txt   text/plain
62                    zip   application/zip
63)};
64
65# ClientHTTPBase
66sub new {
67    my ($class, $service, $sock, $selector_svc) = @_;
68
69    my $self = $class;
70    $self = fields::new($class) unless ref $self;
71    $self->SUPER::new($sock);       # init base fields
72
73    $self->{service}         = $service;
74    $self->{replacement_uri} = undef;
75    $self->{headers_string}  = '';
76    $self->{requests}        = 0;
77    $self->{scratch}         = {};
78    $self->{selector_svc}    = $selector_svc;
79
80    $self->state('reading_headers');
81
82    bless $self, ref $class || $class;
83    $self->watch_read(1);
84    return $self;
85}
86
87sub close {
88    my Perlbal::ClientHTTPBase $self = shift;
89
90    # don't close twice
91    return if $self->{closed};
92
93    # could contain a closure with circular reference
94    $self->{post_sendfile_cb} = undef;
95
96    # close the file we were reproxying, if any
97    CORE::close($self->{reproxy_fh}) if $self->{reproxy_fh};
98
99    # now pass up the line
100    $self->SUPER::close(@_);
101}
102
103# given the response headers we just got, and considering our request
104# headers, determine if we should be sending keep-alive header
105# information back to the client
106sub setup_keepalive {
107    my Perlbal::ClientHTTPBase $self = $_[0];
108    print "ClientHTTPBase::setup_keepalive($self)\n" if Perlbal::DEBUG >= 2;
109
110    # now get the headers we're using
111    my Perlbal::HTTPHeaders $reshd = $_[1];
112    my Perlbal::HTTPHeaders $rqhd = $self->{req_headers};
113
114    # for now, we enforce outgoing HTTP 1.0
115    $reshd->set_version("1.0");
116
117    # if we came in via a selector service, that's whose settings
118    # we respect for persist_client
119    my $svc = $self->{selector_svc} || $self->{service};
120    my $persist_client = $svc->{persist_client} || 0;
121    print "  service's persist_client = $persist_client\n" if Perlbal::DEBUG >= 3;
122
123    # do keep alive if they sent content-length or it's a head request
124    my $do_keepalive = $persist_client && $rqhd->req_keep_alive($reshd);
125    if ($do_keepalive) {
126        print "  doing keep-alive to client\n" if Perlbal::DEBUG >= 3;
127        my $timeout = $self->{service}->{persist_client_timeout};
128        $reshd->header('Connection', 'keep-alive');
129        $reshd->header('Keep-Alive', $timeout ? "timeout=$timeout, max=100" : undef);
130    } else {
131        print "  doing connection: close\n" if Perlbal::DEBUG >= 3;
132        # FIXME: we don't necessarily want to set connection to close,
133        # but really set a space-separated list of tokens which are
134        # specific to the connection.  "close" and "keep-alive" are
135        # just special.
136        $reshd->header('Connection', 'close');
137        $reshd->header('Keep-Alive', undef);
138    }
139}
140
141# called when we've finished writing everything to a client and we need
142# to reset our state for another request.  returns 1 to mean that we should
143# support persistence, 0 means we're discarding this connection.
144sub http_response_sent {
145    my Perlbal::ClientHTTPBase $self = $_[0];
146
147    # close if we're supposed to
148    if (
149        ! defined $self->{res_headers} ||
150        ! $self->{res_headers}->res_keep_alive($self->{req_headers}) ||
151        $self->{do_die}
152        )
153    {
154        # do a final read so we don't have unread_data_waiting and RST
155        # the connection.  IE and others send an extra \r\n after POSTs
156        my $dummy = $self->read(5);
157
158        # close if we have no response headers or they say to close
159        $self->close("no_keep_alive");
160        return 0;
161    }
162
163    # if they just did a POST, set the flag that says we might expect
164    # an unadvertised \r\n coming from some browsers.  Old Netscape
165    # 4.x did this on all POSTs, and Firefox/Safari do it on
166    # XmlHttpRequest POSTs.
167    if ($self->{req_headers}->request_method eq "POST") {
168        $self->{ditch_leading_rn} = 1;
169    }
170
171    # now since we're doing persistence, uncork so the last packet goes.
172    # we will recork when we're processing a new request.
173    $self->tcp_cork(0);
174
175    # reset state
176    $self->{replacement_uri} = undef;
177    $self->{headers_string} = '';
178    $self->{req_headers} = undef;
179    $self->{res_headers} = undef;
180    $self->{reproxy_fh} = undef;
181    $self->{reproxy_file} = undef;
182    $self->{reproxy_file_size} = 0;
183    $self->{reproxy_file_offset} = 0;
184    $self->{read_buf} = [];
185    $self->{read_ahead} = 0;
186    $self->{read_size} = 0;
187    $self->{scratch} = {};
188    $self->{post_sendfile_cb} = undef;
189    $self->state('persist_wait');
190
191    if (my $selector_svc = $self->{selector_svc}) {
192        if (! $selector_svc->run_hook('return_to_base', $self)){
193            $selector_svc->return_to_base($self);
194        }
195    }
196
197    # NOTE: because we only speak 1.0 to clients they can't have
198    # pipeline in a read that we haven't read yet.
199    $self->watch_read(1);
200    $self->watch_write(0);
201    return 1;
202}
203
204sub reproxy_fh {
205    my Perlbal::ClientHTTPBase $self = shift;
206
207    # setter
208    if (@_) {
209        my ($fh, $size) = @_;
210        $self->state('xfer_disk');
211        $self->{reproxy_fh} = $fh;
212        $self->{reproxy_file_offset} = 0;
213        $self->{reproxy_file_size} = $size;
214        # call hook that we're reproxying a file
215        return $fh if $self->{service}->run_hook("start_send_file", $self);
216        # turn on writes (the hook might not have wanted us to)
217        $self->watch_write(1);
218        return $fh;
219    }
220
221    return $self->{reproxy_fh};
222}
223
224sub event_read {
225    my Perlbal::ClientHTTPBase $self = shift;
226
227    # see if we have headers?
228    die "Shouldn't get here!  This is an abstract base class, pretty much, except in the case of the 'selector' role."
229        if $self->{req_headers};
230
231    my $hd = $self->read_request_headers;
232    return unless $hd;
233
234    return if $self->{service}->run_hook('start_http_request', $self);
235
236    # we must stop watching for events now, otherwise if there's
237    # PUT/POST overflow, it'll be sent to ClientHTTPBase, which can't
238    # handle it yet.  must wait for the selector (which has as much
239    # time as it wants) to route as to our subclass, which can then
240    # renable reads.
241    $self->watch_read(0);
242
243    my $select = sub {
244        # now that we have headers, it's time to tell the selector
245        # plugin that it's time for it to select which real service to
246        # use
247        my $selector = $self->{'service'}->selector();
248        return $self->_simple_response(500, "No service selector configured.")
249            unless ref $selector eq "CODE";
250        $selector->($self);
251    };
252
253    my $svc = $self->{'service'};
254    if ($svc->{latency}) {
255        Danga::Socket->AddTimer($svc->{latency} / 1000, $select);
256    } else {
257        $select->();
258    }
259}
260
261# client is ready for more of its file.  so sendfile some more to it.
262# (called by event_write when we're actually in this mode)
263sub event_write_reproxy_fh {
264    my Perlbal::ClientHTTPBase $self = shift;
265
266    my $remain = $self->{reproxy_file_size} - $self->{reproxy_file_offset};
267    $self->tcp_cork(1) if $self->{reproxy_file_offset} == 0;
268
269    # cap at 128k sendfiles
270    my $to_send = $remain > 128 * 1024 ? 128 * 1024 : $remain;
271
272    $self->watch_write(0);
273
274    my $postread = sub {
275        return if $self->{closed};
276
277        my $sent = Perlbal::Socket::sendfile($self->{fd},
278                                             fileno($self->{reproxy_fh}),
279                                             $to_send);
280        #warn "to_send = $to_send, sent = $sent\n";
281        print "REPROXY Sent: $sent\n" if Perlbal::DEBUG >= 2;
282
283        if ($sent < 0) {
284            return $self->close("epipe")     if $! == EPIPE;
285            return $self->close("connreset") if $! == ECONNRESET;
286            print STDERR "Error w/ sendfile: $!\n";
287            $self->close('sendfile_error');
288            return;
289        }
290        $self->{reproxy_file_offset} += $sent;
291
292        if ($sent >= $remain) {
293            return if $self->{service}->run_hook('reproxy_fh_finished', $self);
294
295            # close the sendfile fd
296            CORE::close($self->{reproxy_fh});
297
298            $self->{reproxy_fh} = undef;
299            if (my $cb = $self->{post_sendfile_cb}) {
300                $cb->();
301            } else {
302                $self->http_response_sent;
303            }
304        } else {
305            $self->watch_write(1);
306        }
307    };
308
309    # TODO: way to bypass readahead and go straight to sendfile for common/hot/recent files.
310    # something like:
311    # if ($hot) { $postread->(); return ; }
312
313    if ($to_send < 0) {
314        Perlbal::log('warning', "tried to readahead negative bytes.  filesize=$self->{reproxy_file_size}, offset=$self->{reproxy_file_offset}");
315        # this code, doing sendfile, will fail gracefully with return
316        # code, not 'die', and we'll close with sendfile_error:
317        $postread->();
318        return;
319    }
320
321    Perlbal::AIO::set_file_for_channel($self->{reproxy_file});
322    Perlbal::AIO::aio_readahead($self->{reproxy_fh},
323                                $self->{reproxy_file_offset},
324                                $to_send, $postread);
325}
326
327sub event_write {
328    my Perlbal::ClientHTTPBase $self = shift;
329
330    # Any HTTP client is considered alive if it's writable.
331    # if it's not writable for 30 seconds, we kill it.
332    # subclasses can decide what's appropriate for timeout.
333    $self->{alive_time} = $Perlbal::tick_time;
334
335    # if we're sending a filehandle, go do some more sendfile:
336    if ($self->{reproxy_fh}) {
337        $self->event_write_reproxy_fh;
338        return;
339    }
340
341    # otherwise just kick-start our write buffer.
342    if ($self->write(undef)) {
343        # we've written all data in the queue, so stop waiting for
344        # write notifications:
345        print "All writing done to $self\n" if Perlbal::DEBUG >= 2;
346        $self->watch_write(0);
347    }
348}
349
350# this gets called when a "web" service is serving a file locally.
351sub _serve_request {
352    my Perlbal::ClientHTTPBase $self = shift;
353    my Perlbal::HTTPHeaders $hd = shift;
354
355    my $rm = $hd->request_method;
356    unless ($rm eq "HEAD" || $rm eq "GET") {
357        return $self->_simple_response(403, "Unimplemented method");
358    }
359
360    my $uri = Perlbal::Util::durl($self->{replacement_uri} || $hd->request_uri);
361    my Perlbal::Service $svc = $self->{service};
362
363    # start_serve_request hook
364    return 1 if $self->{service}->run_hook('start_serve_request', $self, \$uri);
365
366    # don't allow directory traversal
367    if ($uri =~ m!/\.\./! || $uri !~ m!^/!) {
368        return $self->_simple_response(403, "Bogus URL");
369    }
370
371    # double question mark means to serve multiple files, comma separated after the
372    # questions.  the uri part before the question mark is the relative base directory
373    # TODO: only do this if $uri has ?? and the service also allows it.  otherwise
374    # we don't want to mess with anybody's meaning of '??' on the backend service
375    return $self->_serve_request_multiple($hd, $uri) if $uri =~ /\?\?/;
376
377    # chop off the query string
378    $uri =~ s/\?.*//;
379
380    return $self->_simple_response(500, "Docroot unconfigured")
381        unless $svc->{docroot};
382
383    my $file = $svc->{docroot} . $uri;
384
385    # update state, since we're now waiting on stat
386    $self->state('wait_stat');
387
388    Perlbal::AIO::aio_stat($file, sub {
389        # client's gone anyway
390        return if $self->{closed};
391        unless (-e _) {
392            return if $self->{service}->run_hook('static_get_poststat_file_missing', $self);
393            return $self->_simple_response(404);
394        }
395
396        my $mtime   = (stat(_))[9];
397        my $lastmod = HTTP::Date::time2str($mtime);
398        my $ims     = $hd->header("If-Modified-Since") || "";
399
400        # IE sends a request header like "If-Modified-Since: <DATE>; length=<length>"
401        # so we have to remove the length bit before comparing it with our date.
402        # then we save the length to compare later.
403        my $ims_len;
404        if ($ims && $ims =~ s/; length=(\d+)//) {
405            $ims_len = $1;
406        }
407
408        my $not_mod = $ims eq $lastmod && -f _;
409
410        my $res;
411        my $not_satisfiable = 0;
412        my $size = -s _ if -f _;
413
414        # extra protection for IE, since it's offering the info anyway.  (see above)
415        $not_mod = 0 if $ims_len && $ims_len != $size;
416
417        my ($status, $range_start, $range_end) = $hd->range($size);
418
419        if ($not_mod) {
420            $res = $self->{res_headers} = Perlbal::HTTPHeaders->new_response(304);
421        } elsif ($status == 416) {
422            $res = $self->{res_headers} = Perlbal::HTTPHeaders->new_response(416);
423            $res->header("Content-Range", $size ? "bytes */$size" : "*");
424            $res->header("Content-Length", 0);
425            $not_satisfiable = 1;
426        } elsif ($status == 206) {
427            # partial content
428            $res = $self->{res_headers} = Perlbal::HTTPHeaders->new_response(206);
429        } else {
430            return if $self->{service}->run_hook('static_get_poststat_pre_send', $self, $mtime);
431            $res = $self->{res_headers} = Perlbal::HTTPHeaders->new_response(200);
432        }
433
434        # now set whether this is keep-alive or not
435        $res->header("Date", HTTP::Date::time2str());
436        $res->header("Server", "Perlbal");
437        $res->header("Last-Modified", $lastmod);
438
439        if (-f _) {
440            # advertise that we support byte range requests
441            $res->header("Accept-Ranges", "bytes");
442
443            unless ($not_mod || $not_satisfiable) {
444                my ($ext) = ($file =~ /\.(\w+)$/);
445                $res->header("Content-Type",
446                             (defined $ext && exists $MimeType->{$ext}) ? $MimeType->{$ext} : "text/plain");
447
448                unless ($status == 206) {
449                    $res->header("Content-Length", $size);
450                } else {
451                    $res->header("Content-Range", "bytes $range_start-$range_end/$size");
452                    $res->header("Content-Length", $range_end - $range_start + 1);
453                }
454            }
455
456            # has to happen after content-length is set to work:
457            $self->setup_keepalive($res);
458
459            return if $self->{service}->run_hook('modify_response_headers', $self);
460
461            if ($rm eq "HEAD" || $not_mod || $not_satisfiable) {
462                # we can return already, since we know the size
463                $self->tcp_cork(1);
464                $self->state('xfer_resp');
465                $self->write($res->to_string_ref);
466                $self->write(sub { $self->http_response_sent; });
467                return;
468            }
469
470            # state update
471            $self->state('wait_open');
472
473            Perlbal::AIO::aio_open($file, 0, 0, sub {
474                my $rp_fh = shift;
475
476                # if client's gone, just close filehandle and abort
477                if ($self->{closed}) {
478                    CORE::close($rp_fh) if $rp_fh;
479                    return;
480                }
481
482                # handle errors
483                if (! $rp_fh) {
484                    # couldn't open the file we had already successfully stat'ed.
485                    # FIXME: do 500 vs. 404 vs whatever based on $!
486                    return $self->close('aio_open_failure');
487                }
488
489                $self->state('xfer_disk');
490                $self->tcp_cork(1);  # cork writes to self
491                $self->write($res->to_string_ref);
492
493                # seek if partial content
494                if ($status == 206) {
495                    sysseek($rp_fh, $range_start, &POSIX::SEEK_SET);
496                    $size = $range_end - $range_start + 1;
497                }
498
499                $self->{reproxy_file} = $file;
500                $self->reproxy_fh($rp_fh, $size);
501            });
502
503        } elsif (-d _) {
504            $self->try_index_files($hd, $res, $uri);
505        }
506    });
507}
508
509sub _serve_request_multiple {
510    my Perlbal::ClientHTTPBase $self = shift;
511    my ($hd, $uri) = @_;
512
513    my @multiple_files;
514    my %statinfo;  # file -> [ stat fields ]
515
516    # double question mark means to serve multiple files, comma
517    # separated after the questions.  the uri part before the question
518    # mark is the relative base directory
519    my ($base, $list) = ($uri =~ /(.+)\?\?(.+)/);
520
521    unless ($base =~ m!/$!) {
522        return $self->_simple_response(500, "Base directory (before ??) must end in slash.")
523    }
524
525    # and remove any trailing ?.+ on the list, so you can do things like cache busting
526    # with a ?v=<modtime> at the end of a list of files.
527    $list =~ s/\?.+//;
528
529    my Perlbal::Service $svc = $self->{service};
530    return $self->_simple_response(500, "Docroot unconfigured")
531        unless $svc->{docroot};
532
533    @multiple_files = split(/,/, $list);
534
535    return $self->_simple_response(403, "Multiple file serving isn't enabled") unless $svc->{enable_concatenate_get};
536    return $self->_simple_response(403, "Too many files requested") if @multiple_files > 100;
537
538    my $remain = @multiple_files + 1;  # 1 for the base directory
539    my $dirbase = $svc->{docroot} . $base;
540    foreach my $file ('', @multiple_files) {
541        Perlbal::AIO::aio_stat("$dirbase$file", sub {
542            $remain--;
543            $statinfo{$file} = $! ? [] : [ stat(_) ];
544            return if $remain || $self->{closed};
545            $self->_serve_request_multiple_poststat($hd, $dirbase, \@multiple_files, \%statinfo);
546        });
547    }
548}
549
550sub _serve_request_multiple_poststat {
551    my Perlbal::ClientHTTPBase $self = shift;
552    my ($hd, $basedir, $filelist, $stats) = @_;
553
554    # base directory must be a directory
555    unless (S_ISDIR($stats->{''}[2] || 0)) {
556        return $self->_simple_response(404, "Base directory not a directory");
557    }
558
559    # files must all exist
560    my $sum_length      = 0;
561    my $most_recent_mod = 0;
562    my $mime;                  # undef until set, or defaults to text/plain later
563    foreach my $f (@$filelist) {
564        my $stat = $stats->{$f};
565        unless (S_ISREG($stat->[2] || 0)) {
566            return if $self->{service}->run_hook('concat_get_poststat_file_missing', $self);
567            return $self->_simple_response(404, "One or more file does not exist");
568        }
569        if (!$mime && $f =~ /\.(\w+)$/ && $MimeType->{$1}) {
570            $mime = $MimeType->{$1};
571        }
572        $sum_length     += $stat->[7];
573        $most_recent_mod = $stat->[9] if
574            $stat->[9] >$most_recent_mod;
575    }
576    $mime ||= 'text/plain';
577
578    my $lastmod = HTTP::Date::time2str($most_recent_mod);
579    my $ims     = $hd->header("If-Modified-Since") || "";
580
581    # IE sends a request header like "If-Modified-Since: <DATE>; length=<length>"
582    # so we have to remove the length bit before comparing it with our date.
583    # then we save the length to compare later.
584    my $ims_len;
585    if ($ims && $ims =~ s/; length=(\d+)//) {
586        $ims_len = $1;
587    }
588
589    # What is -f _ doing here? don't we detect the existance of all files above in the loop?
590    my $not_mod = $ims eq $lastmod && -f _;
591
592    my $res;
593    if ($not_mod) {
594        $res = $self->{res_headers} = Perlbal::HTTPHeaders->new_response(304);
595    } else {
596        return if $self->{service}->run_hook('concat_get_poststat_pre_send', $self, $most_recent_mod);
597        $res = $self->{res_headers} = Perlbal::HTTPHeaders->new_response(200);
598        $res->header("Content-Length", $sum_length);
599    }
600
601    $res->header("Date", HTTP::Date::time2str());
602    $res->header("Server", "Perlbal");
603    $res->header("Last-Modified", $lastmod);
604    $res->header("Content-Type",   $mime);
605    # has to happen after content-length is set to work:
606    $self->setup_keepalive($res);
607    return if $self->{service}->run_hook('modify_response_headers', $self);
608
609    if ($hd->request_method eq "HEAD" || $not_mod) {
610        # we can return already, since we know the size
611        $self->tcp_cork(1);
612        $self->state('xfer_resp');
613        $self->write($res->to_string_ref);
614        $self->write(sub { $self->http_response_sent; });
615        return;
616    }
617
618    $self->tcp_cork(1);  # cork writes to self
619    $self->write($res->to_string_ref);
620    $self->state('wait_open');
621
622    # gotta send all files, one by one...
623    my @remain = @$filelist;
624    $self->{post_sendfile_cb} = sub {
625        unless (@remain) {
626            $self->write(sub { $self->http_response_sent; });
627            return;
628        }
629
630        my $file     = shift @remain;
631        my $fullfile = "$basedir$file";
632        my $size     = $stats->{$file}[7];
633
634        Perlbal::AIO::aio_open($fullfile, 0, 0, sub {
635            my $rp_fh = shift;
636
637            # if client's gone, just close filehandle and abort
638            if ($self->{closed}) {
639                CORE::close($rp_fh) if $rp_fh;
640                  return;
641              }
642
643            # handle errors
644            if (! $rp_fh) {
645                # couldn't open the file we had already successfully stat'ed.
646                # FIXME: do 500 vs. 404 vs whatever based on $!
647                return $self->close('aio_open_failure');
648            }
649
650            $self->{reproxy_file}     = $file;
651            $self->reproxy_fh($rp_fh, $size);
652        });
653    };
654    $self->{post_sendfile_cb}->();
655}
656
657sub try_index_files {
658    my Perlbal::ClientHTTPBase $self = shift;
659    my ($hd, $res, $uri, $filepos) = @_;
660
661    # make sure this starts at 0 initially, and fail if it's past the end
662    $filepos ||= 0;
663    if ($filepos >= scalar(@{$self->{service}->{index_files} || []})) {
664        unless ($self->{service}->{dirindexing}) {
665            # just inform them that listing is disabled
666            $self->_simple_response(200, "Directory listing disabled");
667            return;
668        }
669
670        # ensure uri has one and only one trailing slash for better URLs
671        $uri =~ s!/*$!/!;
672
673        # open the directory and create an index
674        my $body = "<html><body>";
675        my $file = $self->{service}->{docroot} . $uri;
676
677        $res->header("Content-Type", "text/html");
678        opendir(D, $file);
679        foreach my $de (sort readdir(D)) {
680            if (-d "$file/$de") {
681                $body .= "<b><a href='$uri$de/'>$de</a></b><br />\n";
682            } else {
683                $body .= "<a href='$uri$de'>$de</a><br />\n";
684            }
685        }
686        closedir(D);
687
688        $body .= "</body></html>";
689        $res->header("Content-Length", length($body));
690        $self->setup_keepalive($res);
691
692        $self->state('xfer_resp');
693        $self->tcp_cork(1);  # cork writes to self
694        $self->write($res->to_string_ref);
695        $self->write(\$body);
696        $self->write(sub { $self->http_response_sent; });
697        return;
698    }
699
700    # construct the file path we need to check
701    my $file = $self->{service}->{index_files}->[$filepos];
702    my $fullpath = $self->{service}->{docroot} . $uri . '/' . $file;
703
704    # now see if it exists
705    Perlbal::AIO::aio_stat($fullpath, sub {
706        return if $self->{closed};
707        return $self->try_index_files($hd, $res, $uri, $filepos + 1) unless -f _;
708
709        # at this point the file exists, so we just want to serve it
710        $self->{replacement_uri} = $uri . '/' . $file;
711        return $self->_serve_request($hd);
712    });
713}
714
715sub _simple_response {
716    my Perlbal::ClientHTTPBase $self = shift;
717    my ($code, $msg) = @_;  # or bodyref
718
719    my $res = $self->{res_headers} = Perlbal::HTTPHeaders->new_response($code);
720
721    my $body;
722    if ($code != 204 && $code != 304) {
723        $res->header("Content-Type", "text/html");
724        my $en = $res->http_code_english;
725        $body = "<h1>$code" . ($en ? " - $en" : "") . "</h1>\n";
726        $body .= $msg if $msg;
727        $res->header('Content-Length', length($body));
728    }
729
730    $res->header('Server', 'Perlbal');
731
732    $self->setup_keepalive($res);
733
734    $self->state('xfer_resp');
735    $self->tcp_cork(1);  # cork writes to self
736    $self->write($res->to_string_ref);
737    if (defined $body) {
738        unless ($self->{req_headers} && $self->{req_headers}->request_method eq 'HEAD') {
739            # don't write body for head requests
740            $self->write(\$body);
741        }
742    }
743    $self->write(sub { $self->http_response_sent; });
744    return 1;
745}
746
747
748sub send_response {
749    my Perlbal::ClientHTTPBase $self = shift;
750
751    $self->watch_read(0);
752    $self->watch_write(1);
753    return $self->_simple_response(@_);
754}
755
756# method that sends a 500 to the user but logs it and any extra information
757# we have about the error in question
758sub system_error {
759    my Perlbal::ClientHTTPBase $self = shift;
760    my ($msg, $info) = @_;
761
762    # log to syslog
763    Perlbal::log('warning', "system error: $msg ($info)");
764
765    # and return a 500
766    return $self->send_response(500, $msg);
767}
768
769sub event_err {  my $self = shift; $self->close('error'); }
770sub event_hup {  my $self = shift; $self->close('hup'); }
771
772sub as_string {
773    my Perlbal::ClientHTTPBase $self = shift;
774
775    my $ret = $self->SUPER::as_string;
776    my $name = $self->{sock} ? getsockname($self->{sock}) : undef;
777    my $lport = $name ? (Socket::sockaddr_in($name))[0] : undef;
778    $ret .= ": localport=$lport" if $lport;
779    $ret .= "; reqs=$self->{requests}";
780    $ret .= "; $self->{state}";
781
782    my $hd = $self->{req_headers};
783    if (defined $hd) {
784        my $host = $hd->header('Host') || 'unknown';
785        $ret .= "; http://$host" . $hd->request_uri;
786    }
787
788    return $ret;
789}
790
7911;
792
793# Local Variables:
794# mode: perl
795# c-basic-indent: 4
796# indent-tabs-mode: nil
797# End:
Note: See TracBrowser for help on using the browser.