TCMS.pm 9.2 KB

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