TPSGI.pm 39 KB

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