TCMS.pm 11 KB

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