TPSGI.pm 27 KB

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