TPSGI.pm 28 KB

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