TCMS.pm 13 KB

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