server.psgi 8.1 KB

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