From 69c735a961128d7359227d739f65c2a3300452c8 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Tue, 15 Oct 2024 01:39:10 +1300 Subject: [PATCH] Add support for maximum line length. --- lib/protocol/http1/connection.rb | 15 +++++++++++++-- lib/protocol/http1/error.rb | 3 +++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/protocol/http1/connection.rb b/lib/protocol/http1/connection.rb index 547972b..85031ca 100644 --- a/lib/protocol/http1/connection.rb +++ b/lib/protocol/http1/connection.rb @@ -45,18 +45,22 @@ module HTTP1 VALID_FIELD_NAME = /\A#{FIELD_NAME}\z/.freeze VALID_FIELD_VALUE = /\A#{FIELD_VALUE}\z/.freeze + DEFAULT_MAXIMUM_LINE_LENGTH = 8192 + class Connection CRLF = "\r\n" HTTP10 = "HTTP/1.0" HTTP11 = "HTTP/1.1" - def initialize(stream, persistent: true, state: :idle) + def initialize(stream, persistent: true, state: :idle, maximum_line_length: DEFAULT_MAXIMUM_LINE_LENGTH) @stream = stream @persistent = persistent @state = state @count = 0 + + @maximum_line_length = maximum_line_length end attr :stream @@ -282,7 +286,14 @@ def read(length) end def read_line? - @stream.gets(CRLF, chomp: true) + line = @stream.gets(CRLF, @maximum_line_length) + + unless line.chomp!(CRLF) + # This basically means that the request line, response line, header, or chunked length line is too long. + raise LineLengthError, "Line too long!" + end + + return line end def read_line diff --git a/lib/protocol/http1/error.rb b/lib/protocol/http1/error.rb index ca54827..dd2c015 100644 --- a/lib/protocol/http1/error.rb +++ b/lib/protocol/http1/error.rb @@ -14,6 +14,9 @@ class Error < HTTP::Error class ProtocolError < Error end + class LineLengthError < Error + end + # The request was not able to be parsed correctly, or failed some kind of validation. class BadRequest < Error end