TPSGI.pm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. package TPSGI;
  2. # Abstract: Abstraction layer around starman to become a general purpose HTTP server
  3. use strict;
  4. use warnings;
  5. use feature qw{state};
  6. use Carp::Always;
  7. use POSIX();
  8. use Mojo::File;
  9. use Plack::MIME;
  10. use IO::Compress::Gzip;
  11. use Time::HiRes qw{tv_interval};
  12. # For CGI features
  13. use HTTP::Parser::XS qw{HEADERS_AS_HASHREF};
  14. use CGI::Emulate::PSGI;
  15. use Date::Format qw{strftime};
  16. use List::Util();
  17. use File::Find;
  18. use Sys::Hostname();
  19. use Plack::MIME ();
  20. use DateTime::Format::HTTP();
  21. use Time::HiRes qw{gettimeofday tv_interval};
  22. use File::Touch;
  23. use File::Path;
  24. use Cwd qw{abs_path};
  25. use File::Basename qw{dirname basename};
  26. use Log::Dispatch;
  27. use Log::Dispatch::Screen;
  28. use Log::Dispatch::FileRotate;
  29. use Config::Simple;
  30. #1MB chunks
  31. our $CHUNK_SEP = 'perlfsSep666YOLO42069';
  32. our $CHUNK_SIZE = 1024000;
  33. our %content_types = (
  34. text => "text/plain",
  35. html => "text/html",
  36. json => "application/json",
  37. blob => "application/octet-stream",
  38. xml => "text/xml",
  39. xsl => "text/xsl",
  40. css => "text/css",
  41. rss => "application/rss+xml",
  42. email => "multipart/related",
  43. );
  44. our %byct = reverse %content_types;
  45. our %cache_control = (
  46. revalidate => "no-cache, max-age=0",
  47. nocache => "no-store",
  48. static => "public, max-age=604800, immutable",
  49. );
  50. #TODO consider integrating libfile
  51. #Stuff that isn't in upstream finders
  52. my %extra_types = (
  53. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  54. );
  55. my $ct = 'Content-type';
  56. #memoize
  57. my $rq;
  58. my $cur_query = {};
  59. sub log {
  60. my $self = shift;
  61. state $log;
  62. return $log if $log;
  63. my $LOGNAME = abs_path('.').'/log/tpsgi.log';
  64. $LOGNAME = $self->{custom_log} if $self->{custom_log};
  65. my $LOGDIR = dirname($LOGNAME);
  66. File::Path::make_path($LOGDIR) unless -d $LOGDIR;
  67. File::Touch::touch($LOGNAME) unless -f $LOGNAME;
  68. my $LEVEL = $self->{verbose} ? 'debug' : 'info';
  69. # By default only log requests & warnings.
  70. # Otherwise emit debug messages.
  71. my $rotate = Log::Dispatch::FileRotate->new(
  72. name => 'tcms',
  73. filename => $LOGNAME,
  74. min_level => $LEVEL,
  75. 'mode' => 'append',
  76. size => 10 * 1024 * 1024,
  77. max => 6,
  78. );
  79. # Only send fatal events/errors to stdout
  80. my $screen = Log::Dispatch::Screen->new(
  81. name => 'screen',
  82. min_level => $LEVEL,
  83. );
  84. $log = Log::Dispatch->new();
  85. $log->add($rotate);
  86. $log->add($screen);
  87. foreach my $logger (@{$self->{loggers}}) {
  88. $log->add($logger->new( min_level => $LEVEL, log_dir => $LOGDIR ));
  89. }
  90. $log->info( $self->_log("Opening Log $LOGNAME at $LEVEL level") );
  91. return $log;
  92. }
  93. sub _log {
  94. my ( $self, $msg ) = @_;
  95. $msg //= "No message passed. This is almost certainly a bug. ";
  96. #XXX Log lines must start as an ISO8601 date, anything else breaks fail2ban's beautiful mind
  97. my $tstamp = POSIX::strftime "%Y-%m-%dT%H:%M:%SZ", gmtime;
  98. return "[Worker $$] $tstamp : $self->{ip} $msg\n";
  99. }
  100. # Logger short cuts
  101. sub DEBUG {
  102. my $self = shift;
  103. $self->log->debug( $self->_log( shift ) );
  104. }
  105. sub INFO {
  106. my $self = shift;
  107. $self->log->info( $self->_log( shift ) );
  108. }
  109. sub NOTE {
  110. my $self = shift;
  111. $self->log->notice( $self->_log( shift ) );
  112. }
  113. sub WARN {
  114. my $self = shift;
  115. $self->log->warning( $self->_log( shift ) );
  116. }
  117. sub ERROR {
  118. my $self = shift;
  119. $self->log->error( $self->_log( shift ) );
  120. }
  121. sub CRIT {
  122. my $self = shift;
  123. $self->log->critical( $self->_log( shift ) );
  124. }
  125. sub ALERT {
  126. my $self = shift;
  127. $self->log->alert( $self->_log( shift ) );
  128. }
  129. sub EMERG {
  130. my $self = shift;
  131. $self->log->emergency( $self->_log( shift ) );
  132. }
  133. sub FATAL {
  134. my $self = shift;
  135. $self->log->log_and_die( level => 'emergency', message => $self->_log( shift ) );
  136. }
  137. =head1 new(%options)
  138. Options are:
  139. custom_log
  140. verbose
  141. routers
  142. loggers
  143. authn
  144. =cut
  145. sub new {
  146. my ($class, %options) = @_;
  147. my %routes;
  148. no strict 'refs';
  149. foreach my $route (@{$options{routers}}) {
  150. # The router needs to exist and have nonzero numbers of routes.
  151. my ($package) = basename($route) =~ m/(\S+)\.pm$/;
  152. my $r = "$package\:\:routes";
  153. my $success = eval { require $route; 1; };
  154. if ($success) {
  155. my $pkg_routes = *$r{HASH};
  156. @routes{keys(%$pkg_routes)} = values(%$pkg_routes);
  157. } else {
  158. die "Could not load $route!";
  159. }
  160. }
  161. use strict 'refs';
  162. # Set the pattern used to discover the route if needed later.
  163. foreach my $route (keys(%routes)) {
  164. $routes{$route}{pattern} = $route;
  165. }
  166. $options{indices} //=[];
  167. $options{indices} = [@{$options{indices}},qw{index.html index.htm index.cgi}];
  168. my $num_routes = keys(%routes);
  169. INFO("Parsed $num_routes routes from config in $ENV{HOME}/.tpsgi");
  170. $options{routes} = \%routes;
  171. $options{ip} = '0.0.0.0';
  172. return bless(\%options, $class);
  173. }
  174. sub indices {
  175. my $self = shift;
  176. return $self->{indices};
  177. }
  178. sub routes {
  179. my $self = shift;
  180. return $self->{routes};
  181. }
  182. =head2 serve
  183. Serve a file, with options to stream and cache the output.
  184. =cut
  185. sub serve {
  186. my ( $self, $fullpath, $path, $start, $streaming, $ranges, $last_fetch, $deflate ) = @_;
  187. $last_fetch ||= 0;
  188. $deflate ||= 0;
  189. my $mf = Mojo::File->new($path);
  190. my $ext = '.' . $mf->extname();
  191. my $ft;
  192. if ($ext) {
  193. $ft = Plack::MIME->mime_type($ext) if $ext;
  194. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  195. }
  196. $ft ||= $content_types{text};
  197. my @headers = ( $ct => $ft );
  198. #TODO use static Cache-Control for everything but JS/CSS?
  199. push( @headers, 'Cache-control' => $cache_control{revalidate} );
  200. push( @headers, 'Accept-Ranges' => 'bytes' );
  201. my $mt = ( stat($path) )[9];
  202. my $sz = ( stat(_) )[7];
  203. my @gm = gmtime($mt);
  204. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  205. my $code = $mt > $last_fetch ? 200 : 304;
  206. push( @headers, "Last-Modified" => $now_string );
  207. push( @headers, 'Vary' => 'Accept-Encoding' );
  208. if ( open( my $fh, '<', $path ) ) {
  209. return $self->_range( $fullpath, $fh, $ranges, $sz, @headers ) if @$ranges && $streaming;
  210. # Transfer-encoding: chunked
  211. return sub {
  212. my $responder = shift;
  213. push( @headers, 'Content-Length' => $sz );
  214. my $writer = $responder->( [ $code, \@headers ] );
  215. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  216. $writer->write($buf);
  217. }
  218. close $fh;
  219. $writer->close;
  220. }
  221. if $streaming && $sz > $CHUNK_SIZE;
  222. #Return data in the event the caller does not support deflate
  223. if ( !$deflate ) {
  224. push( @headers, "Content-Length" => $sz );
  225. # Append server-timing headers
  226. my $tot = tv_interval($start) * 1000;
  227. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  228. return [ $code, \@headers, $fh ];
  229. }
  230. #Compress everything less than 1MB
  231. push( @headers, "Content-Encoding" => "gzip" );
  232. my $dfh;
  233. IO::Compress::Gzip::gzip( $fh => \$dfh );
  234. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  235. push( @headers, "Content-Length" => length($dfh) );
  236. $self->INFO("GET 200 $fullpath");
  237. # Append server-timing headers
  238. my $tot = tv_interval($start) * 1000;
  239. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  240. return [ $code, \@headers, [$dfh] ];
  241. }
  242. $self->INFO("GET 403 $fullpath");
  243. return [ 403, [ $ct => $content_types{text} ], ["Forbidden"] ];
  244. }
  245. sub _range {
  246. my ( $self, $fullpath, $fh, $ranges, $sz, %headers ) = @_;
  247. # Set mode
  248. my $primary_ct = "Content-Type: $headers{'Content-type'}";
  249. my $is_multipart = scalar(@$ranges) > 1;
  250. if ($is_multipart) {
  251. $headers{'Content-type'} = "multipart/byteranges; boundary=$CHUNK_SEP";
  252. }
  253. my $code = 206;
  254. my $fc = '';
  255. # Calculate the content-length up-front. We have to fix unspecified lengths first, and reject bad requests.
  256. foreach my $range (@$ranges) {
  257. $range->[1] //= $sz - 1;
  258. $self->INFO("GET 416 $fullpath");
  259. return [ 416, [%headers], ["Requested range not satisfiable"] ] if $range->[0] > $sz || $range->[0] < 0 || $range->[1] < 0 || $range->[0] > $range->[1];
  260. }
  261. $headers{'Content-Length'} = List::Util::sum( map { my $arr = $_; $arr->[1] + 1, -$arr->[0] } @$ranges );
  262. #XXX Add the entity header lengths to the value - should hash-ify this to DRY
  263. if ($is_multipart) {
  264. foreach my $range (@$ranges) {
  265. $headers{'Content-Length'} += length("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n");
  266. $fc = "\n";
  267. }
  268. $headers{'Content-Length'} += length("\n--$CHUNK_SEP\--\n");
  269. $fc = '';
  270. }
  271. return sub {
  272. my $responder = shift;
  273. my $writer;
  274. foreach my $range (@$ranges) {
  275. $headers{'Content-Range'} = "bytes $range->[0]-$range->[1]/$sz" unless $is_multipart;
  276. $writer //= $responder->( [ $code, [%headers] ] );
  277. $writer->write("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n") if $is_multipart;
  278. $fc = "\n";
  279. my $len = List::Util::min( $sz, $range->[1] + 1 ) - $range->[0];
  280. $fh->seek( $range->[0], 0 );
  281. while ($len) {
  282. $fh->read( my $buf, List::Util::min( $len, $CHUNK_SIZE ) );
  283. $writer->write($buf);
  284. # Adjust for amount written
  285. $len = List::Util::max( $len - $CHUNK_SIZE, 0 );
  286. }
  287. }
  288. $fh->close();
  289. $writer->write("\n--$CHUNK_SEP\--\n") if $is_multipart;
  290. $writer->close;
  291. };
  292. }
  293. sub _generic {
  294. my ( $type, $code ) = @_;
  295. return [$code, [$ct => $content_types{html}], ["$type"]];
  296. }
  297. =head2 notfound, forbidden, badrequest, toolong, error
  298. If you need to return these HTTP errors, return these within a route:
  299. sub route {
  300. my ($self, $query) = @_;
  301. ...
  302. return $self->notfound($query);
  303. }
  304. =cut
  305. sub notfound {
  306. my ($self, $query, $body) = @_;
  307. $self->INFO("$query->{method} 404 $query->{fullpath}");
  308. $body //= 'Not Found';
  309. return _generic( $body, 404 );
  310. }
  311. sub forbidden {
  312. my ($self, $query, $body) = @_;
  313. $self->INFO("$query->{method} 403 $query->{fullpath}");
  314. $body //= 'Forbidden';
  315. return _generic( 'Forbidden', 403 );
  316. }
  317. sub badrequest {
  318. my ($self, $query, $body) = @_;
  319. $self->INFO("$query->{method} 400 $query->{fullpath}");
  320. $body //= 'Bad Request';
  321. return _generic( $body, 400 );
  322. }
  323. sub toolong {
  324. my ($self, $query, $body) = @_;
  325. $self->INFO("$query->{method} 419 $query->{fullpath}");
  326. $body //= 'URI too long';
  327. return _generic( $body, 419 );
  328. }
  329. sub error {
  330. my ($self, $query, $body) = @_;
  331. my $method = $query->{method} // "?";
  332. my $fp = $query->{fullpath} // "?";
  333. $body //= 'Internal Server Error';
  334. $self->INFO("$method 500 $fp");
  335. return _generic( $body, 500 );
  336. }
  337. sub unavailable {
  338. my ($self, $query, $body) = @_;
  339. $self->INFO("$query->{method} 503 $query->{fullpath}");
  340. $body //= 'Service Unavailable';
  341. return _generic( $body, 503 );
  342. }
  343. my %etags;
  344. my $domain;
  345. sub app {
  346. my $self = shift;
  347. # Start the server timing clock
  348. my $start = [gettimeofday];
  349. my $env = shift;
  350. # Discard the path used in the log, it's too long and enough 4xx error code = ban
  351. return $self->toolong({ method => $env->{REQUEST_METHOD}, fullpath => '...' }) if length( $env->{REQUEST_URI} ) > 2048;
  352. # Various stuff important for logging requests
  353. $domain //= eval { Sys::Hostname::hostname() } // $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST};
  354. my $path = $env->{PATH_INFO};
  355. my $port = $env->{HTTP_X_FORWARDED_PORT} // $env->{HTTP_PORT};
  356. my $pport = defined $port ? ":$port" : "";
  357. my $scheme = $env->{'psgi.url_scheme'} // 'http';
  358. my $method = $env->{REQUEST_METHOD};
  359. # It's important that we log what the user ACTUALLY requested rather than the rewritten path later on.
  360. my $fullpath = "$scheme://$domain$pport$path";
  361. # sigdie can now "do the right thing"
  362. $self->{cur_query} = { route => $path, fullpath => $path, method => $method };
  363. # Check eTags. If we don't know about it, just assume it's good and lazily fill the cache
  364. # XXX yes, this allows cache poisoning...but only for logged in users!
  365. if ( $env->{HTTP_IF_NONE_MATCH} ) {
  366. $self->INFO("$env->{REQUEST_METHOD} 304 $fullpath");
  367. return [ 304, [], [''] ] if $env->{HTTP_IF_NONE_MATCH} eq ( $etags{ $env->{REQUEST_URI} } || '' );
  368. $etags{ $env->{REQUEST_URI} } = $env->{HTTP_IF_NONE_MATCH} unless exists $etags{ $env->{REQUEST_URI} };
  369. }
  370. # TODO: Actually do something with the language passed to the renderer
  371. my $lang = $env->{HTTP_ACCEPT_LANGUAGE};
  372. #TODO: Actually do something with the acceptable output formats in the renderer
  373. my $accept = $env->{HTTP_ACCEPT};
  374. my $last_fetch = 0;
  375. if ( $env->{HTTP_IF_MODIFIED_SINCE} ) {
  376. $last_fetch = DateTime::Format::HTTP->parse_datetime( $env->{HTTP_IF_MODIFIED_SINCE} )->epoch();
  377. }
  378. # Figure out if we want compression or not
  379. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  380. $alist =~ s/\s//g;
  381. my @accept_encodings;
  382. @accept_encodings = split( /,/, $alist );
  383. my $deflate = grep { 'gzip' eq $_ } @accept_encodings;
  384. # Set the IP of the request so we can fail2ban
  385. $self->{ip} = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR};
  386. my $streaming = $env->{'psgi.streaming'};
  387. # If we have an actual route, just use it.
  388. my $r = $self->routes;
  389. my $route_actual = $r->{$path};
  390. # Might be a regexed route.
  391. if (!$route_actual) {
  392. my $matched = List::Util::first { exists $r->{$_}{pattern} && $path =~ m/^$r->{$_}{pattern}$/ } keys(%$r);
  393. $route_actual = $r->{$matched} if $matched;
  394. }
  395. return $self->route( $route_actual, $env, $fullpath, $path, $start, $last_fetch, $deflate ) if $route_actual;
  396. # Do a case insensitive match, because osx and windows
  397. my $file_possible = $self->mangle_filename("www/$path");
  398. my $file_actual = $file_possible if -f $file_possible;
  399. # Dirindices
  400. if (-d $file_possible) {
  401. foreach my $index (@{$self->indices}) {
  402. next if $file_actual;
  403. my $dirindex = $self->mangle_filename("www$path/$index");
  404. $dirindex =~ s|//|/|g;
  405. $file_actual = $dirindex if -f $dirindex;
  406. }
  407. }
  408. my $file_is_cgi = appears_executable($file_actual);
  409. return $self->cgi( $env, $fullpath, $file_actual, $last_fetch, $deflate) if $file_is_cgi;
  410. $self->INFO("Attempting to serve $fullpath [".($file_possible // "")."]");
  411. my @ranges = parse_ranges($env);
  412. return $self->serve( $fullpath, $file_actual, $start, $streaming, \@ranges, $last_fetch, $deflate ) if $file_actual;
  413. return $self->notfound($self->{cur_query});
  414. }
  415. sub mangle_filename {
  416. my ($self,$path) = @_;
  417. # XXX yes, you can have case sensitive OSX, but basically nobody enables that ever
  418. $path = lc($path) if List::Util::any { $^O eq $_ } qw{darwin MSWin32 dos};
  419. $self->DEBUG("Path mangled to $path");
  420. return $path;
  421. }
  422. sub parse_ranges {
  423. my $env = shift;
  424. # Handle HTTP range/streaming requests
  425. my $range = $env->{HTTP_RANGE} || "bytes=0-" if $env->{HTTP_RANGE} || $env->{HTTP_IF_RANGE};
  426. my @ranges;
  427. if ($range) {
  428. $range =~ s/bytes=//g;
  429. push(
  430. @ranges,
  431. map {
  432. [ split( /-/, $_ ) ];
  433. } split( /,/, $range )
  434. );
  435. }
  436. return @ranges;
  437. }
  438. my @executable_extensions = qw{cgi sh exe pl php py};
  439. sub appears_executable {
  440. my $subj = shift;
  441. # Definitely not executable if it does not exist!
  442. return 0 unless $subj;
  443. return 0 unless -x $subj;
  444. my ($extension) = $subj =~ m/\.(\S+)$/;
  445. return 1 if !$extension;
  446. return 1 if grep { $extension eq $_ } @executable_extensions;
  447. return 0;
  448. }
  449. # Handle actual routes
  450. sub route {
  451. my ($self, $route, $env, $fullpath, $path, $start, $last_fetch, $deflate ) = @_;
  452. my $content_type = $env->{CONTENT_TYPE};
  453. # It is the responsibility of each route to respond to HEAD requests correctly
  454. return $self->badrequest($self->{cur_query}) unless List::Util::any { $_ eq $env->{REQUEST_METHOD} } ('HEAD', $route->{method});
  455. my $callback;
  456. if (exists $route->{callbacks}{'*'}) {
  457. $callback = $route->{callbacks}{'*'};
  458. } else {
  459. return $self->badrequest($self->{cur_query}) unless exists $route->{callbacks}{$content_type};
  460. $callback = $route->{callbacks}{$content_type};
  461. }
  462. # Provide static renders if available.
  463. my $streaming = $env->{'psgi.streaming'};
  464. return $self->static( $fullpath, "$fullpath.z", $start, $streaming ) if -f "statics/$fullpath.z" && $deflate;
  465. return $self->static( $fullpath, $fullpath, $start, $streaming ) if -f "statics/$fullpath";
  466. # Build the query data for passing to a route.
  467. # GET, POST, URI captures, then explicit data overrides.
  468. my $query = $self->extract_query($path, $route, $env);
  469. # allow this stuff to survive down to the end of some routes
  470. $query->{last_fetched} = $last_fetch;
  471. $query->{deflate} = $deflate;
  472. $query->{streaming} = $streaming;
  473. my @ranges = parse_ranges($env);
  474. $query->{ranges} = \@ranges;
  475. $query->{start} = $start;
  476. $query->{fullpath} = $fullpath;
  477. $query->{method} = $route->{method};
  478. # This allows for better error handlers if we die in the route.
  479. $self->{cur_query} = $query;
  480. # Setup the CGI vars they expect IF requested
  481. local %ENV = (%ENV, CGI::Emulate::PSGI->emulate_environment($env)) if $route->{env};
  482. {
  483. my $output = $callback->($self, $query);
  484. # If it's streaming, just hand it off
  485. return $output if ref $output eq 'CODE';
  486. die "$fullpath returned no or malformed data!" unless ref $output eq 'ARRAY' && @$output == 3;
  487. my $pport = defined $query->{port} ? ":$query->{port}" : "";
  488. my %headers = @{$output->[1]};
  489. my $bytes = $headers{'Content-Length'} // '?';
  490. $self->INFO("$env->{REQUEST_METHOD} $output->[0] $bytes $fullpath");
  491. # Append server-timing headers if they aren't present
  492. my $tot = tv_interval($start) * 1000;
  493. push( @{ $output->[1] }, 'Server-Timing' => "app;dur=$tot" ) unless List::Util::any { $_ eq 'Server-Timing' } @{ $output->[1] };
  494. return $output;
  495. }
  496. }
  497. sub extract_query {
  498. my ($self, $path, $route, $env) = @_;
  499. my $query = URL::Encode::url_params_mixed( $env->{QUERY_STRING} ) if $env->{QUERY_STRING};
  500. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  501. if ( $env->{REQUEST_METHOD} eq 'POST' ) {
  502. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  503. while ( $env->{'psgi.input'}->read( my $buf, $CHUNK_SIZE ) ) {
  504. $body->add($buf);
  505. }
  506. @$query{ keys( %{ $body->param } ) } = values( %{ $body->param } );
  507. @$query{ keys( %{ $body->upload } ) } = values( %{ $body->upload } );
  508. }
  509. if (ref $route->{captures} eq 'ARRAY') {
  510. my @captures = $path =~ m/^$route->{pattern}$/;
  511. @$query{@{$route->{captures}}} = @captures;
  512. }
  513. if (ref $route->{data} eq 'HASH') {
  514. @$query{keys(%{$route->{data}})} = values(%{$route->{data}});
  515. }
  516. return $query;
  517. }
  518. # Read until we are done with headers, then pass off the filehandle to PSGI for streaming.
  519. # TODO support compression
  520. sub cgi {
  521. my ( $self, $env, $fullpath, $file_actual, $last_fetch, $deflate) = @_;
  522. $self->INFO("Handoff $fullpath to $file_actual for cgi exec");
  523. # Setup the CGI vars they expect
  524. local %ENV = (%ENV, CGI::Emulate::PSGI->emulate_environment($env));
  525. my $pid = open(my $out, '-|', "$file_actual");
  526. my ($code, %headers) = extract_headers($out, $last_fetch);
  527. $code //= 500;
  528. return sub {
  529. my $responder = shift;
  530. my $writer = $responder->( [ $code, [%headers] ] );
  531. while ( $out->read( my $buf, $CHUNK_SIZE ) ) {
  532. $writer->write($buf);
  533. }
  534. $writer->close;
  535. # Wait on the CGI script to do whatever it's doing after closing stdout
  536. close $out;
  537. waitpid($pid, 0);
  538. };
  539. }
  540. sub stream_raw_http {
  541. my ($self, $output, $last_fetch, $callback) = @_;
  542. open(my $out, '<', \$output) or die "I couldn't open a string as a filehandle, which can only happen if you don't compile perl with PerlIO";
  543. my ($code, %headers) = extract_headers($out, $last_fetch, 1);
  544. $code //= 500;
  545. $self->INFO("$self->{cur_query}{method} $code $self->{cur_query}{fullpath}");
  546. return sub {
  547. my $responder = shift;
  548. my $writer = $responder->( [ $code, [%headers] ] );
  549. while ( $out->read( my $buf, $CHUNK_SIZE ) ) {
  550. $writer->write($buf);
  551. }
  552. $writer->close;
  553. close($out);
  554. # Wait on the script to do whatever it's doing after closing stdout
  555. $callback->() if ref $callback eq 'CODE';
  556. };
  557. }
  558. =head2 extract_headers($fh, $last_fetch)
  559. Extract the headers from a filehandle. Set the 'Last Modified' header appropriately based on the output of `stat` on the filehandle.
  560. Returns a code and parsed headers hash. Code will be 304 if the file hasn't changed since $last_fetch, otherwise will be the code in the parsed headers.
  561. =cut
  562. sub extract_headers {
  563. my ($fh, $last_fetch, $is_ref) = @_;
  564. my $headers = '';
  565. # NOTE: this is relying on while advancing the file pointer
  566. while (<$fh>) {
  567. last if $_ eq "\n";
  568. $headers .= $_;
  569. }
  570. my ( undef, undef, $status, undef, $headers_parsed ) = HTTP::Parser::XS::parse_http_response( "$headers\n", HEADERS_AS_HASHREF );
  571. my $code = $status // 200;
  572. $headers_parsed //= {};
  573. if (!$is_ref) {
  574. my $mt = ( stat($fh) )[9];
  575. my @gm = gmtime($mt);
  576. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  577. $code = $mt > $last_fetch ? $status : 304;
  578. $headers_parsed->{"Last-Modified"} = $now_string;
  579. }
  580. return ($code, %$headers_parsed);
  581. }
  582. sub static {
  583. my ( $self, $fullpath, $path, $start, $streaming, $last_fetch ) = @_;
  584. $self->DEBUG("Rendering static for $path");
  585. # XXX because of psgi I can't just vomit the file directly
  586. if ( open( my $fh, '<', "statics/$path" ) ) {
  587. my ($code, $headers_parsed) = (200, {});
  588. ($code, %$headers_parsed) = extract_headers($fh, $last_fetch );
  589. # Append server-timing headers
  590. my $tot = tv_interval($start) * 1000;
  591. $headers_parsed->{'Server-Timing'} = "static;dur=$tot";
  592. #XXX uwsgi just opens the file *again* when we already have a filehandle if it has a path.
  593. # starman by comparison doesn't violate the principle of least astonishment here.
  594. # This is probably a performance optimization, but makes the kind of micromanagement I need to do inconvenient.
  595. # As such, we will just return a stream.
  596. $self->INFO("GET 200 $headers_parsed->{'Content-Length'} $fullpath");
  597. return sub {
  598. my $responder = shift;
  599. #push(@headers, 'Content-Length' => $sz);
  600. my $writer = $responder->( [ $code, [%$headers_parsed] ] );
  601. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  602. $writer->write($buf);
  603. }
  604. close $fh;
  605. $writer->close;
  606. }
  607. if $streaming;
  608. return [ $code, [%$headers_parsed], $fh ];
  609. }
  610. return $self->forbidden($self->{current_query});
  611. }
  612. sub get_config {
  613. my %options = (
  614. verbose => 0,
  615. custom_log => undef,
  616. routers => [],
  617. loggers => [],
  618. auth => undef,
  619. domain => '',
  620. user => '',
  621. );
  622. my $config_file = "$ENV{HOME}/.tpsgi.ini";
  623. if (-f $config_file) {
  624. my $conf = Config::Simple->new($config_file);
  625. my %config;
  626. %config = %{$conf->param(-block => 'default')} if $conf;
  627. # Merge the configuration with the options
  628. foreach my $opt (keys(%options)) {
  629. if ( ref $options{$opt} eq 'ARRAY' ) {
  630. next unless exists $config{$opt};
  631. my @arrayed = ref $config{$opt} eq 'ARRAY' ? @{$config{$opt}} : ($config{$opt});
  632. push(@{$options{$opt}}, @arrayed);
  633. next;
  634. }
  635. $options{$opt} = $config{$opt} if exists $config{$opt};
  636. }
  637. }
  638. return %options;
  639. }
  640. 1;