TCMS.pm 14 KB

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