TCMS.pm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. package TCMS;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures state};
  6. use Clone qw{clone};
  7. use Date::Format qw{strftime};
  8. use Sys::Hostname();
  9. use HTTP::Body ();
  10. use URL::Encode ();
  11. use Text::Xslate ();
  12. use DateTime::Format::HTTP();
  13. use CGI::Cookie ();
  14. use File::Basename();
  15. use IO::Compress::Gzip();
  16. use Time::HiRes qw{gettimeofday tv_interval};
  17. use HTTP::Parser::XS qw{HEADERS_AS_HASHREF};
  18. use List::Util;
  19. use URI();
  20. use Ref::Util qw{is_coderef is_hashref is_arrayref};
  21. #Grab our custom routes
  22. use FindBin;
  23. use lib "$FindBin::Bin/../lib";
  24. use FindBin::libs;
  25. use Trog::Routes::HTML;
  26. use Trog::Routes::JSON;
  27. use Trog::Log qw{:all};
  28. use Trog::Log::DBI;
  29. use Trog::Auth;
  30. use Trog::Utils;
  31. use Trog::Config;
  32. use Trog::Data;
  33. use Trog::Vars;
  34. use Trog::FileHandler;
  35. # Troglodyne philosophy - simple as possible
  36. # Wrap app to return *our* error handler instead of Plack::Util::run_app's
  37. my $cur_query = {};
  38. # Build routes
  39. sub build_routes {
  40. my $conf = Trog::Config::get();
  41. my $data = Trog::Data->new($conf);
  42. my %routes = %{ _routes($data) };
  43. # Transform 'method' / 'callback' to new scheme
  44. my %routes_adj = map {
  45. my $k = $_;
  46. my $v = $routes{$k};
  47. my %cb;
  48. my $method = $v->{method};
  49. my $callback = delete $v->{callback};
  50. #XXX For now we will discard the tPSGI object. We might want it later.
  51. my $cb_wrap = sub {
  52. my ($tpsgi, $query) = @_;
  53. # Set the urchin parameters if necessary.
  54. %$Trog::Log::DBI::urchin = map { $_ => delete $query->{$_} } qw{utm_source utm_medium utm_campaign utm_term utm_content};
  55. # Set the IP of the request so we can fail2ban
  56. $Trog::Log::ip = $query->{req_address};
  57. # Set the referer & ua to go into DB logs, but not logs in general.
  58. # The referer/ua largely has no importance beyond being a proto bug report for log messages.
  59. $Trog::Log::DBI::referer = $query->{referer};
  60. $Trog::Log::DBI::ua = $query->{ua};
  61. # Figure out if we have a logged in user, so we can serve them user-specific files
  62. my $cookies = {};
  63. $cookies = CGI::Cookie->parse( $query->{cookies} ) if $query->{cookies};
  64. my $active_user = '';
  65. $Trog::Log::user = 'nobody';
  66. if ( exists $cookies->{tcmslogin} ) {
  67. $active_user = Trog::Auth::session2user( $cookies->{tcmslogin}->value );
  68. $Trog::Log::user = $active_user if $active_user;
  69. }
  70. # Enrich the query with tcms specific foo
  71. $query->{user_acls} = [];
  72. $query->{user_acls} = Trog::Auth::acls4user($active_user) // [] if $active_user;
  73. # Grab the list of ACLs we want to add to a post, if any.
  74. $query->{acls} = [ $query->{acls} ] if ( $query->{acls} && ref $query->{acls} ne 'ARRAY' );
  75. # Filter out passed ACLs which are naughty
  76. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  77. @{ $query->{acls} } = grep { $_ ne 'admin' } @{ $query->{acls} } unless $is_admin;
  78. $query->{user} = $active_user;
  79. $query->{body} = '';
  80. $query->{social_meta} = 1;
  81. $query->{primary_post} = {};
  82. # Redirecting somewhere naughty not allow
  83. $query->{to} = URI->new( $query->{to} // '' )->path() || $query->{to} if $query->{to};
  84. # Now that we have firmed up the actual routing, let's validate.
  85. return $tpsgi->forbidden($query) if exists $query->{dispatcher}{auth} && !$active_user;
  86. # Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  87. if ( index( $query->{route}, '/templates' ) == 0 || index( $query->{route}, '/statics' ) == 0 || $query->{route} =~ m/.*(\.psgi|\.pm)$/i ) {
  88. return $tpsgi->forbidden($query);
  89. }
  90. no strict 'refs';
  91. $callback->($query);
  92. use strict;
  93. };
  94. #XXX todo support different callbacks per requested content-type
  95. $cb{'*'} = $cb_wrap if $callback;
  96. $v->{callbacks} = \%cb;
  97. $k => $v
  98. } keys(%routes);
  99. return [%routes_adj];
  100. }
  101. our @routes = @{build_routes()};
  102. our %aliases = aliases();
  103. =head2 app()
  104. Dispatches requests based on %routes built above.
  105. The dispatcher here does *not* do anything with the authn/authz data. It sets those in the 'user' and 'acls' parameters of the query object passed to routes.
  106. If a path passed is not a defined route (or regex route), but exists as a file under www/, it will be served up immediately.
  107. =cut
  108. sub _app {
  109. # Make sure all writes are with the proper permissions, none need know of our love
  110. umask 0077;
  111. # Start the server timing clock
  112. my $start = [gettimeofday];
  113. # Build the routing table
  114. state( $conf, $data, %aliases );
  115. # Setup logging
  116. #log_init();
  117. $conf //= Trog::Config::get();
  118. $data //= Trog::Data->new($conf);
  119. my %routes = %{ _routes($data) };
  120. %aliases = $data->aliases() unless %aliases;
  121. # XXX this is built progressively across the forks, leading to inconsistent behavior.
  122. # This should eventually be pre-filled from DB.
  123. my %etags;
  124. my $requestid = Trog::Utils::uuid();
  125. Trog::Log::uuid($requestid);
  126. # Actually start processing the request
  127. my $env = shift;
  128. # Discard the path used in the log, it's too long and enough 4xx error code = ban
  129. return _toolong( { method => $env->{REQUEST_METHOD}, fullpath => '...' } ) if length( $env->{REQUEST_URI} ) > 2048;
  130. # Various stuff important for logging requests
  131. state $domain = $conf->param('general.hostname') || $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST} || eval { Sys::Hostname::hostname() };
  132. my $path = $env->{PATH_INFO};
  133. my $port = $env->{HTTP_X_FORWARDED_PORT} // $env->{HTTP_PORT};
  134. my $pport = defined $port ? ":$port" : "";
  135. my $scheme = $env->{'psgi.url_scheme'} // 'http';
  136. my $method = $env->{REQUEST_METHOD};
  137. # It's important that we log what the user ACTUALLY requested rather than the rewritten path later on.
  138. my $fullpath = "$scheme://$domain$pport$path";
  139. # sigdie can now "do the right thing"
  140. $cur_query = { route => $path, fullpath => $path, method => $method };
  141. # Set the IP of the request so we can fail2ban
  142. $Trog::Log::ip = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR};
  143. # Set the referer & ua to go into DB logs, but not logs in general.
  144. # The referer/ua largely has no importance beyond being a proto bug report for log messages.
  145. $Trog::Log::DBI::referer = $env->{HTTP_REFERER};
  146. $Trog::Log::DBI::ua = $env->{HTTP_UA};
  147. # Check eTags. If we don't know about it, just assume it's good and lazily fill the cache
  148. # XXX yes, this allows cache poisoning...but only for logged in users!
  149. if ( $env->{HTTP_IF_NONE_MATCH} ) {
  150. INFO("$env->{REQUEST_METHOD} 304 0 $fullpath");
  151. return [ 304, [], [''] ] if $env->{HTTP_IF_NONE_MATCH} eq ( $etags{ $env->{REQUEST_URI} } || '' );
  152. $etags{ $env->{REQUEST_URI} } = $env->{HTTP_IF_NONE_MATCH} unless exists $etags{ $env->{REQUEST_URI} };
  153. }
  154. # TODO: Actually do something with the language passed to the renderer
  155. my $lang = $env->{HTTP_ACCEPT_LANGUAGE};
  156. #TODO: Actually do something with the acceptable output formats in the renderer
  157. my $accept = $env->{HTTP_ACCEPT};
  158. # Figure out if we want compression or not
  159. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  160. $alist =~ s/\s//g;
  161. my @accept_encodings;
  162. @accept_encodings = split( /,/, $alist );
  163. my $deflate = grep { 'gzip' eq $_ } @accept_encodings;
  164. # NOTE These two parameters are entirely academic, as we don't use ad tracking cookies, but the UTM parameters.
  165. # UTMs are actually fully sufficient to get you what you want -- e.g. keywords, audience groups, a/b testing, etc.
  166. # and you need to put up cookie consent banners if you bother using tracking cookies, which are horrific UX.
  167. #my $no_track = $env->{HTTP_DNT};
  168. #my $no_sell_info = $env->{HTTP_SEC_GPC};
  169. # We generally prefer this to be handled at the reverse proxy level.
  170. #my $prefer_ssl = $env->{HTTP_UPGRADE_INSECURE_REQUESTS};
  171. my $last_fetch = 0;
  172. if ( $env->{HTTP_IF_MODIFIED_SINCE} ) {
  173. $last_fetch = DateTime::Format::HTTP->parse_datetime( $env->{HTTP_IF_MODIFIED_SINCE} )->epoch();
  174. }
  175. #XXX Don't use statics anything that has a search query
  176. # On one hand, I don't want to DOS the disk, but I'd also like some like ?rss...
  177. # Should probably turn those into aliases.
  178. my $has_query = !!$env->{QUERY_STRING};
  179. my $query = {};
  180. $query = URL::Encode::url_params_mixed( $env->{QUERY_STRING} ) if $env->{QUERY_STRING};
  181. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  182. if ( $env->{REQUEST_METHOD} eq 'POST' ) {
  183. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  184. while ( $env->{'psgi.input'}->read( my $buf, $Trog::Vars::CHUNK_SIZE ) ) {
  185. $body->add($buf);
  186. }
  187. @$query{ keys( %{ $body->param } ) } = values( %{ $body->param } );
  188. @$query{ keys( %{ $body->upload } ) } = values( %{ $body->upload } );
  189. }
  190. # It's mod_rewrite!
  191. $path = '/index' if $path eq '/';
  192. #XXX this is hardcoded in browsers, so just rewrite the path - neeeds to be an alias
  193. $path = '/img/icon/favicon.ico' if $path eq '/favicon.ico';
  194. # Translate alias paths into their actual path
  195. $path = $aliases{$path} if exists $aliases{$path};
  196. # Collapse multiple slashes in the path
  197. $path =~ s/[\/]+/\//g;
  198. #Handle regex/capture routes
  199. if ( !exists $routes{$path} ) {
  200. my @captures;
  201. # XXX maybe this should all just go into $query?
  202. # TODO can optimize by having separate hashes for capture/non-capture routes
  203. foreach my $pattern ( keys(%routes) ) {
  204. @captures = $path =~ m/^$pattern$/;
  205. if (@captures) {
  206. $path = $pattern;
  207. foreach my $field ( @{ $routes{$path}{captures} } ) {
  208. $routes{$path}{data} //= {};
  209. $routes{$path}{data}{$field} = shift @captures;
  210. }
  211. last;
  212. }
  213. }
  214. }
  215. # Set the 'data' in the query that the route specifically overrides, which we are also using for the catpured data
  216. # This also means you have to validate both of them via parameters if you set that up.
  217. @{$query}{ keys( %{ $routes{$path}{'data'} } ) } = values( %{ $routes{$path}{'data'} } ) if ref $routes{$path}{'data'} eq 'HASH' && %{ $routes{$path}{'data'} };
  218. # Ensure any short-circuit routes can log the request, and return the server-timing headers properly
  219. $query->{method} = $method;
  220. $query->{route} = $path;
  221. $query->{fullpath} = $fullpath;
  222. $query->{start} = $start;
  223. # Handle HTTP range/streaming requests
  224. my $range = $env->{HTTP_RANGE} || "bytes=0-" if $env->{HTTP_RANGE} || $env->{HTTP_IF_RANGE};
  225. my $streaming = $env->{'psgi.streaming'};
  226. $query->{streaming} = $streaming;
  227. my @ranges;
  228. if ($range) {
  229. $range =~ s/bytes=//g;
  230. push(
  231. @ranges,
  232. map {
  233. [ split( /-/, $_ ) ];
  234. #$tuples[1] //= $tuples[0] + $Trog::Vars::CHUNK_SIZE;
  235. #\@tuples
  236. } split( /,/, $range )
  237. );
  238. }
  239. # If it's a file, just serve it
  240. return Trog::FileHandler::serve( $fullpath, "www/$path", $start, $streaming, \@ranges, $last_fetch, $deflate ) if -f "www/$path";
  241. # Figure out if we have a logged in user, so we can serve them user-specific files
  242. my $cookies = {};
  243. if ( $env->{HTTP_COOKIE} ) {
  244. $cookies = CGI::Cookie->parse( $env->{HTTP_COOKIE} );
  245. }
  246. my $active_user = '';
  247. $Trog::Log::user = 'nobody';
  248. if ( exists $cookies->{tcmslogin} ) {
  249. $active_user = Trog::Auth::session2user( $cookies->{tcmslogin}->value );
  250. $Trog::Log::user = $active_user if $active_user;
  251. }
  252. return Trog::FileHandler::serve( $fullpath, "totp/$path", $start, $streaming, \@ranges, $last_fetch, $deflate ) if -f "totp/$path" && $active_user;
  253. # Now that we have firmed up the actual routing, let's validate.
  254. return _forbidden($query) if exists $routes{$path}{auth} && !$active_user;
  255. return _notfound($query) unless exists $routes{$path} && ref $routes{$path} eq 'HASH' && keys( %{ $routes{$path} } );
  256. return _badrequest($query) unless grep { $env->{REQUEST_METHOD} eq $_ } ( $routes{$path}{method} || '', 'HEAD' );
  257. # Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  258. if ( index( $path, '/templates' ) == 0 || index( $path, '/statics' ) == 0 || $path =~ m/.*(\.psgi|\.pm)$/i ) {
  259. return _forbidden($query);
  260. }
  261. # Set the urchin parameters if necessary.
  262. %$Trog::Log::DBI::urchin = map { $_ => delete $query->{$_} } qw{utm_source utm_medium utm_campaign utm_term utm_content};
  263. # Now that we've parsed the query and know where we want to go, we should murder everything the route does not explicitly want, and validate what it does
  264. my $parameters = $routes{$path}{parameters};
  265. if ($parameters) {
  266. die "invalid route definition for $path: bad parameters" unless is_hashref($parameters);
  267. my @known_params = keys(%$parameters);
  268. for my $param (@known_params) {
  269. die "Invalid route definition for $path: parameter $param must correspond to a validation CODEREF." unless is_coderef( $parameters->{$param} );
  270. # A missing parameter is not necessarily a problem.
  271. next unless $query->{$param};
  272. # But if we have it, and it's bad, nack it, so that scanners get fail2banned.
  273. DEBUG("Rejected $fullpath for bad query param $param");
  274. return _badrequest($query) unless $parameters->{$param}->( $query->{$param} );
  275. }
  276. # Smack down passing of unnecessary fields
  277. foreach my $field ( keys(%$query) ) {
  278. next if List::Util::any { $field eq $_ } @known_params;
  279. next if List::Util::any { $field eq $_ } qw{start route streaming method fullpath};
  280. DEBUG("Rejected $fullpath for query param $field");
  281. return _badrequest($query);
  282. }
  283. }
  284. # Let's open up our default route before we bother thinking about routing any harder
  285. return $routes{default}{callback}->($query) unless -f "config/setup";
  286. $query->{user_acls} = [];
  287. $query->{user_acls} = Trog::Auth::acls4user($active_user) // [] if $active_user;
  288. # Grab the list of ACLs we want to add to a post, if any.
  289. $query->{acls} = [ $query->{acls} ] if ( $query->{acls} && ref $query->{acls} ne 'ARRAY' );
  290. # Filter out passed ACLs which are naughty
  291. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  292. @{ $query->{acls} } = grep { $_ ne 'admin' } @{ $query->{acls} } unless $is_admin;
  293. # If we have a static render, just use it instead (These will ALWAYS be correct, data saves invalidate this)
  294. # TODO: make this key on admin INSTEAD of active user when we add non-admin users.
  295. if ( !$active_user && !$has_query ) {
  296. return _static( $fullpath, "$path.z", $start, $streaming ) if -f "www/statics/$path.z" && $deflate;
  297. return _static( $fullpath, $path, $start, $streaming ) if -f "www/statics/$path";
  298. }
  299. $query->{deflate} = $deflate;
  300. $query->{user} = $active_user;
  301. #Set various things we don't want overridden
  302. $query->{body} = '';
  303. $query->{dnt} = $env->{HTTP_DNT};
  304. $query->{user} = $active_user;
  305. $query->{domain} = $domain;
  306. $query->{route} = $path;
  307. $query->{scheme} = $scheme;
  308. $query->{social_meta} = 1;
  309. $query->{primary_post} = {};
  310. $query->{has_query} = $has_query;
  311. $query->{port} = $port;
  312. $query->{lang} = $lang;
  313. $query->{accept} = $accept;
  314. # Redirecting somewhere naughty not allow
  315. $query->{to} = URI->new( $query->{to} // '' )->path() || $query->{to} if $query->{to};
  316. DEBUG("DISPATCH $path to $routes{$path}{callback}");
  317. #XXX there is a trick to now use strict refs, but I don't remember it right at the moment
  318. {
  319. no strict 'refs';
  320. my $output = $routes{$path}{callback}->($query);
  321. die "$path returned no data!" unless ref $output eq 'ARRAY' && @$output == 3;
  322. my $pport = defined $query->{port} ? ":$query->{port}" : "";
  323. my %headers = @{ $output->[1] };
  324. my $bytes = $headers{'Content-Length'};
  325. INFO("$env->{REQUEST_METHOD} $output->[0] $bytes $fullpath");
  326. # Append server-timing headers if they aren't present
  327. my $tot = tv_interval($start) * 1000;
  328. push( @{ $output->[1] }, 'Server-Timing' => "app;dur=$tot" ) unless List::Util::any { $_ eq 'Server-Timing' } @{ $output->[1] };
  329. return $output;
  330. }
  331. }
  332. #XXX Return a clone of the routing table ref, because code modifies it later
  333. sub _routes ( $data = {} ) {
  334. state %routes;
  335. return clone( \%routes ) if %routes;
  336. my $conf = Trog::Config::get();
  337. $data = Trog::Data->new($conf) unless $data;
  338. my %roots = $data->routes();
  339. %routes = %Trog::Routes::HTML::routes;
  340. @routes{ keys(%Trog::Routes::JSON::routes) } = values(%Trog::Routes::JSON::routes);
  341. @routes{ keys(%roots) } = values(%roots);
  342. # Add in global routes, here because they *must* know about all other routes
  343. # Also, nobody should ever override these.
  344. $routes{'/robots.txt'} = {
  345. method => 'GET',
  346. callback => \&robots,
  347. };
  348. return clone( \%routes );
  349. }
  350. sub aliases {
  351. my $conf = Trog::Config::get();
  352. my $data = Trog::Data->new($conf);
  353. return $data->aliases();
  354. }
  355. =head2 robots
  356. Return an appropriate robots.txt
  357. This is a "special" route as it needs to know about all the routes in order to disallow noindex=1 routes.
  358. =cut
  359. sub robots ($query) {
  360. state $etag = "robots-" . time();
  361. my $routes = _routes();
  362. # If there's a 'capture' route, we need to format it correctly.
  363. state @banned = map { exists $routes->{$_}{robot_name} ? $routes->{$_}{robot_name} : $_ } grep { $routes->{$_}{noindex} } sort keys(%$routes);
  364. return Trog::Renderer->render(
  365. contenttype => 'text/plain',
  366. template => 'robots.tx',
  367. data => {
  368. etag => $etag,
  369. banned => \@banned,
  370. %$query,
  371. },
  372. code => 200,
  373. );
  374. }
  375. sub _generic ( $type, $query ) {
  376. return _static( "$type.z", $query->{start}, $query->{streaming} ) if -f "www/statics/$type.z";
  377. return _static( $type, $query->{start}, $query->{streaming} ) if -f "www/statics/$type";
  378. my %lookup = (
  379. notfound => \&Trog::Routes::HTML::notfound,
  380. forbidden => \&Trog::Routes::HTML::forbidden,
  381. badrequest => \&Trog::Routes::HTML::badrequest,
  382. toolong => \&Trog::Routes::HTML::toolong,
  383. error => \&Trog::Routes::HTML::error,
  384. );
  385. return $lookup{$type}->($query);
  386. }
  387. # TODO: we need a better linkage between bytes and the message actually sent
  388. sub _notfound ($query) {
  389. INFO("$query->{method} 404 33 $query->{fullpath}");
  390. return _generic( 'notfound', $query );
  391. }
  392. sub _forbidden ($query) {
  393. INFO("$query->{method} 403 23 $query->{fullpath}");
  394. return _generic( 'forbidden', $query );
  395. }
  396. sub _badrequest ($query) {
  397. INFO("$query->{method} 400 11 $query->{fullpath}");
  398. return _generic( 'badrequest', $query );
  399. }
  400. sub _toolong ($query) {
  401. INFO("$query->{method} 419 12 $query->{fullpath}");
  402. return _generic( 'toolong', {} );
  403. }
  404. sub _error ($query) {
  405. $query->{method} //= "UNKNOWN";
  406. $query->{fullpath} //= $query->{route} // '/?';
  407. INFO("$query->{method} 500 21 $query->{fullpath}");
  408. return _generic( 'error', $query );
  409. }
  410. sub _static ( $fullpath, $path, $start, $streaming, $last_fetch = 0 ) {
  411. DEBUG("Rendering static for $path");
  412. # XXX because of psgi I can't just vomit the file directly
  413. if ( open( my $fh, '<', "www/statics/$path" ) ) {
  414. my $headers = '';
  415. # NOTE: this is relying on while advancing the file pointer
  416. while (<$fh>) {
  417. last if $_ eq "\n";
  418. $headers .= $_;
  419. }
  420. my ( undef, undef, $status, undef, $headers_parsed ) = HTTP::Parser::XS::parse_http_response( "$headers\n", HEADERS_AS_HASHREF );
  421. #XXX need to put this into the file itself
  422. my $mt = ( stat($fh) )[9];
  423. my @gm = gmtime($mt);
  424. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  425. my $code = $mt > $last_fetch ? $status : 304;
  426. $headers_parsed->{"Last-Modified"} = $now_string;
  427. # Append server-timing headers
  428. my $tot = tv_interval($start) * 1000;
  429. $headers_parsed->{'Server-Timing'} = "static;dur=$tot";
  430. #XXX uwsgi just opens the file *again* when we already have a filehandle if it has a path.
  431. # starman by comparison doesn't violate the principle of least astonishment here.
  432. # This is probably a performance optimization, but makes the kind of micromanagement I need to do inconvenient.
  433. # As such, we will just return a stream.
  434. INFO("GET 200 $headers_parsed->{'Content-Length'} $fullpath");
  435. return sub {
  436. my $responder = shift;
  437. #push(@headers, 'Content-Length' => $sz);
  438. my $writer = $responder->( [ $code, [%$headers_parsed] ] );
  439. while ( $fh->read( my $buf, $Trog::Vars::CHUNK_SIZE ) ) {
  440. $writer->write($buf);
  441. }
  442. close $fh;
  443. $writer->close;
  444. }
  445. if $streaming;
  446. return [ $code, [%$headers_parsed], $fh ];
  447. }
  448. INFO("GET 403 23 $fullpath");
  449. return [ 403, [ 'Content-Type' => $Trog::Vars::content_types{text} ], ["STAY OUT YOU RED MENACE"] ];
  450. }
  451. 1;