TCMS.pm 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package TCMS;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures};
  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 Encode qw{encode_utf8};
  14. use CGI::Cookie ();
  15. use File::Basename();
  16. use IO::Compress::Deflate();
  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. # 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. #1MB chunks
  34. my $CHUNK_SIZE = 1024000;
  35. # Things we will actually produce from routes rather than just serving up files
  36. my $ct = 'Content-type';
  37. my %content_types = (
  38. plain => "text/plain;",
  39. html => "text/html; charset=UTF-8",
  40. json => "application/json;",
  41. blob => "application/octet-stream;",
  42. );
  43. my $cc = 'Cache-control';
  44. my %cache_control = (
  45. revalidate => "no-cache, max-age=0",
  46. nocache => "no-store",
  47. static => "public, max-age=604800, immutable",
  48. );
  49. #Stuff that isn't in upstream finders
  50. my %extra_types = (
  51. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  52. );
  53. =head2 app()
  54. Dispatches requests based on %routes built above.
  55. 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.
  56. 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.
  57. =cut
  58. sub app {
  59. my $env = shift;
  60. #use Data::Dumper;
  61. #print Dumper($env);
  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. my $query = {};
  67. $query = URL::Encode::url_params_mixed($env->{QUERY_STRING}) if $env->{QUERY_STRING};
  68. my $path = $env->{PATH_INFO};
  69. # Collapse multiple slashes in the path
  70. $path =~ s/[\/]+/\//g;
  71. # Let's open up our default route before we bother to see if users even exist
  72. return $routes{default}{callback}->($query,\&_render) unless -f "config/setup";
  73. my $cookies = {};
  74. if ($env->{HTTP_COOKIE}) {
  75. $cookies = CGI::Cookie->parse($env->{HTTP_COOKIE});
  76. }
  77. my $active_user = '';
  78. if (exists $cookies->{tcmslogin}) {
  79. $active_user = Trog::Auth::session2user($cookies->{tcmslogin}->value);
  80. }
  81. #Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  82. if (index($path,'/templates') == 0 || $path =~ m/.*\.psgi$/i ) {
  83. return Trog::Routes::HTML::forbidden($query, \&_render);
  84. }
  85. # If it's just a file, serve it up
  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 { 'deflate' eq $_ } @accept_encodings;
  91. return _serve("www/$path", $env->{'psgi.streaming'}, $last_fetch, $deflate) if -f "www/$path";
  92. #Handle regex/capture routes
  93. if (!exists $routes{$path}) {
  94. my @captures;
  95. foreach my $pattern (keys(%routes)) {
  96. @captures = $path =~ m/^$pattern$/;
  97. if (@captures) {
  98. $path = $pattern;
  99. foreach my $field (@{$routes{$path}{captures}}) {
  100. $routes{$path}{data} //= {};
  101. $routes{$path}{data}{$field} = shift @captures;
  102. }
  103. last;
  104. }
  105. }
  106. }
  107. $query->{deflate} = $deflate;
  108. $query->{user} = $active_user;
  109. return Trog::Routes::HTML::notfound($query, \&_render) unless exists $routes{$path};
  110. return Trog::Routes::HTML::badrequest($query, \&_render) unless grep { $env->{REQUEST_METHOD} eq $_ } ($routes{$path}{method},'HEAD');
  111. @{$query}{keys(%{$routes{$path}{'data'}})} = values(%{$routes{$path}{'data'}}) if ref $routes{$path}{'data'} eq 'HASH' && %{$routes{$path}{'data'}};
  112. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  113. if ($env->{REQUEST_METHOD} eq 'POST') {
  114. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  115. while ( read($env->{'psgi.input'}, my $buf, $CHUNK_SIZE) ) {
  116. $body->add($buf);
  117. }
  118. @$query{keys(%{$body->param})} = values(%{$body->param});
  119. @$query{keys(%{$body->upload})} = values(%{$body->upload});
  120. }
  121. #Set various things we don't want overridden
  122. $query->{acls} = Trog::Auth::acls4user($active_user) // [] if $active_user;
  123. $query->{user} = $active_user;
  124. $query->{domain} = $env->{HTTP_X_FORWARDED_HOST} || $env->{HTTP_HOST};
  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. my $output = $routes{$path}{callback}->($query, \&_render);
  131. return $output;
  132. };
  133. sub _serve ($path, $streaming=0, $last_fetch=0, $deflate=0) {
  134. my $mf = Mojo::File->new($path);
  135. my $ext = '.'.$mf->extname();
  136. my $ft;
  137. if ($ext) {
  138. $ft = Plack::MIME->mime_type($ext) if $ext;
  139. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  140. }
  141. $ft ||= $content_types{plain};
  142. my @headers = ($ct => $ft);
  143. #TODO use static Cache-Control for everything but JS/CSS?
  144. push(@headers,$cc => $cache_control{revalidate});
  145. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  146. my $mt = (stat($path))[9];
  147. my $sz = (stat(_))[7];
  148. my @gm = gmtime($mt);
  149. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  150. my $code = $mt > $last_fetch ? 200 : 304;
  151. #XXX something broken about the above logic
  152. $code=200;
  153. #XXX doing metadata=preload on videos doesn't work right?
  154. #push(@headers, "Content-Length: $sz");
  155. push(@headers, "Last-Modified" => $now_string);
  156. if (open(my $fh, '<', $path)) {
  157. return sub {
  158. my $responder = shift;
  159. my $writer = $responder->([ $code, \@headers]);
  160. while ( read($fh, my $buf, $CHUNK_SIZE) ) {
  161. $writer->write($buf);
  162. }
  163. close $fh;
  164. $writer->close;
  165. } if $streaming && $sz > $CHUNK_SIZE;
  166. #Return data in the event the caller does not support deflate
  167. if (!$deflate) {
  168. push( @headers, "Content-Length" => $sz );
  169. return [ $code, \@headers, $fh];
  170. }
  171. #Compress everything less than 1MB
  172. push( @headers, "Content-Encoding" => "deflate" );
  173. my $dfh;
  174. IO::Compress::Deflate::deflate( $fh => \$dfh );
  175. print $IO::Compress::Deflate::DeflateError if $IO::Compress::Deflate::DeflateError;
  176. push( @headers, "Content-Length" => length($dfh) );
  177. return [ $code, \@headers, [$dfh]];
  178. }
  179. return [ 403, [$ct => $content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  180. }
  181. sub _render ($template, $vars, @headers) {
  182. my $processor = Text::Xslate->new(
  183. path => 'www/templates',
  184. header => ['header.tx'],
  185. footer => ['footer.tx'],
  186. function => {
  187. iso8601 => sub {
  188. my $t = shift;
  189. my $dt = DateTime->from_epoch( epoch => $t );
  190. return $dt->iso8601;
  191. },
  192. strip_and_trunc => \&Trog::Utils::strip_and_trunc,
  193. },
  194. );
  195. #XXX default vars that need to be pulled from config
  196. $vars->{dir} //= 'ltr';
  197. $vars->{lang} //= 'en-US';
  198. $vars->{title} //= 'tCMS';
  199. #XXX Need to have minification detection and so forth, use LESS
  200. $vars->{stylesheets} //= [];
  201. #XXX Need to have minification detection, use Typescript
  202. $vars->{scripts} //= [];
  203. # Absolute-ize the paths for scripts & stylesheets
  204. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  205. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  206. $vars->{contenttype} //= $content_types{html};
  207. $vars->{cachecontrol} //= $cache_control{revalidate};
  208. $vars->{code} ||= 200;
  209. push(@headers, $ct => $vars->{contenttype});
  210. push(@headers, $cc => $vars->{cachecontrol}) if $vars->{cachecontrol};
  211. my $body = $processor->render($template,$vars);
  212. $body = encode_utf8($body);
  213. #Return data in the event the caller does not support deflate
  214. if (!$vars->{deflate}) {
  215. push( @headers, "Content-Length" => length($body) );
  216. return [ $vars->{code}, \@headers, [$body]];
  217. }
  218. #Compress
  219. push( @headers, "Content-Encoding" => "deflate" );
  220. #Disallow framing UNLESS we are in embed mode
  221. push( @headers, "Content-Security-Policy" => qq{frame-ancestors 'none'} ) unless $vars->{embed};
  222. my $dfh;
  223. IO::Compress::Deflate::deflate( \$body => \$dfh );
  224. print $IO::Compress::Deflate::DeflateError if $IO::Compress::Deflate::DeflateError;
  225. push( @headers, "Content-Length" => length($dfh) );
  226. return [$vars->{code}, \@headers, [$dfh]];
  227. }
  228. 1;