server.psgi 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. my $body = HTTP::Body->new( $env->{CONTENT_TYPE}, $env->{CONTENT_LENGTH} );
  98. my $len = $env->{CONTENT_LENGTH};
  99. while ( $len ) {
  100. read($env->{'psgi.input'}, my $buf, ($len < 8192) ? 8192 : $len );
  101. $len -= length($buf);
  102. $body->add($buf);
  103. }
  104. @$query{keys(%{$body->param})} = values(%{$body->param});
  105. @$query{keys(%{$body->upload})} = values(%{$body->upload});
  106. }
  107. my $output = $routes{$path}{callback}->($query, \&_render);
  108. return $output;
  109. };
  110. sub _serve ($path, $last_fetch=0) {
  111. my $mf = Mojo::File->new($path);
  112. my $ext = '.'.$mf->extname();
  113. my $ft;
  114. $ft = Plack::MIME->mime_type($ext) if $ext;
  115. $ft = "$ct:$ft;" if $ft;
  116. $ft ||= $content_types{plain};
  117. my @headers = ($ft);
  118. #TODO figure out content-disposition
  119. #TODO use static Cache-Control for everything but JS/CSS?
  120. push(@headers,$cache_control{revalidate});
  121. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  122. my $mt = (stat($path))[9];
  123. my @gm = gmtime($mt);
  124. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  125. my $code = $mt > $last_fetch ? 200 : 304;
  126. push(@headers, "Last-Modified: $now_string\n");
  127. my $h = join("\n",@headers);
  128. if (open(my $fh, '<', $path)) {
  129. return [ $code, [$h], $fh];
  130. }
  131. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  132. }
  133. sub _render ($template, $vars, @headers) {
  134. my $processor = Text::Xslate->new(
  135. path => 'www/templates',
  136. header => ['header.tx'],
  137. footer => ['footer.tx'],
  138. );
  139. #XXX default vars that need to be pulled from config
  140. $vars->{dir} //= 'ltr';
  141. $vars->{lang} //= 'en-US';
  142. $vars->{title} //= 'tCMS';
  143. #XXX Need to have minification detection and so forth, use LESS
  144. $vars->{stylesheets} //= [];
  145. #XXX Need to have minification detection, use Typescript
  146. $vars->{scripts} //= [];
  147. # Absolute-ize the paths for scripts & stylesheets
  148. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  149. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  150. $vars->{contenttype} //= $content_types{html};
  151. $vars->{cachecontrol} //= $cache_control{revalidate};
  152. $vars->{code} ||= 200;
  153. push(@headers, $vars->{contenttype});
  154. push(@headers,$vars->{contentdisposition}) if $vars->{contentdisposition};
  155. push(@headers, $vars->{cachecontrol}) if $vars->{cachecontrol};
  156. my $h = join("\n",@headers);
  157. my $body = $processor->render($template,$vars);
  158. return [$vars->{code}, [$h], [encode_utf8($body)]];
  159. }