server.psgi 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 => "$ct:text/plain;",
  30. html => "$ct:text/html; charset=UTF-8",
  31. json => "$ct:application/json;",
  32. blob => "$ct:application/octet-stream;",
  33. );
  34. my $cc = 'Cache-control';
  35. my %cache_control = (
  36. revalidate => "$cc: no-cache, max-age=0;",
  37. nocache => "$cc: no-store;",
  38. static => "$cc: 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 "$ENV{HOME}/.tcms/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 = "$ct:$ft;" if $ft;
  121. $ft ||= $content_types{plain};
  122. my @headers = ($ft);
  123. #TODO use static Cache-Control for everything but JS/CSS?
  124. push(@headers,$cache_control{revalidate});
  125. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  126. my $mt = (stat($path))[9];
  127. #my $sz = (stat(_))[7];
  128. my @gm = gmtime($mt);
  129. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  130. my $code = $mt > $last_fetch ? 200 : 304;
  131. #XXX something broken about the above logic
  132. $code=200;
  133. #XXX doing metadata=preload on videos doesn't work right?
  134. #push(@headers, "Content-Length: $sz\n");
  135. push(@headers, "Last-Modified: $now_string\n");
  136. my $h = join("\n",@headers);
  137. if (open(my $fh, '<', $path)) {
  138. return sub {
  139. my $responder = shift;
  140. my $writer = $responder->([ $code, [$h]]);
  141. while ( read($fh, my $buf, $CHUNK_SIZE) ) {
  142. $writer->write($buf);
  143. }
  144. close $fh;
  145. $writer->close;
  146. } if $streaming;
  147. return [ $code, [$h], $fh];
  148. }
  149. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  150. }
  151. sub _render ($template, $vars, @headers) {
  152. my $processor = Text::Xslate->new(
  153. path => 'www/templates',
  154. header => ['header.tx'],
  155. footer => ['footer.tx'],
  156. );
  157. #XXX default vars that need to be pulled from config
  158. $vars->{dir} //= 'ltr';
  159. $vars->{lang} //= 'en-US';
  160. $vars->{title} //= 'tCMS';
  161. #XXX Need to have minification detection and so forth, use LESS
  162. $vars->{stylesheets} //= [];
  163. #XXX Need to have minification detection, use Typescript
  164. $vars->{scripts} //= [];
  165. # Absolute-ize the paths for scripts & stylesheets
  166. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  167. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  168. $vars->{contenttype} //= $content_types{html};
  169. $vars->{cachecontrol} //= $cache_control{revalidate};
  170. $vars->{code} ||= 200;
  171. push(@headers, $vars->{contenttype});
  172. push(@headers, $vars->{cachecontrol}) if $vars->{cachecontrol};
  173. my $h = join("\n",@headers);
  174. my $body = $processor->render($template,$vars);
  175. return [$vars->{code}, [$h], [encode_utf8($body)]];
  176. }