TPSGI.pm 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. package TPSGI;
  2. # Abstract: Abstraction layer around starman to become a general purpose HTTP server & static renderer.
  3. use strict;
  4. use warnings;
  5. use feature qw{state};
  6. use FindBin;
  7. use Carp::Always;
  8. use UUID();
  9. use POSIX();
  10. use Mojo::File;
  11. use IO::Compress::Gzip;
  12. use Time::HiRes qw{usleep gettimeofday tv_interval};
  13. # For CGI features
  14. use HTTP::Body;
  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 DateTime::Format::HTTP();
  22. use URL::Encode();
  23. use File::Touch;
  24. use File::Path;
  25. use File::Copy;
  26. use Cwd qw{abs_path};
  27. use File::Basename qw{dirname basename};
  28. use Log::Dispatch;
  29. use Log::Dispatch::Screen;
  30. use Log::Dispatch::FileRotate;
  31. use Config::Simple;
  32. use TPSGI::Startup;
  33. # We have a DEBUG var which is plus ultra for extra sensitive stuff beyond just passing verbose
  34. my $debug = $ENV{TPSGI_DEBUG};
  35. #1MB chunks
  36. our $CHUNK_SEP = 'perlfsSep666YOLO42069';
  37. our $CHUNK_SIZE = 1024000;
  38. our %content_types = (
  39. text => "text/plain",
  40. html => "text/html",
  41. json => "application/json",
  42. blob => "application/octet-stream",
  43. xml => "text/xml",
  44. xsl => "text/xsl",
  45. css => "text/css",
  46. rss => "application/rss+xml",
  47. email => "multipart/related",
  48. );
  49. our %byct = reverse %content_types;
  50. our %cache_control = (
  51. revalidate => "no-cache, max-age=0",
  52. nocache => "no-store",
  53. static => "public, max-age=604800, immutable",
  54. );
  55. #TODO consider integrating libfile
  56. #Stuff that isn't in upstream finders
  57. my %extra_types = (
  58. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  59. );
  60. my $ct = 'Content-type';
  61. #memoize
  62. my $rq;
  63. my $generic_handler;
  64. sub request_id {
  65. my ( $self, $regenerate ) = @_;
  66. return $self->{uuid} if $self->{uuid} && !$regenerate;
  67. $self->{uuid} = UUID::uuid();
  68. return $self->{uuid};
  69. }
  70. sub log {
  71. my $self = shift;
  72. state $log;
  73. return $log if $log;
  74. my $LOGNAME = $self->{log_name};
  75. my $LOGDIR = $self->{log_dir};
  76. File::Path::make_path($LOGDIR) unless -d $LOGDIR;
  77. File::Touch::touch($LOGNAME) unless -f $LOGNAME;
  78. my $LEVEL = $self->{verbose} ? 'debug' : 'info';
  79. # By default only log requests & warnings.
  80. # Otherwise emit debug messages.
  81. my $rotate = Log::Dispatch::FileRotate->new(
  82. name => 'tcms',
  83. filename => $LOGNAME,
  84. min_level => $LEVEL,
  85. 'mode' => 'append',
  86. size => 10 * 1024 * 1024,
  87. max => 6,
  88. );
  89. # Only send fatal events/errors to stdout
  90. my $screen = Log::Dispatch::Screen->new(
  91. name => 'screen',
  92. min_level => $LEVEL,
  93. );
  94. $log = Log::Dispatch->new();
  95. $log->add($rotate);
  96. $log->add($screen);
  97. foreach my $logger ( @{ $self->{loggers} } ) {
  98. $log->add( $logger->new( min_level => $LEVEL, log_dir => $LOGDIR ) );
  99. }
  100. $log->info( $self->_log("Opening Log $LOGNAME at $LEVEL level") );
  101. return $log;
  102. }
  103. sub _log {
  104. my ( $self, $msg ) = @_;
  105. $msg //= "No message passed. This is almost certainly a bug. ";
  106. #XXX Log lines must start as an ISO8601 date, anything else breaks fail2ban's beautiful mind
  107. my $tstamp = POSIX::strftime "%Y-%m-%dT%H:%M:%SZ", gmtime;
  108. my $uuid = $self->request_id();
  109. my $udata = $self->{user} ? "[$self->{user}]" : "[nobody]";
  110. return "[Worker $$] {Request $uuid} $udata $tstamp : $self->{ip} $msg\n";
  111. }
  112. # Logger short cuts
  113. sub DEBUG {
  114. my $self = shift;
  115. $self->log->debug( $self->_log(shift) );
  116. }
  117. sub INFO {
  118. my $self = shift;
  119. $self->log->info( $self->_log(shift) );
  120. }
  121. sub NOTE {
  122. my $self = shift;
  123. $self->log->notice( $self->_log(shift) );
  124. }
  125. sub WARN {
  126. my $self = shift;
  127. $self->log->warning( $self->_log(shift) );
  128. }
  129. sub ERROR {
  130. my $self = shift;
  131. $self->log->error( $self->_log(shift) );
  132. }
  133. sub CRIT {
  134. my $self = shift;
  135. $self->log->critical( $self->_log(shift) );
  136. }
  137. sub ALERT {
  138. my $self = shift;
  139. $self->log->alert( $self->_log(shift) );
  140. }
  141. sub EMERG {
  142. my $self = shift;
  143. $self->log->emergency( $self->_log(shift) );
  144. }
  145. sub FATAL {
  146. my $self = shift;
  147. $self->log->log_and_die( level => 'emergency', message => $self->_log(shift) );
  148. }
  149. =head1 new(%options)
  150. Options are:
  151. custom_log
  152. verbose
  153. routers
  154. loggers
  155. auth
  156. =cut
  157. sub new {
  158. my ( $class, %options ) = @_;
  159. # Refuse to run as wrong user, all config will be borked otherwise
  160. my $pname = getpwuid($>);
  161. die "Must run as configured user (got: $pname, want: $options{user})!" unless $pname eq ( $options{user} // '' );
  162. die "Must set http_user in options" unless $options{http_user};
  163. die "Must set tpsgi_dir in options" unless $options{tpsgi_dir};
  164. my $gid = getgrnam( $options{http_user} );
  165. die "No such user $options{http_user}" unless $gid;
  166. $options{gid} = $gid;
  167. my $self = bless( \%options, $class );
  168. $self->{ip} = '0.0.0.0';
  169. my @routes;
  170. my %aliases;
  171. # XXX TODO make these routes able to be fully qualified namespaces (::)!
  172. no strict 'refs';
  173. foreach my $route ( @{ $self->{routers} } ) {
  174. die "No such routing module $route" unless -f "$options{tpsgi_dir}/$route";
  175. # The router needs to exist and have nonzero numbers of routes.
  176. my ($package) = basename($route) =~ m/(\S+)\.pm$/;
  177. my $r = "$package\:\:routes";
  178. my $a = "$package\:\:aliases";
  179. my $w = "$package\:\:watches";
  180. # It also should be a top-level namespace, not somewhere deep down. KISS.
  181. my $libdir = dirname("$options{tpsgi_dir}/$route");
  182. push( @INC, $libdir );
  183. local $@;
  184. $self->DEBUG("require $options{tpsgi_dir}/$route");
  185. my $success = eval { require "$options{tpsgi_dir}/$route"; 1; };
  186. if ($success) {
  187. my $pkg_routes = *$r{ARRAY};
  188. for ( my $i = 0; $i < @$pkg_routes; $i += 2 ) {
  189. $self->DEBUG("Registered route $pkg_routes->[$i]");
  190. }
  191. push( @routes, @$pkg_routes );
  192. my $pkg_aliases = *$a{HASH};
  193. foreach my $al ( keys(%$pkg_aliases) ) {
  194. $self->DEBUG("aliased route $al to $pkg_aliases->{$al}");
  195. }
  196. @aliases{ keys(%$pkg_aliases) } = values(%$pkg_aliases);
  197. # Anything the router wants to watch, along with what to do when it changes.
  198. # Registration is idempotent, which matters because new() runs per request.
  199. my $pkg_watches = *$w{HASH};
  200. foreach my $watched ( keys(%$pkg_watches) ) {
  201. my $spec = $pkg_watches->{$watched};
  202. # Copied rather than used directly, as we don't want to eat the router's own data.
  203. my %args = ref $spec eq 'HASH' ? %$spec : ( callback => $spec );
  204. $self->add_watch( $watched, delete $args{callback}, %args );
  205. }
  206. # First-come first-served error template overrides
  207. $generic_handler = "$package\:\:generic_route";
  208. $generic_handler = undef unless exists &{$generic_handler};
  209. }
  210. else {
  211. die "Could not load $route!\n$@\n";
  212. }
  213. }
  214. use strict 'refs';
  215. # Set the pattern used to discover the route if needed later.
  216. for ( my $i = 0; $i < scalar(@routes); $i += 2 ) {
  217. $routes[ $i + 1 ]{pattern} = $routes[$i];
  218. }
  219. $self->{indices} //= [];
  220. $self->{indices} = [ @{ $self->{indices} }, qw{index.html index.htm index.cgi} ];
  221. $self->{routes} = \@routes;
  222. $self->{aliases} = \%aliases;
  223. $self->{callbacks} = [];
  224. return $self;
  225. }
  226. sub indices {
  227. my $self = shift;
  228. return $self->{indices};
  229. }
  230. sub routes {
  231. my $self = shift;
  232. return $self->{routes};
  233. }
  234. =head2 serve
  235. Serve a file, with options to stream and cache the output.
  236. =cut
  237. sub serve {
  238. my ( $self, $fullpath, $path, $start, $streaming, $ranges, $last_fetch, $deflate ) = @_;
  239. $last_fetch ||= 0;
  240. $deflate ||= 0;
  241. my $mf = Mojo::File->new($path);
  242. my $ext = '.' . $mf->extname();
  243. my $ft;
  244. if ($ext) {
  245. $ft = Plack::MIME->mime_type($ext) if $ext;
  246. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  247. }
  248. $ft ||= $content_types{text};
  249. my @headers = ( $ct => $ft );
  250. #TODO use static Cache-Control for everything but JS/CSS?
  251. push( @headers, 'Cache-control' => $cache_control{revalidate} );
  252. push( @headers, 'Accept-Ranges' => 'bytes' );
  253. $self->DEBUG("FETCH $path");
  254. my $mt = ( stat($path) )[9];
  255. my $sz = ( stat(_) )[7];
  256. my @gm = gmtime($mt);
  257. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  258. my $code = $mt > $last_fetch ? 200 : 304;
  259. push( @headers, "Last-Modified" => $now_string );
  260. push( @headers, 'Vary' => 'Accept-Encoding' );
  261. if ( open( my $fh, '<', $path ) ) {
  262. return $self->_range( $fullpath, $fh, $ranges, $sz, @headers ) if @$ranges && $streaming;
  263. # Transfer-encoding: chunked
  264. return sub {
  265. my $responder = shift;
  266. push( @headers, 'Content-Length' => $sz );
  267. my $writer = $responder->( [ $code, \@headers ] );
  268. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  269. $writer->write($buf);
  270. }
  271. close $fh;
  272. $writer->close;
  273. }
  274. if $streaming && $sz > $CHUNK_SIZE;
  275. #Return data in the event the caller does not support deflate
  276. if ( !$deflate ) {
  277. push( @headers, "Content-Length" => $sz );
  278. # Append server-timing headers
  279. my $tot = tv_interval($start) * 1000;
  280. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  281. return [ $code, \@headers, $fh ];
  282. }
  283. #Compress everything less than 1MB
  284. push( @headers, "Content-Encoding" => "gzip" );
  285. my $dfh;
  286. IO::Compress::Gzip::gzip( $fh => \$dfh );
  287. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  288. push( @headers, "Content-Length" => length($dfh) );
  289. # Copy to the statics if it's not already there
  290. my $static_path = $path;
  291. $static_path =~ s|^[/]*www/||;
  292. $static_path = "$self->{tpsgi_dir}/www/static/$static_path";
  293. if ( !-f $static_path ) {
  294. my $target_dir = dirname($static_path);
  295. $self->INFO("Copying $path to $static_path");
  296. if ( !-d $target_dir ) {
  297. File::Path::make_path( $target_dir, { user => $<, group => $self->{gid}, chmod => 0755 } ) or die "Could not make dir $target_dir";
  298. }
  299. # hardlink to save disk space
  300. link $path, $static_path;
  301. # TODO figure out cache invalidation, I guess check mtime/hash
  302. }
  303. $self->INFO("GET 200 $fullpath");
  304. # Append server-timing headers
  305. my $tot = tv_interval($start) * 1000;
  306. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  307. return [ $code, \@headers, [$dfh] ];
  308. }
  309. $self->INFO("GET 403 $fullpath");
  310. return [ 403, [ $ct => $content_types{text} ], ["Forbidden"] ];
  311. }
  312. sub _range {
  313. my ( $self, $fullpath, $fh, $ranges, $sz, %headers ) = @_;
  314. # Set mode
  315. my $primary_ct = "Content-Type: $headers{'Content-type'}";
  316. my $is_multipart = scalar(@$ranges) > 1;
  317. if ($is_multipart) {
  318. $headers{'Content-type'} = "multipart/byteranges; boundary=$CHUNK_SEP";
  319. }
  320. my $code = 206;
  321. my $fc = '';
  322. # Calculate the content-length up-front. We have to fix unspecified lengths first, and reject bad requests.
  323. foreach my $range (@$ranges) {
  324. $range->[1] //= $sz - 1;
  325. $self->INFO("GET 416 $fullpath");
  326. return [ 416, [%headers], ["Requested range not satisfiable"] ] if $range->[0] > $sz || $range->[0] < 0 || $range->[1] < 0 || $range->[0] > $range->[1];
  327. }
  328. $headers{'Content-Length'} = List::Util::sum( map { my $arr = $_; $arr->[1] + 1, -$arr->[0] } @$ranges );
  329. #XXX Add the entity header lengths to the value - should hash-ify this to DRY
  330. if ($is_multipart) {
  331. foreach my $range (@$ranges) {
  332. $headers{'Content-Length'} += length("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n");
  333. $fc = "\n";
  334. }
  335. $headers{'Content-Length'} += length("\n--$CHUNK_SEP\--\n");
  336. $fc = '';
  337. }
  338. return sub {
  339. my $responder = shift;
  340. my $writer;
  341. foreach my $range (@$ranges) {
  342. $headers{'Content-Range'} = "bytes $range->[0]-$range->[1]/$sz" unless $is_multipart;
  343. $writer //= $responder->( [ $code, [%headers] ] );
  344. $writer->write("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n") if $is_multipart;
  345. $fc = "\n";
  346. my $len = List::Util::min( $sz, $range->[1] + 1 ) - $range->[0];
  347. $fh->seek( $range->[0], 0 );
  348. while ($len) {
  349. $fh->read( my $buf, List::Util::min( $len, $CHUNK_SIZE ) );
  350. $writer->write($buf);
  351. # Adjust for amount written
  352. $len = List::Util::max( $len - $CHUNK_SIZE, 0 );
  353. }
  354. }
  355. $fh->close();
  356. $writer->write("\n--$CHUNK_SEP--\n") if $is_multipart;
  357. $writer->close;
  358. };
  359. }
  360. sub _generic {
  361. my ( $type, $code, $query ) = @_;
  362. if ($generic_handler) {
  363. my $rname = "/$code";
  364. my $title = $type;
  365. no strict 'refs';
  366. return $generic_handler->( $rname, $code, $title, $query );
  367. }
  368. $type .= Carp::longmess() if $debug;
  369. return [ $code, [ $ct => $content_types{html} ], ["$type"] ];
  370. }
  371. =head2 redirect, redirect_permanent, see_also
  372. Redirects to the provided page.
  373. =cut
  374. sub redirect {
  375. my ( $self, $to ) = @_;
  376. $self->INFO("redirect: $to");
  377. return [ 302, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  378. }
  379. sub redirect_permanent {
  380. my ( $self, $to ) = @_;
  381. $self->INFO("permanent redirect: $to");
  382. return [ 301, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  383. }
  384. sub see_also {
  385. my ( $self, $to ) = @_;
  386. $self->INFO("see also: $to");
  387. return [ 303, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  388. }
  389. =head2 ok
  390. Return a generic HTTP 200 OK
  391. =cut
  392. sub ok {
  393. my ( $self, $query, $body ) = @_;
  394. $self->INFO("$query->{method} 200 $query->{fullpath}");
  395. $body //= 'Ok';
  396. return _generic( $body, 200, $query );
  397. }
  398. =head2 notfound, forbidden, badrequest, toolong, error
  399. If you need to return these HTTP errors, return these within a route:
  400. sub route {
  401. my ($self, $query) = @_;
  402. ...
  403. return $self->notfound($query);
  404. }
  405. =cut
  406. sub notfound {
  407. my ( $self, $query, $body ) = @_;
  408. $self->INFO("$query->{method} 404 $query->{fullpath}");
  409. $body //= 'Not Found';
  410. return _generic( $body, 404, $query );
  411. }
  412. sub forbidden {
  413. my ( $self, $query, $body ) = @_;
  414. $self->INFO("$query->{method} 403 $query->{fullpath}");
  415. $body //= 'Forbidden';
  416. return _generic( $body, 403, $query );
  417. }
  418. sub badrequest {
  419. my ( $self, $query, $body ) = @_;
  420. $self->INFO("$query->{method} 400 $query->{fullpath}");
  421. $body //= 'Bad Request';
  422. return _generic( $body, 400, $query );
  423. }
  424. sub toolong {
  425. my ( $self, $query, $body ) = @_;
  426. $self->INFO("$query->{method} 419 $query->{fullpath}");
  427. $body //= 'URI too long';
  428. return _generic( $body, 419, $query );
  429. }
  430. sub error {
  431. my ( $self, $query, $body ) = @_;
  432. my $method = $query->{method} // "?";
  433. my $fp = $query->{fullpath} // "?";
  434. $body //= 'Internal Server Error';
  435. $self->INFO("$method 500 $fp");
  436. return _generic( $body, 500, $query );
  437. }
  438. sub unavailable {
  439. my ( $self, $query, $body ) = @_;
  440. $self->INFO("$query->{method} 503 $query->{fullpath}");
  441. $body //= 'Service Unavailable';
  442. return _generic( $body, 503, $query );
  443. }
  444. my $cur_query = {};
  445. sub app {
  446. my $self = shift;
  447. return eval { _app( $self, @_ ) } || do {
  448. my $env = shift;
  449. $env->{'psgi.errors'}->print($@) if $env->{'psgi.errors'};
  450. # Redact the stack trace past line 1, it usually has things which should not be shown
  451. $cur_query->{message} = $@;
  452. $cur_query->{message} =~ s/\n.*//g if $cur_query->{message} && !$debug;
  453. return $self->error($cur_query);
  454. };
  455. }
  456. my %etags;
  457. sub _app {
  458. my $self = shift;
  459. # Start the server timing clock
  460. my $start = [gettimeofday];
  461. $cur_query = {};
  462. my $env = shift;
  463. $self->{filehandle} = $env->{'psgix.io'} // *STDOUT;
  464. $self->{input} = $env->{'psgi.input'};
  465. # Setup the unique ID for the request
  466. $env->{REQUEST_ID} = $self->request_id(1);
  467. # Discard the path used in the log, it's too long and enough 4xx error code = ban
  468. return $self->toolong( { method => $env->{REQUEST_METHOD}, fullpath => '...' } ) if length( $env->{REQUEST_URI} ) > 2048;
  469. # Various stuff important for logging requests
  470. my $domain = $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST} // eval { Sys::Hostname::hostname() };
  471. my $path = $env->{PATH_INFO} || '/';
  472. # de-pooplicate the path
  473. $path =~ s|//|/|g;
  474. my $port = $env->{HTTP_X_FORWARDED_PORT} // $env->{HTTP_PORT};
  475. my $pport = defined $port ? ":$port" : "";
  476. my $scheme = $env->{'psgi.url_scheme'} // 'http';
  477. my $method = $env->{REQUEST_METHOD};
  478. # It's important that we log what the user ACTUALLY requested rather than the rewritten path later on.
  479. my $fullpath = "$scheme://$domain$pport$path";
  480. # So we can log it for fail2ban
  481. my $ip = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR};
  482. # set the referer & ua to go into DB logs, but not logs in general.
  483. # The referer/ua largely has no importance beyond being a proto bug report for log messages.
  484. my $referer = $env->{HTTP_REFERER};
  485. my $ua = $env->{HTTP_UA};
  486. $cur_query = {
  487. route => $path,
  488. fullpath => $path,
  489. method => $method,
  490. ip => $ip,
  491. ua => $ua,
  492. referer => $referer,
  493. tpsgi => $self,
  494. };
  495. # Disallow any paths that are naughty - this appears to be done by starman automatically.
  496. #if ( index($path, '..') != -1 ) {
  497. # return $self->forbidden($cur_query);
  498. #}
  499. # Support aliased paths
  500. my $aliases = $self->{aliases};
  501. $path = $aliases->{$path} if exists $aliases->{$path};
  502. # Check eTags. If we don't know about it, just assume it's good and lazily fill the cache
  503. # XXX yes, this allows cache poisoning...but only for logged in users!
  504. # This also needs to be IN DB so that we coordinate properly across forks
  505. if ( $env->{HTTP_IF_NONE_MATCH} ) {
  506. $self->INFO("$env->{REQUEST_METHOD} 304 $fullpath");
  507. return [ 304, [], [''] ] if $env->{HTTP_IF_NONE_MATCH} eq ( $etags{ $env->{REQUEST_URI} } || '' );
  508. $etags{ $env->{REQUEST_URI} } = $env->{HTTP_IF_NONE_MATCH} unless exists $etags{ $env->{REQUEST_URI} };
  509. }
  510. # TODO: Actually do something with the language passed to the renderer
  511. my $lang = $env->{HTTP_ACCEPT_LANGUAGE};
  512. #TODO: Actually do something with the acceptable output formats in the renderer
  513. my $accept = $env->{HTTP_ACCEPT};
  514. my $last_fetch = 0;
  515. if ( $env->{HTTP_IF_MODIFIED_SINCE} ) {
  516. $last_fetch = DateTime::Format::HTTP->parse_datetime( $env->{HTTP_IF_MODIFIED_SINCE} )->epoch();
  517. }
  518. # Figure out if we want compression or not
  519. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  520. $alist =~ s/\s//g;
  521. my @accept_encodings;
  522. @accept_encodings = split( /,/, $alist );
  523. my $deflate = grep { 'gzip' eq $_ } @accept_encodings;
  524. # Set the IP of the request so we can fail2ban
  525. $self->{ip} = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR} || $self->{ip};
  526. # Make sure this works further down the line
  527. $env->{REMOTE_ADDR} = $env->{HTTP_X_FORWARDED_FOR} if $env->{HTTP_X_FORWARDED_FOR};
  528. my $streaming = $env->{'psgi.streaming'};
  529. # If we have an actual route, just use it.
  530. my $r = $self->routes;
  531. my $route_index = List::Util::first { ( $r->[$_] // '' ) eq $path } 0 .. scalar(@$r);
  532. my $route_actual;
  533. $route_actual = $r->[ $route_index + 1 ] if defined($route_index);
  534. # Might be a regexed route. Sort reversed so we try the longest routes first.
  535. if ( !$route_actual && @$r ) {
  536. my $matched = List::Util::first {
  537. # Here's where you want to use Regexp::Debugger in the context of call.pl to debug routes... EX:
  538. # perl ./call.pl GET /path/to/route
  539. #print $r->[$_]."\n";
  540. $path =~ m/^$r->[$_]$/;
  541. }
  542. 0 .. scalar(@$r) - 1;
  543. $route_actual = $r->[ $matched + 1 ] if defined($matched);
  544. }
  545. return $self->route( $route_actual, $env, $fullpath, $path, $start, $last_fetch, $deflate, $domain, $port ) if $route_actual;
  546. # Do a case insensitive match, because osx and windows
  547. my $file_possible = $self->mangle_filename("www/$path");
  548. my $file_actual = $file_possible if -f $file_possible;
  549. # Dirindices
  550. if ( -d $file_possible ) {
  551. foreach my $index ( @{ $self->indices } ) {
  552. next if $file_actual;
  553. my $dirindex = $self->mangle_filename("www$path/$index");
  554. $dirindex =~ s|//|/|g;
  555. $file_actual = $dirindex if -f $dirindex;
  556. }
  557. }
  558. my $file_is_cgi = appears_executable($file_actual);
  559. return $self->cgi( $env, $fullpath, $file_actual, $last_fetch, $deflate ) if $file_is_cgi;
  560. $self->INFO( "Attempting to serve $fullpath [" . ( $file_possible // "" ) . "]" );
  561. my @ranges = parse_ranges($env);
  562. return $self->serve( $fullpath, $file_actual, $start, $streaming, \@ranges, $last_fetch, $deflate ) if $file_actual;
  563. return $self->notfound($cur_query);
  564. }
  565. sub mangle_filename {
  566. my ( $self, $path ) = @_;
  567. # XXX yes, you can have case sensitive OSX, but basically nobody enables that ever
  568. $path = lc($path) if List::Util::any { $^O eq $_ } qw{darwin MSWin32 dos};
  569. $self->DEBUG("Path mangled to $path");
  570. return $path;
  571. }
  572. sub parse_ranges {
  573. my $env = shift;
  574. # Handle HTTP range/streaming requests
  575. my $range = $env->{HTTP_RANGE} || "bytes=0-" if $env->{HTTP_RANGE} || $env->{HTTP_IF_RANGE};
  576. my @ranges;
  577. if ($range) {
  578. $range =~ s/bytes=//g;
  579. push(
  580. @ranges,
  581. map { [ split( /-/, $_ ) ]; } split( /,/, $range )
  582. );
  583. }
  584. return @ranges;
  585. }
  586. my @executable_extensions = qw{cgi sh exe pl php py};
  587. sub appears_executable {
  588. my $subj = shift;
  589. # Definitely not executable if it does not exist!
  590. return 0 unless $subj;
  591. return 0 unless -x $subj;
  592. my ($extension) = $subj =~ m/\.(\S+)$/;
  593. return 1 if !$extension;
  594. return 1 if grep { $extension eq $_ } @executable_extensions;
  595. return 0;
  596. }
  597. # Handle actual routes
  598. sub route {
  599. my ( $self, $route, $env, $fullpath, $path, $start, $last_fetch, $deflate, $domain, $port ) = @_;
  600. $self->DEBUG( 'Executing route ' . $route->{pattern} );
  601. $route->{method} = $env->{REQUEST_METHOD} if $route->{method} eq '*';
  602. my $content_type = $env->{CONTENT_TYPE} || 'text/html'; # If not set, that's the assumption.
  603. return $self->badrequest($cur_query) unless List::Util::any { $_ eq $env->{REQUEST_METHOD} } grep { defined $_ } ( 'HEAD', $route->{method} );
  604. my $callback;
  605. if ( exists $route->{callbacks}{'*'} ) {
  606. $callback = $route->{callbacks}{'*'};
  607. }
  608. else {
  609. return $self->badrequest($cur_query) unless exists $route->{callbacks}{$content_type};
  610. $callback = $route->{callbacks}{$content_type};
  611. }
  612. my $streaming = $env->{'psgi.streaming'};
  613. # Build the query data for passing to a route.
  614. # GET, POST, URI captures, then explicit data overrides.
  615. my $query = {};
  616. # If we're running in CGI mode, leave everything as-is.
  617. $query = $self->extract_query( $path, $route, $env ) unless $route->{env};
  618. # We failed validation if $query isn't a hashref.
  619. return $query if ref $query eq 'ARRAY';
  620. # allow this stuff to survive down to the end of some routes
  621. $query->{last_fetched} = $last_fetch;
  622. $query->{deflate} = $deflate;
  623. $query->{streaming} = $streaming;
  624. my @ranges = parse_ranges($env);
  625. $query->{ranges} = \@ranges;
  626. $query->{start} = $start;
  627. # Put things to tv_interval in here for Server-Timing
  628. $query->{fullpath} = $fullpath;
  629. $query->{method} = $route->{method};
  630. $query->{route} = $path;
  631. $query->{cookies} = $env->{HTTP_COOKIE};
  632. $query->{dnt} = $env->{HTTP_DNT};
  633. $query->{nosellinfo} = $env->{HTTP_SEC_GPC};
  634. $query->{port} = $port;
  635. $query->{scheme} = $env->{'psgi.url_scheme'} // 'http';
  636. $query->{method} = $env->{REQUEST_METHOD};
  637. $query->{lang} = $env->{HTTP_ACCEPT_LANGUAGE};
  638. $query->{accept} = $env->{HTTP_ACCEPT};
  639. $query->{has_query} = !!$env->{QUERY_STRING};
  640. $query->{domain} = $domain;
  641. $query->{dispatcher} = $route;
  642. $query->{ip} = $cur_query->{ip};
  643. $query->{ua} = $cur_query->{ua};
  644. $query->{referer} = $cur_query->{referer};
  645. # This allows for better error handlers if we die in the route.
  646. $cur_query = $query;
  647. # Setup the CGI vars they expect IF requested
  648. local %ENV = ( %ENV, CGI::Emulate::PSGI->emulate_environment($env) ) if $route->{env};
  649. # Emulate mod_unique_id
  650. $ENV{UNIQUE_ID} = UUID::uuid() if $route->{env};
  651. # Run any watch callbacks, and make this a truly 'dynamic' application if requested.
  652. $self->handle_changes();
  653. {
  654. my $output = $callback->( $self, $query );
  655. # If it's streaming, just hand it off.
  656. # It's up to the caller to handle things like running post-close callbacks in this event.
  657. return $output if ref $output eq 'CODE';
  658. die "$fullpath returned no or malformed data!" unless ref $output eq 'ARRAY' && @$output == 3;
  659. my $pport = defined $query->{port} ? ":$query->{port}" : "";
  660. my %headers = @{ $output->[1] };
  661. my $bytes = $headers{'Content-Length'} // '?';
  662. $self->INFO("$env->{REQUEST_METHOD} $output->[0] $bytes $fullpath");
  663. # Append server-timing headers if they aren't present
  664. my $tot = tv_interval($start) * 1000;
  665. push( @{ $output->[1] }, 'Server-Timing' => "app;dur=$tot" ) unless List::Util::any { $_ eq 'Server-Timing' } @{ $output->[1] };
  666. # In the event that we have post-close callbacks, go ahead and run them.
  667. return $self->stream_raw_psgi( $output, $query ) if @{ $self->{callbacks} };
  668. return $output;
  669. }
  670. }
  671. sub extract_query {
  672. my ( $self, $path, $route, $env ) = @_;
  673. my $query = URL::Encode::url_params_mixed( $env->{QUERY_STRING} ) if $env->{QUERY_STRING};
  674. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  675. if ( $env->{REQUEST_METHOD} eq 'POST' ) {
  676. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  677. while ( $env->{'psgi.input'}->read( my $buf, $CHUNK_SIZE ) ) {
  678. $body->add($buf);
  679. }
  680. @$query{ keys( %{ $body->param } ) } = values( %{ $body->param } );
  681. @$query{ keys( %{ $body->upload } ) } = values( %{ $body->upload } );
  682. }
  683. if ( ref $route->{captures} eq 'ARRAY' ) {
  684. my @captures = $path =~ m/^$route->{pattern}$/;
  685. @$query{ @{ $route->{captures} } } = @captures;
  686. }
  687. if ( ref $route->{data} eq 'HASH' ) {
  688. @$query{ keys( %{ $route->{data} } ) } = values( %{ $route->{data} } );
  689. }
  690. # Now that we've parsed the query and know where we want to go,
  691. # we should (optionally) murder everything the route does not explicitly want, and validate what it does
  692. my $parameters = $route->{parameters};
  693. if ( ref $parameters eq 'HASH' && %$parameters ) {
  694. my @known_params = keys(%$parameters);
  695. for my $param (@known_params) {
  696. die "Invalid route definition for $path: parameter $param must correspond to a validation CODEREF." unless ref $parameters->{$param} eq 'CODE';
  697. # A missing parameter is not necessarily a problem.
  698. next unless $query->{$param};
  699. # But if we have it, and it's bad, nack it, so that scanners get fail2banned.
  700. $self->DEBUG("Rejected $path for bad query param $param");
  701. return $self->badrequest($query) unless $parameters->{$param}->( $query->{$param} );
  702. }
  703. # Without this logging will break.
  704. push( @known_params, qw{tpsgi ip ua user referer route dispatcher} );
  705. # Smack down passing of unnecessary fields; this catches bugs
  706. foreach my $field ( keys(%$query) ) {
  707. next if List::Util::any { $field eq $_ } @known_params;
  708. $self->WARN("Unexpected parameter $field passed");
  709. return $self->badrequest($query);
  710. }
  711. }
  712. return $query;
  713. }
  714. # Read until we are done with headers, then pass off the filehandle to PSGI for streaming.
  715. # TODO support compression
  716. sub cgi {
  717. my ( $self, $env, $fullpath, $file_actual, $last_fetch, $deflate ) = @_;
  718. $self->INFO("Handoff $fullpath to $file_actual for cgi exec");
  719. # Setup the CGI vars they expect
  720. local %ENV = ( %ENV, CGI::Emulate::PSGI->emulate_environment($env) );
  721. my $pid = open( my $out, '-|', "$file_actual" );
  722. my ( $code, $offset, %headers ) = extract_headers( $out, $last_fetch );
  723. $code //= 500;
  724. return sub {
  725. my $responder = shift;
  726. my $writer = $responder->( [ $code, [%headers] ] );
  727. while ( $out->read( my $buf, $CHUNK_SIZE ) ) {
  728. $writer->write($buf);
  729. }
  730. $writer->close;
  731. # Wait on the CGI script to do whatever it's doing after closing stdout
  732. close $out;
  733. waitpid( $pid, 0 );
  734. };
  735. }
  736. # Use when you just have a .cgi file you want to run without pipe-open
  737. # XXX this is extraordinarily unsafe, inefficient and kills workers.
  738. # XXX it also has an 'apache-ism' of just assigning the HTTP status line for you.
  739. # But sometimes you have to bite the bullet and do this to migrate stuff effectively.
  740. sub stream_raw_cgi {
  741. my ( $self, $cgi ) = @_;
  742. # Discard STDIN in favor of the HTTP body
  743. close(STDIN);
  744. *STDIN = $self->{input};
  745. # Similarly make 'print' do what CGIs expect
  746. my $fh = $self->{filehandle};
  747. select $fh;
  748. do($cgi);
  749. # We may or may not actually get here.
  750. close($fh) if $fh;
  751. exit 0;
  752. }
  753. # Used primarily when we have post-close callbacks
  754. sub stream_raw_psgi {
  755. my ( $self, $response, $data ) = @_;
  756. my $time_to_here = tv_interval( $data->{start} );
  757. $self->DEBUG("Routing took $time_to_here s");
  758. my $post_routing = [gettimeofday];
  759. my $fh = $self->{filehandle};
  760. print $fh "HTTP/1.1 $response->[0]\n";
  761. # Emit the rest of the headers
  762. foreach ( my $i = 0; $i < @{ $response->[1] }; $i += 2 ) {
  763. my $header = $response->[1][$i];
  764. my $value = $response->[1][ $i + 1 ];
  765. print $fh "$header: $value\n";
  766. }
  767. print $fh "\n";
  768. # Emit the body
  769. print $fh $response->[2][0];
  770. close($fh);
  771. $self->DEBUG( "Response written in " . ( tv_interval($post_routing) ) . " s" );
  772. while ( my $callback = shift @{ $self->{callbacks} } ) {
  773. if ( ref $callback eq 'CODE' ) {
  774. my $post_start = [gettimeofday];
  775. local $@;
  776. eval { $callback->() };
  777. $self->ERROR("Post-close callback encountered exception: $@") if $@;
  778. $self->DEBUG( "Post-close callback took " . ( tv_interval($post_start) ) . " s" );
  779. }
  780. }
  781. exit 0;
  782. }
  783. sub stream_raw_http {
  784. my ( $self, $data, $last_fetch, $to_fork, $callback, $error_handler ) = @_;
  785. my $time_to_here = tv_interval( $data->{start} );
  786. $self->DEBUG("Routing took $time_to_here s");
  787. my $post_routing = [gettimeofday];
  788. my $fh = $self->{filehandle};
  789. # The CGIs you are executing here SHOULD NOT emit a status line.
  790. # Most apache CGIs you find don't anyways, so this is usually not a big deal.
  791. print $fh "HTTP/1.1 200 OK\n";
  792. # Emit our server-timing header.
  793. print $fh "Server-Timing: " . $self->build_server_timing($data) . "\n"; #app;dur=".($time_to_here*1000)."\n";
  794. # We *must* fork because we can't rely on the child to close stdout.
  795. my $pid = _fork(
  796. sub {
  797. $self->DEBUG( "Forking child took" . ( tv_interval($post_routing) ) . " s" );
  798. local $@;
  799. eval { $to_fork->() };
  800. $self->ERROR("Raw HTTTP streaming encountered exception: $@") if $@;
  801. if ( ref $error_handler eq 'CODE' ) {
  802. local $@;
  803. eval { $error_handler->() };
  804. $self->ERROR("HTTP streaming error handler encountered exception: $@") if $@;
  805. }
  806. },
  807. $fh
  808. );
  809. waitpid( $pid, 0 );
  810. close($fh);
  811. $self->DEBUG( "Response written in " . ( tv_interval($post_routing) ) . " s" );
  812. if ( ref $callback eq 'CODE' ) {
  813. my $post_start = [gettimeofday];
  814. local $@;
  815. eval { $callback->() };
  816. $self->ERROR("Post-close callback encountered exception: $@") if $@;
  817. $self->DEBUG( "Post-close callback took " . ( tv_interval($post_start) ) . " s" );
  818. }
  819. exit 0;
  820. }
  821. sub _fork {
  822. my ( $callback, $fh ) = @_;
  823. select $fh;
  824. $| = 1;
  825. my $pid = fork();
  826. die "Could not fork child" unless defined $pid;
  827. if ( $pid == 0 ) {
  828. $callback->();
  829. exit 0;
  830. }
  831. select STDOUT;
  832. return $pid;
  833. }
  834. =head2 extract_headers($fh, $last_fetch)
  835. Extract the headers from a filehandle. Set the 'Last Modified' header appropriately based on the output of `stat` on the filehandle.
  836. 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.
  837. =cut
  838. sub extract_headers {
  839. my ( $fh, $last_fetch, $is_ref ) = @_;
  840. my $headers = '';
  841. # NOTE: this is relying on while advancing the file pointer
  842. while (<$fh>) {
  843. last if $_ eq "\n";
  844. $headers .= $_;
  845. }
  846. #XXX still a toctou
  847. my $offset = $fh->tell();
  848. my ( undef, undef, $status, undef, $headers_parsed ) = HTTP::Parser::XS::parse_http_response( "$headers\n", HEADERS_AS_HASHREF );
  849. my $code = $status // 200;
  850. $headers_parsed //= {};
  851. if ( !$is_ref ) {
  852. my $mt = ( stat($fh) )[9];
  853. my @gm = gmtime($mt);
  854. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  855. $code = $mt > $last_fetch ? $status : 304;
  856. $headers_parsed->{"Last-Modified"} = $now_string;
  857. }
  858. return ( $code, $offset, %$headers_parsed );
  859. }
  860. sub static {
  861. my ( $self, $fullpath, $path, $start, $streaming, $last_fetch ) = @_;
  862. $self->DEBUG("Rendering static for $path");
  863. # XXX because of psgi I can't just vomit the file directly
  864. if ( open( my $fh, '<', "statics/$path" ) ) {
  865. my ( $code, $offset, $headers_parsed ) = ( 200, undef, {} );
  866. ( $code, $offset, %$headers_parsed ) = extract_headers( $fh, $last_fetch );
  867. # Append server-timing headers
  868. my $tot = tv_interval($start) * 1000;
  869. $headers_parsed->{'Server-Timing'} = "static;dur=$tot";
  870. #XXX uwsgi just opens the file *again* when we already have a filehandle if it has a path.
  871. # starman by comparison doesn't violate the principle of least astonishment here.
  872. # This is probably a performance optimization, but makes the kind of micromanagement I need to do inconvenient.
  873. # As such, we will just return a stream.
  874. $self->INFO("GET 200 $headers_parsed->{'Content-Length'} $fullpath");
  875. return sub {
  876. my $responder = shift;
  877. #push(@headers, 'Content-Length' => $sz);
  878. my $writer = $responder->( [ $code, [%$headers_parsed] ] );
  879. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  880. $writer->write($buf);
  881. }
  882. close $fh;
  883. $writer->close;
  884. }
  885. if $streaming;
  886. return [ $code, [%$headers_parsed], $fh ];
  887. }
  888. return $self->forbidden( $self->{current_query} );
  889. }
  890. sub get_config { return TPSGI::Startup::get_config(@_) }
  891. # Convenience method to keep track of server-timing
  892. sub checkpoint {
  893. my ( $self, $data, $name ) = @_;
  894. $data->{checkpoints} //= [ [ start => $data->{start} ] ];
  895. push( @{ $data->{checkpoints} }, [ $name => [gettimeofday] ] );
  896. }
  897. sub build_server_timing {
  898. my ( $self, $data ) = @_;
  899. my @st;
  900. my $last_interval;
  901. foreach my $checkpoint ( @{ $data->{checkpoints} } ) {
  902. if ($last_interval) {
  903. my $dur = tv_interval( $last_interval, $checkpoint->[1] ) * 1000;
  904. push( @st, "$checkpoint->[0];dur=$dur" );
  905. }
  906. $last_interval = $checkpoint->[1];
  907. }
  908. my $tot = tv_interval( $data->{start} ) * 1000;
  909. push( @st, "tot;dur=$tot" );
  910. delete $data->{checkpoints};
  911. return join( ', ', @st );
  912. }
  913. =head2 add_post_close_callback()
  914. Add a thing to do after closing stdout; useful for housekeeping that doesn't need to hold up pageload.
  915. =cut
  916. sub add_post_close_callback {
  917. my ( $self, $cb ) = @_;
  918. push( @{ $self->{callbacks} }, $cb );
  919. }
  920. =head2 signal_restart_parent()
  921. Instruct tPSGI to reload after closing stdout.
  922. =cut
  923. sub signal_restart_parent {
  924. my ($self) = @_;
  925. $self->add_post_close_callback( \&_restart_parent );
  926. }
  927. # Instruct tPSGI to reload.
  928. sub _restart_parent {
  929. my $parent = getppid;
  930. kill 'HUP', $parent;
  931. }
  932. =head2 save_render($path, $extension, $body)
  933. Save a static render of the page.
  934. Good to queue after closing stdout.
  935. Passed file extension slapped on the end of the path.
  936. You can then serve them as statics with an appropriately done try_files block in nginx.
  937. =cut
  938. # fixup matrix
  939. my %fixup = (
  940. text => 'txt',
  941. blob => 'bin',
  942. );
  943. sub save_render {
  944. my ( $self, $path, $extension, $body ) = @_;
  945. return unless $path && $extension;
  946. # If this is an index, let's make it so
  947. if ( $path =~ m|/$| ) {
  948. $path = $path . 'index';
  949. }
  950. # Fixup the extension if needed.
  951. $extension = $fixup{$extension} if exists $fixup{$extension};
  952. my $path_fixed = $path;
  953. $path_fixed =~ s/\.\Q$extension\E$//;
  954. $path_fixed = "$path_fixed.$extension";
  955. my $path2file = "$self->{tpsgi_dir}/www/static/" . dirname($path_fixed);
  956. if ( !-d $path2file ) {
  957. File::Path::make_path( $path2file, { user => $<, group => $self->{gid}, chmod => 0755 } ) or die "Could not create directory $path2file";
  958. }
  959. my $file = "$self->{tpsgi_dir}/www/static/$path_fixed";
  960. my $verb = -f $file ? 'Overwrite' : 'Write';
  961. $self->INFO("$verb $path as static/$path_fixed");
  962. open( my $fh, '>', $file ) or die "Could not open $file for writing";
  963. print $fh $body;
  964. close $fh;
  965. chmod( 0755, $file );
  966. chown( $<, $self->{gid}, $file );
  967. }
  968. =head2 invalidate_render($path, $extension)
  969. Remove an existing static render of a path.
  970. =cut
  971. sub invalidate_render {
  972. my ( $self, $path, $extension ) = @_;
  973. return unless $path && $extension;
  974. # Fixup the extension if needed.
  975. $extension = $fixup{$extension} if exists $fixup{$extension};
  976. my $path_fixed = $path;
  977. $path_fixed =~ s/\.\Q$extension\E$//;
  978. $path_fixed = "$path_fixed.$extension";
  979. my $file = "$self->{tpsgi_dir}/www/static/$path_fixed";
  980. return unless -f $file;
  981. $self->_invalidate($file);
  982. }
  983. sub _invalidate {
  984. my ( $self, $file ) = @_;
  985. $self->INFO("Delete $file");
  986. unlink "$file";
  987. }
  988. =head2 invalidate_renders($extension)
  989. Remove all existing static renders with the provided extension.
  990. Useful when it's not easy to figure out what to re-render due to including templates in other templates, etc.
  991. =cut
  992. sub invalidate_renders {
  993. my ( $self, $extension ) = @_;
  994. File::Find::find(
  995. {
  996. wanted => sub {
  997. my $object = $_;
  998. $self->_invalidate($object) if ( -f $object && $object =~ m/\.\Q$extension\E$/ );
  999. },
  1000. no_chdir => 1,
  1001. bydepth => 1,
  1002. },
  1003. "$self->{tpsgi_dir}/www/static/"
  1004. );
  1005. }
  1006. sub watch_for_changes { return TPSGI::Startup::watch_for_changes(@_) }
  1007. =head2 add_watch($path, $callback, %options)
  1008. Add an arbitrary file or directory to the inotify watchlist, along with a
  1009. callback to run when it changes. Returns the inotify watch descriptor.
  1010. The callback is invoked as:
  1011. $callback->( $tpsgi, $change );
  1012. ...where $change is a HASH reference describing what happened:
  1013. path => full path of the thing which changed
  1014. watched => the path the watch was registered against
  1015. events => ARRAY reference of event names, e.g. [ 'MODIFY' ]
  1016. name => entry within a watched directory, if the watch was on a directory
  1017. wd => inotify watch descriptor
  1018. mask => raw inotify event mask
  1019. Which makes the common case - blowing away a static render because the thing it
  1020. was generated from changed - look like:
  1021. $tpsgi->add_watch( "data/posts.json", sub {
  1022. my ( $tpsgi, $change ) = @_;
  1023. $tpsgi->invalidate_renders('html');
  1024. });
  1025. %options are passed through to TPSGI::Startup::add_watch, so you may also pass
  1026. 'events' (defaults to CREATE, MODIFY, DELETE and MOVE) and 'key' (an explicit
  1027. dedupe key for the callback).
  1028. Some caveats worth knowing about:
  1029. =over
  1030. =item * Watches live in the inotify instance tarbaby sets up before forking, and
  1031. are therefore shared by every worker. Whichever worker notices a change first
  1032. consumes it for all of them, so register the same callbacks in every worker
  1033. (declare them in your router module, which every worker loads) and make sure
  1034. they're safe to run in any worker.
  1035. =item * Changes are only noticed when a request comes in, since nothing is
  1036. sitting in a select loop over the inotify FD. Renders are invalidated promptly
  1037. in practice, but not instantly.
  1038. =item * Watching a directory rather than a single file is more robust, as
  1039. watching a file which is later replaced wholesale (the usual write-tempfile-then-
  1040. rename dance) only survives because we re-establish the watch afterwards. If
  1041. the file is deleted and not immediately recreated, the watch is gone for good.
  1042. =back
  1043. =cut
  1044. sub add_watch {
  1045. my ( $self, $path, $callback, %options ) = @_;
  1046. my $existing = TPSGI::Startup::is_watched($path);
  1047. # A watch we can't establish (the usual cause being a path which isn't there yet)
  1048. # shouldn't be fatal to the request which happened to be the one registering it.
  1049. local $@;
  1050. my $wd = eval {
  1051. TPSGI::Startup::add_watch(
  1052. %options,
  1053. path => $path,
  1054. callback => $callback,
  1055. );
  1056. };
  1057. if ( !defined $wd ) {
  1058. my $why = $@;
  1059. $why =~ s/\n.*//s if $why;
  1060. $self->WARN("Could not watch $path for changes: $why");
  1061. return undef;
  1062. }
  1063. $self->DEBUG("Watching $path for changes") unless $existing;
  1064. return $wd;
  1065. }
  1066. =head2 remove_watch($path)
  1067. Drop a path, and any callbacks registered against it, from the watchlist.
  1068. =cut
  1069. sub remove_watch {
  1070. my ( $self, $path ) = @_;
  1071. return TPSGI::Startup::remove_watch($path);
  1072. }
  1073. =head2 handle_changes
  1074. Drain the inotify queue, running the callbacks registered for whatever changed,
  1075. and restart tPSGI if any of the relevant libdir files changed (assuming
  1076. autoreload is on). Powers both the autorestart feature and app-registered
  1077. watches.
  1078. =cut
  1079. sub handle_changes {
  1080. my $self = shift;
  1081. my @changes = TPSGI::Startup::pending_changes();
  1082. return 0 unless @changes;
  1083. my $had_changes = 0;
  1084. my @rewatch;
  1085. foreach my $change (@changes) {
  1086. my $watch = $change->{watch};
  1087. # A watch descriptor we know nothing about belongs to a worker which registered
  1088. # watches we didn't. All we can sensibly do with those is the old behavior.
  1089. if ( !$watch ) {
  1090. $had_changes++ if $change->{path} =~ m/\.pm$/;
  1091. next;
  1092. }
  1093. $had_changes++ if $watch->{restart} && $change->{path} =~ m/\.pm$/;
  1094. foreach my $cb ( @{ $watch->{callbacks} } ) {
  1095. local $@;
  1096. my $ok = eval { $cb->{code}->( $self, $change ); 1 };
  1097. $self->WARN("Watch callback for $change->{path} died: $@") unless $ok;
  1098. }
  1099. # The kernel drops watches on files which get replaced or deleted, so put them back.
  1100. push( @rewatch, $change->{wd} ) if grep { $_ eq 'IGNORED' } @{ $change->{events} };
  1101. }
  1102. TPSGI::Startup::rewatch($_) foreach @rewatch;
  1103. return 0 unless $had_changes && $self->{autoreload};
  1104. # We don't have to clean up the wds, that is handled in the destructor for Inotify
  1105. $self->INFO("Relevant Change in libdirs detected, reloading\n");
  1106. $self->signal_restart_parent();
  1107. return 0;
  1108. }
  1109. =head2 restart_if_changes
  1110. Deprecated alias for handle_changes().
  1111. =cut
  1112. sub restart_if_changes { goto &handle_changes }
  1113. 1;