Class: Protocol::HTTP1::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/protocol/http1/connection.rb

Constant Summary collapse

CRLF =
"\r\n"
HTTP10 =
"HTTP/1.0"
HTTP11 =
"HTTP/1.1"
HEAD =
"HEAD"
CONNECT =
"CONNECT"
VALID_CONTENT_LENGTH =
/\A\d+\z/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stream, persistent = true) ⇒ Connection

Returns a new instance of Connection.



53
54
55
56
57
58
59
# File 'lib/protocol/http1/connection.rb', line 53

def initialize(stream, persistent = true)
	@stream = stream
	
	@persistent = persistent
	
	@count = 0
end

Instance Attribute Details

#countObject (readonly)

The number of requests processed.



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

def count
  @count
end

#persistentObject

Whether the connection is persistent. This determines what connection headers are sent in the response and whether the connection can be reused after the response is sent. This setting is automatically managed according to the nature of the request and response. Changing to false is safe. Changing to true from outside this class should generally be avoided and, depending on the response semantics, may be reset to false anyway.



71
72
73
# File 'lib/protocol/http1/connection.rb', line 71

def persistent
  @persistent
end

#streamObject (readonly)

Returns the value of attribute stream.



61
62
63
# File 'lib/protocol/http1/connection.rb', line 61

def stream
  @stream
end

Instance Method Details

#closeObject

Close the connection and underlying stream.



129
130
131
# File 'lib/protocol/http1/connection.rb', line 129

def close
	@stream&.close
end

#extract_content_length(headers) ⇒ Object



441
442
443
444
445
446
447
448
449
# File 'lib/protocol/http1/connection.rb', line 441

def extract_content_length(headers)
	if content_length = headers.delete(CONTENT_LENGTH)
		if content_length =~ VALID_CONTENT_LENGTH
			yield Integer(content_length, 10)
		else
			raise BadRequest, "Invalid content length: #{content_length.dump}"
		end
	end
end

#hijack!IO

Effectively close the connection and return the underlying IO.

Returns:

  • (IO)

    the underlying non-blocking IO.



118
119
120
121
122
123
124
125
126
# File 'lib/protocol/http1/connection.rb', line 118

def hijack!
	@persistent = false
	stream = @stream
	
	@stream.flush
	@stream = nil
	
	return stream
end

#hijacked?Boolean

Indicates whether the connection has been hijacked meaning its IO has been handed over and is not usable anymore.

Returns:

  • (Boolean)

    hijack status



112
113
114
# File 'lib/protocol/http1/connection.rb', line 112

def hijacked?
	@stream.nil?
end

#persistent?(version, method, headers) ⇒ Boolean

Returns:

  • (Boolean)


76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/protocol/http1/connection.rb', line 76

def persistent?(version, method, headers)
	if method == HTTP::Methods::CONNECT
		return false
	end
	
	if version == HTTP10
		if connection = headers[CONNECTION]
			return connection.keep_alive?
		else
			return false
		end
	else
		if connection = headers[CONNECTION]
			return !connection.close?
		else
			return true
		end
	end
end

#read_body(headers, remainder = false) ⇒ Object



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/protocol/http1/connection.rb', line 502

def read_body(headers, remainder = false)
	# 3.  If a Transfer-Encoding header field is present and the chunked
	# transfer coding (Section 4.1) is the final encoding, the message
	# body length is determined by reading and decoding the chunked
	# data until the transfer coding indicates the data is complete.
	if transfer_encoding = headers.delete(TRANSFER_ENCODING)
		# If a message is received with both a Transfer-Encoding and a
		# Content-Length header field, the Transfer-Encoding overrides the
		# Content-Length.  Such a message might indicate an attempt to
		# perform request smuggling (Section 9.5) or response splitting
		# (Section 9.4) and ought to be handled as an error.  A sender MUST
		# remove the received Content-Length field prior to forwarding such
		# a message downstream.
		if headers[CONTENT_LENGTH]
			raise BadRequest, "Message contains both transfer encoding and content length!"
		end
		
		if transfer_encoding.last == CHUNKED
			return read_chunked_body(headers)
		else
			# If a Transfer-Encoding header field is present in a response and
			# the chunked transfer coding is not the final encoding, the
			# message body length is determined by reading the connection until
			# it is closed by the server.  If a Transfer-Encoding header field
			# is present in a request and the chunked transfer coding is not
			# the final encoding, the message body length cannot be determined
			# reliably; the server MUST respond with the 400 (Bad Request)
			# status code and then close the connection.
			return read_remainder_body
		end
	end
	
	# 5.  If a valid Content-Length header field is present without
	# Transfer-Encoding, its decimal value defines the expected message
	# body length in octets.  If the sender closes the connection or
	# the recipient times out before the indicated number of octets are
	# received, the recipient MUST consider the message to be
	# incomplete and close the connection.
	extract_content_length(headers) do |length|
		if length > 0
			return read_fixed_body(length)
		else
			return nil
		end
	end
	
	# http://tools.ietf.org/html/rfc2068#section-19.7.1.1
	if remainder
		# 7.  Otherwise, this is a response message without a declared message
		# body length, so the message body length is determined by the
		# number of octets received prior to the server closing the
		# connection.
		return read_remainder_body
	end
