TPSGI.pm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. package TPSGI;
  2. # Abstract: Abstraction layer around starman to become a general purpose HTTP server
  3. use strict;
  4. use warnings;
  5. use feature qw{state};
  6. use FindBin;
  7. use Cwd();
  8. use Carp::Always;
  9. use UUID();
  10. use POSIX();
  11. use Mojo::File;
  12. use Plack::MIME;
  13. use IO::Compress::Gzip;
  14. use Time::HiRes qw{usleep gettimeofday tv_interval};
  15. # For CGI features
  16. use HTTP::Parser::XS qw{HEADERS_AS_HASHREF};
  17. use CGI::Emulate::PSGI;
  18. use Date::Format qw{strftime};
  19. use List::Util();
  20. use File::Find;
  21. use Sys::Hostname();
  22. use Plack::MIME ();
  23. use DateTime::Format::HTTP();
  24. use URL::Encode();
  25. use File::Touch;
  26. use File::Path;
  27. use Cwd qw{abs_path};
  28. use File::Basename qw{dirname basename};
  29. use Log::Dispatch;
  30. use Log::Dispatch::Screen;
  31. use Log::Dispatch::FileRotate;
  32. use Config::Simple;
  33. # Generally we want the users to be able to DB::enable_profile() and DB::disable_profile() as they choose.
  34. BEGIN {
  35. # If we have manually set the NYTPROF var, use it and don't try to control
  36. # When to stop or start it.
  37. my $basedir = Cwd::abs_path("$FindBin::Bin");
  38. $ENV{NYTPROF} ||= "sigexit=1:savesrc=0:start=no:file=$basedir/prof/nytprof.out";
  39. require Devel::NYTProf;
  40. mkdir "$basedir/prof";
  41. }
  42. # We have a DEBUG var which is plus ultra for extra sensitive stuff beyond just passing verbose
  43. my $debug = $ENV{TPSGI_DEBUG};
  44. #1MB chunks
  45. our $CHUNK_SEP = 'perlfsSep666YOLO42069';
  46. our $CHUNK_SIZE = 1024000;
  47. our %content_types = (
  48. text => "text/plain",
  49. html => "text/html",
  50. json => "application/json",
  51. blob => "application/octet-stream",
  52. xml => "text/xml",
  53. xsl => "text/xsl",
  54. css => "text/css",
  55. rss => "application/rss+xml",
  56. email => "multipart/related",
  57. );
  58. our %byct = reverse %content_types;
  59. our %cache_control = (
  60. revalidate => "no-cache, max-age=0",
  61. nocache => "no-store",
  62. static => "public, max-age=604800, immutable",
  63. );
  64. #TODO consider integrating libfile
  65. #Stuff that isn't in upstream finders
  66. my %extra_types = (
  67. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  68. );
  69. my $ct = 'Content-type';
  70. #memoize
  71. my $rq;
  72. sub request_id {
  73. my ($self, $regenerate) = @_;
  74. return $self->{uuid} if $self->{uuid} && !$regenerate;
  75. $self->{uuid} = UUID::uuid();
  76. return $self->{uuid};
  77. }
  78. sub log {
  79. my $self = shift;
  80. state $log;
  81. return $log if $log;
  82. my $LOGNAME = abs_path('.').'/log/tpsgi.log';
  83. $LOGNAME = $self->{custom_log} if $self->{custom_log};
  84. my $LOGDIR = dirname($LOGNAME);
  85. File::Path::make_path($LOGDIR) unless -d $LOGDIR;
  86. File::Touch::touch($LOGNAME) unless -f $LOGNAME;
  87. my $LEVEL = $self->{verbose} ? 'debug' : 'info';
  88. # By default only log requests & warnings.
  89. # Otherwise emit debug messages.
  90. my $rotate = Log::Dispatch::FileRotate->new(
  91. name => 'tcms',
  92. filename => $LOGNAME,
  93. min_level => $LEVEL,
  94. 'mode' => 'append',
  95. size => 10 * 1024 * 1024,
  96. max => 6,
  97. );
  98. # Only send fatal events/errors to stdout
  99. my $screen = Log::Dispatch::Screen->new(
  100. name => 'screen',
  101. min_level => $LEVEL,
  102. );
  103. $log = Log::Dispatch->new();
  104. $log->add($rotate);
  105. $log->add($screen);
  106. foreach my $logger (@{$self->{loggers}}) {
  107. $log->add($logger->new( min_level => $LEVEL, log_dir => $LOGDIR ));
  108. }
  109. $log->info( $self->_log("Opening Log $LOGNAME at $LEVEL level") );
  110. return $log;
  111. }
  112. sub _log {
  113. my ( $self, $msg ) = @_;
  114. $msg //= "No message passed. This is almost certainly a bug. ";
  115. #XXX Log lines must start as an ISO8601 date, anything else breaks fail2ban's beautiful mind
  116. my $tstamp = POSIX::strftime "%Y-%m-%dT%H:%M:%SZ", gmtime;
  117. my $uuid = $self->request_id();
  118. return "[Worker $$] {Request $uuid} $tstamp : $self->{ip} $msg\n";
  119. }
  120. # Logger short cuts
  121. sub DEBUG {
  122. my $self = shift;
  123. $self->log->debug( $self->_log( shift ) );
  124. }
  125. sub INFO {
  126. my $self = shift;
  127. $self->log->info( $self->_log( shift ) );
  128. }
  129. sub NOTE {
  130. my $self = shift;
  131. $self->log->notice( $self->_log( shift ) );
  132. }
  133. sub WARN {
  134. my $self = shift;
  135. $self->log->warning( $self->_log( shift ) );
  136. }
  137. sub ERROR {
  138. my $self = shift;
  139. $self->log->error( $self->_log( shift ) );
  140. }
  141. sub CRIT {
  142. my $self = shift;
  143. $self->log->critical( $self->_log( shift ) );
  144. }
  145. sub ALERT {
  146. my $self = shift;
  147. $self->log->alert( $self->_log( shift ) );
  148. }
  149. sub EMERG {
  150. my $self = shift;
  151. $self->log->emergency( $self->_log( shift ) );
  152. }
  153. sub FATAL {
  154. my $self = shift;
  155. $self->log->log_and_die( level => 'emergency', message => $self->_log( shift ) );
  156. }
  157. =head1 new(%options)
  158. Options are:
  159. custom_log
  160. verbose
  161. routers
  162. loggers
  163. auth
  164. =cut
  165. sub new {
  166. my ($class, %options) = @_;
  167. # Refuse to run as wrong user, all config will be borked otherwise
  168. my $pname = getpwuid($>);
  169. die "Must run as configured user (got: $pname, want: $options{user})!" unless $pname eq ($options{user} // '');
  170. my $self = bless(\%options, $class);
  171. $self->{ip} = '0.0.0.0';
  172. my @routes;
  173. # XXX TODO make these routes able to be fully qualified namespaces (::)!
  174. no strict 'refs';
  175. foreach my $route (@{$self->{routers}}) {
  176. # The router needs to exist and have nonzero numbers of routes.
  177. my ($package) = basename($route) =~ m/(\S+)\.pm$/;
  178. my $r = "$package\:\:routes";
  179. local $@;
  180. $self->DEBUG("require $route");
  181. my $success = eval { require $route; 1; };
  182. if ($success) {
  183. my $pkg_routes = *$r{ARRAY};
  184. for (my $i=0; $i < @$pkg_routes; $i += 2) {
  185. $self->DEBUG("Registered route $pkg_routes->[$i]");
  186. }
  187. push(@routes,@$pkg_routes);
  188. } else {
  189. die "Could not load $route!\n$@\n";
  190. }
  191. }
  192. use strict 'refs';
  193. # Set the pattern used to discover the route if needed later.
  194. for (my $i=0; $i < scalar(@routes); $i += 2 ) {
  195. $routes[$i+1]{pattern} = $routes[$i];
  196. }
  197. $self->{indices} //=[];
  198. $self->{indices} = [@{$self->{indices}},qw{index.html index.htm index.cgi}];
  199. $self->{routes} = \@routes;
  200. return $self;
  201. }
  202. sub indices {
  203. my $self = shift;
  204. return $self->{indices};
  205. }
  206. sub routes {
  207. my $self = shift;
  208. return $self->{routes};
  209. }
  210. =head2 serve
  211. Serve a file, with options to stream and cache the output.
  212. =cut
  213. sub serve {
  214. my ( $self, $fullpath, $path, $start, $streaming, $ranges, $last_fetch, $deflate ) = @_;
  215. $last_fetch ||= 0;
  216. $deflate ||= 0;
  217. my $mf = Mojo::File->new($path);
  218. my $ext = '.' . $mf->extname();
  219. my $ft;
  220. if ($ext) {
  221. $ft = Plack::MIME->mime_type($ext) if $ext;
  222. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  223. }
  224. $ft ||= $content_types{text};
  225. my @headers = ( $ct => $ft );
  226. #TODO use static Cache-Control for everything but JS/CSS?
  227. push( @headers, 'Cache-control' => $cache_control{revalidate} );
  228. push( @headers, 'Accept-Ranges' => 'bytes' );
  229. my $mt = ( stat($path) )[9];
  230. my $sz = ( stat(_) )[7];
  231. my @gm = gmtime($mt);
  232. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  233. my $code = $mt > $last_fetch ? 200 : 304;
  234. push( @headers, "Last-Modified" => $now_string );
  235. push( @headers, 'Vary' => 'Accept-Encoding' );
  236. if ( open( my $fh, '<', $path ) ) {
  237. return $self->_range( $fullpath, $fh, $ranges, $sz, @headers ) if @$ranges && $streaming;
  238. # Transfer-encoding: chunked
  239. return sub {
  240. my $responder = shift;
  241. push( @headers, 'Content-Length' => $sz );
  242. my $writer = $responder->( [ $code, \@headers ] );
  243. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  244. $writer->write($buf);
  245. }
  246. close $fh;
  247. $writer->close;
  248. }
  249. if $streaming && $sz > $CHUNK_SIZE;
  250. #Return data in the event the caller does not support deflate
  251. if ( !$deflate ) {
  252. push( @headers, "Content-Length" => $sz );
  253. # Append server-timing headers
  254. my $tot = tv_interval($start) * 1000;
  255. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  256. return [ $code, \@headers, $fh ];
  257. }
  258. #Compress everything less than 1MB
  259. push( @headers, "Content-Encoding" => "gzip" );
  260. my $dfh;
  261. IO::Compress::Gzip::gzip( $fh => \$dfh );
  262. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  263. push( @headers, "Content-Length" => length($dfh) );
  264. $self->INFO("GET 200 $fullpath");
  265. # Append server-timing headers
  266. my $tot = tv_interval($start) * 1000;
  267. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  268. return [ $code, \@headers, [$dfh] ];
  269. }
  270. $self->INFO("GET 403 $fullpath");
  271. return [ 403, [ $ct => $content_types{text} ], ["Forbidden"] ];
  272. }
  273. sub _range {
  274. my ( $self, $fullpath, $fh, $ranges, $sz, %headers ) = @_;
  275. # Set mode
  276. my $primary_ct = "Content-Type: $headers{'Content-type'}";
  277. my $is_multipart = scalar(@$ranges) > 1;
  278. if ($is_multipart) {
  279. $headers{'Content-type'} = "multipart/byteranges; boundary=$CHUNK_SEP";
  280. }
  281. my $code = 206;
  282. my $fc = '';
  283. # Calculate the content-length up-front. We have to fix unspecified lengths first, and reject bad requests.
  284. foreach my $range (@$ranges) {
  285. $range->[1] //= $sz - 1;
  286. $self->INFO("GET 416 $fullpath");
  287. return [ 416, [%headers], ["Requested range not satisfiable"] ] if $range->[0] > $sz || $range->[0] < 0 || $range->[1] < 0 || $range->[0] > $range->[1];
  288. }
  289. $headers{'Content-Length'} = List::Util::sum( map { my $arr = $_; $arr->[1] + 1, -$arr->[0] } @$ranges );
  290. #XXX Add the entity header lengths to the value - should hash-ify this to DRY
  291. if ($is_multipart) {
  292. foreach my $range (@$ranges) {
  293. $headers{'Content-Length'} += length("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n");
  294. $fc = "\n";
  295. }
  296. $headers{'Content-Length'} += length("\n--$CHUNK_SEP\--\n");
  297. $fc = '';
  298. }
  299. return sub {
  300. my $responder = shift;
  301. my $writer;
  302. foreach my $range (@$ranges) {
  303. $headers{'Content-Range'} = "bytes $range->[0]-$range->[1]/$sz" unless $is_multipart;
  304. $writer //= $responder->( [ $code, [%headers] ] );
  305. $writer->write("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n") if $is_multipart;
  306. $fc = "\n";
  307. my $len = List::Util::min( $sz, $range->[1] + 1 ) - $range->[0];
  308. $fh->seek( $range->[0], 0 );
  309. while ($len) {
  310. $fh->read( my $buf, List::Util::min( $len, $CHUNK_SIZE ) );
  311. $writer->write($buf);
  312. # Adjust for amount written
  313. $len = List::Util::max( $len - $CHUNK_SIZE, 0 );
  314. }
  315. }
  316. $fh->close();
  317. $writer->write("\n--$CHUNK_SEP\--\n") if $is_multipart;
  318. $writer->close;
  319. };
  320. }
  321. sub _generic {
  322. my ( $type, $code ) = @_;
  323. $type .= Carp::longmess() if $debug;
  324. return [$code, [$ct => $content_types{html}], ["$type"]];
  325. }
  326. =head2 notfound, forbidden, badrequest, toolong, error
  327. If you need to return these HTTP errors, return these within a route:
  328. sub route {
  329. my ($self, $query) = @_;
  330. ...
  331. return $self->notfound($query);
  332. }
  333. =cut
  334. sub notfound {
  335. my ($self, $query, $body) = @_;
  336. $self->INFO("$query->{method} 404 $query->{fullpath}");
  337. $body //= 'Not Found';
  338. return _generic( $body, 404 );
  339. }
  340. sub forbidden {
  341. my ($self, $query, $body) = @_;
  342. $self->INFO("$query->{method} 403 $query->{fullpath}");
  343. $body //= 'Forbidden';
  344. return _generic( $body, 403 );
  345. }
  346. sub badrequest {
  347. my ($self, $query, $body) = @_;
  348. $self->INFO("$query->{method} 400 $query->{fullpath}");
  349. $body //= 'Bad Request';
  350. return _generic( $body, 400 );
  351. }
  352. sub toolong {
  353. my ($self, $query, $body) = @_;
  354. $self->INFO("$query->{method} 419 $query->{fullpath}");
  355. $body //= 'URI too long';
  356. return _generic( $body, 419 );
  357. }
  358. sub error {
  359. my ($self, $query, $body) = @_;
  360. my $method = $query->{method} // "?";
  361. my $fp = $query->{fullpath} // "?";
  362. $body //= 'Internal Server Error';
  363. $self->INFO("$method 500 $fp");
  364. return _generic( $body, 500 );
  365. }
  366. sub unavailable {
  367. my ($self, $query, $body) = @_;
  368. $self->INFO("$query->{method} 503 $query->{fullpath}");
  369. $body //= 'Service Unavailable';
  370. return _generic( $body, 503 );
  371. }
  372. my $cur_query = {};
  373. sub app {
  374. my $self = shift;
  375. return eval { _app($self, @_) } || do {
  376. my $env = shift;
  377. $env->{'psgi.errors'}->print($@) if $env->{'psgi.errors'};
  378. # Redact the stack trace past line 1, it usually has things which should not be shown
  379. $cur_query->{message} = $@;
  380. $cur_query->{message} =~ s/\n.*//g if $cur_query->{message} && !$debug;
  381. return $self->error($cur_query);
  382. };
  383. }
  384. my %etags;
  385. sub _app {
  386. my $self = shift;
  387. # Start the server timing clock
  388. my $start = [gettimeofday];
  389. $cur_query = {};
  390. # Don't make things group read/write
  391. umask 0007;
  392. my $env = shift;
  393. $self->{filehandle} = $env->{'psgix.io'} // *STDOUT;
  394. # Setup the unique ID for the request
  395. $env->{REQUEST_ID} = $self->request_id(1);
  396. # Discard the path used in the log, it's too long and enough 4xx error code = ban
  397. return $self->toolong({ method => $env->{REQUEST_METHOD}, fullpath => '...' }) if length( $env->{REQUEST_URI} ) > 2048;
  398. # Various stuff important for logging requests
  399. my $domain = $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST} // eval { Sys::Hostname::hostname() };
  400. my $path = $env->{PATH_INFO};
  401. my $port = $env->{HTTP_X_FORWARDED_PORT} // $env->{HTTP_PORT};
  402. my $pport = defined $port ? ":$port" : "";
  403. my $scheme = $env->{'psgi.url_scheme'} // 'http';
  404. my $method = $env->{REQUEST_METHOD};
  405. # It's important that we log what the user ACTUALLY requested rather than the rewritten path later on.
  406. my $fullpath = "$scheme://$domain$pport$path";
  407. # So we can log it for fail2ban
  408. my $ip = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR};
  409. # set the referer & ua to go into DB logs, but not logs in general.
  410. # The referer/ua largely has no importance beyond being a proto bug report for log messages.
  411. my $referer = $env->{HTTP_REFERER};
  412. my $ua = $env->{HTTP_UA};
  413. $cur_query = {
  414. route => $path,
  415. fullpath => $path,
  416. method => $method,
  417. ip => $ip,
  418. ua => $ua,
  419. referer => $referer,
  420. };
  421. # Check eTags. If we don't know about it, just assume it's good and lazily fill the cache
  422. # XXX yes, this allows cache poisoning...but only for logged in users!
  423. # This also needs to be IN DB so that we coordinate properly across forks
  424. if ( $env->{HTTP_IF_NONE_MATCH} ) {
  425. $self->INFO("$env->{REQUEST_METHOD} 304 $fullpath");
  426. return [ 304, [], [''] ] if $env->{HTTP_IF_NONE_MATCH} eq ( $etags{ $env->{REQUEST_URI} } || '' );
  427. $etags{ $env->{REQUEST_URI} } = $env->{HTTP_IF_NONE_MATCH} unless exists $etags{ $env->{REQUEST_URI} };
  428. }
  429. # TODO: Actually do something with the language passed to the renderer
  430. my $lang = $env->{HTTP_ACCEPT_LANGUAGE};
  431. #TODO: Actually do something with the acceptable output formats in the renderer
  432. my $accept = $env->{HTTP_ACCEPT};
  433. my $last_fetch = 0;
  434. if ( $env->{HTTP_IF_MODIFIED_SINCE} ) {
  435. $last_fetch = DateTime::Format::HTTP->parse_datetime( $env->{HTTP_IF_MODIFIED_SINCE} )->epoch();
  436. }
  437. # Figure out if we want compression or not
  438. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  439. $alist =~ s/\s//g;
  440. my @accept_encodings;
  441. @accept_encodings = split( /,/, $alist );
  442. my $deflate = grep { 'gzip' eq $_ } @accept_encodings;
  443. # Set the IP of the request so we can fail2ban
  444. $self->{ip} = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR} || $self->{ip};
  445. # Make sure this works further down the line
  446. $env->{REMOTE_ADDR} = $env->{HTTP_X_FORWARDED_FOR} if $env->{HTTP_X_FORWARDED_FOR};
  447. my $streaming = $env->{'psgi.streaming'};
  448. # If we have an actual route, just use it.
  449. my $r = $self->routes;
  450. my $route_index = List::Util::first { ($r->[$_] // '') eq $path } 0..scalar(@$r);
  451. my $route_actual;
  452. $route_actual = $r->[$route_index+1] if defined($route_index);
  453. # Might be a regexed route. Sort reversed so we try the longest routes first.
  454. if (!$route_actual && @$r) {
  455. my $matched = List::Util::first {
  456. # Here's where you want to use Regexp::Debugger in the context of call.pl to debug routes... EX:
  457. # perl ./call.pl GET /path/to/route
  458. #print $r->[$_]."\n";
  459. $path =~ m/^$r->[$_]$/;
  460. } 0..scalar(@$r)-1;
  461. $route_actual = $r->[$matched+1] if defined($matched);
  462. }
  463. return $self->route( $route_actual, $env, $fullpath, $path, $start, $last_fetch, $deflate ) if $route_actual;
  464. # Do a case insensitive match, because osx and windows
  465. my $file_possible = $self->mangle_filename("www/$path");
  466. my $file_actual = $file_possible if -f $file_possible;
  467. # Dirindices
  468. if (-d $file_possible) {
  469. foreach my $index (@{$self->indices}) {
  470. next if $file_actual;
  471. my $dirindex = $self->mangle_filename("www$path/$index");
  472. $dirindex =~ s|//|/|g;
  473. $file_actual = $dirindex if -f $dirindex;
  474. }
  475. }
  476. my $file_is_cgi = appears_executable($file_actual);
  477. return $self->cgi( $env, $fullpath, $file_actual, $last_fetch, $deflate) if $file_is_cgi;
  478. $self->INFO("Attempting to serve $fullpath [".($file_possible // "")."]");
  479. my @ranges = parse_ranges($env);
  480. return $self->serve( $fullpath, $file_actual, $start, $streaming, \@ranges, $last_fetch, $deflate ) if $file_actual;
  481. return $self->notfound($cur_query);
  482. }
  483. sub mangle_filename {
  484. my ($self,$path) = @_;
  485. # XXX yes, you can have case sensitive OSX, but basically nobody enables that ever
  486. $path = lc($path) if List::Util::any { $^O eq $_ } qw{darwin MSWin32 dos};
  487. $self->DEBUG("Path mangled to $path");
  488. return $path;
  489. }
  490. sub parse_ranges {
  491. my $env = shift;
  492. # Handle HTTP range/streaming requests
  493. my $range = $env->{HTTP_RANGE} || "bytes=0-" if $env->{HTTP_RANGE} || $env->{HTTP_IF_RANGE};
  494. my @ranges;
  495. if ($range) {
  496. $range =~ s/bytes=//g;
  497. push(
  498. @ranges,
  499. map {
  500. [ split( /-/, $_ ) ];
  501. } split( /,/, $range )
  502. );
  503. }
  504. return @ranges;
  505. }
  506. my @executable_extensions = qw{cgi sh exe pl php py};
  507. sub appears_executable {
  508. my $subj = shift;
  509. # Definitely not executable if it does not exist!
  510. return 0 unless $subj;
  511. return 0 unless -x $subj;
  512. my ($extension) = $subj =~ m/\.(\S+)$/;
  513. return 1 if !$extension;
  514. return 1 if grep { $extension eq $_ } @executable_extensions;
  515. return 0;
  516. }
  517. # Handle actual routes
  518. sub route {
  519. my ($self, $route, $env, $fullpath, $path, $start, $last_fetch, $deflate ) = @_;
  520. $self->DEBUG('Executing route '.$route->{pattern});
  521. my $content_type = $env->{CONTENT_TYPE} || 'text/html'; # If not set, that's the assumption.
  522. # It is the responsibility of each route to respond to HEAD requests correctly
  523. return $self->badrequest($cur_query) unless List::Util::any { $_ eq $env->{REQUEST_METHOD} } grep { defined $_ } ('HEAD', $route->{method});
  524. my $callback;
  525. if (exists $route->{callbacks}{'*'}) {
  526. $callback = $route->{callbacks}{'*'};
  527. } else {
  528. return $self->badrequest($cur_query) unless exists $route->{callbacks}{$content_type};
  529. $callback = $route->{callbacks}{$content_type};
  530. }
  531. # Provide static renders if available.
  532. my $streaming = $env->{'psgi.streaming'};
  533. return $self->static( $fullpath, "$fullpath.z", $start, $streaming ) if -f "statics/$fullpath.z" && $deflate;
  534. return $self->static( $fullpath, $fullpath, $start, $streaming ) if -f "statics/$fullpath";
  535. # Build the query data for passing to a route.
  536. # GET, POST, URI captures, then explicit data overrides.
  537. my $query = $self->extract_query($path, $route, $env);
  538. # allow this stuff to survive down to the end of some routes
  539. $query->{last_fetched} = $last_fetch;
  540. $query->{deflate} = $deflate;
  541. $query->{streaming} = $streaming;
  542. my @ranges = parse_ranges($env);
  543. $query->{ranges} = \@ranges;
  544. $query->{start} = $start;
  545. # Put things to tv_interval in here for Server-Timing
  546. $query->{fullpath} = $fullpath;
  547. $query->{method} = $route->{method};
  548. # This allows for better error handlers if we die in the route.
  549. $cur_query = $query;
  550. # Setup the CGI vars they expect IF requested
  551. local %ENV = (%ENV, CGI::Emulate::PSGI->emulate_environment($env)) if $route->{env};
  552. {
  553. my $output = $callback->($self, $query);
  554. # If it's streaming, just hand it off
  555. return $output if ref $output eq 'CODE';
  556. die "$fullpath returned no or malformed data!" unless ref $output eq 'ARRAY' && @$output == 3;
  557. my $pport = defined $query->{port} ? ":$query->{port}" : "";
  558. my %headers = @{$output->[1]};
  559. my $bytes = $headers{'Content-Length'} // '?';
  560. $self->INFO("$env->{REQUEST_METHOD} $output->[0] $bytes $fullpath");
  561. # Append server-timing headers if they aren't present
  562. my $tot = tv_interval($start) * 1000;
  563. push( @{ $output->[1] }, 'Server-Timing' => "app;dur=$tot" ) unless List::Util::any { $_ eq 'Server-Timing' } @{ $output->[1] };
  564. return $output;
  565. }
  566. }
  567. sub extract_query {
  568. my ($self, $path, $route, $env) = @_;
  569. my $query = URL::Encode::url_params_mixed( $env->{QUERY_STRING} ) if $env->{QUERY_STRING};
  570. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  571. if ( $env->{REQUEST_METHOD} eq 'POST' ) {
  572. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  573. while ( $env->{'psgi.input'}->read( my $buf, $CHUNK_SIZE ) ) {
  574. $body->add($buf);
  575. }
  576. @$query{ keys( %{ $body->param } ) } = values( %{ $body->param } );
  577. @$query{ keys( %{ $body->upload } ) } = values( %{ $body->upload } );
  578. }
  579. if (ref $route->{captures} eq 'ARRAY') {
  580. my @captures = $path =~ m/^$route->{pattern}$/;
  581. @$query{@{$route->{captures}}} = @captures;
  582. }
  583. if (ref $route->{data} eq 'HASH') {
  584. @$query{keys(%{$route->{data}})} = values(%{$route->{data}});
  585. }
  586. return $query;
  587. }
  588. # Read until we are done with headers, then pass off the filehandle to PSGI for streaming.
  589. # TODO support compression
  590. sub cgi {
  591. my ( $self, $env, $fullpath, $file_actual, $last_fetch, $deflate) = @_;
  592. $self->INFO("Handoff $fullpath to $file_actual for cgi exec");
  593. # Setup the CGI vars they expect
  594. local %ENV = (%ENV, CGI::Emulate::PSGI->emulate_environment($env));
  595. my $pid = open(my $out, '-|', "$file_actual");
  596. my ($code, $offset, %headers) = extract_headers($out, $last_fetch);
  597. $code //= 500;
  598. return sub {
  599. my $responder = shift;
  600. my $writer = $responder->( [ $code, [%headers] ] );
  601. while ( $out->read( my $buf, $CHUNK_SIZE ) ) {
  602. $writer->write($buf);
  603. }
  604. $writer->close;
  605. # Wait on the CGI script to do whatever it's doing after closing stdout
  606. close $out;
  607. waitpid($pid, 0);
  608. };
  609. }
  610. sub stream_raw_and_i_mean_it {
  611. my ($self, $data, $output, $last_fetch, $to_fork, $callback) = @_;
  612. return sub {
  613. my $responder = shift;
  614. };
  615. }
  616. sub stream_raw_http {
  617. my ($self, $data, $last_fetch, $to_fork, $callback, $error_handler) = @_;
  618. my $time_to_here = tv_interval($data->{start});
  619. $self->DEBUG("Routing took $time_to_here s");
  620. my $post_routing = [gettimeofday];
  621. my $fh = $self->{filehandle};
  622. # The CGIs you are executing here SHOULD NOT emit a status line.
  623. # Most apache CGIs you find don't anyways, so this is usually not a big deal.
  624. print $fh "HTTP/1.1 200 OK\n";
  625. # Emit our server-timing header.
  626. print $fh "Server-Timing: ".$self->build_server_timing($data)."\n"; #app;dur=".($time_to_here*1000)."\n";
  627. # We *must* fork because we can't rely on the child to close stdout.
  628. my $pid = _fork(sub {
  629. $self->DEBUG("Forking child took".(tv_interval($post_routing))." s");
  630. local $@;
  631. eval { $to_fork->() };
  632. $self->ERROR("Raw HTTTP streaming encountered exception: $@") if $@;
  633. if (ref $error_handler eq 'CODE') {
  634. local $@;
  635. eval { $error_handler->() };
  636. $self->ERROR("HTTP streaming error handler encountered exception: $@") if $@;
  637. }
  638. }, $fh);
  639. waitpid($pid, 0);
  640. close($fh);
  641. $self->DEBUG("Response written in ".(tv_interval($post_routing))." s");
  642. if (ref $callback eq 'CODE') {
  643. my $post_start = [gettimeofday];
  644. local $@;
  645. eval { $callback->() };
  646. $self->ERROR("Post-close callback encountered exception: $@") if $@;
  647. $self->DEBUG("Post-close callback took ".(tv_interval($post_start))." s");
  648. }
  649. exit 0;
  650. }
  651. sub _fork {
  652. my ($callback, $fh) = @_;
  653. select $fh;
  654. $|=1;
  655. my $pid = fork();
  656. die "Could not fork child" unless defined $pid;
  657. if ($pid == 0) {
  658. $callback->();
  659. exit 0;
  660. }
  661. select STDOUT;
  662. return $pid;
  663. }
  664. =head2 extract_headers($fh, $last_fetch)
  665. Extract the headers from a filehandle. Set the 'Last Modified' header appropriately based on the output of `stat` on the filehandle.
  666. 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.
  667. =cut
  668. sub extract_headers {
  669. my ($fh, $last_fetch, $is_ref) = @_;
  670. my $headers = '';
  671. # NOTE: this is relying on while advancing the file pointer
  672. while (<$fh>) {
  673. last if $_ eq "\n";
  674. $headers .= $_;
  675. }
  676. #XXX still a toctou
  677. my $offset = $fh->tell();
  678. my ( undef, undef, $status, undef, $headers_parsed ) = HTTP::Parser::XS::parse_http_response( "$headers\n", HEADERS_AS_HASHREF );
  679. my $code = $status // 200;
  680. $headers_parsed //= {};
  681. if (!$is_ref) {
  682. my $mt = ( stat($fh) )[9];
  683. my @gm = gmtime($mt);
  684. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  685. $code = $mt > $last_fetch ? $status : 304;
  686. $headers_parsed->{"Last-Modified"} = $now_string;
  687. }
  688. return ($code, $offset, %$headers_parsed);
  689. }
  690. sub static {
  691. my ( $self, $fullpath, $path, $start, $streaming, $last_fetch ) = @_;
  692. $self->DEBUG("Rendering static for $path");
  693. # XXX because of psgi I can't just vomit the file directly
  694. if ( open( my $fh, '<', "statics/$path" ) ) {
  695. my ($code, $offset, $headers_parsed) = (200, undef, {});
  696. ($code, $offset, %$headers_parsed) = extract_headers($fh, $last_fetch );
  697. # Append server-timing headers
  698. my $tot = tv_interval($start) * 1000;
  699. $headers_parsed->{'Server-Timing'} = "static;dur=$tot";
  700. #XXX uwsgi just opens the file *again* when we already have a filehandle if it has a path.
  701. # starman by comparison doesn't violate the principle of least astonishment here.
  702. # This is probably a performance optimization, but makes the kind of micromanagement I need to do inconvenient.
  703. # As such, we will just return a stream.
  704. $self->INFO("GET 200 $headers_parsed->{'Content-Length'} $fullpath");
  705. return sub {
  706. my $responder = shift;
  707. #push(@headers, 'Content-Length' => $sz);
  708. my $writer = $responder->( [ $code, [%$headers_parsed] ] );
  709. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  710. $writer->write($buf);
  711. }
  712. close $fh;
  713. $writer->close;
  714. }
  715. if $streaming;
  716. return [ $code, [%$headers_parsed], $fh ];
  717. }
  718. return $self->forbidden($self->{current_query});
  719. }
  720. sub get_config {
  721. $ENV{HOME} ||= Cwd::getcwd();
  722. my %options = (
  723. verbose => 0,
  724. custom_log => undef,
  725. routers => [],
  726. loggers => [],
  727. auth => undef,
  728. domain => '',
  729. user => '',
  730. binds => [],
  731. basedir => $ENV{'HOME'},
  732. );
  733. my $config_file = "$ENV{HOME}/.tpsgi.ini";
  734. if (-f $config_file) {
  735. my $conf = Config::Simple->new($config_file);
  736. my %config;
  737. %config = %{$conf->param(-block => 'default')} if $conf;
  738. # Merge the configuration with the options
  739. foreach my $opt (keys(%options)) {
  740. if ( ref $options{$opt} eq 'ARRAY' ) {
  741. next unless exists $config{$opt};
  742. my @arrayed = ref $config{$opt} eq 'ARRAY' ? @{$config{$opt}} : ($config{$opt});
  743. push(@{$options{$opt}}, @arrayed);
  744. next;
  745. }
  746. $options{$opt} = $config{$opt} if exists $config{$opt};
  747. }
  748. }
  749. return %options;
  750. }
  751. # Convenience method to keep track of server-timing
  752. sub checkpoint {
  753. my ($self, $data, $name) = @_;
  754. $data->{checkpoints} //= [[ start => $data->{start} ]];
  755. push(@{$data->{checkpoints}}, [ $name => [gettimeofday] ]);
  756. }
  757. sub build_server_timing {
  758. my ($self, $data) = @_;
  759. my @st;
  760. my $last_interval;
  761. foreach my $checkpoint (@{$data->{checkpoints}}) {
  762. if ($last_interval) {
  763. my $dur = tv_interval($last_interval, $checkpoint->[1]) * 1000;
  764. push(@st, "$checkpoint->[0];dur=$dur");
  765. }
  766. $last_interval = $checkpoint->[1];
  767. }
  768. my $tot = tv_interval($data->{start}) * 1000;
  769. push(@st, "tot;dur=$tot");
  770. delete $data->{checkpoints};
  771. return join(', ', @st);
  772. }
  773. 1;