TPSGI.pm 39 KB

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