TPSGI.pm 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  1. package TPSGI;
  2. # ABSTRACT: Abstraction layer around starman to become a general purpose HTTP server & static renderer.
  3. use 5.040;
  4. use warnings FATAL => 'all';
  5. use re '/aasx';
  6. use Carp::Always;
  7. use UUID();
  8. use POSIX();
  9. use Mojo::File;
  10. use IO::Compress::Gzip;
  11. use Plack::MIME;
  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::Basename qw{dirname basename};
  26. use Module::Runtime();
  27. use Log::Dispatch;
  28. use Log::Dispatch::Screen;
  29. use Log::Dispatch::FileRotate;
  30. use TPSGI::Startup;
  31. # We have a DEBUG var which is plus ultra for extra sensitive stuff beyond just passing verbose
  32. our $debug = $ENV{TPSGI_DEBUG};
  33. #1MB chunks
  34. our $CHUNK_SEP = 'perlfsSep666YOLO42069';
  35. our $CHUNK_SIZE = 1024000;
  36. our %content_types = (
  37. text => "text/plain",
  38. html => "text/html",
  39. json => "application/json",
  40. blob => "application/octet-stream",
  41. xml => "text/xml",
  42. xsl => "text/xsl",
  43. css => "text/css",
  44. rss => "application/rss+xml",
  45. email => "multipart/related",
  46. );
  47. our %byct = reverse %content_types;
  48. our %cache_control = (
  49. revalidate => "no-cache, max-age=0",
  50. nocache => "no-store",
  51. static => "public, max-age=604800, immutable",
  52. );
  53. #TODO consider integrating libfile
  54. #Stuff that isn't in upstream finders
  55. my %extra_types = (
  56. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  57. );
  58. my $ct = 'Content-type';
  59. my $generic_handler;
  60. =head2 request_id($regenerate) = STRING
  61. The UUID of the request being answered, which every log line carries. A true
  62. $regenerate makes a new one, which app() does as each request comes in.
  63. =cut
  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. # The line each of the logging methods writes.
  71. my sub log_line {
  72. my ( $self, $msg ) = @_;
  73. $msg //= "No message passed. This is almost certainly a bug. ";
  74. #XXX Log lines must start as an ISO8601 date, anything else breaks fail2ban's beautiful mind
  75. my $tstamp = POSIX::strftime "%Y-%m-%dT%H:%M:%SZ", gmtime;
  76. my $uuid = $self->request_id();
  77. my $udata = $self->{user} ? "[$self->{user}]" : "[nobody]";
  78. return "[Worker $$] {Request $uuid} $udata $tstamp : $self->{ip} $msg\n";
  79. }
  80. =head2 log() = Log::Dispatch
  81. The process's Log::Dispatch, made by build_log() the first time it is asked
  82. for.
  83. =cut
  84. sub log { ## no critic (ProhibitBuiltinHomonyms) -- a method, which nothing calls as the builtin
  85. my $self = shift;
  86. state $log;
  87. return $log //= $self->build_log();
  88. }
  89. =head2 build_log() = Log::Dispatch
  90. A new Log::Dispatch from the options: the rotated file at C<log_name>, the
  91. screen, and each class that C<loggers> names, which is loaded by name. log()
  92. keeps the first one this makes.
  93. =cut
  94. sub build_log {
  95. my $self = shift;
  96. my $LOGNAME = $self->{log_name};
  97. my $LOGDIR = $self->{log_dir};
  98. File::Path::make_path($LOGDIR) unless -d $LOGDIR;
  99. File::Touch::touch($LOGNAME) unless -e $LOGNAME;
  100. my $LEVEL = $self->{verbose} ? 'debug' : 'info';
  101. # By default only log requests & warnings.
  102. # Otherwise emit debug messages.
  103. my $rotate = Log::Dispatch::FileRotate->new(
  104. name => 'tcms',
  105. filename => $LOGNAME,
  106. min_level => $LEVEL,
  107. 'mode' => 'append',
  108. size => 10_485_760, # 10 MiB
  109. max => 6,
  110. );
  111. # Only send fatal events/errors to stdout
  112. my $screen = Log::Dispatch::Screen->new(
  113. name => 'screen',
  114. min_level => $LEVEL,
  115. );
  116. my $log = Log::Dispatch->new();
  117. $log->add($rotate);
  118. $log->add($screen);
  119. # The first line is logged while new() is still loading the routers, so a
  120. # logger that an application ships beside its router is not loaded yet.
  121. foreach my $logger ( @{ $self->{loggers} } ) {
  122. $log->add( Module::Runtime::use_module($logger)->new( min_level => $LEVEL, log_dir => $LOGDIR ) );
  123. }
  124. $log->info( log_line( $self, "Opening Log $LOGNAME at $LEVEL level" ) );
  125. return $log;
  126. }
  127. =head2 DEBUG, INFO, NOTE, WARN, ERROR, CRIT, ALERT, EMERG, FATAL($message)
  128. Log $message at that level, stamped with the time, the worker, the request and
  129. the user. FATAL logs at the emergency level and then dies with the line.
  130. =cut
  131. sub DEBUG {
  132. my ( $self, $msg ) = @_;
  133. return $self->log->debug( log_line( $self, $msg ) );
  134. }
  135. sub INFO {
  136. my ( $self, $msg ) = @_;
  137. return $self->log->info( log_line( $self, $msg ) );
  138. }
  139. sub NOTE {
  140. my ( $self, $msg ) = @_;
  141. return $self->log->notice( log_line( $self, $msg ) );
  142. }
  143. sub WARN {
  144. my ( $self, $msg ) = @_;
  145. return $self->log->warning( log_line( $self, $msg ) );
  146. }
  147. sub ERROR {
  148. my ( $self, $msg ) = @_;
  149. return $self->log->error( log_line( $self, $msg ) );
  150. }
  151. sub CRIT {
  152. my ( $self, $msg ) = @_;
  153. return $self->log->critical( log_line( $self, $msg ) );
  154. }
  155. sub ALERT {
  156. my ( $self, $msg ) = @_;
  157. return $self->log->alert( log_line( $self, $msg ) );
  158. }
  159. sub EMERG {
  160. my ( $self, $msg ) = @_;
  161. return $self->log->emergency( log_line( $self, $msg ) );
  162. }
  163. sub FATAL {
  164. my ( $self, $msg ) = @_;
  165. return $self->log->log_and_die( level => 'emergency', message => log_line( $self, $msg ) );
  166. }
  167. =head2 new(%options)
  168. Load the routers and build the routing table. It dies unless it runs as
  169. C<user>, and C<http_user> and C<tpsgi_dir> are set. get_config() returns the
  170. options, and among them are:
  171. custom_log
  172. verbose
  173. routers
  174. loggers
  175. auth
  176. =cut
  177. sub new {
  178. my ( $class, %options ) = @_;
  179. # Refuse to run as wrong user, all config will be borked otherwise
  180. my $pname = getpwuid($>);
  181. die "Must run as configured user (got: $pname, want: $options{user})!" unless $pname eq ( $options{user} // '' );
  182. die "Must set http_user in options" unless $options{http_user};
  183. die "Must set tpsgi_dir in options" unless $options{tpsgi_dir};
  184. my $gid = getgrnam( $options{http_user} );
  185. die "No such user $options{http_user}" unless $gid;
  186. $options{gid} = $gid;
  187. my $self = bless( \%options, $class );
  188. $self->{ip} = '0.0.0.0';
  189. my @routes;
  190. my %aliases;
  191. # XXX TODO make these routes able to be fully qualified namespaces (::)!
  192. foreach my $route ( @{ $self->{routers} } ) {
  193. die "No such routing module $route" unless -e "$options{tpsgi_dir}/$route";
  194. # The router needs to exist and have nonzero numbers of routes.
  195. my ($package) = basename($route) =~ m/(\S+)[.]pm$/;
  196. # It also should be a top-level namespace, not somewhere deep down. KISS.
  197. my $libdir = dirname("$options{tpsgi_dir}/$route");
  198. push( @INC, $libdir );
  199. local $@;
  200. $self->DEBUG("require $options{tpsgi_dir}/$route");
  201. my $success = eval { require "$options{tpsgi_dir}/$route"; 1; }; ## no critic (RequireBarewordIncludes) -- a router is named by its file
  202. if ($success) {
  203. my ( $pkg_routes, $pkg_aliases, $pkg_watches ) = do {
  204. no strict 'refs'; # the router's own package variables, by name
  205. ( \@{"${package}::routes"}, \%{"${package}::aliases"}, \%{"${package}::watches"} );
  206. };
  207. for ( my $i = 0; $i < @$pkg_routes; $i += 2 ) {
  208. $self->DEBUG("Registered route $pkg_routes->[$i]");
  209. }
  210. push( @routes, @$pkg_routes );
  211. foreach my $al ( keys(%$pkg_aliases) ) {
  212. $self->DEBUG("aliased route $al to $pkg_aliases->{$al}");
  213. }
  214. @aliases{ keys(%$pkg_aliases) } = values(%$pkg_aliases);
  215. # Anything the router wants to watch, along with what to do when it changes.
  216. # Registration is idempotent, which matters because new() runs per request.
  217. foreach my $watched ( keys(%$pkg_watches) ) {
  218. my $spec = $pkg_watches->{$watched};
  219. # Copied rather than used directly, as we don't want to eat the router's own data.
  220. my %args = ref $spec eq 'HASH' ? %$spec : ( callback => $spec );
  221. $self->add_watch( $watched, delete $args{callback}, %args );
  222. }
  223. # First-come first-served error template overrides
  224. $generic_handler = $package->can('generic_route');
  225. }
  226. else {
  227. die "Could not load $route!\n$@\n";
  228. }
  229. }
  230. # Set the pattern used to discover the route if needed later.
  231. for ( my $i = 0; $i < scalar(@routes); $i += 2 ) {
  232. $routes[ $i + 1 ]{pattern} = $routes[$i];
  233. }
  234. $self->{indices} //= [];
  235. $self->{indices} = [ @{ $self->{indices} }, qw{index.html index.htm index.cgi} ];
  236. $self->{routes} = \@routes;
  237. $self->{aliases} = \%aliases;
  238. $self->{callbacks} = [];
  239. return $self;
  240. }
  241. =head2 indices() = ARRAYREF
  242. The directory index files, in the order they are tried: the C<indices> option,
  243. then F<index.html>, F<index.htm> and F<index.cgi>.
  244. =cut
  245. sub indices {
  246. my $self = shift;
  247. return $self->{indices};
  248. }
  249. =head2 routes() = ARRAYREF
  250. The routing table: each route's pattern, then its definition, for every router
  251. in the order they were loaded.
  252. =cut
  253. sub routes {
  254. my $self = shift;
  255. return $self->{routes};
  256. }
  257. =head2 serve($fullpath, $path, $start, $streaming, $ranges, $last_fetch, $deflate)
  258. Serve a file, with options to stream and cache the output.
  259. =cut
  260. sub serve { ## no critic (ProhibitManyArgs) -- routers call it with these, in this order
  261. my ( $self, $fullpath, $path, $start, $streaming, $ranges, $last_fetch, $deflate ) = @_;
  262. $last_fetch ||= 0;
  263. $deflate ||= 0;
  264. my $mf = Mojo::File->new($path);
  265. my $ext = '.' . $mf->extname();
  266. my $ft;
  267. if ($ext) {
  268. $ft = Plack::MIME->mime_type($ext) if $ext;
  269. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  270. }
  271. $ft ||= $content_types{text};
  272. my @headers = ( $ct => $ft );
  273. #TODO use static Cache-Control for everything but JS/CSS?
  274. push( @headers, 'Cache-control' => $cache_control{revalidate} );
  275. push( @headers, 'Accept-Ranges' => 'bytes' );
  276. $self->DEBUG("FETCH $path");
  277. my $mt = ( stat($path) )[9];
  278. my $sz = ( stat(_) )[7];
  279. my @gm = gmtime($mt);
  280. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  281. my $code = $mt > $last_fetch ? 200 : 304;
  282. push( @headers, "Last-Modified" => $now_string );
  283. push( @headers, 'Vary' => 'Accept-Encoding' );
  284. # The handle is the body of the response, so the server closes it.
  285. if ( open( my $fh, '<', $path ) ) { ## no critic (RequireBriefOpen)
  286. return $self->serve_ranges( $fh, $ranges, size => $sz, headers => {@headers}, fullpath => $fullpath ) if @$ranges && $streaming;
  287. # Transfer-encoding: chunked
  288. return sub {
  289. my $responder = shift;
  290. push( @headers, 'Content-Length' => $sz );
  291. my $writer = $responder->( [ $code, \@headers ] );
  292. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  293. $writer->write($buf);
  294. }
  295. close($fh) or $self->WARN("Could not close $path: $!");
  296. $writer->close;
  297. }
  298. if $streaming && $sz > $CHUNK_SIZE;
  299. #Return data in the event the caller does not support deflate
  300. if ( !$deflate ) {
  301. push( @headers, "Content-Length" => $sz );
  302. # Append server-timing headers
  303. my $tot = tv_interval($start) * 1000;
  304. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  305. return [ $code, \@headers, $fh ];
  306. }
  307. #Compress everything less than 1MB
  308. push( @headers, "Content-Encoding" => "gzip" );
  309. my $dfh;
  310. IO::Compress::Gzip::gzip( $fh => \$dfh );
  311. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  312. push( @headers, "Content-Length" => length($dfh) );
  313. # Copy to the statics if it's not already there
  314. my $static_path = $path;
  315. $static_path =~ s{^/*www/}{};
  316. $static_path = "$self->{tpsgi_dir}/www/static/$static_path";
  317. my $target_dir = dirname($static_path);
  318. if ( !-d $target_dir ) {
  319. File::Path::make_path( $target_dir, { user => $<, group => $self->{gid}, chmod => 0o755 } ) or die "Could not make dir $target_dir";
  320. }
  321. # hardlink to save disk space. One that is there already is this file.
  322. # TODO figure out cache invalidation, I guess check mtime/hash
  323. if ( link $path, $static_path ) {
  324. $self->INFO("Copying $path to $static_path");
  325. }
  326. elsif ( !$!{EEXIST} ) {
  327. $self->WARN("Could not link $path to $static_path: $!");
  328. }
  329. $self->INFO("GET 200 $fullpath");
  330. # Append server-timing headers
  331. my $tot = tv_interval($start) * 1000;
  332. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  333. return [ $code, \@headers, [$dfh] ];
  334. }
  335. $self->INFO("GET 403 $fullpath");
  336. return [ 403, [ $ct => $content_types{text} ], ["Forbidden"] ];
  337. }
  338. =head2 serve_ranges($fh, $ranges, %args) = PSGI response
  339. Answer a Range request from $fh with a 206, or a 416 when a range is outside
  340. the file. $ranges is what parse_ranges() returns, and %args is C<size>, the
  341. size of the file, C<headers>, a HASH reference of the response headers so far,
  342. and C<fullpath>, the URL for the log. More than one range is answered as
  343. multipart/byteranges.
  344. =cut
  345. sub serve_ranges {
  346. my ( $self, $fh, $ranges, %args ) = @_;
  347. my $sz = $args{size};
  348. my %headers = %{ $args{headers} };
  349. my $fullpath = $args{fullpath};
  350. # Set mode
  351. my $primary_ct = "Content-Type: $headers{'Content-type'}";
  352. my $is_multipart = scalar(@$ranges) > 1;
  353. if ($is_multipart) {
  354. $headers{'Content-type'} = "multipart/byteranges; boundary=$CHUNK_SEP";
  355. }
  356. my $code = 206;
  357. my $fc = '';
  358. # Calculate the content-length up-front. We have to fix unspecified lengths first, and reject bad requests.
  359. foreach my $range (@$ranges) {
  360. $range->[1] //= $sz - 1;
  361. if ( $range->[0] > $sz || $range->[0] < 0 || $range->[1] < 0 || $range->[0] > $range->[1] ) {
  362. $self->INFO("GET 416 $fullpath");
  363. return [ 416, [%headers], ["Requested range not satisfiable"] ];
  364. }
  365. }
  366. $headers{'Content-Length'} = List::Util::sum( map { $_->[1] + 1 - $_->[0] } @$ranges );
  367. #XXX Add the entity header lengths to the value - should hash-ify this to DRY
  368. if ($is_multipart) {
  369. foreach my $range (@$ranges) {
  370. $headers{'Content-Length'} += length("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n");
  371. $fc = "\n";
  372. }
  373. $headers{'Content-Length'} += length("\n--$CHUNK_SEP\--\n");
  374. $fc = '';
  375. }
  376. return sub {
  377. my $responder = shift;
  378. my $writer;
  379. foreach my $range (@$ranges) {
  380. $headers{'Content-Range'} = "bytes $range->[0]-$range->[1]/$sz" unless $is_multipart;
  381. $writer //= $responder->( [ $code, [%headers] ] );
  382. $writer->write("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n") if $is_multipart;
  383. $fc = "\n";
  384. my $len = List::Util::min( $sz, $range->[1] + 1 ) - $range->[0];
  385. $fh->seek( $range->[0], 0 );
  386. while ($len) {
  387. $fh->read( my $buf, List::Util::min( $len, $CHUNK_SIZE ) );
  388. $writer->write($buf);
  389. # Adjust for amount written
  390. $len = List::Util::max( $len - $CHUNK_SIZE, 0 );
  391. }
  392. }
  393. $fh->close();
  394. $writer->write("\n--$CHUNK_SEP--\n") if $is_multipart;
  395. $writer->close;
  396. };
  397. }
  398. # The page for an error code, which the router's generic_route() makes when it
  399. # has one.
  400. my sub generic {
  401. my ( $type, $code, $query ) = @_;
  402. if ($generic_handler) {
  403. my $rname = "/$code";
  404. my $title = $type;
  405. return $generic_handler->( $rname, $code, $title, $query );
  406. }
  407. $type .= Carp::longmess() if $debug;
  408. return [ $code, [ $ct => $content_types{html} ], ["$type"] ];
  409. }
  410. =head2 redirect, redirect_permanent, see_also
  411. Redirects to the provided page.
  412. =cut
  413. sub redirect {
  414. my ( $self, $to ) = @_;
  415. $self->INFO("redirect: $to");
  416. return [ 302, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  417. }
  418. sub redirect_permanent {
  419. my ( $self, $to ) = @_;
  420. $self->INFO("permanent redirect: $to");
  421. return [ 301, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  422. }
  423. sub see_also {
  424. my ( $self, $to ) = @_;
  425. $self->INFO("see also: $to");
  426. return [ 303, [ "Location" => $to, "Content-Length" => 0 ], [''] ];
  427. }
  428. =head2 ok
  429. Return a generic HTTP 200 OK
  430. =cut
  431. sub ok {
  432. my ( $self, $query, $body ) = @_;
  433. $self->INFO("$query->{method} 200 $query->{fullpath}");
  434. $body //= 'Ok';
  435. return generic( $body, 200, $query );
  436. }
  437. =head2 notfound, forbidden, badrequest, toolong, error, unavailable
  438. If you need to return these HTTP errors, return these within a route:
  439. sub route {
  440. my ($self, $query) = @_;
  441. ...
  442. return $self->notfound($query);
  443. }
  444. =cut
  445. sub notfound {
  446. my ( $self, $query, $body ) = @_;
  447. $self->INFO("$query->{method} 404 $query->{fullpath}");
  448. $body //= 'Not Found';
  449. return generic( $body, 404, $query );
  450. }
  451. sub forbidden {
  452. my ( $self, $query, $body ) = @_;
  453. $self->INFO("$query->{method} 403 $query->{fullpath}");
  454. $body //= 'Forbidden';
  455. return generic( $body, 403, $query );
  456. }
  457. sub badrequest {
  458. my ( $self, $query, $body ) = @_;
  459. $self->INFO("$query->{method} 400 $query->{fullpath}");
  460. $body //= 'Bad Request';
  461. return generic( $body, 400, $query );
  462. }
  463. sub toolong {
  464. my ( $self, $query, $body ) = @_;
  465. $self->INFO("$query->{method} 419 $query->{fullpath}");
  466. $body //= 'URI too long';
  467. return generic( $body, 419, $query );
  468. }
  469. sub error {
  470. my ( $self, $query, $body ) = @_;
  471. my $method = $query->{method} // "?";
  472. my $fp = $query->{fullpath} // "?";
  473. $body //= 'Internal Server Error';
  474. $self->INFO("$method 500 $fp");
  475. return generic( $body, 500, $query );
  476. }
  477. sub unavailable {
  478. my ( $self, $query, $body ) = @_;
  479. $self->INFO("$query->{method} 503 $query->{fullpath}");
  480. $body //= 'Service Unavailable';
  481. return generic( $body, 503, $query );
  482. }
  483. my $cur_query = {};
  484. =head2 app($env) = PSGI response
  485. The PSGI application: respond() to the request, or answer it with error() when
  486. that dies.
  487. =cut
  488. sub app {
  489. my ( $self, $env ) = @_;
  490. return eval { $self->respond($env) } || do {
  491. my $err = $@;
  492. $env->{'psgi.errors'}->print($err) if $env->{'psgi.errors'};
  493. # psgi.errors is the server's stderr, which a daemonized server sends
  494. # nowhere unless it was started with --error-log. The log is the one
  495. # place that is always there, so the reason goes in it whole.
  496. $self->ERROR("Request failed: $err");
  497. # Redact the stack trace past line 1, it usually has things which should not be shown
  498. $cur_query->{message} = $err;
  499. $cur_query->{message} =~ s/\n.*//g if $cur_query->{message} && !$debug;
  500. return $self->error($cur_query);
  501. };
  502. }
  503. =head2 cannot_start($error, $env, %options) = ARRAYREF
  504. What to answer with when new() died, so there is no object to answer with.
  505. Usually a router that would not load: a missing module, a syntax error.
  506. The error goes to psgi.errors, and to the log by way of a stand-in built from
  507. the same options, so it lands in the same places a request's own errors do. If
  508. building the log is what failed -- a logger that will not load -- psgi.errors
  509. is all there is, and the answer is still a 500 rather than a second exception.
  510. The answer is a page of our own, not the router's error page: the router is
  511. what failed. With TPSGI_DEBUG set it carries the error itself, trace and all,
  512. for the same reason the error pages add one; without, it says nothing a visitor
  513. could use to map the installation.
  514. The worker retires once it has answered, on a server that offers
  515. psgix.harakiri, which Starman does. A router that died while it compiled
  516. leaves its file in %INC as a failure, and every later require of it in this
  517. process says only "Attempt to reload ... aborted" -- so a load that failed
  518. once, to a race or a lock, would otherwise fail for every request the worker
  519. ever serves. A fresh worker tries again from nothing.
  520. =cut
  521. sub cannot_start {
  522. my ( $error, $env, %options ) = @_;
  523. $env->{'psgi.errors'}->print($error) if ref $env eq 'HASH' && $env->{'psgi.errors'};
  524. # When the log will not build either, psgi.errors above is all there is.
  525. eval { bless( { %options, ip => '0.0.0.0' }, __PACKAGE__ )->ERROR("Could not start: $error"); 1 }; ## no critic (RequireCheckingReturnValueOfEval)
  526. $env->{'psgix.harakiri.commit'} = 1 if ref $env eq 'HASH' && $env->{'psgix.harakiri'};
  527. my $detail = '';
  528. if ($debug) {
  529. ( my $escaped = $error ) =~ s/([&<>"])/'&#' . ord($1) . ';'/ge;
  530. $detail = "<pre>$escaped</pre>";
  531. }
  532. my $page = "<!doctype html><html><head><meta charset=\"utf-8\"><title>Internal Server Error</title></head>" . "<body><h1>Internal Server Error</h1>$detail</body></html>";
  533. return [ 500, [ $ct => $content_types{html} ], [$page] ];
  534. }
  535. my %etags;
  536. # A router's pattern means what the router wrote, so none of this file's
  537. # default flags apply to it: /aa would make \w ASCII only, /x would drop its
  538. # spaces, and /s would change what a dot matches.
  539. my sub match_route {
  540. my ( $path, $pattern ) = @_;
  541. no re '/aasx';
  542. return $path =~ m/^$pattern$/; ## no critic (RequireDefault RequireExtendedFormatting RequireDotMatchAnything)
  543. }
  544. =head2 respond($env) = PSGI response
  545. Answer one request: from a route when one matches, by running a CGI when the
  546. file under F<www/> is executable, and otherwise by serving the file.
  547. =cut
  548. sub respond {
  549. my ( $self, $env ) = @_;
  550. # Start the server timing clock
  551. my $start = [gettimeofday];
  552. $cur_query = {};
  553. $self->{filehandle} = $env->{'psgix.io'} // *STDOUT;
  554. $self->{input} = $env->{'psgi.input'};
  555. # Setup the unique ID for the request
  556. $env->{REQUEST_ID} = $self->request_id(1);
  557. # Discard the path used in the log, it's too long and enough 4xx error code = ban
  558. return $self->toolong( { method => $env->{REQUEST_METHOD}, fullpath => '...' } ) if length( $env->{REQUEST_URI} ) > 2048;
  559. # Various stuff important for logging requests
  560. my $domain = $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST} // eval { Sys::Hostname::hostname() };
  561. my $path = $env->{PATH_INFO} || '/';
  562. # de-pooplicate the path
  563. $path =~ s{//}{/}g;
  564. my $port = $env->{HTTP_X_FORWARDED_PORT} // $env->{HTTP_PORT};
  565. my $pport = defined $port ? ":$port" : "";
  566. my $scheme = $env->{'psgi.url_scheme'} // 'http';
  567. my $method = $env->{REQUEST_METHOD};
  568. # It's important that we log what the user ACTUALLY requested rather than the rewritten path later on.
  569. my $fullpath = "$scheme://$domain$pport$path";
  570. # So we can log it for fail2ban
  571. my $ip = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR};
  572. # set the referer & ua to go into DB logs, but not logs in general.
  573. # The referer/ua largely has no importance beyond being a proto bug report for log messages.
  574. my $referer = $env->{HTTP_REFERER};
  575. my $ua = $env->{HTTP_UA};
  576. $cur_query = {
  577. route => $path,
  578. fullpath => $path,
  579. method => $method,
  580. ip => $ip,
  581. ua => $ua,
  582. referer => $referer,
  583. tpsgi => $self,
  584. };
  585. # Paths with .. in them are not refused here, because starman appears to
  586. # refuse them already.
  587. # Support aliased paths
  588. my $aliases = $self->{aliases};
  589. $path = $aliases->{$path} if exists $aliases->{$path};
  590. # Check eTags. If we don't know about it, just assume it's good and lazily fill the cache
  591. # XXX yes, this allows cache poisoning...but only for logged in users!
  592. # This also needs to be IN DB so that we coordinate properly across forks
  593. if ( $env->{HTTP_IF_NONE_MATCH} ) {
  594. $self->INFO("$env->{REQUEST_METHOD} 304 $fullpath");
  595. return [ 304, [], [''] ] if $env->{HTTP_IF_NONE_MATCH} eq ( $etags{ $env->{REQUEST_URI} } || '' );
  596. $etags{ $env->{REQUEST_URI} } = $env->{HTTP_IF_NONE_MATCH} unless exists $etags{ $env->{REQUEST_URI} };
  597. }
  598. # TODO: Actually do something with the language passed to the renderer, HTTP_ACCEPT_LANGUAGE
  599. # TODO: Actually do something with the acceptable output formats in the renderer, HTTP_ACCEPT
  600. my $last_fetch = 0;
  601. if ( $env->{HTTP_IF_MODIFIED_SINCE} ) {
  602. $last_fetch = DateTime::Format::HTTP->parse_datetime( $env->{HTTP_IF_MODIFIED_SINCE} )->epoch();
  603. }
  604. # Figure out if we want compression or not
  605. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  606. $alist =~ s/\s//g;
  607. my @accept_encodings = split( /,/, $alist );
  608. my $deflate = grep { 'gzip' eq $_ } @accept_encodings;
  609. # Set the IP of the request so we can fail2ban
  610. $self->{ip} = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR} || $self->{ip};
  611. # Make sure this works further down the line
  612. $env->{REMOTE_ADDR} = $env->{HTTP_X_FORWARDED_FOR} if $env->{HTTP_X_FORWARDED_FOR};
  613. my $streaming = $env->{'psgi.streaming'};
  614. # If we have an actual route, just use it.
  615. my $r = $self->routes;
  616. my $route_index = List::Util::first { ( $r->[$_] // '' ) eq $path } 0 .. scalar(@$r);
  617. my $route_actual;
  618. $route_actual = $r->[ $route_index + 1 ] if defined($route_index);
  619. # Might be a regexed route. Sort reversed so we try the longest routes first.
  620. if ( !$route_actual && @$r ) {
  621. my $matched = List::Util::first {
  622. # Here's where you want to use Regexp::Debugger in the context of call.pl to debug routes... EX:
  623. # perl ./call.pl GET /path/to/route
  624. match_route( $path, $r->[$_] );
  625. }
  626. 0 .. scalar(@$r) - 1;
  627. $route_actual = $r->[ $matched + 1 ] if defined($matched);
  628. }
  629. if ($route_actual) {
  630. return $self->route(
  631. $route_actual, $env,
  632. fullpath => $fullpath,
  633. path => $path,
  634. start => $start,
  635. last_fetch => $last_fetch,
  636. deflate => $deflate,
  637. domain => $domain,
  638. port => $port,
  639. );
  640. }
  641. # Do a case insensitive match, because osx and windows
  642. my $file_possible = $self->mangle_filename("www/$path");
  643. my $file_actual;
  644. $file_actual = $file_possible if -e $file_possible && !-d _;
  645. # Dirindices
  646. if ( -d $file_possible ) {
  647. foreach my $index ( @{ $self->indices } ) {
  648. next if $file_actual;
  649. my $dirindex = $self->mangle_filename("www$path/$index");
  650. $dirindex =~ s{//}{/}g;
  651. $file_actual = $dirindex if -e $dirindex && !-d _;
  652. }
  653. }
  654. my $file_is_cgi = appears_executable($file_actual);
  655. return $self->cgi( $env, $fullpath, $file_actual, $last_fetch ) if $file_is_cgi;
  656. $self->INFO( "Attempting to serve $fullpath [" . ( $file_possible // "" ) . "]" );
  657. my @ranges = parse_ranges($env);
  658. return $self->serve( $fullpath, $file_actual, $start, $streaming, \@ranges, $last_fetch, $deflate ) if $file_actual;
  659. return $self->notfound($cur_query);
  660. }
  661. =head2 mangle_filename($path) = STRING
  662. $path, lowercased on the systems whose filesystems ignore case.
  663. =cut
  664. sub mangle_filename {
  665. my ( $self, $path ) = @_;
  666. # XXX yes, you can have case sensitive OSX, but basically nobody enables that ever
  667. $path = lc($path) if List::Util::any { $^O eq $_ } qw{darwin MSWin32 dos};
  668. $self->DEBUG("Path mangled to $path");
  669. return $path;
  670. }
  671. =head2 parse_ranges($env) = LIST
  672. The byte ranges of the request's Range header, as ARRAY references of start
  673. and end. An end that the header leaves out is undef. If-Range without Range
  674. asks for the whole file.
  675. =cut
  676. sub parse_ranges {
  677. my $env = shift;
  678. # Handle HTTP range/streaming requests
  679. my $range;
  680. $range = $env->{HTTP_RANGE} || "bytes=0-" if $env->{HTTP_RANGE} || $env->{HTTP_IF_RANGE};
  681. my @ranges;
  682. if ($range) {
  683. $range =~ s{bytes=}{}g;
  684. push(
  685. @ranges,
  686. map { [ split( /-/, $_ ) ]; } split( /,/, $range )
  687. );
  688. }
  689. return @ranges;
  690. }
  691. my @executable_extensions = qw{cgi sh exe pl php py};
  692. =head2 appears_executable($path) = BOOL
  693. Whether $path is a CGI to run rather than a file to serve: it is executable,
  694. and it has no extension or one of C<cgi>, C<sh>, C<exe>, C<pl>, C<php> and C<py>.
  695. =cut
  696. sub appears_executable {
  697. my $subj = shift;
  698. # Definitely not executable if it does not exist!
  699. return 0 unless $subj;
  700. return 0 unless -x $subj; ## no critic (ProhibitFiletest_rwxRWX) -- whether to run it, not whether we may
  701. my ($extension) = $subj =~ m/[.](\S+)$/;
  702. return 1 if !$extension;
  703. return 1 if List::Util::any { $extension eq $_ } @executable_extensions;
  704. return 0;
  705. }
  706. =head2 route($route, $env, %request) = PSGI response
  707. Run the callback of $route that answers the request's content type, with the
  708. query that extract_query() builds. respond() calls it, with %request holding
  709. C<fullpath>, C<path>, C<start>, C<last_fetch>, C<deflate>, C<domain> and
  710. C<port>.
  711. =cut
  712. sub route {
  713. my ( $self, $route, $env, %request ) = @_;
  714. my ( $fullpath, $path, $start ) = @request{qw{fullpath path start}};
  715. $self->DEBUG( 'Executing route ' . $route->{pattern} );
  716. $route->{method} = $env->{REQUEST_METHOD} if $route->{method} eq '*';
  717. my $content_type = $env->{CONTENT_TYPE} || 'text/html'; # If not set, that's the assumption.
  718. return $self->badrequest($cur_query) unless List::Util::any { $_ eq $env->{REQUEST_METHOD} } grep { defined $_ } ( 'HEAD', $route->{method} );
  719. my $callback;
  720. if ( exists $route->{callbacks}{'*'} ) {
  721. $callback = $route->{callbacks}{'*'};
  722. }
  723. else {
  724. return $self->badrequest($cur_query) unless exists $route->{callbacks}{$content_type};
  725. $callback = $route->{callbacks}{$content_type};
  726. }
  727. my $streaming = $env->{'psgi.streaming'};
  728. # Build the query data for passing to a route.
  729. # GET, POST, URI captures, then explicit data overrides.
  730. my $query = {};
  731. # If we're running in CGI mode, leave everything as-is.
  732. $query = $self->extract_query( $path, $route, $env ) unless $route->{env};
  733. # We failed validation if $query isn't a hashref.
  734. return $query if ref $query eq 'ARRAY';
  735. # allow this stuff to survive down to the end of some routes
  736. $query->{last_fetched} = $request{last_fetch};
  737. $query->{deflate} = $request{deflate};
  738. $query->{streaming} = $streaming;
  739. my @ranges = parse_ranges($env);
  740. $query->{ranges} = \@ranges;
  741. $query->{start} = $start;
  742. # Put things to tv_interval in here for Server-Timing
  743. $query->{fullpath} = $fullpath;
  744. $query->{method} = $route->{method};
  745. $query->{route} = $path;
  746. $query->{cookies} = $env->{HTTP_COOKIE};
  747. $query->{dnt} = $env->{HTTP_DNT};
  748. $query->{nosellinfo} = $env->{HTTP_SEC_GPC};
  749. $query->{port} = $request{port};
  750. $query->{scheme} = $env->{'psgi.url_scheme'} // 'http';
  751. $query->{method} = $env->{REQUEST_METHOD};
  752. $query->{lang} = $env->{HTTP_ACCEPT_LANGUAGE};
  753. $query->{accept} = $env->{HTTP_ACCEPT};
  754. $query->{has_query} = !!$env->{QUERY_STRING};
  755. $query->{domain} = $request{domain};
  756. $query->{dispatcher} = $route;
  757. $query->{ip} = $cur_query->{ip};
  758. $query->{ua} = $cur_query->{ua};
  759. $query->{referer} = $cur_query->{referer};
  760. # This allows for better error handlers if we die in the route.
  761. $cur_query = $query;
  762. # Setup the CGI vars they expect IF requested
  763. local %ENV = ( %ENV, CGI::Emulate::PSGI->emulate_environment($env) ) if $route->{env};
  764. # Emulate mod_unique_id
  765. local $ENV{UNIQUE_ID} = UUID::uuid() if $route->{env};
  766. # Run any watch callbacks, and make this a truly 'dynamic' application if requested.
  767. $self->handle_changes();
  768. my $output = $callback->( $self, $query );
  769. # If it's streaming, just hand it off.
  770. # It's up to the caller to handle things like running post-close callbacks in this event.
  771. return $output if ref $output eq 'CODE';
  772. die "$fullpath returned no or malformed data!" unless ref $output eq 'ARRAY' && @$output == 3;
  773. my %headers = @{ $output->[1] };
  774. my $bytes = $headers{'Content-Length'} // '?';
  775. $self->INFO("$env->{REQUEST_METHOD} $output->[0] $bytes $fullpath");
  776. # Append server-timing headers if they aren't present
  777. my $tot = tv_interval($start) * 1000;
  778. push( @{ $output->[1] }, 'Server-Timing' => "app;dur=$tot" ) unless List::Util::any { $_ eq 'Server-Timing' } @{ $output->[1] };
  779. # In the event that we have post-close callbacks, go ahead and run them.
  780. return $self->stream_raw_psgi( $output, $query ) if @{ $self->{callbacks} };
  781. return $output;
  782. }
  783. =head2 extract_query($path, $route, $env) = HASHREF
  784. The query a route's callback is given: the query string, then the POST body,
  785. then the route's captures and its C<data>, each over the last. When the route
  786. names C<parameters>, a parameter that fails its validator, or one it does not
  787. name, gets a badrequest() instead.
  788. =cut
  789. sub extract_query {
  790. my ( $self, $path, $route, $env ) = @_;
  791. my $query;
  792. $query = URL::Encode::url_params_mixed( $env->{QUERY_STRING} ) if $env->{QUERY_STRING};
  793. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  794. if ( $env->{REQUEST_METHOD} eq 'POST' ) {
  795. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  796. while ( $env->{'psgi.input'}->read( my $buf, $CHUNK_SIZE ) ) {
  797. $body->add($buf);
  798. }
  799. @$query{ keys( %{ $body->param } ) } = values( %{ $body->param } );
  800. @$query{ keys( %{ $body->upload } ) } = values( %{ $body->upload } );
  801. }
  802. if ( ref $route->{captures} eq 'ARRAY' ) {
  803. my @captures = match_route( $path, $route->{pattern} );
  804. @$query{ @{ $route->{captures} } } = @captures;
  805. }
  806. if ( ref $route->{data} eq 'HASH' ) {
  807. @$query{ keys( %{ $route->{data} } ) } = values( %{ $route->{data} } );
  808. }
  809. # Now that we've parsed the query and know where we want to go,
  810. # we should (optionally) murder everything the route does not explicitly want, and validate what it does
  811. my $parameters = $route->{parameters};
  812. if ( ref $parameters eq 'HASH' && %$parameters ) {
  813. my @known_params = keys(%$parameters);
  814. for my $param (@known_params) {
  815. die "Invalid route definition for $path: parameter $param must correspond to a validation CODEREF." unless ref $parameters->{$param} eq 'CODE';
  816. # A missing parameter is not necessarily a problem.
  817. next unless $query->{$param};
  818. # But if we have it, and it's bad, nack it, so that scanners get fail2banned.
  819. $self->DEBUG("Rejected $path for bad query param $param");
  820. return $self->badrequest($query) unless $parameters->{$param}->( $query->{$param} );
  821. }
  822. # Without this logging will break.
  823. push( @known_params, qw{tpsgi ip ua user referer route dispatcher} );
  824. # Smack down passing of unnecessary fields; this catches bugs
  825. foreach my $field ( keys(%$query) ) {
  826. next if List::Util::any { $field eq $_ } @known_params;
  827. $self->WARN("Unexpected parameter $field passed");
  828. return $self->badrequest($query);
  829. }
  830. }
  831. return $query;
  832. }
  833. =head2 cgi($env, $fullpath, $file_actual, $last_fetch) = PSGI response
  834. Run $file_actual as a CGI. Read until we are done with headers, then pass off
  835. the filehandle to PSGI for streaming.
  836. =cut
  837. # TODO support compression
  838. sub cgi {
  839. my ( $self, $env, $fullpath, $file_actual, $last_fetch ) = @_;
  840. $self->INFO("Handoff $fullpath to $file_actual for cgi exec");
  841. # Setup the CGI vars they expect
  842. local %ENV = ( %ENV, CGI::Emulate::PSGI->emulate_environment($env) );
  843. # Running the CGI is the job. The handle is read to its end in the stream below.
  844. my $pid = open( my $out, '-|', $file_actual ) or die "Could not run $file_actual: $!"; ## no critic (ProhibitPipeOpen RequireBriefOpen)
  845. my ( $code, undef, %headers ) = extract_headers( $out, $last_fetch );
  846. $code //= 500;
  847. return sub {
  848. my $responder = shift;
  849. my $writer = $responder->( [ $code, [%headers] ] );
  850. while ( $out->read( my $buf, $CHUNK_SIZE ) ) {
  851. $writer->write($buf);
  852. }
  853. $writer->close;
  854. # Wait on the CGI script to do whatever it's doing after closing stdout
  855. close($out) or $self->WARN("$file_actual exited with status $?");
  856. waitpid( $pid, 0 );
  857. };
  858. }
  859. =head2 stream_raw_cgi($cgi)
  860. Run the perl file $cgi in this process, as a CGI: its STDIN is the request body,
  861. and what it prints goes to the client. The worker exits when it is done.
  862. Use when you just have a .cgi file you want to run without pipe-open.
  863. XXX this is extraordinarily unsafe, inefficient and kills workers.
  864. XXX it also has an 'apache-ism' of just assigning the HTTP status line for you.
  865. But sometimes you have to bite the bullet and do this to migrate stuff effectively.
  866. =cut
  867. sub stream_raw_cgi {
  868. my ( $self, $cgi ) = @_;
  869. # Discard STDIN in favor of the HTTP body. Not localized, because this
  870. # process exits at the end of this sub.
  871. close(STDIN) or $self->DEBUG("STDIN was not open: $!");
  872. *STDIN = $self->{input}; ## no critic (RequireLocalizedPunctuationVars)
  873. # Similarly make 'print' do what CGIs expect
  874. my $fh = $self->{filehandle};
  875. select($fh); ## no critic (ProhibitOneArgSelect)
  876. do($cgi);
  877. # We may or may not actually get here.
  878. close($fh) or $self->WARN("Could not close the response: $!") if $fh;
  879. exit 0;
  880. }
  881. =head2 stream_raw_psgi($response, $query)
  882. Write the PSGI $response straight to the client's socket, close it, then run
  883. the callbacks that add_post_close_callback() queued. route() does this when
  884. there are any. The worker exits when it is done.
  885. =cut
  886. sub stream_raw_psgi {
  887. my ( $self, $response, $data ) = @_;
  888. my $time_to_here = tv_interval( $data->{start} );
  889. $self->DEBUG("Routing took $time_to_here s");
  890. my $post_routing = [gettimeofday];
  891. my $fh = $self->{filehandle};
  892. my $head = "HTTP/1.1 $response->[0]\n";
  893. # Emit the rest of the headers
  894. foreach ( my $i = 0; $i < @{ $response->[1] }; $i += 2 ) {
  895. my $header = $response->[1][$i];
  896. my $value = $response->[1][ $i + 1 ];
  897. $head .= "$header: $value\n";
  898. }
  899. # Then the body
  900. print {$fh} "$head\n", $response->[2][0];
  901. close($fh) or $self->WARN("Could not close the response: $!");
  902. $self->DEBUG( "Response written in " . ( tv_interval($post_routing) ) . " s" );
  903. while ( my $callback = shift @{ $self->{callbacks} } ) {
  904. if ( ref $callback eq 'CODE' ) {
  905. my $post_start = [gettimeofday];
  906. local $@;
  907. eval { $callback->(); 1 } or $self->ERROR("Post-close callback encountered exception: $@");
  908. $self->DEBUG( "Post-close callback took " . ( tv_interval($post_start) ) . " s" );
  909. }
  910. }
  911. exit 0;
  912. }
  913. =head2 stream_raw_http($query, $last_fetch, $to_fork, $callback, $error_handler)
  914. Answer with a 200 whose headers and body a forked child prints: $to_fork runs
  915. in the child with the client's socket selected, and then $error_handler, when
  916. there is one. Once the child exits and the socket is closed, $callback runs.
  917. The worker exits when it is done.
  918. =cut
  919. sub stream_raw_http { ## no critic (ProhibitManyArgs) -- routers call it with these, in this order
  920. my ( $self, $data, $last_fetch, $to_fork, $callback, $error_handler ) = @_;
  921. my $time_to_here = tv_interval( $data->{start} );
  922. $self->DEBUG("Routing took $time_to_here s");
  923. my $post_routing = [gettimeofday];
  924. my $fh = $self->{filehandle};
  925. # The CGIs you are executing here SHOULD NOT emit a status line.
  926. # Most apache CGIs you find don't anyways, so this is usually not a big deal.
  927. # Then our server-timing header.
  928. print {$fh} "HTTP/1.1 200 OK\n", "Server-Timing: " . $self->build_server_timing($data) . "\n";
  929. # We *must* fork because we can't rely on the child to close stdout.
  930. $fh->autoflush(1);
  931. my $pid = fork() // die "Could not fork child";
  932. if ( $pid == 0 ) {
  933. # So that what the child prints goes to the client.
  934. select($fh); ## no critic (ProhibitOneArgSelect)
  935. $self->DEBUG( "Forking child took" . ( tv_interval($post_routing) ) . " s" );
  936. local $@;
  937. eval { $to_fork->(); 1 } or $self->ERROR("Raw HTTTP streaming encountered exception: $@");
  938. if ( ref $error_handler eq 'CODE' ) {
  939. local $@;
  940. eval { $error_handler->(); 1 } or $self->ERROR("HTTP streaming error handler encountered exception: $@");
  941. }
  942. exit 0;
  943. }
  944. waitpid( $pid, 0 );
  945. close($fh) or $self->WARN("Could not close the response: $!");
  946. $self->DEBUG( "Response written in " . ( tv_interval($post_routing) ) . " s" );
  947. if ( ref $callback eq 'CODE' ) {
  948. my $post_start = [gettimeofday];
  949. local $@;
  950. eval { $callback->(); 1 } or $self->ERROR("Post-close callback encountered exception: $@");
  951. $self->DEBUG( "Post-close callback took " . ( tv_interval($post_start) ) . " s" );
  952. }
  953. exit 0;
  954. }
  955. =head2 extract_headers($fh, $last_fetch)
  956. Extract the headers from a filehandle. Set the 'Last Modified' header appropriately based on the output of `stat` on the filehandle.
  957. 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.
  958. =cut
  959. sub extract_headers {
  960. my ( $fh, $last_fetch, $is_ref ) = @_;
  961. my $headers = '';
  962. # NOTE: this is relying on while advancing the file pointer
  963. while (<$fh>) {
  964. last if $_ eq "\n";
  965. $headers .= $_;
  966. }
  967. #XXX still a toctou
  968. my $offset = $fh->tell();
  969. my ( undef, undef, $status, undef, $headers_parsed ) = HTTP::Parser::XS::parse_http_response( "$headers\n", HEADERS_AS_HASHREF );
  970. my $code = $status // 200;
  971. $headers_parsed //= {};
  972. if ( !$is_ref ) {
  973. my $mt = ( stat($fh) )[9];
  974. my @gm = gmtime($mt);
  975. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  976. $code = $mt > $last_fetch ? $status : 304;
  977. $headers_parsed->{"Last-Modified"} = $now_string;
  978. }
  979. return ( $code, $offset, %$headers_parsed );
  980. }
  981. =head2 static($fullpath, $path, $start, $streaming, $last_fetch) = PSGI response
  982. Answer with the static render of $path that save_render() made, headers and
  983. all, or forbidden() when there is none.
  984. =cut
  985. sub static { ## no critic (ProhibitManyArgs) -- routers call it with these, in this order
  986. my ( $self, $fullpath, $path, $start, $streaming, $last_fetch ) = @_;
  987. $self->DEBUG("Rendering static for $path");
  988. # XXX because of psgi I can't just vomit the file directly
  989. # The handle is the body of the response, so the server closes it.
  990. if ( open( my $fh, '<', "statics/$path" ) ) { ## no critic (RequireBriefOpen)
  991. my ( $code, $offset, $headers_parsed ) = ( 200, undef, {} );
  992. ( $code, $offset, %$headers_parsed ) = extract_headers( $fh, $last_fetch );
  993. # Append server-timing headers
  994. my $tot = tv_interval($start) * 1000;
  995. $headers_parsed->{'Server-Timing'} = "static;dur=$tot";
  996. #XXX uwsgi just opens the file *again* when we already have a filehandle if it has a path.
  997. # starman by comparison doesn't violate the principle of least astonishment here.
  998. # This is probably a performance optimization, but makes the kind of micromanagement I need to do inconvenient.
  999. # As such, we will just return a stream.
  1000. $self->INFO("GET 200 $headers_parsed->{'Content-Length'} $fullpath");
  1001. return sub {
  1002. my $responder = shift;
  1003. #push(@headers, 'Content-Length' => $sz);
  1004. my $writer = $responder->( [ $code, [%$headers_parsed] ] );
  1005. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  1006. $writer->write($buf);
  1007. }
  1008. close($fh) or $self->WARN("Could not close statics/$path: $!");
  1009. $writer->close;
  1010. }
  1011. if $streaming;
  1012. return [ $code, [%$headers_parsed], $fh ];
  1013. }
  1014. return $self->forbidden( $self->{current_query} );
  1015. }
  1016. =head2 get_config() = HASH
  1017. TPSGI::Startup::get_config(): F<~/.tpsgi.ini>, over the defaults.
  1018. =cut
  1019. sub get_config { return TPSGI::Startup::get_config() }
  1020. =head2 checkpoint($query, $name)
  1021. Mark the time as $name, for the Server-Timing header that
  1022. build_server_timing() makes.
  1023. =cut
  1024. sub checkpoint {
  1025. my ( $self, $data, $name ) = @_;
  1026. $data->{checkpoints} //= [ [ start => $data->{start} ] ];
  1027. push( @{ $data->{checkpoints} }, [ $name => [gettimeofday] ] );
  1028. return;
  1029. }
  1030. =head2 build_server_timing($query) = STRING
  1031. A Server-Timing header value: how long each checkpoint() took after the one
  1032. before it, and the total since the request started.
  1033. =cut
  1034. sub build_server_timing {
  1035. my ( $self, $data ) = @_;
  1036. my @st;
  1037. my $last_interval;
  1038. foreach my $checkpoint ( @{ $data->{checkpoints} } ) {
  1039. if ($last_interval) {
  1040. my $dur = tv_interval( $last_interval, $checkpoint->[1] ) * 1000;
  1041. push( @st, "$checkpoint->[0];dur=$dur" );
  1042. }
  1043. $last_interval = $checkpoint->[1];
  1044. }
  1045. my $tot = tv_interval( $data->{start} ) * 1000;
  1046. push( @st, "tot;dur=$tot" );
  1047. delete $data->{checkpoints};
  1048. return join( ', ', @st );
  1049. }
  1050. =head2 add_post_close_callback()
  1051. Add a thing to do after closing stdout; useful for housekeeping that doesn't need to hold up pageload.
  1052. =cut
  1053. sub add_post_close_callback {
  1054. my ( $self, $cb ) = @_;
  1055. push( @{ $self->{callbacks} }, $cb );
  1056. return;
  1057. }
  1058. =head2 signal_restart_parent()
  1059. Instruct tPSGI to reload after closing stdout.
  1060. =cut
  1061. sub signal_restart_parent {
  1062. my ($self) = @_;
  1063. $self->add_post_close_callback( sub { kill 'HUP', getppid } );
  1064. return;
  1065. }
  1066. =head2 save_render($path, $extension, $body)
  1067. Save a static render of the page.
  1068. Good to queue after closing stdout.
  1069. Passed file extension slapped on the end of the path.
  1070. You can then serve them as statics with an appropriately done try_files block in nginx.
  1071. =cut
  1072. # Remove one static render.
  1073. my sub invalidate_file {
  1074. my ( $self, $file ) = @_;
  1075. $self->INFO("Remove static render $file");
  1076. return unlink $file;
  1077. }
  1078. # fixup matrix
  1079. my %fixup = (
  1080. text => 'txt',
  1081. blob => 'bin',
  1082. );
  1083. sub save_render {
  1084. my ( $self, $path, $extension, $body ) = @_;
  1085. return unless $path && $extension;
  1086. # If this is an index, let's make it so
  1087. if ( $path =~ m{/$} ) {
  1088. $path = $path . 'index';
  1089. }
  1090. # Fixup the extension if needed.
  1091. $extension = $fixup{$extension} if exists $fixup{$extension};
  1092. my $path_fixed = $path;
  1093. $path_fixed =~ s/[.]\Q$extension\E$//;
  1094. $path_fixed = "$path_fixed.$extension";
  1095. my $path2file = "$self->{tpsgi_dir}/www/static/" . dirname($path_fixed);
  1096. if ( !-d $path2file ) {
  1097. File::Path::make_path( $path2file, { user => $<, group => $self->{gid}, chmod => 0o755 } ) or die "Could not create directory $path2file";
  1098. }
  1099. my $file = "$self->{tpsgi_dir}/www/static/$path_fixed";
  1100. my $verb = -e $file ? 'Overwrite' : 'Write';
  1101. $self->INFO("$verb $path as static/$path_fixed");
  1102. open( my $fh, '>', $file ) or die "Could not open $file for writing";
  1103. print {$fh} $body;
  1104. close($fh) or die "Could not write $file: $!";
  1105. chmod( 0755, $file );
  1106. chown( $<, $self->{gid}, $file );
  1107. return;
  1108. }
  1109. =head2 invalidate_render($path, $extension)
  1110. Remove an existing static render of a path.
  1111. =cut
  1112. sub invalidate_render {
  1113. my ( $self, $path, $extension ) = @_;
  1114. return unless $path && $extension;
  1115. # Fixup the extension if needed.
  1116. $extension = $fixup{$extension} if exists $fixup{$extension};
  1117. my $path_fixed = $path;
  1118. $path_fixed =~ s/[.]\Q$extension\E$//;
  1119. $path_fixed = "$path_fixed.$extension";
  1120. my $file = "$self->{tpsgi_dir}/www/static/$path_fixed";
  1121. return unless -e $file;
  1122. return invalidate_file( $self, $file );
  1123. }
  1124. =head2 invalidate_renders($extension)
  1125. Remove all existing static renders with the provided extension.
  1126. Useful when it's not easy to figure out what to re-render due to including templates in other templates, etc.
  1127. =cut
  1128. sub invalidate_renders {
  1129. my ( $self, $extension ) = @_;
  1130. File::Find::find(
  1131. {
  1132. wanted => sub {
  1133. my $object = $_;
  1134. invalidate_file( $self, $object ) if ( !-d $object && $object =~ m/[.]\Q$extension\E$/ );
  1135. },
  1136. no_chdir => 1,
  1137. bydepth => 1,
  1138. },
  1139. "$self->{tpsgi_dir}/www/static/"
  1140. );
  1141. return;
  1142. }
  1143. =head2 watch_for_changes(@dirs)
  1144. TPSGI::Startup::watch_for_changes(), which watches the .pm files under @dirs for
  1145. autoreload. A function, not a method.
  1146. =cut
  1147. sub watch_for_changes {
  1148. my (@dirs) = @_;
  1149. return TPSGI::Startup::watch_for_changes(@dirs);
  1150. }
  1151. =head2 add_watch($path, $callback, %options)
  1152. Add an arbitrary file or directory to the inotify watchlist, along with a
  1153. callback to run when it changes. Returns the inotify watch descriptor.
  1154. The callback is invoked as:
  1155. $callback->( $tpsgi, $change );
  1156. ...where $change is a HASH reference describing what happened:
  1157. path => full path of the thing which changed
  1158. watched => the path the watch was registered against
  1159. events => ARRAY reference of event names, e.g. [ 'MODIFY' ]
  1160. name => entry within a watched directory, if the watch was on a directory
  1161. wd => inotify watch descriptor
  1162. mask => raw inotify event mask
  1163. Which makes the common case - blowing away a static render because the thing it
  1164. was generated from changed - look like:
  1165. $tpsgi->add_watch( "data/posts.json", sub {
  1166. my ( $tpsgi, $change ) = @_;
  1167. $tpsgi->invalidate_renders('html');
  1168. });
  1169. %options are passed through to TPSGI::Startup::add_watch, so you may also pass
  1170. 'events' (defaults to CREATE, MODIFY, DELETE and MOVE) and 'key' (an explicit
  1171. dedupe key for the callback).
  1172. Some caveats worth knowing about:
  1173. =over
  1174. =item * Watches live in the inotify instance tarbaby sets up before forking, and
  1175. are therefore shared by every worker. Whichever worker notices a change first
  1176. consumes it for all of them, so register the same callbacks in every worker
  1177. (declare them in your router module, which every worker loads) and make sure
  1178. they're safe to run in any worker.
  1179. =item * Changes are only noticed when a request comes in, since nothing is
  1180. sitting in a select loop over the inotify FD. Renders are invalidated promptly
  1181. in practice, but not instantly.
  1182. =item * Watching a directory rather than a single file is more robust, as
  1183. watching a file which is later replaced wholesale (the usual write-tempfile-then-
  1184. rename dance) only survives because we re-establish the watch afterwards. If
  1185. the file is deleted and not immediately recreated, the watch is gone for good.
  1186. =back
  1187. =cut
  1188. sub add_watch {
  1189. my ( $self, $path, $callback, %options ) = @_;
  1190. my $existing = TPSGI::Startup::is_watched($path);
  1191. # A watch we can't establish (the usual cause being a path which isn't there yet)
  1192. # shouldn't be fatal to the request which happened to be the one registering it.
  1193. local $@;
  1194. my $wd = eval {
  1195. TPSGI::Startup::add_watch(
  1196. %options,
  1197. path => $path,
  1198. callback => $callback,
  1199. );
  1200. };
  1201. if ( !defined $wd ) {
  1202. my $why = $@;
  1203. $why =~ s/\n.*// if $why;
  1204. $self->WARN("Could not watch $path for changes: $why");
  1205. return undef;
  1206. }
  1207. $self->DEBUG("Watching $path for changes") unless $existing;
  1208. return $wd;
  1209. }
  1210. =head2 remove_watch($path)
  1211. Drop a path, and any callbacks registered against it, from the watchlist.
  1212. =cut
  1213. sub remove_watch {
  1214. my ( $self, $path ) = @_;
  1215. return TPSGI::Startup::remove_watch($path);
  1216. }
  1217. =head2 handle_changes
  1218. Drain the inotify queue, running the callbacks registered for whatever changed,
  1219. and restart tPSGI if any of the relevant libdir files changed (assuming
  1220. autoreload is on). Powers both the autorestart feature and app-registered
  1221. watches.
  1222. =cut
  1223. sub handle_changes {
  1224. my $self = shift;
  1225. my @changes = TPSGI::Startup::pending_changes();
  1226. return 0 unless @changes;
  1227. my $had_changes = 0;
  1228. my @rewatch;
  1229. foreach my $change (@changes) {
  1230. my $watch = $change->{watch};
  1231. # A watch descriptor we know nothing about belongs to a worker which registered
  1232. # watches we didn't. All we can sensibly do with those is the old behavior.
  1233. if ( !$watch ) {
  1234. $had_changes++ if $change->{path} =~ m/[.]pm$/;
  1235. next;
  1236. }
  1237. $had_changes++ if $watch->{restart} && $change->{path} =~ m/[.]pm$/;
  1238. foreach my $cb ( @{ $watch->{callbacks} } ) {
  1239. local $@;
  1240. my $ok = eval { $cb->{code}->( $self, $change ); 1 };
  1241. $self->WARN("Watch callback for $change->{path} died: $@") unless $ok;
  1242. }
  1243. # The kernel drops watches on files which get replaced or deleted, so put them back.
  1244. push( @rewatch, $change->{wd} ) if List::Util::any { $_ eq 'IGNORED' } @{ $change->{events} };
  1245. }
  1246. TPSGI::Startup::rewatch($_) foreach @rewatch;
  1247. return 0 unless $had_changes && $self->{autoreload};
  1248. # We don't have to clean up the wds, that is handled in the destructor for Inotify
  1249. $self->INFO("Relevant Change in libdirs detected, reloading\n");
  1250. $self->signal_restart_parent();
  1251. return 0;
  1252. }
  1253. =head2 restart_if_changes
  1254. Deprecated alias for handle_changes().
  1255. =cut
  1256. sub restart_if_changes { goto &handle_changes }
  1257. 1;
  1258. __END__
  1259. =head1 SYNOPSIS
  1260. A router module, which C<routers> in F<~/.tpsgi.ini> names:
  1261. package My::Routes;
  1262. our @routes = (
  1263. '/hello' => {
  1264. method => 'GET',
  1265. callbacks => { 'text/html' => \&hello },
  1266. },
  1267. );
  1268. sub hello {
  1269. my ( $tpsgi, $query ) = @_;
  1270. return [ 200, [ 'Content-Type' => 'text/html' ], ['Hello world'] ];
  1271. }
  1272. =head1 DESCRIPTION
  1273. Start it with the Starman options you want, from the directory of the
  1274. application, with tarbaby on the PATH:
  1275. tpsgi ... [starman args]
  1276. A PSGI server built to migrate old mod_perl/apache stacks onto psgi, and that powers tCMS.
  1277. Will execute any executable file (chmod +x) in www/ as CGI, and otherwise host any static file therein.
  1278. The idea here is as a bridge between old and new which allows you to modernize at your own pace, gradually turning CGIs into routes.
  1279. The other idea is that we don't want to add any extra abstraction if we don't have to, while gently guiding into better practices.
  1280. Shops used to having full control over the HTTP response should continue to do so, rather than being locked into one framework or another.
  1281. This allows them to continue doing whatever funky thing they have been doing, like COMET, et cetera.
  1282. The best way to do that is to expect raw PSGI to be output.
  1283. =head1 CONFIGURATION
  1284. Obeys ~/.tpsgi.ini -- this is what will control all the custom aspects mentioned below:
  1285. verbose : Whether to print all log messages or not
  1286. custom_log : Custom location for default (rotated) log
  1287. routers : Router module(s), separate with comma. Relative to TPSGI install dir.
  1288. indices : Dirindex files. In addition to index.html, index.htm, index.cgi
  1289. loggers : Logger module(s), separate with comma. Each is a Log::Dispatch::Output class. tPSGI loads it by name, so it can live beside a router
  1290. auth : Authentication module
  1291. domain : Domain name of the application, used by things like service files
  1292. basedir : Directory you want to chdir into on startup. Relative to TPSGI install dir. Default '.'
  1293. user : Who to run as
  1294. http_user : Who's proxying this application (used for statics)
  1295. autoreload : Whether or not to automatically reload the application when library files change. Default 0.
  1296. You can run bin/tpsgi-config to get any config value needed by scripts.
  1297. We wrap starman with a custom script, C<bin/tarbaby> that implements Plack::Loader::Reload far less dangerously.
  1298. It only reloads the code relevant to tPSGI and your application itself.
  1299. All the CPAN deps should be updated out-of-band and the service manually restarted, as this is far more fraught.
  1300. =head1 CUSTOM ROUTING
  1301. All passed routing modules will be required, and combined to form a routing table so you have an analogue to rewrite rules.
  1302. Routing Modules look like so:
  1303. our @routes = (
  1304. '/foo/(\w+)/save' => {
  1305. method => 'GET',
  1306. callbacks => { # Run these subroutines to execute the appropriate handler given the content-type. Expects normal PSGI output.
  1307. 'text/html' => \&render,
  1308. 'application/json' => \&dump,
  1309. },
  1310. noindex => 0, # Explicitly exclude this in robots.txt
  1311. nomap => 0, # Don't put this in the sitemap
  1312. acls => ['admin'], # Route requires both authentication by auth handler and the auth'd user to have the provided ACLs.
  1313. data => { baz => 'throb' }, # Arbitrary data to inject into the GET/POST data hashref
  1314. captures => ['name','parameter'], # Name parameters of the capture groups in the route key. Suppose we want /foo/don/keys here.
  1315. static => 1, # Whether we can save a static render of this
  1316. invalidates => ['/foo/(\w+)'], # Static renders which are invalidated by this route returning a successful response code.
  1317. },
  1318. ...
  1319. );
  1320. Note that this is an array, as we want this to preserve order. Fat commas are used to hint that this is in fact a tuple.
  1321. Router callbacks are passed the TPSGI object and the raw query, which means you can do:
  1322. sub route {
  1323. my ($self, $query) = @_;
  1324. $self->INFO("whatever");
  1325. $self->ERROR("eeee");
  1326. $self->DEBUG("blah");
  1327. # Either from the GET or POST data, POST is preferred when both are present.
  1328. my $param = $query->{param};
  1329. my %headers = ...;
  1330. return [200, \%headers, ["Hello world"]]
  1331. }
  1332. =head1 WATCHING FILES FOR CHANGES
  1333. tPSGI already watches your library directories with inotify so that it can reload itself when your
  1334. code changes. Your application can put arbitrary files and directories onto that same watchlist,
  1335. along with a callback to run when they change. The usual reason to want this is throwing away a
  1336. static render because the thing it was generated from changed underneath it.
  1337. Routing modules declare these the same way they declare routes:
  1338. our %watches = (
  1339. # A bare coderef is the common case: run this when the path changes.
  1340. 'data/posts.json' => sub {
  1341. my ($tpsgi, $change) = @_;
  1342. $tpsgi->invalidate_renders('html');
  1343. },
  1344. # Or spell it out if you want to be picky about which events you care about.
  1345. 'www/assets' => {
  1346. callback => \&asset_changed,
  1347. events => [qw{CREATE MOVE}],
  1348. },
  1349. );
  1350. ...or register them at runtime with C<< $tpsgi->add_watch($path, $callback, %options) >>, and drop them
  1351. again with C<< $tpsgi->remove_watch($path) >>.
  1352. Callbacks are passed the TPSGI object and a hashref describing what happened:
  1353. sub asset_changed {
  1354. my ($tpsgi, $change) = @_;
  1355. $change->{path}; # full path of the thing which changed
  1356. $change->{watched}; # the path the watch was registered against
  1357. $change->{events}; # arrayref of event names, e.g. ['MODIFY']
  1358. $tpsgi->invalidate_render($change->{path}, 'html');
  1359. }
  1360. A few things worth knowing:
  1361. =over
  1362. =item *
  1363. Watches are shared by every worker, so whichever worker notices a change first consumes it for all
  1364. of them. Declare your watches in your routing module (which every worker loads) rather than from
  1365. inside a single route, and make the callbacks safe to run in any worker.
  1366. =item *
  1367. Nothing sits in a select loop over the inotify descriptor, so changes are noticed when the next
  1368. request comes in. Prompt, but not instant.
  1369. =item *
  1370. Watching the containing directory is more robust than watching a single file. Watches on files
  1371. which get replaced wholesale (write a tempfile, rename over the target) are re-established
  1372. afterwards, but a file which is deleted and not recreated takes its watch with it.
  1373. =back
  1374. =head1 CUSTOM AUTHENTICATION HANDLING
  1375. The (optional) Authentication handler can be passed, and look like so:
  1376. package Auth::Handler;
  1377. # Is user who they say they are
  1378. sub authenticate {
  1379. my (%auth_payload) = @_;
  1380. ...
  1381. return ($session_cookie);
  1382. }
  1383. # is the user authorized to do $thing
  1384. sub authorized {
  1385. my ($user, $priv) = @_;
  1386. ...
  1387. return 1 || 0;
  1388. }
  1389. # Available ACLs
  1390. sub acls {
  1391. ...
  1392. return %acls;
  1393. }
  1394. # Dump acls for user
  1395. sub acls_for_user {
  1396. my $user = shift;
  1397. ...
  1398. return %acls;
  1399. }
  1400. # What is the user for this session token
  1401. sub user_for_session {
  1402. my $session = shift;
  1403. ...
  1404. return $user;
  1405. }
  1406. In the event that auth or route handlers are found, these events will be noted in the startup log.
  1407. =head1 LOGGING
  1408. By default we have two log handlers...which you can augment with your own, based on Log::Dispatch.
  1409. The first default is to print ERROR and worse to the STDOUT of the PSGI server.
  1410. The other is to emit INFO or better to logs/tpsgi.log
  1411. Pass your own dispatch subclasses and watch it go whir.
  1412. =head1 SERVICE CONFIGURATION
  1413. Proper operation of this as a production service requires some things:
  1414. =over
  1415. =item 1.
  1416. You have a user which has this repository as their home directory.
  1417. =item 2.
  1418. You run the shell script, tpsgi.sh in service/ to run this as a service.
  1419. =item 3.
  1420. You set the username and the domain name of the service in .tpsgi.ini
  1421. =item 4.
  1422. You set your PATH appropriately to pick up on things like custom perls in a .bashrc
  1423. =item 5.
  1424. You set the group of your reverse proxy application in .tpsgi.ini (the http_user variable)
  1425. =back
  1426. run service/tpsgi.sh as root and you should be set supposing the above is true.
  1427. In general the operation is like so:
  1428. =over
  1429. =item 1.
  1430. nginx (or whatever) looks for a sock file owned $USER:$WEB_GROUP, and reverse proxies to this
  1431. =item 2.
  1432. tpsgi is actively listening on this sock file.
  1433. =back
  1434. Generally you'll just run bin/build_service and then systemctl start $domain.
  1435. It's configured to start as root, then drop privs thanks to Net::Server's capabilities inherited in starman.
  1436. =head2 Secrets the application needs
  1437. An application often needs a key or a password that has no business living in
  1438. its own checkout, where it would go into every backup alongside whatever it
  1439. protects. bin/build_service makes one and puts it in systemd's credential
  1440. store; the unit imports it and service/tpsgi.sh hands it on.
  1441. You do not have to do anything for this. build_service writes
  1442. C</etc/credstore.encrypted/tpsgi-vault> if it is not there already, encrypted
  1443. with C<systemd-creds --with-key=auto>: sealed to the TPM when the machine has a
  1444. usable one, and to the host key when it does not. It says which you got, since
  1445. that is the difference between a stolen disk being useless and a stolen disk
  1446. being a stolen key. An existing key is left alone.
  1447. systemd decrypts it into a ramdisk at C</run/credentials/$service> that only this
  1448. service can read. Nothing breaks if it is not there: C<ImportCredential=> is
  1449. quiet about a credential that does not exist, so an installation whose
  1450. application wants no secrets starts normally.
  1451. The workers are chrooted into the application directory and that ramdisk is
  1452. outside it, so service/tpsgi.sh reads the credential before the chroot happens
  1453. and exports it -- C<tpsgi-vault> becomes C<TPSGI_VAULT_KEY>. An application taking
  1454. one is expected to read it out of its environment as it starts and delete it
  1455. there and then, so that nothing it forks afterwards inherits it.
  1456. It is named for tPSGI rather than for whatever is being served, because this is
  1457. tPSGI's unit and one service is one application in one directory.
  1458. The key is not backed up and cannot be recovered. That is deliberate: it lives
  1459. and dies with the machine, so that it is never sitting in the same backup as the
  1460. data it protects. Rebuilding the host means whatever was sealed under it is
  1461. gone and gets stored again.
  1462. =cut