TCMS.pm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 Plack::MIME ();
  13. use Mojo::File ();
  14. use DateTime::Format::HTTP();
  15. use CGI::Cookie ();
  16. use File::Basename();
  17. use IO::Compress::Gzip();
  18. use Time::HiRes qw{gettimeofday tv_interval};
  19. use HTTP::Parser::XS qw{HEADERS_AS_HASHREF};
  20. use List::Util;
  21. use URI();
  22. #Grab our custom routes
  23. use FindBin::libs;
  24. use Trog::Routes::HTML;
  25. use Trog::Routes::JSON;
  26. use Trog::Log qw{:all};
  27. use Trog::Log::DBI;
  28. use Trog::Auth;
  29. use Trog::Utils;
  30. use Trog::Config;
  31. use Trog::Data;
  32. use Trog::Vars;
  33. use Trog::FileHandler;
  34. # Troglodyne philosophy - simple as possible
  35. # Wrap app to return *our* error handler instead of Plack::Util::run_app's
  36. my $cur_query = {};
  37. sub app {
  38. return eval { _app(@_) } || do {
  39. my $env = shift;
  40. $env->{'psgi.errors'}->print($@);
  41. # Redact the stack trace past line 1, it usually has things which should not be shown
  42. $cur_query->{message} = $@;
  43. $cur_query->{message} =~ s/\n.*//g if $cur_query->{message};
  44. return _error($cur_query);
  45. };
  46. }
  47. =head2 app()
  48. Dispatches requests based on %routes built above.
  49. 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.
  50. 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.
  51. =cut
  52. sub _app {
  53. # Start the server timing clock
  54. my $start = [gettimeofday];
  55. # Build the routing table
  56. state ($conf, $data, %aliases);
  57. $conf //= Trog::Config::get();
  58. $data //= Trog::Data->new($conf);
  59. my %routes = %{_routes($data)};
  60. %aliases = $data->aliases() unless %aliases;
  61. # XXX this is built progressively across the forks, leading to inconsistent behavior.
  62. # This should eventually be pre-filled from DB.
  63. my %etags;
  64. # Setup logging
  65. log_init();
  66. my $requestid = Trog::Utils::uuid();
  67. Trog::Log::uuid($requestid);
  68. # Actually start processing the request
  69. my $env = shift;
  70. # Discard the path used in the log, it's too long and enough 4xx error code = ban
  71. return _toolong( { method => $env->{REQUEST_METHOD}, fullpath => '...' } ) if length( $env->{REQUEST_URI} ) > 2048;
  72. # Various stuff important for logging requests
  73. state $domain = $conf->param('general.hostname') || $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST} || eval { Sys::Hostname::hostname() };
  74. my $path = $env->{PATH_INFO};
  75. my $port = $env->{HTTP_X_FORWARDED_PORT} // $env->{HTTP_PORT};
  76. my $pport = defined $port ? ":$port" : "";
  77. my $scheme = $env->{'psgi.url_scheme'} // 'http';
  78. my $method = $env->{REQUEST_METHOD};
  79. # It's important that we log what the user ACTUALLY requested rather than the rewritten path later on.
  80. my $fullpath = "$scheme://$domain$pport$path";
  81. # sigdie can now "do the right thing"
  82. $cur_query = { route => $path, fullpath => $path, method => $method };
  83. # Check eTags. If we don't know about it, just assume it's good and lazily fill the cache
  84. # XXX yes, this allows cache poisoning...but only for logged in users!
  85. if ( $env->{HTTP_IF_NONE_MATCH} ) {
  86. INFO("$env->{REQUEST_METHOD} 304 $fullpath");
  87. return [ 304, [], [''] ] if $env->{HTTP_IF_NONE_MATCH} eq ( $etags{ $env->{REQUEST_URI} } || '' );
  88. $etags{ $env->{REQUEST_URI} } = $env->{HTTP_IF_NONE_MATCH} unless exists $etags{ $env->{REQUEST_URI} };
  89. }
  90. # TODO: Actually do something with the language passed to the renderer
  91. my $lang = $env->{HTTP_ACCEPT_LANGUAGE};
  92. #TODO: Actually do something with the acceptable output formats in the renderer
  93. my $accept = $env->{HTTP_ACCEPT};
  94. # These two parameters are entirely academic, as no integration with any kind of analytics is implemented.
  95. #my $no_track = $env->{HTTP_DNT};
  96. #my $no_sell_info = $env->{HTTP_SEC_GPC};
  97. # Set the referer & ua to go into DB logs, but not logs in general.
  98. $Trog::Log::DBI::referer = $env->{HTTP_REFERER};
  99. $Trog::Log::DBI::ua = $env->{HTTP_UA};
  100. # We generally prefer this to be handled at the reverse proxy level.
  101. #my $prefer_ssl = $env->{HTTP_UPGRADE_INSECURE_REQUESTS};
  102. my $last_fetch = 0;
  103. if ( $env->{HTTP_IF_MODIFIED_SINCE} ) {
  104. $last_fetch = DateTime::Format::HTTP->parse_datetime( $env->{HTTP_IF_MODIFIED_SINCE} )->epoch();
  105. }
  106. #XXX Don't use statics anything that has a search query
  107. # On one hand, I don't want to DOS the disk, but I'd also like some like ?rss...
  108. # Should probably turn those into aliases.
  109. my $has_query = !!$env->{QUERY_STRING};
  110. my $query = {};
  111. $query = URL::Encode::url_params_mixed( $env->{QUERY_STRING} ) if $env->{QUERY_STRING};
  112. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  113. if ( $env->{REQUEST_METHOD} eq 'POST' ) {
  114. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  115. while ( $env->{'psgi.input'}->read( my $buf, $Trog::Vars::CHUNK_SIZE ) ) {
  116. $body->add($buf);
  117. }
  118. @$query{ keys( %{ $body->param } ) } = values( %{ $body->param } );
  119. @$query{ keys( %{ $body->upload } ) } = values( %{ $body->upload } );
  120. }
  121. # Grab the list of ACLs we want to add to a post, if any.
  122. $query->{acls} = [ $query->{acls} ] if ( $query->{acls} && ref $query->{acls} ne 'ARRAY' );
  123. # It's mod_rewrite!
  124. $path = '/index' if $path eq '/';
  125. #XXX this is hardcoded in browsers, so just rewrite the path
  126. $path = '/img/icon/favicon.ico' if $path eq '/favicon.ico';
  127. # Translate alias paths into their actual path
  128. $path = $aliases{$path} if exists $aliases{$path};
  129. # Figure out if we want compression or not
  130. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  131. $alist =~ s/\s//g;
  132. my @accept_encodings;
  133. @accept_encodings = split( /,/, $alist );
  134. my $deflate = grep { 'gzip' eq $_ } @accept_encodings;
  135. # Collapse multiple slashes in the path
  136. $path =~ s/[\/]+/\//g;
  137. # Let's open up our default route before we bother to see if users even exist
  138. return $routes{default}{callback}->($query) unless -f "config/setup";
  139. my $cookies = {};
  140. if ( $env->{HTTP_COOKIE} ) {
  141. $cookies = CGI::Cookie->parse( $env->{HTTP_COOKIE} );
  142. }
  143. # Set the IP of the request so we can fail2ban
  144. $Trog::Log::ip = $env->{HTTP_X_FORWARDED_FOR} || $env->{REMOTE_ADDR};
  145. my $active_user = '';
  146. $Trog::Log::user = 'nobody';
  147. if ( exists $cookies->{tcmslogin} ) {
  148. $active_user = Trog::Auth::session2user( $cookies->{tcmslogin}->value );
  149. $Trog::Log::user = $active_user if $active_user;
  150. }
  151. $query->{user_acls} = [];
  152. $query->{user_acls} = Trog::Auth::acls4user($active_user) // [] if $active_user;
  153. # Filter out passed ACLs which are naughty
  154. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  155. @{ $query->{acls} } = grep { $_ ne 'admin' } @{ $query->{acls} } unless $is_admin;
  156. # Ensure any short-circuit routes can log the request
  157. $query->{method} = $method;
  158. $query->{route} = $path;
  159. # Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  160. if ( index( $path, '/templates' ) == 0 || index( $path, '/statics' ) == 0 || $path =~ m/.*(\.psgi|\.pm)$/i ) {
  161. return _forbidden($query);
  162. }
  163. my $streaming = $env->{'psgi.streaming'};
  164. $query->{streaming} = $streaming;
  165. # If we have a static render, just use it instead (These will ALWAYS be correct, data saves invalidate this)
  166. # TODO: make this key on admin INSTEAD of active user when we add non-admin users.
  167. $query->{start} = $start;
  168. if ( !$active_user && !$has_query ) {
  169. return _static( $fullpath, "$path.z", $start, $streaming ) if -f "www/statics/$path.z" && $deflate;
  170. return _static( $fullpath, $path, $start, $streaming ) if -f "www/statics/$path";
  171. }
  172. # Handle HTTP range/streaming requests
  173. my $range = $env->{HTTP_RANGE} || "bytes=0-" if $env->{HTTP_RANGE} || $env->{HTTP_IF_RANGE};
  174. my @ranges;
  175. if ($range) {
  176. $range =~ s/bytes=//g;
  177. push(
  178. @ranges,
  179. map {
  180. [ split( /-/, $_ ) ];
  181. #$tuples[1] //= $tuples[0] + $Trog::Vars::CHUNK_SIZE;
  182. #\@tuples
  183. } split( /,/, $range )
  184. );
  185. }
  186. return Trog::FileHandler::serve( $fullpath, "www/$path", $start, $streaming, \@ranges, $last_fetch, $deflate ) if -f "www/$path";
  187. return Trog::FileHandler::serve( $fullpath, "totp/$path", $start, $streaming, \@ranges, $last_fetch, $deflate ) if -f "totp/$path" && $active_user;
  188. #Handle regex/capture routes
  189. if ( !exists $routes{$path} ) {
  190. my @captures;
  191. # TODO can optimize by having separate hashes for capture/non-capture routes
  192. foreach my $pattern ( keys(%routes) ) {
  193. @captures = $path =~ m/^$pattern$/;
  194. if (@captures) {
  195. $path = $pattern;
  196. foreach my $field ( @{ $routes{$path}{captures} } ) {
  197. $routes{$path}{data} //= {};
  198. $routes{$path}{data}{$field} = shift @captures;
  199. }
  200. last;
  201. }
  202. }
  203. }
  204. $query->{fullpath} = $fullpath;
  205. $query->{deflate} = $deflate;
  206. $query->{user} = $active_user;
  207. return _forbidden($query) if exists $routes{$path}{auth} && !$active_user;
  208. return _notfound($query) unless exists $routes{$path} && ref $routes{$path} eq 'HASH' && keys( %{ $routes{$path} } );
  209. return _badrequest($query) unless grep { $env->{REQUEST_METHOD} eq $_ } ( $routes{$path}{method} || '', 'HEAD' );
  210. @{$query}{ keys( %{ $routes{$path}{'data'} } ) } = values( %{ $routes{$path}{'data'} } ) if ref $routes{$path}{'data'} eq 'HASH' && %{ $routes{$path}{'data'} };
  211. #Set various things we don't want overridden
  212. $query->{body} = '';
  213. $query->{dnt} = $env->{HTTP_DNT};
  214. $query->{user} = $active_user;
  215. $query->{domain} = $domain;
  216. $query->{route} = $path;
  217. $query->{scheme} = $scheme;
  218. $query->{social_meta} = 1;
  219. $query->{primary_post} = {};
  220. $query->{has_query} = $has_query;
  221. $query->{port} = $port;
  222. $query->{lang} = $lang;
  223. $query->{accept} = $accept;
  224. # Redirecting somewhere naughty not allow
  225. $query->{to} = URI->new( $query->{to} // '' )->path() || $query->{to} if $query->{to};
  226. #XXX there is a trick to now use strict refs, but I don't remember it right at the moment
  227. {
  228. no strict 'refs';
  229. my $output = $routes{$path}{callback}->($query);
  230. die "$path returned no data!" unless ref $output eq 'ARRAY' && @$output == 3;
  231. my $pport = defined $query->{port} ? ":$query->{port}" : "";
  232. INFO("$env->{REQUEST_METHOD} $output->[0] $fullpath");
  233. # Append server-timing headers
  234. my $tot = tv_interval($start) * 1000;
  235. push( @{ $output->[1] }, 'Server-Timing' => "app;dur=$tot" );
  236. return $output;
  237. }
  238. }
  239. #XXX Return a clone of the routing table ref, because code modifies it later
  240. sub _routes ($data) {
  241. state %routes;
  242. return clone(\%routes) if %routes;
  243. if (!$data) {
  244. my $conf = Trog::Config::get();
  245. $data = Trog::Data->new($conf);
  246. }
  247. my %roots = $data->routes();
  248. %routes = %Trog::Routes::HTML::routes;
  249. @routes{ keys(%Trog::Routes::JSON::routes) } = values(%Trog::Routes::JSON::routes);
  250. @routes{ keys(%roots) } = values(%roots);
  251. # Add in global routes, here because they *must* know about all other routes
  252. # Also, nobody should ever override these.
  253. $routes{'/robots.txt'} = {
  254. method => 'GET',
  255. callback => \&robots,
  256. };
  257. return clone(\%routes);
  258. }
  259. =head2 robots
  260. Return an appropriate robots.txt
  261. This is a "special" route as it needs to know about all the routes in order to disallow noindex=1 routes.
  262. =cut
  263. sub robots ($query) {
  264. state $etag = "robots-" . time();
  265. my $routes = _routes();
  266. # If there's a 'capture' route, we need to format it correctly.
  267. state @banned = map { exists $routes->{$_}{robot_name} ? $routes->{$_}{robot_name} : $_ } grep { $routes->{$_}{noindex} } sort keys(%$routes);
  268. return Trog::Renderer->render(
  269. contenttype => 'text/plain',
  270. template => 'robots.tx',
  271. data => {
  272. etag => $etag,
  273. banned => \@banned,
  274. %$query,
  275. },
  276. code => 200,
  277. );
  278. }
  279. sub _generic ( $type, $query ) {
  280. return _static( "$type.z", $query->{start}, $query->{streaming} ) if -f "www/statics/$type.z";
  281. return _static( $type, $query->{start}, $query->{streaming} ) if -f "www/statics/$type";
  282. my %lookup = (
  283. notfound => \&Trog::Routes::HTML::notfound,
  284. forbidden => \&Trog::Routes::HTML::forbidden,
  285. badrequest => \&Trog::Routes::HTML::badrequest,
  286. toolong => \&Trog::Routes::HTML::toolong,
  287. error => \&Trog::Routes::HTML::error,
  288. );
  289. return $lookup{$type}->($query);
  290. }
  291. sub _notfound ($query) {
  292. INFO("$query->{method} 404 $query->{fullpath}");
  293. return _generic( 'notfound', $query );
  294. }
  295. sub _forbidden ($query) {
  296. INFO("$query->{method} 403 $query->{fullpath}");
  297. return _generic( 'forbidden', $query );
  298. }
  299. sub _badrequest ($query) {
  300. INFO("$query->{method} 400 $query->{fullpath}");
  301. return _generic( 'badrequest', $query );
  302. }
  303. sub _toolong ($query) {
  304. INFO("$query->{method} 419 $query->{fullpath}");
  305. return _generic( 'toolong', {} );
  306. }
  307. sub _error ($query) {
  308. $query->{method} //= "UNKNOWN";
  309. $query->{fullpath} //= $query->{route} // '/?';
  310. INFO("$query->{method} 500 $query->{fullpath}");
  311. return _generic( 'error', $query );
  312. }
  313. sub _static ( $fullpath, $path, $start, $streaming, $last_fetch = 0 ) {
  314. DEBUG("Rendering static for $path");
  315. # XXX because of psgi I can't just vomit the file directly
  316. if ( open( my $fh, '<', "www/statics/$path" ) ) {
  317. my $headers = '';
  318. # NOTE: this is relying on while advancing the file pointer
  319. while (<$fh>) {
  320. last if $_ eq "\n";
  321. $headers .= $_;
  322. }
  323. my ( undef, undef, $status, undef, $headers_parsed ) = HTTP::Parser::XS::parse_http_response( "$headers\n", HEADERS_AS_HASHREF );
  324. #XXX need to put this into the file itself
  325. my $mt = ( stat($fh) )[9];
  326. my @gm = gmtime($mt);
  327. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  328. my $code = $mt > $last_fetch ? $status : 304;
  329. $headers_parsed->{"Last-Modified"} = $now_string;
  330. # Append server-timing headers
  331. my $tot = tv_interval($start) * 1000;
  332. $headers_parsed->{'Server-Timing'} = "static;dur=$tot";
  333. #XXX uwsgi just opens the file *again* when we already have a filehandle if it has a path.
  334. # starman by comparison doesn't violate the principle of least astonishment here.
  335. # This is probably a performance optimization, but makes the kind of micromanagement I need to do inconvenient.
  336. # As such, we will just return a stream.
  337. INFO("GET 200 $fullpath");
  338. return sub {
  339. my $responder = shift;
  340. #push(@headers, 'Content-Length' => $sz);
  341. my $writer = $responder->( [ $code, [%$headers_parsed] ] );
  342. while ( $fh->read( my $buf, $Trog::Vars::CHUNK_SIZE ) ) {
  343. $writer->write($buf);
  344. }
  345. close $fh;
  346. $writer->close;
  347. }
  348. if $streaming;
  349. return [ $code, [%$headers_parsed], $fh ];
  350. }
  351. INFO("GET 403 $fullpath");
  352. return [ 403, [ 'Content-Type' => $Trog::Vars::content_types{text} ], ["STAY OUT YOU RED MENACE"] ];
  353. }
  354. 1;