server.psgi 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. use strict;
  2. use warnings;
  3. no warnings 'experimental';
  4. use feature qw{signatures};
  5. use Date::Format qw{strftime};
  6. use URL::Encode ();
  7. use Text::Xslate ();
  8. use Plack::MIME ();
  9. use Mojo::File ();
  10. use DateTime::Format::HTTP();
  11. use Encode qw{encode_utf8};
  12. use CGI::Cookie ();
  13. #Grab our custom routes
  14. use lib 'lib';
  15. use Trog::Routes::HTML;
  16. use Trog::Routes::JSON;
  17. use Trog::Auth;
  18. # Troglodyne philosophy - simple as possible
  19. # Import the routes
  20. my %routes = %Trog::Routes::HTML::routes;
  21. @routes{keys(%Trog::Routes::JSON::routes)} = values(%Trog::Routes::JSON::routes);
  22. # Things we will actually produce from routes rather than just serving up files
  23. my $ct = 'Content-type';
  24. my %content_types = (
  25. plain => "$ct:text/plain;",
  26. html => "$ct:text/html; charset=UTF-8",
  27. json => "$ct:application/json;",
  28. blob => "$ct:application/octet-stream;",
  29. );
  30. my $cd = 'Content-disposition';
  31. my %content_dispositions = (
  32. attachment => 'attachment; filename=',
  33. inline => 'inline; filename=',
  34. );
  35. my $cc = 'Cache-control';
  36. my %cache_control = (
  37. revalidate => "$cc: no-cache, max-age=0;",
  38. nocache => "$cc: no-store;",
  39. static => "$cc: public, max-age=604800, immutable",
  40. );
  41. my $app = sub {
  42. my $env = shift;
  43. my $last_fetch = 0;
  44. if ($env->{HTTP_IF_MODIFIED_SINCE}) {
  45. $last_fetch = DateTime::Format::HTTP->parse_datetime($env->{HTTP_IF_MODIFIED_SINCE})->epoch();
  46. }
  47. my $query = {};
  48. $query = URL::Encode::url_params_mixed($env->{QUERY_STRING}) if $env->{QUERY_STRING};
  49. my $path = $env->{PATH_INFO};
  50. # Let's open up our default route before we bother to see if users even exist
  51. return $routes{default}{callback}->($query,$env->{'psgi.input'}, \&_render) unless -f "$ENV{HOME}/.tcms/setup";
  52. my $cookies = {};
  53. if ($env->{HTTP_COOKIE}) {
  54. $cookies = CGI::Cookie->parse($env->{HTTP_COOKIE});
  55. }
  56. my $active_user = '';
  57. if (exists $cookies->{tcmslogin}) {
  58. $active_user = Trog::Auth::session2user($cookies->{tcmslogin}->value);
  59. }
  60. $query->{user} = $active_user;
  61. $query->{domain} = $env->{HTTP_HOST};
  62. $query->{route} = $path;
  63. #Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  64. if (index($path,'/templates') == 0 || $path =~ m/.*\.psgi$/i ) {
  65. return Trog::Routes::HTML::forbidden($query,$env->{'psgi.input'}, \&_render);
  66. }
  67. # If it's just a file, serve it up
  68. return _serve("www/$path", $last_fetch) if -f "www/$path";
  69. #Handle regex/capture routes
  70. if (!exists $routes{$path}) {
  71. my @captures;
  72. foreach my $pattern (keys(%routes)) {
  73. @captures = $path =~ m/^$pattern$/;
  74. if (@captures) {
  75. $path = $pattern;
  76. foreach my $field (@{$routes{$path}{captures}}) {
  77. $routes{$path}{data} //= {};
  78. $routes{$path}{data}{$field} = shift @captures;
  79. }
  80. last;
  81. }
  82. }
  83. }
  84. #TODO reject inappropriate content-lengths
  85. return Trog::Routes::HTML::notfound($query,$env->{'psgi.input'}, \&_render) unless exists $routes{$path};
  86. return Trog::Routes::HTML::badrequest($query,$env->{'psgi.input'}, \&_render) unless $routes{$path}{method} eq $env->{REQUEST_METHOD};
  87. @{$query}{keys(%{$routes{$path}{'data'}})} = values(%{$routes{$path}{'data'}}) if ref $routes{$path}{'data'} eq 'HASH' && %{$routes{$path}{'data'}};
  88. my $output = $routes{$path}{callback}->($query,$env->{'psgi.input'}, \&_render);
  89. return $output;
  90. };
  91. sub _serve ($path, $last_fetch=0) {
  92. my $mf = Mojo::File->new($path);
  93. my $ext = '.'.$mf->extname();
  94. my $ft;
  95. $ft = Plack::MIME->mime_type($ext) if $ext;
  96. $ft = "$ct:$ft;" if $ft;
  97. $ft ||= $content_types{plain};
  98. my @headers = ($ft);
  99. #TODO figure out content-disposition
  100. #TODO use static Cache-Control for everything but JS/CSS?
  101. push(@headers,$cache_control{revalidate});
  102. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  103. my $mt = (stat($path))[9];
  104. my @gm = gmtime($mt);
  105. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  106. my $code = $mt > $last_fetch ? 200 : 304;
  107. push(@headers, "Last-Modified: $now_string\n");
  108. my $h = join("\n",@headers);
  109. if (open(my $fh, '<', $path)) {
  110. return [ $code, [$h], $fh];
  111. }
  112. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  113. }
  114. sub _render ($template, $vars, @headers) {
  115. my $processor = Text::Xslate->new(
  116. path => 'www/templates',
  117. header => ['header.tx'],
  118. footer => ['footer.tx'],
  119. );
  120. #XXX default vars that need to be pulled from config
  121. $vars->{dir} //= 'ltr';
  122. $vars->{lang} //= 'en-US';
  123. $vars->{title} //= 'tCMS';
  124. #XXX Need to have minification detection and so forth, use LESS
  125. $vars->{stylesheets} //= [];
  126. #XXX Need to have minification detection, use Typescript
  127. $vars->{scripts} //= [];
  128. # Absolute-ize the paths for scripts & stylesheets
  129. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  130. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  131. $vars->{contenttype} //= $content_types{html};
  132. $vars->{cachecontrol} //= $cache_control{revalidate};
  133. $vars->{code} ||= 200;
  134. push(@headers, $vars->{contenttype});
  135. push(@headers,$vars->{contentdisposition}) if $vars->{contentdisposition};
  136. push(@headers, $vars->{cachecontrol}) if $vars->{cachecontrol};
  137. my $h = join("\n",@headers);
  138. my $body = $processor->render($template,$vars);
  139. return [$vars->{code}, [$h], [encode_utf8($body)]];
  140. }