TCMS.pm 11 KB

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