TPSGI.pm 34 KB

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