end

#read_chunked_body(headers) ⇒ Object



416
417
418
# File 'lib/protocol/http1/connection.rb', line 416

def read_chunked_body(headers)
	Body::Chunked.new(@stream, headers)
end

#read_fixed_body(length) ⇒ Object



420
421
422
# File 'lib/protocol/http1/connection.rb', line 420

def read_fixed_body(length)
	Body::Fixed.new(@stream, length)
end

#read_head_body(length) ⇒ Object



428
429
430
# File 'lib/protocol/http1/connection.rb', line 428

def read_head_body(length)
	Protocol::HTTP::Body::Head.new(length)
end

#read_headersObject



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/protocol/http1/connection.rb', line 233

def read_headers
	fields = []
	
	while line = read_line
		# Empty line indicates end of headers:
		break if line.empty?
		
		if match = line.match(HEADER)
			fields << [match[1], match[2]]
		else
			raise BadHeader, "Could not parse header: #{line.dump}"
		end
	end
	
	return HTTP::Headers.new(fields)
end

#read_lineObject



180
181
182
# File 'lib/protocol/http1/connection.rb', line 180

def read_line
	read_line? or raise EOFError
end

#read_line?Boolean

Returns:

  • (Boolean)


176
177
178
# File 'lib/protocol/http1/connection.rb', line 176

def read_line?
	@stream.gets(CRLF, chomp: true)
end

#read_remainder_bodyObject



424
425
426
# File 'lib/protocol/http1/connection.rb', line 424

def read_remainder_body
	Body::Remainder.new(@stream)
end

#read_requestObject



196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/protocol/http1/connection.rb', line 196

def read_request
	method, path, version = read_request_line
	return unless method
	
	headers = read_headers
	
	@persistent = persistent?(version, method, headers)
	
	body = read_request_body(method, headers)
	
	@count += 1
	
	return headers.delete(HOST), method, path, version, headers, body
end

#read_request_body(method, headers) ⇒ Object



487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/protocol/http1/connection.rb', line 487

def read_request_body(method, headers)
	# 2.  Any 2xx (Successful) response to a CONNECT request implies that
	# the connection will become a tunnel immediately after the empty
	# line that concludes the header fields.  A client MUST ignore any
	# Content-Length or Transfer-Encoding header fields received in
	# such a message.
	if method == HTTP::Methods::CONNECT
		return read_tunnel_body
	end
	
	# 6.  If this is a request message and none of the above are true, then
	# the message body length is zero (no message body is present).
	return read_body(headers)
end

#read_request_lineObject



184
185
186
187
188
189
190
191
192
193
194
# File 'lib/protocol/http1/connection.rb', line 184

def read_request_line
	return unless line = read_line?
	
	if match = line.match(REQUEST_LINE)
		_, method, path, version = *match
	else
		raise InvalidRequest, line.inspect
	end
	
	return method, path, version
end

#read_response(method) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/protocol/http1/connection.rb', line 219

def read_response(method)
	version, status, reason = read_response_line
	
	headers = read_headers
	
	@persistent = persistent?(version, method, headers)
	
	body = read_response_body(method, status, headers)
	
	@count += 1
	
	return version, status, reason, headers, body
end

#read_response_body(method, status, headers) ⇒ Object



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/protocol/http1/connection.rb', line 451

