server.psgi 6.9 KB

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