server.psgi 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. # Things we will actually produce from routes rather than just serving up files
  25. my $ct = 'Content-type';
  26. my %content_types = (
  27. plain => "$ct:text/plain;",
  28. html => "$ct:text/html; charset=UTF-8",
  29. json => "$ct:application/json;",
  30. blob => "$ct:application/octet-stream;",
  31. );
  32. my $cc = 'Cache-control';
  33. my %cache_control = (
  34. revalidate => "$cc: no-cache, max-age=0;",
  35. nocache => "$cc: no-store;",
  36. static => "$cc: public, max-age=604800, immutable",
  37. );
  38. =head2 $app
  39. Dispatches requests based on %routes built above.
  40. 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.
  41. 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.
  42. =cut
  43. my $app = sub {
  44. my $env = shift;
  45. my $last_fetch = 0;
  46. if ($env->{HTTP_IF_MODIFIED_SINCE}) {
  47. $last_fetch = DateTime::Format::HTTP->parse_datetime($env->{HTTP_IF_MODIFIED_SINCE})->epoch();
  48. }
  49. my $query = {};
  50. $query = URL::Encode::url_params_mixed($env->{QUERY_STRING}) if $env->{QUERY_STRING};
  51. my $path = $env->{PATH_INFO};
  52. # Let's open up our default route before we bother to see if users even exist
  53. return $routes{default}{callback}->($query,\&_render) unless -f "$ENV{HOME}/.tcms/setup";
  54. my $cookies = {};
  55. if ($env->{HTTP_COOKIE}) {
  56. $cookies = CGI::Cookie->parse($env->{HTTP_COOKIE});
  57. }
  58. my ($active_user,$user_id) = ('','');
  59. if (exists $cookies->{tcmslogin}) {
  60. ($active_user,$user_id) = Trog::Auth::session2user($cookies->{tcmslogin}->value);
  61. }
  62. #Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  63. if (index($path,'/templates') == 0 || $path =~ m/.*\.psgi$/i ) {
  64. return Trog::Routes::HTML::forbidden($query, \&_render);
  65. }
  66. # If it's just a file, serve it up
  67. return _serve("www/$path", $env->{'psgi.streaming'}, $last_fetch) if -f "www/$path";
  68. #Handle regex/capture routes
  69. if (!exists $routes{$path}) {
  70. my @captures;
  71. foreach my $pattern (keys(%routes)) {
  72. @captures = $path =~ m/^$pattern$/;
  73. if (@captures) {
  74. $path = $pattern;
  75. foreach my $field (@{$routes{$path}{captures}}) {
  76. $routes{$path}{data} //= {};
  77. $routes{$path}{data}{$field} = shift @captures;
  78. }
  79. last;
  80. }
  81. }
  82. }
  83. $query->{user} = $active_user;
  84. return Trog::Routes::HTML::notfound($query, \&_render) unless exists $routes{$path};
  85. return Trog::Routes::HTML::badrequest($query, \&_render) unless $routes{$path}{method} eq $env->{REQUEST_METHOD};
  86. @{$query}{keys(%{$routes{$path}{'data'}})} = values(%{$routes{$path}{'data'}}) if ref $routes{$path}{'data'} eq 'HASH' && %{$routes{$path}{'data'}};
  87. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  88. if ($env->{REQUEST_METHOD} eq 'POST') {
  89. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  90. my $len = $env->{CONTENT_LENGTH};
  91. while ( $len ) {
  92. read($env->{'psgi.input'}, my $buf, ($len < 8192) ? 8192 : $len );
  93. $len -= length($buf);
  94. $body->add($buf);
  95. }
  96. @$query{keys(%{$body->param})} = values(%{$body->param});
  97. @$query{keys(%{$body->upload})} = values(%{$body->upload});
  98. }
  99. #Set various things we don't want overridden
  100. $query->{acls} = Trog::Auth::acls4user($user_id) // [] if $user_id;
  101. $query->{user} = $active_user;
  102. $query->{domain} = $env->{HTTP_HOST};
  103. $query->{route} = $env->{REQUEST_URI};
  104. $query->{scheme} = $env->{'psgi.url_scheme'} // 'http';
  105. my $output = $routes{$path}{callback}->($query, \&_render);
  106. return $output;
  107. };
  108. sub _serve ($path, $streaming=0, $last_fetch=0) {
  109. my $mf = Mojo::File->new($path);
  110. my $ext = '.'.$mf->extname();
  111. my $ft;
  112. $ft = Plack::MIME->mime_type($ext) if $ext;
  113. $ft = "$ct:$ft;" if $ft;
  114. $ft ||= $content_types{plain};
  115. my @headers = ($ft);
  116. #TODO use static Cache-Control for everything but JS/CSS?
  117. push(@headers,$cache_control{revalidate});
  118. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  119. my $mt = (stat($path))[9];
  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. push(@headers, "Last-Modified: $now_string\n");
  126. my $h = join("\n",@headers);
  127. if (open(my $fh, '<', $path)) {
  128. return sub {
  129. my $responder = shift;
  130. my $writer = $responder->([ $code, [$h]]);
  131. my $it = 10000;
  132. $fh->autoflush(1);
  133. while ( read($fh, my $buf, $it) ) {
  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. }