Class: Protocol::HTTP1::Body::Chunked

Inherits:
HTTP::Body::Readable
  • Object
show all
Defined in:
lib/protocol/http1/body/chunked.rb

Constant Summary collapse

CRLF =
"\r\n"
VALID_CHUNK_LENGTH =
/\A[0-9a-fA-F]+\z/

Instance Method Summary collapse

Constructor Details

#initialize(stream, headers) ⇒ Chunked



15
16
17
18
19
20
21
22
23
# File 'lib/protocol/http1/body/chunked.rb', line 15

def initialize(stream, headers)
  @stream = stream
  @finished = false
  
  @headers = headers
  
  @length = 0
  @count = 0
end

Instance Method Details

#close(error = nil) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/protocol/http1/body/chunked.rb', line 29

def close(error = nil)
  # We only close the connection if we haven't completed reading the entire body:
  unless @finished
    @stream.close
    @finished = true
  end
  
  super
end

#empty?Boolean



25
26
27
# File 'lib/protocol/http1/body/chunked.rb', line 25

def empty?
  @finished
end

#inspectObject



74
75
76
# File 'lib/protocol/http1/body/chunked.rb', line 74

def inspect
  "\#<#{self.class} #{@length} bytes read in #{@count} chunks>"
end

#readObject

Follows the procedure outlined in tools.ietf.org/html/rfc7230#section-4.1.3



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/protocol/http1/body/chunked.rb', line 42

def read
  return nil if @finished
  
  length, _extensions = read_line.split(";", 2)
  
  unless length =~ VALID_CHUNK_LENGTH
    raise BadRequest, "Invalid chunk length: #{length.dump}"
  end
  
  # It is possible this line contains chunk extension, so we use `to_i` to only consider the initial integral part:
  length = Integer(length, 16)
  
  if length == 0
    @finished = true
    
    read_trailer
    
    return nil
  end
  
  # Read trailing CRLF:
  chunk = @stream.read(length + 2)
  
  # ...and chomp it off:
  chunk.chomp!(CRLF)
  
  @length += length
  @count += 1
  
  return chunk
end