TPSGI.pm 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. # It also should be a top-level namespace, not somewhere deep down. KISS.
  180. my $libdir = dirname("$options{tpsgi_dir}/$route");
  181. push( @INC, $libdir );
  182. local $@;
  183. $self->DEBUG("require $options{tpsgi_dir}/$route");
  184. my $success = eval { require "$options{tpsgi_dir}/$route"; 1; };
  185. if ($success) {
  186. my $pkg_routes = *$r{ARRAY};
  187. for ( my $i = 0; $i < @$pkg_routes; $i += 2 ) {
  188. $self->DEBUG("Registered route $pkg_routes->[$i]");
  189. }
  190. push( @routes, @$pkg_routes );
  191. my $pkg_aliases = *$a{HASH};
  192. foreach my $al ( keys(%$pkg_aliases) ) {
  193. $self->DEBUG("aliased route $al to $pkg_aliases->{$al}");
  194. }
  195. @aliases{ keys(%$pkg_aliases) } = values(%$pkg_aliases);
  196. # First-come first-served error template overrides
  197. $generic_handler = "$package\:\:generic_route";
  198. }
  199. else {
  200. die "Could not load $route!\n$@\n";
  201. }
  202. }
  203. use strict 'refs';
  204. # Set the pattern used to discover the route if needed later.
  205. for ( my $i = 0; $i < scalar(@routes); $i += 2 ) {
  206. $routes[ $i + 1 ]{pattern} = $routes[$i];
  207. }
  208. $self->{indices} //= [];
  209. $self->{indices} = [ @{ $self->{indices} }, qw{index.html index.htm index.cgi} ];
  210. $self->{routes} = \@routes;
  211. $self->{aliases} = \%aliases;
  212. $self->{callbacks} = [];
  213. return $self;
  214. }
  215. sub indices {
  216. my $self = shift;
  217. return $self->{indices};
  218. }
  219. sub routes {
  220. my $self = shift;
  221. return $self->{routes};
  222. }
  223. =head2 serve
  224. Serve a file, with options to stream and cache the output.
  225. =cut
  226. sub serve {
  227. my ( $self, $fullpath, $path, $start, $streaming, $ranges, $last_fetch, $deflate ) = @_;
  228. $last_fetch ||= 0;
  229. $deflate ||= 0;
  230. my $mf = Mojo::File->new($path);
  231. my $ext = '.' . $mf->extname();
  232. my $ft;
  233. if ($ext) {
  234. $ft = Plack::MIME->mime_type($ext) if $ext;
  235. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  236. }
  237. $ft ||= $content_types{text};
  238. my @headers = ( $ct => $ft );
  239. #TODO use static Cache-Control for everything but JS/CSS?
  240. push( @headers, 'Cache-control' => $cache_control{revalidate} );
  241. push( @headers, 'Accept-Ranges' => 'bytes' );
  242. $self->DEBUG("FETCH $path");
  243. my $mt = ( stat($path) )[9];
  244. my $sz = ( stat(_) )[7];
  245. my @gm = gmtime($mt);
  246. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  247. my $code = $mt > $last_fetch ? 200 : 304;
  248. push( @headers, "Last-Modified" => $now_string );
  249. push( @headers, 'Vary' => 'Accept-Encoding' );
  250. if ( open( my $fh, '<', $path ) ) {
  251. return $self->_range( $fullpath, $fh, $ranges, $sz, @headers ) if @$ranges && $streaming;
  252. # Transfer-encoding: chunked
  253. return sub {
  254. my $responder = shift;
  255. push( @headers, 'Content-Length' => $sz );
  256. my $writer = $responder->( [ $code, \@headers ] );
  257. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  258. $writer->write($buf);
  259. }
  260. close $fh;
  261. $writer->close;
  262. }
  263. if $streaming && $sz > $CHUNK_SIZE;
  264. #Return data in the event the caller does not support deflate
  265. if ( !$deflate ) {
  266. push( @headers, "Content-Length" => $sz );
  267. # Append server-timing headers
  268. my $tot = tv_interval($start) * 1000;
  269. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  270. return [ $code, \@headers, $fh ];
  271. }
  272. #Compress everything less than 1MB
  273. push( @headers, "Content-Encoding" => "gzip" );
  274. my $dfh;
  275. IO::Compress::Gzip::gzip( $fh => \$dfh );
  276. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  277. push( @headers, "Content-Length" => length($dfh) );
  278. # Copy to the statics if it's not already there
  279. my $static_path = $path;
  280. $static_path =~ s|^[/]*www/||;
  281. $static_path = "$self->{tpsgi_dir}/www/static/$static_path";
  282. if ( !-f $static_path ) {
  283. my $target_dir = dirname($static_path);
  284. $self->INFO("Copying $path to $static_path");
  285. if ( !-d $target_dir ) {
  286. File::Path::make_path( $target_dir, { user => $<, group => $self->{gid}, chmod => 0755 } ) or die "Could not make dir $target_dir";
  287. }
  288. # hardlink to save disk space
  289. link $path, $static_path;
  290. # TODO figure out cache invalidation, I guess check mtime/hash
  291. }
  292. $self->INFO("GET 200 $fullpath");
  293. # Append server-timing headers
  294. my $tot = tv_interval($start) * 1000;
  295. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  296. return [ $code, \@headers, [$dfh] ];
  297. }
  298. $self->INFO("GET 403 $fullpath");
  299. return [ 403, [ $ct => $content_types{text} ], ["Forbidden"] ];
  300. }
  301. sub _range {
  302. my ( $self, $fullpath, $fh, $ranges, $sz, %headers ) = @_;
  303. # Set mode
  304. my $primary_ct = "Content-Type: $headers{'Content-type'}";
  305. my $is_multipart = scalar(@$ranges) > 1;
  306. if ($is_multipart) {
  307. $headers{'Content-type'} = "multipart/byteranges; boundary=$CHUNK_SEP";
  308. }
  309. my $code = 206;
  310. my $fc = '';
  311. # Calculate the content-length up-front. We have to fix unspecified lengths first, and reject bad requests.
  312. foreach my $range (@$ranges) {
  313. $range->[1] //= $sz - 1;
  314. $self->INFO("GET 416 $fullpath");
  315. return [ 416, [%headers], ["Requested range not satisfiable"] ] if $range->[0] > $sz || $range->[0] < 0 || $range->[1] < 0 || $range->[0] > $range->[1];
  316. }
  317. $headers{'Content-Length'} = List::Util::sum( map { my $arr = $_; $arr->[1] + 1, -$arr->[0] } @$ranges );
  318. #XXX Add the entity header lengths to the value - should hash-ify this to DRY
  319. if ($is_multipart) {
  320. foreach my $range (@$ranges) {
  321. $headers{'Content-Length'} += length("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n");
  322. $fc = "\n";
  323. }
  324. $headers{'Content-Length'} += length("\n--$CHUNK_SEP\--\n");
  325. $fc = '';
  326. }
  327. return sub {
  328. my $responder = shift;
  329. my $writer;
  330. foreach my $range (@$ranges) {
  331. $headers{'Content-Range'} = "bytes $range->[0]-$range->[1]/$sz" unless $is_multipart;
  332. $writer //= $responder->( [ $code, [%headers] ] );
  333. $writer->write("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n") if $is_multipart;
  334. $fc = "\n";
  335. my $len = List::Util::min( $sz, $range->[1] + 1 ) - $range->[0];
  336. $fh->seek( $range->[0], 0 );
  337. while ($len) {
  338. $fh->read( my $buf, List::Util::min( $len, $CHUNK_SIZE ) );
  339. $writer->write($buf);
  340. # Adjust for amount written
  341. $len = List::Util::max( $len - $CHUNK_SIZE, 0 );
  342. }
  343. }
  344. $fh->close();
  345. $writer->write("\n--$CHUNK_SEP--\n") if $is_multipart;
  346. $writer->close;
  347. };
  348. }
  349. sub _generic {
  350. my ( $type, $code, $query ) = @_;
  351. if ($generic_handler) {
  352. my $rname = "/$code";
  353. my $title = $type;
  354. no strict 'refs';
  355. return $generic_handler->( $rname, $code, $title, $query );
  356. }
  357. $type .= Carp::longmess() if $debug;
  358. return [ $code, [ $ct => $content_types{html} ], ["$type"] ];
  359. }
  360. =head2 redirect, redirect_permanent, see_also
  361. Redirects to the provided page.
  362. =cut
  363. sub redirect {
  364. my ( $self, $to ) = @_;
  365. $self->INFO("redirect: $to");
  366. return [ 302, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  367. }
  368. sub redirect_permanent {
  369. my ( $self, $to ) = @_;
  370. $self->INFO("permanent redirect: $to");
  371. return [ 301, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  372. }
  373. sub see_also {
  374. my ( $self, $to ) = @_;
  375. $self->INFO("see also: $to");
  376. return [ 303, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  377. }
  378. =head2 ok
  379. Return a generic HTTP 200 OK
  380. =cut
  381. sub ok {
  382. my ( $self, $query, $body ) = @_;
  383. $self->INFO("$query->{method} 200 $query->{fullpath}");
  384. $body //= 'Ok';
  385. return _generic( $body, 200, $query );
  386. }
  387. =head2 notfound, forbidden, badrequest, toolong, error
  388. If you need to return these HTTP errors, return these within a route:
  389. sub route {
  390. my ($self, $query) = @_;
  391. ...
  392. return $self->notfound($query);
  393. }
  394. =cut
  395. sub notfound {
  396. my ( $self, $query, $body ) = @_;
  397. $self->INFO("$query->{method} 404 $query->{fullpath}");
  398. $body //= 'Not Found';
  399. return _generic( $body, 404, $query );
  400. }
  401. sub forbidden {
  402. my ( $self, $query, $body ) = @_;
  403. $self->INFO("$query->{method} 403 $query->{fullpath}");
  404. $body //= 'Forbidden';
  405. return _generic( $body, 403, $query );
  406. }
  407. sub badrequest {
  408. my ( $self, $query, $body ) = @_;
  409. $self->INFO("$query->{method} 400 $query->{fullpath}");
  410. $body //= 'Bad Request';
  411. return _generic( $body, 400, $query );
  412. }
  413. sub toolong {
  414. my ( $self, $query, $body ) = @_;
  415. $self->INFO("$query->{method} 419 $query->{fullpath}");
  416. $body //= 'URI too long';
  417. return _generic( $body, 419, $query );
  418. }
  419. sub error {
  420. my ( $self, $query, $body ) = @_;
  421. my $method = $query->{method} // "?";
  422. my $fp = $query->{fullpath} // "?";
  423. $body //= 'Internal Server Error';
  424. $self->INFO("$method 500 $fp");
  425. return _generic( $body, 500, $query );
  426. }
  427. sub unavailable {
  428. my ( $self, $query, $body ) = @_;
  429. $self->INFO("$query->{method} 503 $query->{fullpath}");
  430. $body //= 'Service Unavailable';
  431. return _generic( $body, 503, $query );
  432. }
  433. my $cur_query = {};
  434. sub app {
  435. my $self = shift;
  436. return eval { _app( $self, @_ ) } || do {
  437. my $env = shift;
  438. $env->{'psgi.errors'}->print($@) if $env->{'psgi.errors'};
  439. # Redact the stack trace past line 1, it usually has things which should not be shown
  440. $cur_query->{message} = $@;
  441. $cur_query->{message} =~ s/\n.*//g if $cur_query->{message} && !$debug;
  442. return $self->error($cur_query);
  443. };
  444. }
  445. my %etags;
  446. sub _app {
  447. my $self = shift;
  448. # Start the server timing clock
  449. my $start = [gettimeofday];
  450. $cur_query = {};
  451. my $env = shift;
  452. $self->{filehandle} = $env->{'psgix.io'} // *STDOUT;
  453. # Setup the unique ID for the request
  454. $env->{REQUEST_ID} = $self->request_id(1);
  455. # Discard the path used in the log, it's too long and enough 4xx error code = ban
  456. return $self->toolong( { method => $env->{REQUEST_METHOD}, fullpath => '...' } ) if length( $env->{REQUEST_URI} ) > 2048;
  457. # Various stuff important for logging requests
  458. my $domain = $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST} // eval { Sys::Hostname::hostname() };
  459. my $path = $env->{PATH_INFO} || '/';
  460. # de-pooplicate the path
  461. $path =~ s|//|/|g;
  462. my $port = $env->{HTTP_X_FORWARDED_PORT} // $env->{HTTP_PORT};
  463. my $pport = defined $port ? ":$port" : "";
  464. my $scheme = $env->{'psgi.url_scheme'} // 'http';
  465. my $method = $env->{REQUEST_METHOD};
  466. # It's important that we log what the user ACTUALLY requested rather than the rewritten path later on.
  467. my $fullpath = "$scheme://$domain$pport$path";
  468. # So we can log it for fail2ban
  469. my $ip = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR};
  470. # set the referer & ua to go into DB logs, but not logs in general.
  471. # The referer/ua largely has no importance beyond being a proto bug report for log messages.
  472. my $referer = $env->{HTTP_REFERER};
  473. my $ua = $env->{HTTP_UA};
  474. $cur_query = {
  475. route => $path,
  476. fullpath => $path,
  477. method => $method,
  478. ip => $ip,
  479. ua => $ua,
  480. referer => $referer,
  481. tpsgi => $self,
  482. };
  483. # Disallow any paths that are naughty - this appears to be done by starman automatically.
  484. #if ( index($path, '..') != -1 ) {
  485. # return $self->forbidden($cur_query);
  486. #}
  487. # Support aliased paths
  488. my $aliases = $self->{aliases};
  489. $path = $aliases->{$path} if exists $aliases->{$path};
  490. # Check eTags. If we don't know about it, just assume it's good and lazily fill the cache
  491. # XXX yes, this allows cache poisoning...but only for logged in users!
  492. # This also needs to be IN DB so that we coordinate properly across forks
  493. if ( $env->{HTTP_IF_NONE_MATCH} ) {
  494. $self->INFO("$env->{REQUEST_METHOD} 304 $fullpath");
  495. return [ 304, [], [''] ] if $env->{HTTP_IF_NONE_MATCH} eq ( $etags{ $env->{REQUEST_URI} } || '' );
  496. $etags{ $env->{REQUEST_URI} } = $env->{HTTP_IF_NONE_MATCH} unless exists $etags{ $env->{REQUEST_URI} };
  497. }
  498. # TODO: Actually do something with the language passed to the renderer
  499. my $lang = $env->{HTTP_ACCEPT_LANGUAGE};
  500. #TODO: Actually do something with the acceptable output formats in the renderer
  501. my $accept = $env->{HTTP_ACCEPT};
  502. my $last_fetch = 0;
  503. if ( $env->{HTTP_IF_MODIFIED_SINCE} ) {
  504. $last_fetch = DateTime::Format::HTTP->parse_datetime( $env->{HTTP_IF_MODIFIED_SINCE} )->epoch();
  505. }
  506. # Figure out if we want compression or not
  507. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  508. $alist =~ s/\s//g;
  509. my @accept_encodings;
  510. @accept_encodings = split( /,/, $alist );
  511. my $deflate = grep { 'gzip' eq $_ } @accept_encodings;
  512. # Set the IP of the request so we can fail2ban
  513. $self->{ip} = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR} || $self->{ip};
  514. # Make sure this works further down the line
  515. $env->{REMOTE_ADDR} = $env->{HTTP_X_FORWARDED_FOR} if $env->{HTTP_X_FORWARDED_FOR};
  516. my $streaming = $env->{'psgi.streaming'};
  517. # If we have an actual route, just use it.
  518. my $r = $self->routes;
  519. my $route_index = List::Util::first { ( $r->[$_] // '' ) eq $path } 0 .. scalar(@$r);
  520. my $route_actual;
  521. $route_actual = $r->[ $route_index + 1 ] if defined($route_index);
  522. # Might be a regexed route. Sort reversed so we try the longest routes first.
  523. if ( !$route_actual && @$r ) {
  524. my $matched = List::Util::first {
  525. # Here's where you want to use Regexp::Debugger in the context of call.pl to debug routes... EX:
  526. # perl ./call.pl GET /path/to/route
  527. #print $r->[$_]."\n";
  528. $path =~ m/^$r->[$_]$/;
  529. }
  530. 0 .. scalar(@$r) - 1;
  531. $route_actual = $r->[ $matched + 1 ] if defined($matched);
  532. }
  533. return $self->route( $route_actual, $env, $fullpath, $path, $start, $last_fetch, $deflate, $domain, $port ) if $route_actual;
  534. # Do a case insensitive match, because osx and windows
  535. my $file_possible = $self->mangle_filename("www/$path");
  536. my $file_actual = $file_possible if -f $file_possible;
  537. # Dirindices
  538. if ( -d $file_possible ) {
  539. foreach my $index ( @{ $self->indices } ) {
  540. next if $file_actual;
  541. my $dirindex = $self->mangle_filename("www$path/$index");
  542. $dirindex =~ s|//|/|g;
  543. $file_actual = $dirindex if -f $dirindex;
  544. }
  545. }
  546. my $file_is_cgi = appears_executable($file_actual);
  547. return $self->cgi( $env, $fullpath, $file_actual, $last_fetch, $deflate ) if $file_is_cgi;
  548. $self->INFO( "Attempting to serve $fullpath [" . ( $file_possible // "" ) . "]" );
  549. my @ranges = parse_ranges($env);
  550. return $self->serve( $fullpath, $file_actual, $start, $streaming, \@ranges, $last_fetch, $deflate ) if $file_actual;
  551. return $self->notfound($cur_query);
  552. }
  553. sub mangle_filename {
  554. my ( $self, $path ) = @_;
  555. # XXX yes, you can have case sensitive OSX, but basically nobody enables that ever
  556. $path = lc($path) if List::Util::any { $^O eq $_ } qw{darwin MSWin32 dos};
  557. $self->DEBUG("Path mangled to $path");
  558. return $path;
  559. }
  560. sub parse_ranges {
  561. my $env = shift;
  562. # Handle HTTP range/streaming requests
  563. my $range = $env->{HTTP_RANGE} || "bytes=0-" if $env->{HTTP_RANGE} || $env->{HTTP_IF_RANGE};
  564. my @ranges;
  565. if ($range) {
  566. $range =~ s/bytes=//g;
  567. push(
  568. @ranges,
  569. map { [ split( /-/, $_ ) ]; } split( /,/, $range )
  570. );
  571. }
  572. return @ranges;
  573. }
  574. my @executable_extensions = qw{cgi sh exe pl php py};
  575. sub appears_executable {
  576. my $subj = shift;
  577. # Definitely not executable if it does not exist!
  578. return 0 unless $subj;
  579. return 0 unless -x $subj;
  580. my ($extension) = $subj =~ m/\.(\S+)$/;
  581. return 1 if !$extension;
  582. return 1 if grep { $extension eq $_ } @executable_extensions;
  583. return 0;
  584. }
  585. # Handle actual routes
  586. sub route {
  587. my ( $self, $route, $env, $fullpath, $path, $start, $last_fetch, $deflate, $domain, $port ) = @_;
  588. $self->DEBUG( 'Executing route ' . $route->{pattern} );
  589. my $content_type = $env->{CONTENT_TYPE} || 'text/html'; # If not set, that's the assumption.
  590. # It is the responsibility of each route to respond to HEAD requests correctly
  591. return $self->badrequest($cur_query) unless List::Util::any { $_ eq $env->{REQUEST_METHOD} } grep { defined $_ } ( 'HEAD', $route->{method} );
  592. my $callback;
  593. if ( exists $route->{callbacks}{'*'} ) {
  594. $callback = $route->{callbacks}{'*'};
  595. }
  596. else {
  597. return $self->badrequest($cur_query) unless exists $route->{callbacks}{$content_type};
  598. $callback = $route->{callbacks}{$content_type};
  599. }
  600. my $streaming = $env->{'psgi.streaming'};
  601. # Build the query data for passing to a route.
  602. # GET, POST, URI captures, then explicit data overrides.
  603. my $query = $self->extract_query( $path, $route, $env );
  604. # We failed validation if $query isn't a hashref.
  605. return $query if ref $query eq 'ARRAY';
  606. # allow this stuff to survive down to the end of some routes
  607. $query->{last_fetched} = $last_fetch;
  608. $query->{deflate} = $deflate;
  609. $query->{streaming} = $streaming;
  610. my @ranges = parse_ranges($env);
  611. $query->{ranges} = \@ranges;
  612. $query->{start} = $start;
  613. # Put things to tv_interval in here for Server-Timing
  614. $query->{fullpath} = $fullpath;
  615. $query->{method} = $route->{method};
  616. $query->{route} = $path;
  617. $query->{cookies} = $env->{HTTP_COOKIE};
  618. $query->{dnt} = $env->{HTTP_DNT};
  619. $query->{nosellinfo} = $env->{HTTP_SEC_GPC};
  620. $query->{port} = $port;
  621. $query->{scheme} = $env->{'psgi.url_scheme'} // 'http';
  622. $query->{method} = $env->{REQUEST_METHOD};
  623. $query->{lang} = $env->{HTTP_ACCEPT_LANGUAGE};
  624. $query->{accept} = $env->{HTTP_ACCEPT};
  625. $query->{has_query} = !!$env->{QUERY_STRING};
  626. $query->{domain} = $domain;
  627. $query->{dispatcher} = $route;
  628. $query->{ip} = $cur_query->{ip};
  629. $query->{ua} = $cur_query->{ua};
  630. $query->{referer} = $cur_query->{referer};
  631. # This allows for better error handlers if we die in the route.
  632. $cur_query = $query;
  633. # Setup the CGI vars they expect IF requested
  634. local %ENV = ( %ENV, CGI::Emulate::PSGI->emulate_environment($env) ) if $route->{env};
  635. # Make this a truly 'dynamic' application if requested.
  636. $self->restart_if_changes() if $self->{autoreload};
  637. {
  638. my $output = $callback->( $self, $query );
  639. # If it's streaming, just hand it off.
  640. # It's up to the caller to handle things like running post-close callbacks in this event.
  641. return $output if ref $output eq 'CODE';
  642. die "$fullpath returned no or malformed data!" unless ref $output eq 'ARRAY' && @$output == 3;
  643. my $pport = defined $query->{port} ? ":$query->{port}" : "";
  644. my %headers = @{ $output->[1] };
  645. my $bytes = $headers{'Content-Length'} // '?';
  646. $self->INFO("$env->{REQUEST_METHOD} $output->[0] $bytes $fullpath");
  647. # Append server-timing headers if they aren't present
  648. my $tot = tv_interval($start) * 1000;
  649. push( @{ $output->[1] }, 'Server-Timing' => "app;dur=$tot" ) unless List::Util::any { $_ eq 'Server-Timing' } @{ $output->[1] };
  650. # In the event that we have post-close callbacks, go ahead and run them.
  651. return $self->stream_raw_psgi( $output, $query ) if @{ $self->{callbacks} };
  652. return $output;
  653. }
  654. }
  655. sub extract_query {
  656. my ( $self, $path, $route, $env ) = @_;
  657. my $query = URL::Encode::url_params_mixed( $env->{QUERY_STRING} ) if $env->{QUERY_STRING};
  658. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  659. if ( $env->{REQUEST_METHOD} eq 'POST' ) {
  660. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  661. while ( $env->{'psgi.input'}->read( my $buf, $CHUNK_SIZE ) ) {
  662. $body->add($buf);
  663. }
  664. @$query{ keys( %{ $body->param } ) } = values( %{ $body->param } );
  665. @$query{ keys( %{ $body->upload } ) } = values( %{ $body->upload } );
  666. }
  667. if ( ref $route->{captures} eq 'ARRAY' ) {
  668. my @captures = $path =~ m/^$route->{pattern}$/;
  669. @$query{ @{ $route->{captures} } } = @captures;
  670. }
  671. if ( ref $route->{data} eq 'HASH' ) {
  672. @$query{ keys( %{ $route->{data} } ) } = values( %{ $route->{data} } );
  673. }
  674. # Now that we've parsed the query and know where we want to go,
  675. # we should (optionally) murder everything the route does not explicitly want, and validate what it does
  676. my $parameters = $route->{parameters};
  677. if (ref $parameters eq 'HASH' && %$parameters) {
  678. my @known_params = keys(%$parameters);
  679. for my $param (@known_params) {
  680. die "Invalid route definition for $path: parameter $param must correspond to a validation CODEREF." unless ref $parameters->{$param} eq 'CODE';
  681. # A missing parameter is not necessarily a problem.
  682. next unless $query->{$param};
  683. # But if we have it, and it's bad, nack it, so that scanners get fail2banned.
  684. $self->DEBUG("Rejected $path for bad query param $param");
  685. return $self->badrequest($query) unless $parameters->{$param}->( $query->{$param} );
  686. }
  687. # Without this logging will break.
  688. push(@known_params, qw{tpsgi ip ua user referer route dispatcher});
  689. # Smack down passing of unnecessary fields; this catches bugs
  690. foreach my $field ( keys(%$query) ) {
  691. next if List::Util::any { $field eq $_ } @known_params;
  692. $self->WARN("Unexpected parameter $field passed");
  693. return $self->badrequest($query);
  694. }
  695. }
  696. return $query;
  697. }
  698. # Read until we are done with headers, then pass off the filehandle to PSGI for streaming.
  699. # TODO support compression
  700. sub cgi {
  701. my ( $self, $env, $fullpath, $file_actual, $last_fetch, $deflate ) = @_;
  702. $self->INFO("Handoff $fullpath to $file_actual for cgi exec");
  703. # Setup the CGI vars they expect
  704. local %ENV = ( %ENV, CGI::Emulate::PSGI->emulate_environment($env) );
  705. my $pid = open( my $out, '-|', "$file_actual" );
  706. my ( $code, $offset, %headers ) = extract_headers( $out, $last_fetch );
  707. $code //= 500;
  708. return sub {
  709. my $responder = shift;
  710. my $writer = $responder->( [ $code, [%headers] ] );
  711. while ( $out->read( my $buf, $CHUNK_SIZE ) ) {
  712. $writer->write($buf);
  713. }
  714. $writer->close;
  715. # Wait on the CGI script to do whatever it's doing after closing stdout
  716. close $out;
  717. waitpid( $pid, 0 );
  718. };
  719. }
  720. # Used primarily when we have post-close callbacks
  721. sub stream_raw_psgi {
  722. my ( $self, $response, $data ) = @_;
  723. my $time_to_here = tv_interval( $data->{start} );
  724. $self->DEBUG("Routing took $time_to_here s");
  725. my $post_routing = [gettimeofday];
  726. my $fh = $self->{filehandle};
  727. print $fh "HTTP/1.1 $response->[0]\n";
  728. # Emit the rest of the headers
  729. foreach ( my $i = 0; $i < @{ $response->[1] }; $i += 2 ) {
  730. my $header = $response->[1][$i];
  731. my $value = $response->[1][ $i + 1 ];
  732. print $fh "$header: $value\n";
  733. }
  734. print $fh "\n";
  735. # Emit the body
  736. print $fh $response->[2][0];
  737. close($fh);
  738. $self->DEBUG( "Response written in " . ( tv_interval($post_routing) ) . " s" );
  739. while ( my $callback = shift @{ $self->{callbacks} } ) {
  740. if ( ref $callback eq 'CODE' ) {
  741. my $post_start = [gettimeofday];
  742. local $@;
  743. eval { $callback->() };
  744. $self->ERROR("Post-close callback encountered exception: $@") if $@;
  745. $self->DEBUG( "Post-close callback took " . ( tv_interval($post_start) ) . " s" );
  746. }
  747. }
  748. exit 0;
  749. }
  750. sub stream_raw_http {
  751. my ( $self, $data, $last_fetch, $to_fork, $callback, $error_handler ) = @_;
  752. my $time_to_here = tv_interval( $data->{start} );
  753. $self->DEBUG("Routing took $time_to_here s");
  754. my $post_routing = [gettimeofday];
  755. my $fh = $self->{filehandle};
  756. # The CGIs you are executing here SHOULD NOT emit a status line.
  757. # Most apache CGIs you find don't anyways, so this is usually not a big deal.
  758. print $fh "HTTP/1.1 200 OK\n";
  759. # Emit our server-timing header.
  760. print $fh "Server-Timing: " . $self->build_server_timing($data) . "\n"; #app;dur=".($time_to_here*1000)."\n";
  761. # We *must* fork because we can't rely on the child to close stdout.
  762. my $pid = _fork(
  763. sub {
  764. $self->DEBUG( "Forking child took" . ( tv_interval($post_routing) ) . " s" );
  765. local $@;
  766. eval { $to_fork->() };
  767. $self->ERROR("Raw HTTTP streaming encountered exception: $@") if $@;
  768. if ( ref $error_handler eq 'CODE' ) {
  769. local $@;
  770. eval { $error_handler->() };
  771. $self->ERROR("HTTP streaming error handler encountered exception: $@") if $@;
  772. }
  773. },
  774. $fh
  775. );
  776. waitpid( $pid, 0 );
  777. close($fh);
  778. $self->DEBUG( "Response written in " . ( tv_interval($post_routing) ) . " s" );
  779. if ( ref $callback eq 'CODE' ) {
  780. my $post_start = [gettimeofday];
  781. local $@;
  782. eval { $callback->() };
  783. $self->ERROR("Post-close callback encountered exception: $@") if $@;
  784. $self->DEBUG( "Post-close callback took " . ( tv_interval($post_start) ) . " s" );
  785. }
  786. exit 0;
  787. }
  788. sub _fork {
  789. my ( $callback, $fh ) = @_;
  790. select $fh;
  791. $| = 1;
  792. my $pid = fork();
  793. die "Could not fork child" unless defined $pid;
  794. if ( $pid == 0 ) {
  795. $callback->();
  796. exit 0;
  797. }
  798. select STDOUT;
  799. return $pid;
  800. }
  801. =head2 extract_headers($fh, $last_fetch)
  802. Extract the headers from a filehandle. Set the 'Last Modified' header appropriately based on the output of `stat` on the filehandle.
  803. 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.
  804. =cut
  805. sub extract_headers {
  806. my ( $fh, $last_fetch, $is_ref ) = @_;
  807. my $headers = '';
  808. # NOTE: this is relying on while advancing the file pointer
  809. while (<$fh>) {
  810. last if $_ eq "\n";
  811. $headers .= $_;
  812. }
  813. #XXX still a toctou
  814. my $offset = $fh->tell();
  815. my ( undef, undef, $status, undef, $headers_parsed ) = HTTP::Parser::XS::parse_http_response( "$headers\n", HEADERS_AS_HASHREF );
  816. my $code = $status // 200;
  817. $headers_parsed //= {};
  818. if ( !$is_ref ) {
  819. my $mt = ( stat($fh) )[9];
  820. my @gm = gmtime($mt);
  821. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  822. $code = $mt > $last_fetch ? $status : 304;
  823. $headers_parsed->{"Last-Modified"} = $now_string;
  824. }
  825. return ( $code, $offset, %$headers_parsed );
  826. }
  827. sub static {
  828. my ( $self, $fullpath, $path, $start, $streaming, $last_fetch ) = @_;
  829. $self->DEBUG("Rendering static for $path");
  830. # XXX because of psgi I can't just vomit the file directly
  831. if ( open( my $fh, '<', "statics/$path" ) ) {
  832. my ( $code, $offset, $headers_parsed ) = ( 200, undef, {} );
  833. ( $code, $offset, %$headers_parsed ) = extract_headers( $fh, $last_fetch );
  834. # Append server-timing headers
  835. my $tot = tv_interval($start) * 1000;
  836. $headers_parsed->{'Server-Timing'} = "static;dur=$tot";
  837. #XXX uwsgi just opens the file *again* when we already have a filehandle if it has a path.
  838. # starman by comparison doesn't violate the principle of least astonishment here.
  839. # This is probably a performance optimization, but makes the kind of micromanagement I need to do inconvenient.
  840. # As such, we will just return a stream.
  841. $self->INFO("GET 200 $headers_parsed->{'Content-Length'} $fullpath");
  842. return sub {
  843. my $responder = shift;
  844. #push(@headers, 'Content-Length' => $sz);
  845. my $writer = $responder->( [ $code, [%$headers_parsed] ] );
  846. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  847. $writer->write($buf);
  848. }
  849. close $fh;
  850. $writer->close;
  851. }
  852. if $streaming;
  853. return [ $code, [%$headers_parsed], $fh ];
  854. }
  855. return $self->forbidden( $self->{current_query} );
  856. }
  857. sub get_config { return TPSGI::Startup::get_config(@_) }
  858. # Convenience method to keep track of server-timing
  859. sub checkpoint {
  860. my ( $self, $data, $name ) = @_;
  861. $data->{checkpoints} //= [ [ start => $data->{start} ] ];
  862. push( @{ $data->{checkpoints} }, [ $name => [gettimeofday] ] );
  863. }
  864. sub build_server_timing {
  865. my ( $self, $data ) = @_;
  866. my @st;
  867. my $last_interval;
  868. foreach my $checkpoint ( @{ $data->{checkpoints} } ) {
  869. if ($last_interval) {
  870. my $dur = tv_interval( $last_interval, $checkpoint->[1] ) * 1000;
  871. push( @st, "$checkpoint->[0];dur=$dur" );
  872. }
  873. $last_interval = $checkpoint->[1];
  874. }
  875. my $tot = tv_interval( $data->{start} ) * 1000;
  876. push( @st, "tot;dur=$tot" );
  877. delete $data->{checkpoints};
  878. return join( ', ', @st );
  879. }
  880. =head2 add_post_close_callback()
  881. Add a thing to do after closing stdout; useful for housekeeping that doesn't need to hold up pageload.
  882. =cut
  883. sub add_post_close_callback {
  884. my ( $self, $cb ) = @_;
  885. push( @{ $self->{callbacks} }, $cb );
  886. }
  887. =head2 signal_restart_parent()
  888. Instruct tPSGI to reload after closing stdout.
  889. =cut
  890. sub signal_restart_parent {
  891. my ($self) = @_;
  892. $self->add_post_close_callback( \&_restart_parent );
  893. }
  894. # Instruct tPSGI to reload.
  895. sub _restart_parent {
  896. my $parent = getppid;
  897. kill 'HUP', $parent;
  898. }
  899. =head2 save_render($path, $extension, $body)
  900. Save a static render of the page.
  901. Good to queue after closing stdout.
  902. Passed file extension slapped on the end of the path.
  903. You can then serve them as statics with an appropriately done try_files block in nginx.
  904. =cut
  905. # fixup matrix
  906. my %fixup = (
  907. text => 'txt',
  908. blob => 'bin',
  909. );
  910. sub save_render {
  911. my ( $self, $path, $extension, $body ) = @_;
  912. return unless $path && $extension;
  913. # If this is an index, let's make it so
  914. if ($path =~ m|/$|) {
  915. $path = $path.'index';
  916. }
  917. # Fixup the extension if needed.
  918. $extension = $fixup{$extension} if exists $fixup{$extension};
  919. my $path_fixed = $path;
  920. $path_fixed =~ s/\.\Q$extension\E$//;
  921. $path_fixed = "$path_fixed.$extension";
  922. my $path2file = "$self->{tpsgi_dir}/www/static/" . dirname($path_fixed);
  923. if ( !-d $path2file ) {
  924. File::Path::make_path( $path2file, { user => $<, group => $self->{gid}, chmod => 0755 } ) or die "Could not create directory $path2file";
  925. }
  926. my $file = "$self->{tpsgi_dir}/www/static/$path_fixed";
  927. my $verb = -f $file ? 'Overwrite' : 'Write';
  928. $self->INFO("$verb $path as static/$path_fixed");
  929. open( my $fh, '>', $file ) or die "Could not open $file for writing";
  930. print $fh $body;
  931. close $fh;
  932. chmod( 0755, $file );
  933. chown( $<, $self->{gid}, $file );
  934. }
  935. =head2 invalidate_render($path, $extension)
  936. Remove an existing static render of a path.
  937. =cut
  938. sub invalidate_render {
  939. my ( $self, $path, $extension ) = @_;
  940. return unless $path && $extension;
  941. # Fixup the extension if needed.
  942. $extension = $fixup{$extension} if exists $fixup{$extension};
  943. my $path_fixed = $path;
  944. $path_fixed =~ s/\.\Q$extension\E$//;
  945. $path_fixed = "$path_fixed.$extension";
  946. my $file = "$self->{tpsgi_dir}/www/static/$path_fixed";
  947. return unless -f $file;
  948. $self->_invalidate($file);
  949. }
  950. sub _invalidate {
  951. my ($self, $file) = @_;
  952. $self->INFO("Delete $file");
  953. unlink "$file";
  954. }
  955. =head2 invalidate_renders($extension)
  956. Remove all existing static renders with the provided extension.
  957. Useful when it's not easy to figure out what to re-render due to including templates in other templates, etc.
  958. =cut
  959. sub invalidate_renders {
  960. my ($self, $extension) = @_;
  961. File::Find::find( {
  962. wanted => sub {
  963. my $object = $_;
  964. $self->_invalidate($object) if (-f $object && $object =~ m/\.\Q$extension\E$/);
  965. },
  966. no_chdir => 1,
  967. bydepth => 1,
  968. },
  969. "$self->{tpsgi_dir}/www/static/");
  970. }
  971. sub watch_for_changes { return TPSGI::Startup::watch_for_changes(@_) }
  972. =head2 restart_if_changes
  973. Restart tPSGI if any of the relevant libdir files change.
  974. Powers the autorestart feature.
  975. =cut
  976. sub restart_if_changes {
  977. my $self = shift;
  978. my @result = $TPSGI::Startup::inotify->read();
  979. my $had_changes = 0;
  980. foreach my $res (@result) {
  981. if ( $res->{name} =~ m/\.pm$/ ) {
  982. $had_changes++;
  983. last;
  984. }
  985. }
  986. return 0 unless $had_changes;
  987. # We don't have to clean up the wds, that is handled in the destructor for Inotify
  988. $self->INFO("Relevant Change in libdirs detected, reloading\n");
  989. $self->signal_restart_parent();
  990. return 0;
  991. }
  992. 1;