TPSGI.pm 29 KB

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