| 1 | package YATT::Toplevel::Server; | ||
| 2 | use strict; | ||
| 3 | use warnings qw(FATAL all NONFATAL misc); | ||
| 4 | |||
| 5 | use YATT::Toplevel::CGI qw(*PATH_INFO rootname capture Config); | ||
| 6 | |||
| 7 | use base qw(HTTP::Server::Simple::CGI | ||
| 8 | YATT::Toplevel::CGI); | ||
| 9 | |||
| 10 | use Carp; | ||
| 11 | |||
| 12 | use YATT::Util::Taint; | ||
| 13 | use YATT::Util; | ||
| 14 | |||
| 15 | sub default_port () { 8766 } | ||
| 16 | |||
| 17 | sub run_server { | ||
| 18 | my ($pack, $dir, %args) = @_; | ||
| 19 | my $server = $pack->SUPER::new(delete $args{port} || $pack->default_port); | ||
| 20 | my Config $top = $pack->new_config(auto_reload => 1 | ||
| 21 | , find_root_upward => 0 | ||
| 22 | , %args)->create_toplevel($dir); | ||
| 23 | $server->{TOP} = $top; | ||
| 24 | unless (chdir($top->{cf_docs})) { | ||
| 25 | die "Can't chdir to docs: $top->{cf_docs}"; | ||
| 26 | } | ||
| 27 | $server->SUPER::run; | ||
| 28 | } | ||
| 29 | |||
| 30 | my %TYPE = qw(js text/javascript); | ||
| 31 | |||
| 32 | sub handle_request { | ||
| 33 | my ($server, $cgi) = @_; | ||
| 34 | my Config $top = $server->{TOP}; | ||
| 35 | $cgi->charset($top->{cf_charset} || 'utf-8'); | ||
| 36 | |||
| 37 | my $file = $cgi->path_info; | ||
| 38 | my @args; | ||
| 39 | unless (-e "$top->{cf_docs}$file") { | ||
| 40 | push @args, $top->trim_trailing_pathinfo(\$file, $top->{cf_docs}); | ||
| 41 | } | ||
| 42 | |||
| 43 | unless ($file =~ m{\.html?$}) { | ||
| 44 | my ($ext, $type, $fh); | ||
| 45 | unless (($ext) = $file =~ m{\.(\w+)$} and my $type = $TYPE{$ext}) { | ||
| 46 | print "HTTP/1.0 500\r\n\r\n"; | ||
| 47 | print "Unsupported file type $file"; | ||
| 48 | } elsif (not open my $fh, '<', "$top->{cf_docs}$file") { | ||
| 49 | print "HTTP/1.0 404\r\n\r\n"; | ||
| 50 | print "Not found: $file ($!)\n"; | ||
| 51 | } else { | ||
| 52 | print "HTTP/1.0 200\r\n"; | ||
| 53 | print $cgi->header(-type => $type, -Content_length => -s $fh); | ||
| 54 | local $_ = ""; | ||
| 55 | print while sysread $fh, $_, 2048; | ||
| 56 | } | ||
| 57 | return; | ||
| 58 | } | ||
| 59 | |||
| 60 | my ($renderer, $pkg, $widget); | ||
| 61 | my ($html, $error); | ||
| 62 | |||
| 63 | local $SIG{__DIE__} = sub { | ||
| 64 | print STDERR Carp::longmess('error while request handling: ', @_); | ||
| 65 | die @_; | ||
| 66 | }; | ||
| 67 | |||
| 68 | if (catch { | ||
| 69 | ($renderer, $pkg, $widget) = $top->registry->get_handler_to | ||
| 70 | (render => $top->canonicalize_html_filename($file)); | ||
| 71 | } \ $error or catch { | ||
| 72 | $html = capture { | ||
| 73 | $renderer->($pkg, $widget->reorder_cgi_params($cgi, \@args)) | ||
| 74 | } | ||
| 75 | } \ $error) { | ||
| 76 | print "HTTP/1.0 500\r\n\r\n"; | ||
| 77 | print $error; | ||
| 78 | } else { | ||
| 79 | print "HTTP/1.0 200\r\n"; | ||
| 80 | print $cgi->header; | ||
| 81 | print $html; | ||
| 82 | } | ||
| 83 | } | ||
| 84 | |||
| 85 | 1; |