server.psgi 9.1 KB

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