TCMS.pm 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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::Deflate();
  16. use Time::HiRes qw{gettimeofday tv_interval};
  17. #Grab our custom routes
  18. use lib 'lib';
  19. use Trog::Routes::HTML;
  20. use Trog::Routes::JSON;
  21. use Trog::Auth;
  22. use Trog::Utils;
  23. use Trog::Config;
  24. use Trog::Data;
  25. use Trog::Vars;
  26. # Troglodyne philosophy - simple as possible
  27. # Import the routes
  28. my $conf = Trog::Config::get();
  29. my $data = Trog::Data->new($conf);
  30. my %roots = $data->routes();
  31. my %routes = %Trog::Routes::HTML::routes;
  32. @routes{keys(%Trog::Routes::JSON::routes)} = values(%Trog::Routes::JSON::routes);
  33. @routes{keys(%roots)} = values(%roots);
  34. my %aliases = $data->aliases();
  35. #1MB chunks
  36. my $CHUNK_SIZE = 1024000;
  37. #Stuff that isn't in upstream finders
  38. my %extra_types = (
  39. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  40. );
  41. =head2 app()
  42. Dispatches requests based on %routes built above.
  43. 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.
  44. 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.
  45. =cut
  46. sub app {
  47. # Start the server timing clock
  48. my $start = [gettimeofday];
  49. my $env = shift;
  50. my $last_fetch = 0;
  51. if ($env->{HTTP_IF_MODIFIED_SINCE}) {
  52. $last_fetch = DateTime::Format::HTTP->parse_datetime($env->{HTTP_IF_MODIFIED_SINCE})->epoch();
  53. }
  54. my $query = {};
  55. $query = URL::Encode::url_params_mixed($env->{QUERY_STRING}) if $env->{QUERY_STRING};
  56. my $path = $env->{PATH_INFO};
  57. # Translate alias paths into their actual path
  58. $path = $aliases{$path} if exists $aliases{$path};
  59. # Collapse multiple slashes in the path
  60. $path =~ s/[\/]+/\//g;
  61. # Let's open up our default route before we bother to see if users even exist
  62. return $routes{default}{callback}->($query) unless -f "config/setup";
  63. my $cookies = {};
  64. if ($env->{HTTP_COOKIE}) {
  65. $cookies = CGI::Cookie->parse($env->{HTTP_COOKIE});
  66. }
  67. my $active_user = '';
  68. if (exists $cookies->{tcmslogin}) {
  69. $active_user = Trog::Auth::session2user($cookies->{tcmslogin}->value);
  70. }
  71. #Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  72. if (index($path,'/templates') == 0 || $path =~ m/.*\.psgi$/i ) {
  73. return Trog::Routes::HTML::forbidden($query);
  74. }
  75. # If it's just a file, serve it up
  76. my $alist = $env->{HTTP_ACCEPT_ENCODING} || '';
  77. $alist =~ s/\s//g;
  78. my @accept_encodings;
  79. @accept_encodings = split(/,/, $alist);
  80. my $deflate = grep { 'deflate' eq $_ } @accept_encodings;
  81. return _serve("www/$path", $start, $env->{'psgi.streaming'}, $last_fetch, $deflate) if -f "www/$path";
  82. #Handle regex/capture routes
  83. if (!exists $routes{$path}) {
  84. my @captures;
  85. foreach my $pattern (keys(%routes)) {
  86. @captures = $path =~ m/^$pattern$/;
  87. if (@captures) {
  88. $path = $pattern;
  89. foreach my $field (@{$routes{$path}{captures}}) {
  90. $routes{$path}{data} //= {};
  91. $routes{$path}{data}{$field} = shift @captures;
  92. }
  93. last;
  94. }
  95. }
  96. }
  97. $query->{deflate} = $deflate;
  98. $query->{user} = $active_user;
  99. return Trog::Routes::HTML::notfound($query) unless exists $routes{$path};
  100. return Trog::Routes::HTML::badrequest($query) unless grep { $env->{REQUEST_METHOD} eq $_ } ($routes{$path}{method},'HEAD');
  101. @{$query}{keys(%{$routes{$path}{'data'}})} = values(%{$routes{$path}{'data'}}) if ref $routes{$path}{'data'} eq 'HASH' && %{$routes{$path}{'data'}};
  102. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  103. if ($env->{REQUEST_METHOD} eq 'POST') {
  104. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  105. while ( read($env->{'psgi.input'}, my $buf, $CHUNK_SIZE) ) {
  106. $body->add($buf);
  107. }
  108. @$query{keys(%{$body->param})} = values(%{$body->param});
  109. @$query{keys(%{$body->upload})} = values(%{$body->upload});
  110. }
  111. #Set various things we don't want overridden
  112. $query->{acls} = Trog::Auth::acls4user($active_user) // [] if $active_user;
  113. $query->{user} = $active_user;
  114. $query->{domain} = $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST};
  115. $query->{route} = $path;
  116. #$query->{route} = $env->{REQUEST_URI};
  117. #$query->{route} =~ s/\?\Q$env->{QUERY_STRING}\E//;
  118. $query->{scheme} = $env->{'psgi.url_scheme'} // 'http';
  119. $query->{social_meta} = 1;
  120. $query->{primary_post} = {};
  121. #XXX there is a trick to now use strict refs, but I don't remember it right at the moment
  122. {
  123. no strict 'refs';
  124. my $output = $routes{$path}{callback}->($query);
  125. # Append server-timing headers
  126. my $tot = tv_interval($start) * 1000;
  127. push(@{$output->[1]}, 'Server-Timing' => "app;dur=$tot");
  128. return $output;
  129. }
  130. };
  131. sub _serve ($path, $start, $streaming=0, $last_fetch=0, $deflate=0) {
  132. my $mf = Mojo::File->new($path);
  133. my $ext = '.'.$mf->extname();
  134. my $ft;
  135. if ($ext) {
  136. $ft = Plack::MIME->mime_type($ext) if $ext;
  137. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  138. }
  139. $ft ||= $Trog::Vars::content_types{plain};
  140. my $ct = 'Content-type';
  141. my @headers = ($ct => $ft);
  142. #TODO use static Cache-Control for everything but JS/CSS?
  143. push(@headers,'Cache-control' => $Trog::Vars::cache_control{revalidate});
  144. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  145. my $mt = (stat($path))[9];
  146. my $sz = (stat(_))[7];
  147. my @gm = gmtime($mt);
  148. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  149. my $code = $mt > $last_fetch ? 200 : 304;
  150. #XXX something broken about the above logic
  151. $code=200;
  152. #XXX doing metadata=preload on videos doesn't work right?
  153. #push(@headers, "Content-Length: $sz");
  154. push(@headers, "Last-Modified" => $now_string);
  155. if (open(my $fh, '<', $path)) {
  156. return sub {
  157. my $responder = shift;
  158. my $writer = $responder->([ $code, \@headers]);
  159. while ( read($fh, my $buf, $CHUNK_SIZE) ) {
  160. $writer->write($buf);
  161. }
  162. close $fh;
  163. $writer->close;
  164. } if $streaming && $sz > $CHUNK_SIZE;
  165. #Return data in the event the caller does not support deflate
  166. if (!$deflate) {
  167. push( @headers, "Content-Length" => $sz );
  168. # Append server-timing headers
  169. my $tot = tv_interval($start) * 1000;
  170. push(@headers, 'Server-Timing' => "file;dur=$tot");
  171. return [ $code, \@headers, $fh];
  172. }
  173. #Compress everything less than 1MB
  174. push( @headers, "Content-Encoding" => "deflate" );
  175. my $dfh;
  176. IO::Compress::Deflate::deflate( $fh => \$dfh );
  177. print $IO::Compress::Deflate::DeflateError if $IO::Compress::Deflate::DeflateError;
  178. push( @headers, "Content-Length" => length($dfh) );
  179. # Append server-timing headers
  180. my $tot = tv_interval($start) * 1000;
  181. push(@headers, 'Server-Timing' => "file;dur=$tot");
  182. return [ $code, \@headers, [$dfh]];
  183. }
  184. return [ 403, [$ct => $Trog::Vars::content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  185. }
  186. 1;