server.psgi 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. #Grab our custom routes
  15. use lib 'lib';
  16. use Trog::Routes::HTML;
  17. use Trog::Routes::JSON;
  18. use Trog::Auth;
  19. # Troglodyne philosophy - simple as possible
  20. # Import the routes
  21. my %routes = %Trog::Routes::HTML::routes;
  22. @routes{keys(%Trog::Routes::JSON::routes)} = values(%Trog::Routes::JSON::routes);
  23. # Things we will actually produce from routes rather than just serving up files
  24. my $ct = 'Content-type';
  25. my %content_types = (
  26. plain => "$ct:text/plain;",
  27. html => "$ct:text/html; charset=UTF-8",
  28. json => "$ct:application/json;",
  29. blob => "$ct:application/octet-stream;",
  30. );
  31. my $cd = 'Content-disposition';
  32. my %content_dispositions = (
  33. attachment => 'attachment; filename=',
  34. inline => 'inline; filename=',
  35. );
  36. my $cc = 'Cache-control';
  37. my %cache_control = (
  38. revalidate => "$cc: no-cache, max-age=0;",
  39. nocache => "$cc: no-store;",
  40. static => "$cc: public, max-age=604800, immutable",
  41. );
  42. =head2 $app
  43. Dispatches requests based on %routes built above.
  44. 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.
  45. 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.
  46. =cut
  47. my $app = sub {
  48. my $env = shift;
  49. my $last_fetch = 0;
  50. if ($env->{HTTP_IF_MODIFIED_SINCE}) {
  51. $last_fetch = DateTime::Format::HTTP->parse_datetime($env->{HTTP_IF_MODIFIED_SINCE})->epoch();
  52. }
  53. my $query = {};
  54. $query = URL::Encode::url_params_mixed($env->{QUERY_STRING}) if $env->{QUERY_STRING};
  55. my $path = $env->{PATH_INFO};
  56. # Let's open up our default route before we bother to see if users even exist
  57. return $routes{default}{callback}->($query,$env->{'psgi.input'}, \&_render) unless -f "$ENV{HOME}/.tcms/setup";
  58. my $cookies = {};
  59. if ($env->{HTTP_COOKIE}) {
  60. $cookies = CGI::Cookie->parse($env->{HTTP_COOKIE});
  61. }
  62. my ($active_user,$user_id) = ('','');
  63. if (exists $cookies->{tcmslogin}) {
  64. ($active_user,$user_id) = Trog::Auth::session2user($cookies->{tcmslogin}->value);
  65. }
  66. $query->{acls} = Trog::Auth::acls4user($user_id) // [] if $user_id;
  67. $query->{user} = $active_user;
  68. $query->{domain} = $env->{HTTP_HOST};
  69. $query->{route} = $path;
  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", $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. #TODO reject inappropriate content-lengths
  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. #TODO don't slurp
  98. my $slurpee = '';
  99. my $input = $env->{'psgi.input'};
  100. while (<$input>) { $slurpee .= $_ }
  101. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  102. $body->add($slurpee);
  103. @$query{keys(%{$body->param})} = values(%{$body->param});
  104. @$query{keys(%{$body->upload})} = values(%{$body->upload});
  105. }
  106. my $output = $routes{$path}{callback}->($query, \&_render);
  107. return $output;
  108. };
  109. sub _serve ($path, $last_fetch=0) {
  110. my $mf = Mojo::File->new($path);
  111. my $ext = '.'.$mf->extname();
  112. my $ft;
  113. $ft = Plack::MIME->mime_type($ext) if $ext;
  114. $ft = "$ct:$ft;" if $ft;
  115. $ft ||= $content_types{plain};
  116. my @headers = ($ft);
  117. #TODO figure out content-disposition
  118. #TODO use static Cache-Control for everything but JS/CSS?
  119. push(@headers,$cache_control{revalidate});
  120. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  121. my $mt = (stat($path))[9];
  122. my @gm = gmtime($mt);
  123. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  124. my $code = $mt > $last_fetch ? 200 : 304;
  125. push(@headers, "Last-Modified: $now_string\n");
  126. my $h = join("\n",@headers);
  127. if (open(my $fh, '<', $path)) {
  128. return [ $code, [$h], $fh];
  129. }
  130. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  131. }
  132. sub _render ($template, $vars, @headers) {
  133. my $processor = Text::Xslate->new(
  134. path => 'www/templates',
  135. header => ['header.tx'],
  136. footer => ['footer.tx'],
  137. );
  138. #XXX default vars that need to be pulled from config
  139. $vars->{dir} //= 'ltr';
  140. $vars->{lang} //= 'en-US';
  141. $vars->{title} //= 'tCMS';
  142. #XXX Need to have minification detection and so forth, use LESS
  143. $vars->{stylesheets} //= [];
  144. #XXX Need to have minification detection, use Typescript
  145. $vars->{scripts} //= [];
  146. # Absolute-ize the paths for scripts & stylesheets
  147. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  148. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  149. $vars->{contenttype} //= $content_types{html};
  150. $vars->{cachecontrol} //= $cache_control{revalidate};
  151. $vars->{code} ||= 200;
  152. push(@headers, $vars->{contenttype});
  153. push(@headers,$vars->{contentdisposition}) if $vars->{contentdisposition};
  154. push(@headers, $vars->{cachecontrol}) if $vars->{cachecontrol};
  155. my $h = join("\n",@headers);
  156. my $body = $processor->render($template,$vars);
  157. return [$vars->{code}, [$h], [encode_utf8($body)]];
  158. }