server.psgi 7.7 KB

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