server.psgi 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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->{og_type} = 'website';
  114. $query->{twitter_type} = 'summary';
  115. $query->{primary_post} = {};
  116. my $output = $routes{$path}{callback}->($query, \&_render);
  117. return $output;
  118. };
  119. sub _serve ($path, $streaming=0, $last_fetch=0) {
  120. my $mf = Mojo::File->new($path);
  121. my $ext = '.'.$mf->extname();
  122. my $ft;
  123. if ($ext) {
  124. $ft = Plack::MIME->mime_type($ext) if $ext;
  125. $ft ||= $extra_types{$ext} if exists $extra_types{$ext};
  126. }
  127. $ft ||= $content_types{plain};
  128. my @headers = ($ct => $ft);
  129. #TODO use static Cache-Control for everything but JS/CSS?
  130. push(@headers,$cc => $cache_control{revalidate});
  131. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  132. my $mt = (stat($path))[9];
  133. my $sz = (stat(_))[7];
  134. my @gm = gmtime($mt);
  135. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  136. my $code = $mt > $last_fetch ? 200 : 304;
  137. #XXX something broken about the above logic
  138. $code=200;
  139. #XXX doing metadata=preload on videos doesn't work right?
  140. #push(@headers, "Content-Length: $sz");
  141. push(@headers, "Last-Modified" => $now_string);
  142. if (open(my $fh, '<', $path)) {
  143. return sub {
  144. my $responder = shift;
  145. my $writer = $responder->([ $code, \@headers]);
  146. while ( read($fh, my $buf, $CHUNK_SIZE) ) {
  147. $writer->write($buf);
  148. }
  149. close $fh;
  150. $writer->close;
  151. } if $streaming && $sz > $CHUNK_SIZE;
  152. #Compress everything less than 1MB
  153. push( @headers, "Content-Encoding" => "deflate" );
  154. my $dfh;
  155. IO::Compress::Deflate::deflate( $fh => \$dfh );
  156. print $IO::Compress::Deflate::DeflateError if $IO::Compress::Deflate::DeflateError;
  157. push( @headers, "Content-Length" => length($dfh) );
  158. return [ $code, \@headers, [$dfh]];
  159. }
  160. return [ 403, [$ct => $content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  161. }
  162. sub _render ($template, $vars, @headers) {
  163. my $processor = Text::Xslate->new(
  164. path => 'www/templates',
  165. header => ['header.tx'],
  166. footer => ['footer.tx'],
  167. function => {
  168. iso8601 => sub {
  169. my $t = shift;
  170. my $dt = DateTime->from_epoch( epoch => $t );
  171. return $dt->iso8601;
  172. },
  173. strip_and_trunc => \&Trog::Utils::strip_and_trunc,
  174. },
  175. );
  176. #XXX default vars that need to be pulled from config
  177. $vars->{dir} //= 'ltr';
  178. $vars->{lang} //= 'en-US';
  179. $vars->{title} //= 'tCMS';
  180. #XXX Need to have minification detection and so forth, use LESS
  181. $vars->{stylesheets} //= [];
  182. #XXX Need to have minification detection, use Typescript
  183. $vars->{scripts} //= [];
  184. # Absolute-ize the paths for scripts & stylesheets
  185. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  186. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  187. $vars->{contenttype} //= $content_types{html};
  188. $vars->{cachecontrol} //= $cache_control{revalidate};
  189. $vars->{code} ||= 200;
  190. push(@headers, $ct => $vars->{contenttype});
  191. push(@headers, $cc => $vars->{cachecontrol}) if $vars->{cachecontrol};
  192. my $body = $processor->render($template,$vars);
  193. #Compress
  194. push( @headers, "Content-Encoding" => "deflate" );
  195. my $dfh;
  196. $body = encode_utf8($body);
  197. IO::Compress::Deflate::deflate( \$body => \$dfh );
  198. print $IO::Compress::Deflate::DeflateError if $IO::Compress::Deflate::DeflateError;
  199. push( @headers, "Content-Length" => length($dfh) );
  200. return [$vars->{code}, \@headers, [$dfh]];
  201. }