server.psgi 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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,$env->{'psgi.input'}, \&_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. $query->{acls} = Trog::Auth::acls4user($user_id) // [] if $user_id;
  63. $query->{user} = $active_user;
  64. $query->{domain} = $env->{HTTP_HOST};
  65. $query->{route} = $path;
  66. #Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  67. if (index($path,'/templates') == 0 || $path =~ m/.*\.psgi$/i ) {
  68. return Trog::Routes::HTML::forbidden($query, \&_render);
  69. }
  70. # If it's just a file, serve it up
  71. return _serve("www/$path", $last_fetch) if -f "www/$path";
  72. #Handle regex/capture routes
  73. if (!exists $routes{$path}) {
  74. my @captures;
  75. foreach my $pattern (keys(%routes)) {
  76. @captures = $path =~ m/^$pattern$/;
  77. if (@captures) {
  78. $path = $pattern;
  79. foreach my $field (@{$routes{$path}{captures}}) {
  80. $routes{$path}{data} //= {};
  81. $routes{$path}{data}{$field} = shift @captures;
  82. }
  83. last;
  84. }
  85. }
  86. }
  87. #TODO reject inappropriate content-lengths
  88. return Trog::Routes::HTML::notfound($query, \&_render) unless exists $routes{$path};
  89. return Trog::Routes::HTML::badrequest($query, \&_render) unless $routes{$path}{method} eq $env->{REQUEST_METHOD};
  90. @{$query}{keys(%{$routes{$path}{'data'}})} = values(%{$routes{$path}{'data'}}) if ref $routes{$path}{'data'} eq 'HASH' && %{$routes{$path}{'data'}};
  91. #Actually parse the POSTDATA and dump it into the QUERY object if this is a POST
  92. if ($env->{REQUEST_METHOD} eq 'POST') {
  93. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  94. my $len = $env->{CONTENT_LENGTH};
  95. while ( $len ) {
  96. read($env->{'psgi.input'}, my $buf, ($len < 8192) ? 8192 : $len );
  97. $len -= length($buf);
  98. $body->add($buf);
  99. }
  100. @$query{keys(%{$body->param})} = values(%{$body->param});
  101. @$query{keys(%{$body->upload})} = values(%{$body->upload});
  102. }
  103. my $output = $routes{$path}{callback}->($query, \&_render);
  104. return $output;
  105. };
  106. sub _serve ($path, $last_fetch=0) {
  107. my $mf = Mojo::File->new($path);
  108. my $ext = '.'.$mf->extname();
  109. my $ft;
  110. $ft = Plack::MIME->mime_type($ext) if $ext;
  111. $ft = "$ct:$ft;" if $ft;
  112. $ft ||= $content_types{plain};
  113. my @headers = ($ft);
  114. #TODO use static Cache-Control for everything but JS/CSS?
  115. push(@headers,$cache_control{revalidate});
  116. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  117. my $mt = (stat($path))[9];
  118. my @gm = gmtime($mt);
  119. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  120. my $code = $mt > $last_fetch ? 200 : 304;
  121. push(@headers, "Last-Modified: $now_string\n");
  122. my $h = join("\n",@headers);
  123. if (open(my $fh, '<', $path)) {
  124. return [ $code, [$h], $fh];
  125. }
  126. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  127. }
  128. sub _render ($template, $vars, @headers) {
  129. my $processor = Text::Xslate->new(
  130. path => 'www/templates',
  131. header => ['header.tx'],
  132. footer => ['footer.tx'],
  133. );
  134. #XXX default vars that need to be pulled from config
  135. $vars->{dir} //= 'ltr';
  136. $vars->{lang} //= 'en-US';
  137. $vars->{title} //= 'tCMS';
  138. #XXX Need to have minification detection and so forth, use LESS
  139. $vars->{stylesheets} //= [];
  140. #XXX Need to have minification detection, use Typescript
  141. $vars->{scripts} //= [];
  142. # Absolute-ize the paths for scripts & stylesheets
  143. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  144. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  145. $vars->{contenttype} //= $content_types{html};
  146. $vars->{cachecontrol} //= $cache_control{revalidate};
  147. $vars->{code} ||= 200;
  148. push(@headers, $vars->{contenttype});
  149. push(@headers, $vars->{cachecontrol}) if $vars->{cachecontrol};
  150. my $h = join("\n",@headers);
  151. my $body = $processor->render($template,$vars);
  152. return [$vars->{code}, [$h], [encode_utf8($body)]];
  153. }