server.psgi 7.1 KB

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