def read_response_body(method, status, headers)
	# RFC 7230 3.3.3
	# 1.  Any response to a HEAD request and any response with a 1xx
	# (Informational), 204 (No Content), or 304 (Not Modified) status
	# code is always terminated by the first empty line after the
	# header fields, regardless of the header fields present in the
	# message, and thus cannot contain a message body.
	if method == HTTP::Methods::HEAD
		extract_content_length(headers) do |length|
			if length > 0
				return read_head_body(length)
			else
				return nil
			end
		end
		
		# There is no body for a HEAD request if there is no content length:
		return nil
	end
	
	if (status >= 100 and status < 200) or status == 204 or status == 304
		return nil
	end
	
	# 2.  Any 2xx (Successful) response to a CONNECT request implies that
	# the connection will become a tunnel immediately after the empty
	# line that concludes the header fields.  A client MUST ignore any
	# Content-Length or Transfer-Encoding header fields received in
	# such a message.
	if method == HTTP::Methods::CONNECT and status == 200
		return read_tunnel_body
	end
	
	return read_body(headers, true)
end

#read_response_lineObject



211
212
213
214
215
216
217
# File 'lib/protocol/http1/connection.rb', line 211

def read_response_line
	version, status, reason = read_line.split(/\s+/, 3)
	
	status = Integer(status)
	
	return version, status, reason
end

#read_tunnel_bodyObject



432
433
434
# File 'lib/protocol/http1/connection.rb', line 432

def read_tunnel_body
	read_remainder_body
end

#write_body(version, body, head = false, trailer = nil) ⇒ Object



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/protocol/http1/connection.rb', line 385

def write_body(version, body, head = false, trailer = nil)
	# HTTP/1.0 cannot in any case handle trailers.
	if version == HTTP10 # or te: trailers was not present (strictly speaking not required.)
		trailer = nil
	end
	
	# While writing the body, we don't know if trailers will be added. We must choose a different body format depending on whether there is the chance of trailers, even if trailer.any? is currently false.
	#
	# Below you notice `and trailer.nil?`. I tried this but content-length is more important than trailers.
	
	if body.nil?
		write_connection_header(version)
		write_empty_body(body)
	elsif length = body.length # and trailer.nil?
		write_connection_header(version)
		write_fixed_length_body(body, length, head)
	elsif body.empty?
		# Even thought this code is the same as the first clause `body.nil?`, HEAD responses have an empty body but still carry a content length. `write_fixed_length_body` takes care of this appropriately.
		write_connection_header(version)
		write_empty_body(body)
	elsif version == HTTP11
		write_connection_header(version)
		# We specifically ensure that non-persistent connections do not use chunked response, so that hijacking works as expected.
		write_chunked_body(body, head, trailer)
	else
		@persistent = false
		write_connection_header(version)
		write_body_and_close(body, head)
	end
end

#write_body_and_close(body, head) ⇒ Object



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/protocol/http1/connection.rb', line 365

def write_body_and_close(body, head)
	# We can't be persistent because we don't know the data length:
	@persistent = false
	
	@stream.write("\r\n")
	@stream.flush unless body.ready?
	
	if head
		body.close
	else
		body.each do |chunk|
			@stream.write(chunk)
			
			@stream.flush unless body.ready?
		end
	end
	
	@stream.close_write
end

#write_chunked_body(body, head, trailer = nil) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/protocol/http1/connection.rb', line 331

def write_chunked_body(body, head, trailer = nil)
	@stream.write("transfer-encoding: chunked\r\n\r\n")
	
	if head
		@stream.flush
		
		body.close
		
		return
	end
	
	@stream.flush unless body.ready?
	
	body.each do |chunk|
		next if chunk.size == 0
		
		@stream.write("#{chunk.bytesize.to_s(16).upcase}\r\n")
		@stream.write(chunk)
		@stream.write(CRLF)
		
		@stream.flush unless body.ready?
	end
	
	if trailer&.any?
		@stream.write("0\r\n")
		write_headers(trailer)
		@stream.write("\r\n")
	else
		@stream.write("0\r\n\r\n")
	end
	
	@stream.flush
end

#write_connection_header(version) ⇒ Object

Write the appropriate header for connection persistence.



97
98
99
100
101
102
103
# File 'lib/protocol/http1/connection.rb', line 97

