TCMS.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. # Troglodyne philosophy - simple as possible
  31. # Import the routes
  32. my $conf = Trog::Config::get();
  33. my $data = Trog::Data->new($conf);
  34. my %roots = $data->routes();
  35. my %routes = %Trog::Routes::HTML::routes;
  36. @routes{ keys(%Trog::Routes::JSON::routes) } = values(%Trog::Routes::JSON::routes);
  37. @routes{ keys(%roots) } = values(%roots);
  38. my %aliases = $data->aliases();
  39. # XXX this is built progressively across the forks, leading to inconsistent behavior.
  40. # This should eventually be pre-filled from DB.
  41. my %etags;
  42. #1MB chunks
  43. my $CHUNK_SIZE = 1024000;
  44. my $CHUNK_SEP = 'tCMSep666YOLO42069';
  45. #Stuff that isn't in upstream finders
  46. my %extra_types = (
  47. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  48. );
  49. =head2 app()
  50. Dispatches requests based on %routes built above.
  51. 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.
  52. 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.
  53. =cut
  54. sub app {
  55. # Start the server timing clock
  56. my $start = [gettimeofday];
  57. my $env = shift;
  58. return _toolong() if length( $env->{REQUEST_URI} ) > 2048;
  59. # Check eTags. If we don't know about it, just assume it's good and lazily fill the cache
  60. # XXX yes, this allows cache poisoning...but only for logged in users!
  61. if ( $env->{HTTP_IF_NONE_MATCH} ) {
  62. return [ 304, [], [''] ] if $env->{HTTP_IF_NONE_MATCH} eq ( $etags{ $env->{REQUEST_URI} } || '' );
  63. $etags{ $env->{REQUEST_URI} } = $env->{HTTP_IF_NONE_MATCH} unless exists $etags{ $env->{REQUEST_URI} };
  64. }
  65. my $last_fetch = 0;
  66. if ( $env->{HTTP_IF_MODIFIED_SINCE} ) {
  67. $last_fetch = DateTime::Format::HTTP->parse_datetime( $env->{HTTP_IF_MODIFIED_SINCE} )->epoch();
  68. }
  69. #XXX Don't use statics anything that has a search query
  70. # On one hand, I don't want to DOS the disk, but I'd also like some like ?rss...
  71. # Should probably turn those into aliases.
  72. my $has_query = !!$env->{QUERY_STRING};
  73. my $query = {};
  74. $query = URL::Encode::url_params_mixed( $env->{QUERY_STRING} ) if $env->{QUERY_STRING};
  75. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  76. if ( $env->{REQUEST_METHOD} eq 'POST' ) {
  77. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  78. while ( $env->{'psgi.input'}->read( my $buf, $CHUNK_SIZE ) ) {
  79. $body->add($buf);
  80. }
  81. @$query{ keys( %{ $body->param } ) } = values( %{ $body->param } );
  82. @$query{ keys( %{ $body->upload } ) } = values( %{ $body->upload } );
  83. }
  84. # Grab the list of ACLs we want to add to a post, if any.
  85. $query->{acls} = [ $query->{acls} ] if ( $query->{acls} && ref $query->{acls} ne 'ARRAY' );
  86. my $path = $env->{PATH_INFO};
  87. $path = '/index' if $path eq '/';
  88. # Translate alias paths into their actual path
  89. $path = $aliases{$path} if exists $aliases{$path};
  90. # Figure out if we want compression or not
  91. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  92. $alist =~ s/\s//g;
  93. my @accept_encodings;
  94. @accept_encodings = split( /,/, $alist );
  95. my $deflate = grep { 'gzip' eq $_ } @accept_encodings;
  96. # Collapse multiple slashes in the path
  97. $path =~ s/[\/]+/\//g;
  98. # Let's open up our default route before we bother to see if users even exist
  99. return $routes{default}{callback}->($query) unless -f "config/setup";
  100. my $cookies = {};
  101. if ( $env->{HTTP_COOKIE} ) {
  102. $cookies = CGI::Cookie->parse( $env->{HTTP_COOKIE} );
  103. }
  104. my $active_user = '';
  105. $Trog::Log::user = 'nobody';
  106. if ( exists $cookies->{tcmslogin} ) {
  107. $active_user = Trog::Auth::session2user( $cookies->{tcmslogin}->value );
  108. $Trog::Log::user = $active_user if $active_user;
  109. }
  110. $query->{user_acls} = [];
  111. $query->{user_acls} = Trog::Auth::acls4user($active_user) // [] if $active_user;
  112. # Log the request.
  113. Trog::Log::uuid(UUID::Tiny::create_uuid_as_string( UUID::Tiny::UUID_V1, UUID::Tiny::UUID_NS_DNS ));
  114. INFO("$env->{REQUEST_METHOD} $path");
  115. # Filter out passed ACLs which are naughty
  116. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  117. @{ $query->{acls} } = grep { $_ ne 'admin' } @{ $query->{acls} } unless $is_admin;
  118. # Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  119. if ( index( $path, '/templates' ) == 0 || index( $path, '/statics' ) == 0 || $path =~ m/.*(\.psgi|\.pm)$/i ) {
  120. return _forbidden($query);
  121. }
  122. my $streaming = $env->{'psgi.streaming'};
  123. $query->{streaming} = $streaming;
  124. # If we have a static render, just use it instead (These will ALWAYS be correct, data saves invalidate this)
  125. # TODO: make this key on admin INSTEAD of active user when we add non-admin users.
  126. $query->{start} = $start;
  127. if ( !$active_user && !$has_query ) {
  128. return _static( "$path.z", $start, $streaming ) if -f "www/statics/$path.z" && $deflate;
  129. return _static( $path, $start, $streaming ) if -f "www/statics/$path";
  130. }
  131. # Handle HTTP range/streaming requests
  132. my $range = $env->{HTTP_RANGE} || "bytes=0-" if $env->{HTTP_RANGE} || $env->{HTTP_IF_RANGE};
  133. my @ranges;
  134. if ($range) {
  135. $range =~ s/bytes=//g;
  136. push(
  137. @ranges,
  138. map {
  139. [ split( /-/, $_ ) ];
  140. #$tuples[1] //= $tuples[0] + $CHUNK_SIZE;
  141. #\@tuples
  142. } split( /,/, $range )
  143. );
  144. }
  145. return _serve( "www/$path", $start, $streaming, \@ranges, $last_fetch, $deflate ) if -f "www/$path";
  146. return _serve( "totp/$path", $start, $streaming, \@ranges, $last_fetch, $deflate ) if -f "totp/$path" && $active_user;
  147. #Handle regex/capture routes
  148. if ( !exists $routes{$path} ) {
  149. my @captures;
  150. foreach my $pattern ( keys(%routes) ) {
  151. @captures = $path =~ m/^$pattern$/;
  152. if (@captures) {
  153. $path = $pattern;
  154. foreach my $field ( @{ $routes{$path}{captures} } ) {
  155. $routes{$path}{data} //= {};
  156. $routes{$path}{data}{$field} = shift @captures;
  157. }
  158. last;
  159. }
  160. }
  161. }
  162. $query->{deflate} = $deflate;
  163. $query->{user} = $active_user;
  164. return _forbidden($query) if $routes{$path}{auth} && !$active_user;
  165. return _notfound($query) unless exists $routes{$path};
  166. return _badrequest($query) unless grep { $env->{REQUEST_METHOD} eq $_ } ( $routes{$path}{method} || '', 'HEAD' );
  167. @{$query}{ keys( %{ $routes{$path}{'data'} } ) } = values( %{ $routes{$path}{'data'} } ) if ref $routes{$path}{'data'} eq 'HASH' && %{ $routes{$path}{'data'} };
  168. #Set various things we don't want overridden
  169. $query->{body} = '';
  170. $query->{dnt} = $env->{HTTP_DNT};
  171. $query->{user} = $active_user;
  172. $query->{domain} = $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST};
  173. $query->{route} = $path;
  174. $query->{scheme} = $env->{'psgi.url_scheme'} // 'http';
  175. $query->{social_meta} = 1;
  176. $query->{primary_post} = {};
  177. $query->{has_query} = $has_query;
  178. #XXX there is a trick to now use strict refs, but I don't remember it right at the moment
  179. {
  180. no strict 'refs';
  181. my $output = $routes{$path}{callback}->($query);
  182. # Append server-timing headers
  183. my $tot = tv_interval($start) * 1000;
  184. push( @{ $output->[1] }, 'Server-Timing' => "app;dur=$tot" );
  185. return $output;
  186. }
  187. }
  188. sub _generic ( $type, $query ) {
  189. return _static( "$type.z", $query->{start}, $query->{streaming} ) if -f "www/statics/$type.z";
  190. return _static( $type, $query->{start}, $query->{streaming} ) if -f "www/statics/$type";
  191. my %lookup = (
  192. notfound => \&Trog::Routes::HTML::notfound,
  193. forbidden => \&Trog::Routes::HTML::forbidden,
  194. badrequest => \&Trog::Routes::HTML::badrequest,
  195. toolong => \&Trog::Routes::HTML::toolong,
  196. );
  197. return $lookup{$type}->($query);
  198. }
  199. sub _notfound ($query) {
  200. return _generic( 'notfound', $query );
  201. }
  202. sub _forbidden ($query) {
  203. return _generic( 'forbidden', $query );
  204. }
  205. sub _badrequest ($query) {
  206. return _generic( 'badrequest', $query );
  207. }
  208. sub _toolong() {
  209. return _generic( 'toolong', {} );
  210. }
  211. sub _static ( $path, $start, $streaming, $last_fetch = 0 ) {
  212. # XXX because of psgi I can't just vomit the file directly
  213. if ( open( my $fh, '<', "www/statics/$path" ) ) {
  214. my $headers = '';
  215. # NOTE: this is relying on while advancing the file pointer
  216. while (<$fh>) {
  217. last if $_ eq "\n";
  218. $headers .= $_;
  219. }
  220. my ( undef, undef, $status, undef, $headers_parsed ) = HTTP::Parser::XS::parse_http_response( "$headers\n", HEADERS_AS_HASHREF );
  221. #XXX need to put this into the file itself
  222. my $mt = ( stat($fh) )[9];
  223. my @gm = gmtime($mt);
  224. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  225. my $code = $mt > $last_fetch ? $status : 304;
  226. $headers_parsed->{"Last-Modified"} = $now_string;
  227. # Append server-timing headers
  228. my $tot = tv_interval($start) * 1000;
  229. $headers_parsed->{'Server-Timing'} = "static;dur=$tot";
  230. #XXX uwsgi just opens the file *again* when we already have a filehandle if it has a path.
  231. # starman by comparison doesn't violate the principle of least astonishment here.
  232. # This is probably a performance optimization, but makes the kind of micromanagement I need to do inconvenient.
  233. # As such, we will just return a stream.
  234. return sub {
  235. my $responder = shift;
  236. #push(@headers, 'Content-Length' => $sz);
  237. my $writer = $responder->( [ $code, [%$headers_parsed] ] );
  238. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  239. $writer->write($buf);
  240. }
  241. close $fh;
  242. $writer->close;
  243. }
  244. if $streaming;
  245. return [ $code, [%$headers_parsed], $fh ];
  246. }
  247. return [ 403, [ 'Content-Type' => $Trog::Vars::content_types{plain} ], ["STAY OUT YOU RED MENACE"] ];
  248. }
  249. sub _range ( $fh, $ranges, $sz, %headers ) {
  250. # Set mode
  251. my $primary_ct = "Content-Type: $headers{'Content-type'}";
  252. my $is_multipart = scalar(@$ranges) > 1;
  253. if ($is_multipart) {
  254. $headers{'Content-type'} = "multipart/byteranges; boundary=$CHUNK_SEP";
  255. }
  256. my $code = 206;
  257. my $fc = '';
  258. # Calculate the content-length up-front. We have to fix unspecified lengths first, and reject bad requests.
  259. foreach my $range (@$ranges) {
  260. $range->[1] //= $sz - 1;
  261. return [ 416, [%headers], ["Requested range not satisfiable"] ] if $range->[0] > $sz || $range->[0] < 0 || $range->[1] < 0 || $range->[0] > $range->[1];
  262. }
  263. $headers{'Content-Length'} = List::Util::sum( map { my $arr = $_; $arr->[1] + 1, -$arr->[0] } @$ranges );
  264. #XXX Add the entity header lengths to the value - should hash-ify this to DRY
  265. if ($is_multipart) {
  266. foreach my $range (@$ranges) {
  267. $headers{'Content-Length'} += length("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n");
  268. $fc = "\n";
  269. }
  270. $headers{'Content-Length'} += length("\n--$CHUNK_SEP\--\n");
  271. $fc = '';
  272. }
  273. return sub {
  274. my $responder = shift;
  275. my $writer;
  276. foreach my $range (@$ranges) {
  277. $headers{'Content-Range'} = "bytes $range->[0]-$range->[1]/$sz" unless $is_multipart;
  278. $writer //= $responder->( [ $code, [%headers] ] );
  279. $writer->write("$fc--$CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n") if $is_multipart;
  280. $fc = "\n";
  281. my $len = List::Util::min( $sz, $range->[1] + 1 ) - $range->[0];
  282. $fh->seek( $range->[0], 0 );
  283. while ($len) {
  284. $fh->read( my $buf, List::Util::min( $len, $CHUNK_SIZE ) );
  285. $writer->write($buf);
  286. # Adjust for amount written
  287. $len = List::Util::max( $len - $CHUNK_SIZE, 0 );
  288. }
  289. }
  290. $fh->close();
  291. $writer->write("\n--$CHUNK_SEP\--\n") if $is_multipart;
  292. $writer->close;
  293. };
  294. }
  295. sub _serve ( $path, $start, $streaming, $ranges, $last_fetch = 0, $deflate = 0 ) {
  296. my $mf = Mojo::File->new($path);
  297. my $ext = '.' . $mf->extname();
  298. my $ft;
  299. if ($ext) {
  300. $ft = Plack::MIME->mime_type($ext) if $ext;
  301. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  302. }
  303. $ft ||= $Trog::Vars::content_types{plain};
  304. my $ct = 'Content-type';
  305. my @headers = ( $ct => $ft );
  306. #TODO use static Cache-Control for everything but JS/CSS?
  307. push( @headers, 'Cache-control' => $Trog::Vars::cache_control{revalidate} );
  308. push( @headers, 'Accept-Ranges' => 'bytes' );
  309. my $mt = ( stat($path) )[9];
  310. my $sz = ( stat(_) )[7];
  311. my @gm = gmtime($mt);
  312. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  313. my $code = $mt > $last_fetch ? 200 : 304;
  314. push( @headers, "Last-Modified" => $now_string );
  315. push( @headers, 'Vary' => 'Accept-Encoding' );
  316. if ( open( my $fh, '<', $path ) ) {
  317. return _range( $fh, $ranges, $sz, @headers ) if @$ranges && $streaming;
  318. # Transfer-encoding: chunked
  319. return sub {
  320. my $responder = shift;
  321. push( @headers, 'Content-Length' => $sz );
  322. my $writer = $responder->( [ $code, \@headers ] );
  323. while ( $fh->read( my $buf, $CHUNK_SIZE ) ) {
  324. $writer->write($buf);
  325. }
  326. close $fh;
  327. $writer->close;
  328. }
  329. if $streaming && $sz > $CHUNK_SIZE;
  330. #Return data in the event the caller does not support deflate
  331. if ( !$deflate ) {
  332. push( @headers, "Content-Length" => $sz );
  333. # Append server-timing headers
  334. my $tot = tv_interval($start) * 1000;
  335. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  336. return [ $code, \@headers, $fh ];
  337. }
  338. #Compress everything less than 1MB
  339. push( @headers, "Content-Encoding" => "gzip" );
  340. my $dfh;
  341. IO::Compress::Gzip::gzip( $fh => \$dfh );
  342. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  343. push( @headers, "Content-Length" => length($dfh) );
  344. # Append server-timing headers
  345. my $tot = tv_interval($start) * 1000;
  346. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  347. return [ $code, \@headers, [$dfh] ];
  348. }
  349. return [ 403, [ $ct => $Trog::Vars::content_types{plain} ], ["STAY OUT YOU RED MENACE"] ];
  350. }
  351. 1;