TPSGI.pm 24 KB

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