TCMS.pm 7.0 KB

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