TCMS.pm 9.3 KB

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