TCMS.pm 8.0 KB

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