server.psgi 8.9 KB

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