def write_connection_header(version)
	if version == HTTP10
		@stream.write("connection: keep-alive\r\n") if @persistent
	else
		@stream.write("connection: close\r\n") unless @persistent
	end
end

#write_empty_body(body) ⇒ Object



292
293
294
295
296
297
# File 'lib/protocol/http1/connection.rb', line 292

def write_empty_body(body)
	@stream.write("content-length: 0\r\n\r\n")
	@stream.flush
	
	body&.close
end

#write_fixed_length_body(body, length, head) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/protocol/http1/connection.rb', line 299

def write_fixed_length_body(body, length, head)
	@stream.write("content-length: #{length}\r\n\r\n")
	
	if head
		@stream.flush
		
		body.close
		
		return
	end
	
	@stream.flush unless body.ready?
	
	chunk_length = 0
	body.each do |chunk|
		chunk_length += chunk.bytesize
		
		if chunk_length > length
			raise ContentLengthError, "Trying to write #{chunk_length} bytes, but content length was #{length} bytes!"
		end
		
		@stream.write(chunk)
		@stream.flush unless body.ready?
	end
	
	@stream.flush
	
	if chunk_length != length
		raise ContentLengthError, "Wrote #{chunk_length} bytes, but content length was #{length} bytes!"
	end
end

#write_headers(headers) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/protocol/http1/connection.rb', line 156

def write_headers(headers)
	headers.each do |name, value|
		# Convert it to a string:
		name = name.to_s
		value = value.to_s
		
		# Validate it:
		unless name.match?(VALID_FIELD_NAME)
			raise BadHeader, "Invalid header name: #{name.inspect}"
		end
		
		unless value.match?(VALID_FIELD_VALUE)
			raise BadHeader, "Invalid header value for #{name}: #{value.inspect}"
		end
		
		# Write it:
		@stream.write("#{name}: #{value}\r\n")
	end
end

#write_interim_response(version, status, headers, reason = Reason::DESCRIPTIONS[status]) ⇒ Object



147
148
149
150
151
152
153
154
# File 'lib/protocol/http1/connection.rb', line 147

def write_interim_response(version, status, headers, reason = Reason::DESCRIPTIONS[status])
	@stream.write("#{version} #{status} #{reason}\r\n")
	
	write_headers(headers)
	
	@stream.write("\r\n")
	@stream.flush
end

#write_request(authority, method, path, version, headers) ⇒ Object



133
134
135
136
137
138
# File 'lib/protocol/http1/connection.rb', line 133

def write_request(authority, method, path, version, headers)
	@stream.write("#{method} #{path} #{version}\r\n")
	@stream.write("host: #{authority}\r\n")
	
	write_headers(headers)
end

#write_response(version, status, headers, reason = Reason::DESCRIPTIONS[status]) ⇒ Object



140
141
142
143
144
145
# File 'lib/protocol/http1/connection.rb', line 140

def write_response(version, status, headers, reason = Reason::DESCRIPTIONS[status])
	# Safari WebSockets break if no reason is given:
	@stream.write("#{version} #{status} #{reason}\r\n")
	
	write_headers(headers)
end

#write_tunnel_body(version, body = nil) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/protocol/http1/connection.rb', line 272

def write_tunnel_body(version, body = nil)
	@persistent = false
	
	write_connection_header(version)
	
	@stream.write("\r\n")
	@stream.flush # Don't remove me!
	
	if body
		body.each do |chunk|
			@stream.write(chunk)
			@stream.flush
		end
		
		@stream.close_write
	end
	
	return @stream
end

#write_upgrade_body(protocol, body = nil) ⇒ Object

Parameters:

  • protocol (String)

    the protocol to upgrade to.



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/protocol/http1/connection.rb', line 251

def write_upgrade_body(protocol, body = nil)
	# Once we upgrade the connection, it can no longer handle other requests:
	@persistent = false
	
	write_upgrade_header(protocol)
	
	@stream.write("\r\n")
	@stream.flush # Don't remove me!
	
	if body
		body.each do |chunk|
			@stream.write(chunk)
			@stream.flush
		end
		
		@stream.close_write
	end
	
	return @stream
end

#write_upgrade_header(upgrade) ⇒ Object



105
106
107
# File 'lib/protocol/http1/connection.rb', line 105

def write_upgrade_header(upgrade)
	@stream.write("connection: upgrade\r\nupgrade: #{upgrade}\r\n")
end