TPSGI.pm 28 KB

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