FileHandler.pm 4.9 KB

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