FileHandler.pm 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package Trog::FileHandler;
  2. use 5.040;
  3. use re '/aasx';
  4. use warnings FATAL => 'all';
  5. use POSIX qw{strftime};
  6. use IO::Compress::Gzip;
  7. use Time::HiRes qw{tv_interval};
  8. use Trog::Log qw{:all};
  9. use Trog::Vars;
  10. use Trog::Utils;
  11. my sub range ( $fullpath, $fh, $ranges, $sz, %headers ) {
  12. # Set mode
  13. my $primary_ct = "Content-Type: $headers{'Content-type'}";
  14. my $is_multipart = scalar(@$ranges) > 1;
  15. if ($is_multipart) {
  16. $headers{'Content-type'} = "multipart/byteranges; boundary=$Trog::Vars::CHUNK_SEP";
  17. }
  18. my $code = 206;
  19. my $fc = '';
  20. # Calculate the content-length up-front. We have to fix unspecified lengths first, and reject bad requests.
  21. foreach my $range (@$ranges) {
  22. $range->[1] //= $sz - 1;
  23. INFO("GET 416 31 $fullpath");
  24. return [ 416, [%headers], ["Requested range not satisfiable"] ] if $range->[0] > $sz || $range->[0] < 0 || $range->[1] < 0 || $range->[0] > $range->[1];
  25. }
  26. $headers{'Content-Length'} = List::Util::sum( map { $_->[1] + 1 - $_->[0] } @$ranges );
  27. #XXX Add the entity header lengths to the value - should hash-ify this to DRY
  28. if ($is_multipart) {
  29. foreach my $range (@$ranges) {
  30. $headers{'Content-Length'} += length("$fc--$Trog::Vars::CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n");
  31. $fc = "\n";
  32. }
  33. $headers{'Content-Length'} += length("\n--$Trog::Vars::CHUNK_SEP\--\n");
  34. $fc = '';
  35. }
  36. #TODO log these requests with their length correctly
  37. return sub {
  38. my $responder = shift;
  39. my $writer;
  40. foreach my $range (@$ranges) {
  41. $headers{'Content-Range'} = "bytes $range->[0]-$range->[1]/$sz" unless $is_multipart;
  42. $writer //= $responder->( [ $code, [%headers] ] );
  43. $writer->write("$fc--$Trog::Vars::CHUNK_SEP\n$primary_ct\nContent-Range: bytes $range->[0]-$range->[1]/$sz\n\n") if $is_multipart;
  44. $fc = "\n";
  45. my $len = List::Util::min( $sz, $range->[1] + 1 ) - $range->[0];
  46. $fh->seek( $range->[0], 0 );
  47. while ($len) {
  48. $fh->read( my $buf, List::Util::min( $len, $Trog::Vars::CHUNK_SIZE ) );
  49. $writer->write($buf);
  50. # Adjust for amount written
  51. $len = List::Util::max( $len - $Trog::Vars::CHUNK_SIZE, 0 );
  52. }
  53. }
  54. $fh->close();
  55. $writer->write("\n--$Trog::Vars::CHUNK_SEP\--\n") if $is_multipart;
  56. $writer->close;
  57. };
  58. }
  59. =head2 serve
  60. Serve a file, with options to stream and cache the output.
  61. =cut
  62. sub serve ( $fullpath, $path, $start, $streaming, $ranges, $last_fetch = 0, $deflate = 0 ) {
  63. my $ft = Trog::Utils::mime_type($path);
  64. $ft ||= $Trog::Vars::content_types{text};
  65. my $ct = 'Content-type';
  66. my @headers = ( $ct => $ft );
  67. #TODO use static Cache-Control for everything but JS/CSS?
  68. push( @headers, 'Cache-control' => $Trog::Vars::cache_control{revalidate} );
  69. push( @headers, 'Accept-Ranges' => 'bytes' );
  70. my $mt = ( stat($path) )[9];
  71. my $sz = ( stat(_) )[7];
  72. my @gm = gmtime($mt);
  73. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  74. my $code = $mt > $last_fetch ? 200 : 304;
  75. push( @headers, "Last-Modified" => $now_string );
  76. push( @headers, 'Vary' => 'Accept-Encoding' );
  77. if ( open( my $fh, '<', $path ) ) { ## no critic (InputOutput::RequireBriefOpen) -- streamed to the client, which closes it
  78. return range( $fullpath, $fh, $ranges, $sz, @headers ) if @$ranges && $streaming;
  79. # Transfer-encoding: chunked
  80. return sub {
  81. my $responder = shift;
  82. push( @headers, 'Content-Length' => $sz );
  83. my $writer = $responder->( [ $code, \@headers ] );
  84. while ( $fh->read( my $buf, $Trog::Vars::CHUNK_SIZE ) ) {
  85. $writer->write($buf);
  86. }
  87. close($fh); ## no critic (RequireCheckedSyscalls) -- read to the end, with nothing to lose
  88. $writer->close;
  89. }
  90. if $streaming && $sz > $Trog::Vars::CHUNK_SIZE;
  91. #Return data in the event the caller does not support deflate
  92. if ( !$deflate ) {
  93. push( @headers, "Content-Length" => $sz );
  94. INFO("GET 200 $sz $fullpath");
  95. # Append server-timing headers
  96. my $tot = tv_interval($start) * 1000;
  97. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  98. return [ $code, \@headers, $fh ];
  99. }
  100. #Compress everything less than 1MB
  101. push( @headers, "Content-Encoding" => "gzip" );
  102. my $dfh;
  103. IO::Compress::Gzip::gzip( $fh => \$dfh );
  104. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  105. push( @headers, "Content-Length" => length($dfh) );
  106. INFO( "GET 200 " . length($dfh) . " $fullpath" );
  107. # Append server-timing headers
  108. my $tot = tv_interval($start) * 1000;
  109. push( @headers, 'Server-Timing' => "file;dur=$tot" );
  110. return [ $code, \@headers, [$dfh] ];
  111. }
  112. INFO("GET 403 23 $fullpath");
  113. return [ 403, [ $ct => $Trog::Vars::content_types{text} ], ["STAY OUT YOU RED MENACE"] ];
  114. }
  115. 1;