TPSGI.pm 41 KB

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