1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 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 330 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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 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 486 487 488 489 490 491 492 493 494 495
|
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2018-2025, by Samuel Williams.
require_relative "error"
require_relative "header/split"
require_relative "header/multiple"
require_relative "header/cookie"
require_relative "header/connection"
require_relative "header/cache_control"
require_relative "header/etag"
require_relative "header/etags"
require_relative "header/vary"
require_relative "header/authorization"
require_relative "header/date"
require_relative "header/priority"
require_relative "header/trailer"
require_relative "header/server_timing"
require_relative "header/digest"
require_relative "header/accept"
require_relative "header/accept_charset"
require_relative "header/accept_encoding"
require_relative "header/accept_language"
require_relative "header/transfer_encoding"
require_relative "header/te"
module Protocol
module HTTP
# @namespace
module Header
end
# Headers are an array of key-value pairs. Some header keys represent multiple values.
class Headers
Split = Header::Split
Multiple = Header::Multiple
TRAILER = "trailer"
# Construct an instance from a headers Array or Hash. No-op if already an instance of `Headers`. If the underlying array is frozen, it will be duped.
#
# @return [Headers] an instance of headers.
def self.[] headers
if headers.nil?
return self.new
end
if headers.is_a?(self)
if headers.frozen?
return headers.dup
else
return headers
end
end
fields = headers.to_a
if fields.frozen?
fields = fields.dup
end
return self.new(fields)
end
# Initialize the headers with the specified fields.
#
# @parameter fields [Array] An array of `[key, value]` pairs.
# @parameter tail [Integer | Nil] The index of the trailer start in the @fields array.
def initialize(fields = [], tail = nil, indexed: nil, policy: POLICY)
@fields = fields
# Marks where trailer start in the @fields array:
@tail = tail
# The cached index of headers:
@indexed = nil
@policy = policy
end
# @attribute [Hash] The policy for the headers.
attr :policy
# Set the policy for the headers.
#
# The policy is used to determine how headers are merged and normalized. For example, if a header is specified multiple times, the policy will determine how the values are merged.
#
# @parameter policy [Hash] The policy for the headers.
def policy=(policy)
@policy = policy
@indexed = nil
end
# Initialize a copy of the headers.
#
# @parameter other [Headers] The headers to copy.
def initialize_dup(other)
super
@fields = @fields.dup
@indexed = @indexed.dup
end
# Clear all headers.
def clear
@fields.clear
@tail = nil
@indexed = nil
end
# Flatten trailer into the headers, in-place.
def flatten!
if @tail
self.delete(TRAILER)
@tail = nil
end
return self
end
# Flatten trailer into the headers, returning a new instance of {Headers}.
def flatten
self.dup.flatten!
end
# @attribute [Array] An array of `[key, value]` pairs.
attr :fields
# @attribute [Integer | Nil] The index where trailers begin.
attr :tail
# @returns [Array] The fields of the headers.
def to_a
@fields
end
# @returns [Boolean] Whether there are any trailers.
def trailer?
@tail != nil
end
# Record the current headers, and prepare to add trailers.
#
# This method is typically used after headers are sent to capture any additional headers which should then be sent as trailers.
#
# A sender that intends to generate one or more trailer fields in a message should generate a trailer header field in the header section of that message to indicate which fields might be present in the trailers.
#
# @parameter names [Array] The trailer header names which will be added later.
# @yields {|name, value| ...} the trailing headers if a block is given.
# @returns An enumerator which is suitable for iterating over trailers.
def trailer!(&block)
@tail ||= @fields.size
return trailer(&block)
end
# Enumerate all headers in the trailer, if there are any.
def trailer(&block)
return to_enum(:trailer) unless block_given?
if @tail
@fields.drop(@tail).each(&block)
end
end
# Freeze the headers, and ensure the indexed hash is generated.
def freeze
return if frozen?
# Ensure @indexed is generated:
self.to_h
@fields.freeze
@indexed.freeze
super
end
# @returns [Boolean] Whether the headers are empty.
def empty?
@fields.empty?
end
# Enumerate all header keys and values.
#
# @yields {|key, value| ...}
# @parameter key [String] The header key.
# @parameter value [String] The header value.
def each(&block)
@fields.each(&block)
end
# @returns [Boolean] Whether the headers include the specified key.
def include? key
self[key] != nil
end
alias key? include?
# @returns [Array] All the keys of the headers.
def keys
self.to_h.keys
end
# Extract the specified keys from the headers.
#
# @parameter keys [Array] The keys to extract.
def extract(keys)
deleted, @fields = @fields.partition do |field|
keys.include?(field.first.downcase)
end
if @indexed
keys.each do |key|
@indexed.delete(key)
end
end
return deleted
end
# Add the specified header key value pair.
#
# @parameter key [String] the header key.
# @parameter value [String] the header value to assign.
def add(key, value)
# The value MUST be a string, so we convert it to a string to prevent errors later on.
value = value.to_s
if @indexed
merge_into(@indexed, key.downcase, value)
end
@fields << [key, value]
end
alias []= add
# Set the specified header key to the specified value, replacing any existing header keys with the same name.
#
# @parameter key [String] the header key to replace.
# @parameter value [String] the header value to assign.
def set(key, value)
# TODO This could be a bit more efficient:
self.delete(key)
self.add(key, value)
end
# Merge the headers into this instance.
def merge!(headers)
headers.each do |key, value|
self.add(key, value)
end
return self
end
# Merge the headers into a new instance of {Headers}.
def merge(headers)
self.dup.merge!(headers)
end
# The policy for various headers, including how they are merged and normalized.
POLICY = {
# Headers which may only be specified once:
"content-disposition" => false,
"content-length" => false,
"content-type" => false,
"expect" => false,
"from" => false,
"host" => false,
"location" => false,
"max-forwards" => false,
"range" => false,
"referer" => false,
"retry-after" => false,
"server" => false,
"transfer-encoding" => Header::TransferEncoding,
"user-agent" => false,
"trailer" => Header::Trailer,
# Custom headers:
"connection" => Header::Connection,
"cache-control" => Header::CacheControl,
"te" => Header::TE,
"vary" => Header::Vary,
"priority" => Header::Priority,
# Headers specifically for proxies:
"via" => Split,
"x-forwarded-for" => Split,
# Authorization headers:
"authorization" => Header::Authorization,
"proxy-authorization" => Header::Authorization,
# Cache validations:
"etag" => Header::ETag,
"if-match" => Header::ETags,
"if-none-match" => Header::ETags,
"if-range" => false,
# Headers which may be specified multiple times, but which can't be concatenated:
"www-authenticate" => Multiple,
"proxy-authenticate" => Multiple,
# Custom headers:
"set-cookie" => Header::SetCookie,
"cookie" => Header::Cookie,
# Date headers:
# These headers include a comma as part of the formatting so they can't be concatenated.
"date" => Header::Date,
"expires" => Header::Date,
"last-modified" => Header::Date,
"if-modified-since" => Header::Date,
"if-unmodified-since" => Header::Date,
# Accept headers:
"accept" => Header::Accept,
"accept-charset" => Header::AcceptCharset,
"accept-encoding" => Header::AcceptEncoding,
"accept-language" => Header::AcceptLanguage,
# Performance headers:
"server-timing" => Header::ServerTiming,
# Content integrity headers:
"digest" => Header::Digest,
}.tap{|hash| hash.default = Split}
# Delete all header values for the given key, and return the merged value.
#
# @parameter key [String] The header key.
# @returns [String | Array | Object] The merged header value.
def delete(key)
deleted, @fields = @fields.partition do |field|
field.first.downcase == key
end
if deleted.empty?
return nil
end
if @indexed
return @indexed.delete(key)
elsif policy = @policy[key]
(key, value), *tail = deleted
merged = policy.new(value)
tail.each{|k,v| merged << v}
return merged
else
key, value = deleted.last
return value
end
end
# Merge the value into the hash according to the policy for the given key.
#
# @parameter hash [Hash] The hash to merge into.
# @parameter key [String] The header key.
# @parameter value [String] The raw header value.
protected def merge_into(hash, key, value, trailer = @tail)
if policy = @policy[key]
# Check if we're adding to trailers and this header is allowed:
if trailer && !policy.trailer?
return false
end
if current_value = hash[key]
current_value << value
else
hash[key] = policy.new(value)
end
else
# By default, headers are not allowed in trailers:
if trailer
return false
end
if hash.key?(key)
raise DuplicateHeaderError, key
end
hash[key] = value
end
end
# Get the value of the specified header key.
#
# @parameter key [String] The header key.
# @returns [String | Array | Object] The header value.
def [] key
to_h[key]
end
# Compute a hash table of headers, where the keys are normalized to lower case and the values are normalized according to the policy for that header.
#
# @returns [Hash] A hash table of `{key, value}` pairs.
def to_h
unless @indexed
@indexed = {}
@fields.each_with_index do |(key, value), index|
trailer = (@tail && index >= @tail)
merge_into(@indexed, key.downcase, value, trailer)
end
end
return @indexed
end
alias as_json to_h
# Inspect the headers.
#
# @returns [String] A string representation of the headers.
def inspect
"#<#{self.class} #{@fields.inspect}>"
end
# Compare this object to another object. May depend on the order of the fields.
#
# @returns [Boolean] Whether the other object is equal to this one.
def == other
case other
when Hash
to_h == other
when Headers
@fields == other.fields
else
@fields == other
end
end
# Used for merging objects into a sequential list of headers. Normalizes header keys and values.
class Merged
include Enumerable
# Construct a merged list of headers.
#
# @parameter *all [Array] An array of all headers to merge.
def initialize(*all)
@all = all
end
# @returns [Array] A list of all headers, in the order they were added, as `[key, value]` pairs.
def fields
each.to_a
end
# @returns [Headers] A new instance of {Headers} containing all the merged headers.
def flatten
Headers.new(fields)
end
# Clear the references to all headers.
def clear
@all.clear
end
# Add a new set of headers to the merged list.
#
# @parameter headers [Headers | Array | Hash] A list of headers to add.
def << headers
@all << headers
return self
end
# Enumerate all headers in the merged list.
#
# @yields {|key, value| ...} The header key and value.
# @parameter key [String] The header key (lower case).
# @parameter value [String] The header value.
def each(&block)
return to_enum unless block_given?
@all.each do |headers|
headers.each do |key, value|
yield key.to_s.downcase, value.to_s
end
end
end
end
end
end
end
|