TPSGI.pm 64 KB

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