FileHandler.pm 4.9 KB

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