/
common.cr
409 lines (367 loc) · 12.3 KB
/
common.cr
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
{% if !flag?(:without_zlib) %}
require "flate"
require "gzip"
{% end %}
module HTTP
# :nodoc:
MAX_HEADER_SIZE = 16_384
# :nodoc:
enum BodyType
OnDemand
Prohibited
Mandatory
end
SUPPORTED_VERSIONS = {"HTTP/1.0", "HTTP/1.1"}
# :nodoc:
def self.parse_headers_and_body(io, body_type : BodyType = BodyType::OnDemand, decompress = true)
headers = Headers.new
headers_size = 0
while line = io.gets(MAX_HEADER_SIZE, chomp: true)
headers_size += line.bytesize
break if headers_size > MAX_HEADER_SIZE
if line.empty?
body = nil
if body_type.prohibited?
body = nil
elsif content_length = content_length(headers)
if content_length != 0
# Don't create IO for Content-Length == 0
body = FixedLengthContent.new(io, content_length)
end
elsif headers["Transfer-Encoding"]? == "chunked"
body = ChunkedContent.new(io)
elsif body_type.mandatory?
body = UnknownLengthContent.new(io)
end
if decompress && body
{% if flag?(:without_zlib) %}
raise "Can't decompress because `-D without_zlib` was passed at compile time"
{% else %}
encoding = headers["Content-Encoding"]?
case encoding
when "gzip"
body = Gzip::Reader.new(body, sync_close: true)
when "deflate"
body = Flate::Reader.new(body, sync_close: true)
end
{% end %}
end
check_content_type_charset(body, headers)
yield headers, body
break
end
name, value = parse_header(line)
break unless headers.add?(name, value)
end
end
private def self.check_content_type_charset(body, headers)
return unless body
if charset = content_type_and_charset(headers).charset
body.set_encoding(charset, invalid: :skip)
end
end
# :nodoc:
def self.parse_header(line)
# This is basically
#
# ```
# line = "Server: nginx"
# name, value = line.split ':', 2
# {name, value.lstrip} # => {"Server", "nginx"}
# ```
#
# except that it's faster because we only create 2 strings
# instead of 3 (two from the split and one for the lstrip),
# and there's no need for the array returned by split.
cstr = line.to_unsafe
bytesize = line.bytesize
# Get the colon index and name
colon_index = cstr.to_slice(bytesize).index(':'.ord) || 0
name = line.byte_slice(0, colon_index)
# Get where the header value starts (skip space)
middle_index = colon_index + 1
while middle_index < bytesize && cstr[middle_index].unsafe_chr.ascii_whitespace?
middle_index += 1
end
# Get where the header value ends (chomp line)
right_index = bytesize
if middle_index >= right_index
return {name, ""}
elsif right_index > 1 && cstr[right_index - 2] === '\r' && cstr[right_index - 1] === '\n'
right_index -= 2
elsif right_index > 0 && cstr[right_index - 1] === '\n'
right_index -= 1
end
value = line.byte_slice(middle_index, right_index - middle_index)
{name, value}
end
# :nodoc:
def self.serialize_headers_and_body(io, headers, body, body_io, version)
if body
serialize_headers_and_string_body(io, headers, body)
elsif body_io
content_length = content_length(headers)
if content_length
serialize_headers(io, headers)
copied = IO.copy(body_io, io)
if copied != content_length
raise ArgumentError.new("Content-Length header is #{content_length} but body had #{copied} bytes")
end
elsif Client::Response.supports_chunked?(version)
headers["Transfer-Encoding"] = "chunked"
serialize_headers(io, headers)
serialize_chunked_body(io, body_io)
else
body = body_io.gets_to_end
serialize_headers_and_string_body(io, headers, body)
end
else
serialize_headers(io, headers)
end
end
def self.serialize_headers_and_string_body(io, headers, body)
headers["Content-Length"] = body.bytesize.to_s
serialize_headers(io, headers)
io << body
end
def self.serialize_headers(io, headers)
headers.each do |name, values|
values.each do |value|
io << name << ": " << value << "\r\n"
end
end
io << "\r\n"
end
def self.serialize_chunked_body(io, body)
buf = uninitialized UInt8[8192]
while (buf_length = body.read(buf.to_slice)) > 0
buf_length.to_s(16, io)
io << "\r\n"
io.write(buf.to_slice[0, buf_length])
io << "\r\n"
end
io << "0\r\n\r\n"
end
# :nodoc:
def self.content_length(headers)
length_headers = headers.get? "Content-Length"
return nil unless length_headers
first_header = length_headers[0]
if length_headers.size > 1 && length_headers.any? { |header| header != first_header }
raise ArgumentError.new("Multiple Content-Length headers received did not match: #{length_headers}")
end
first_header.to_u64
end
# :nodoc:
def self.keep_alive?(message)
case message.headers["Connection"]?.try &.downcase
when "keep-alive"
return true
when "close", "upgrade"
return false
end
case message.version
when "HTTP/1.0"
false
else
true
end
end
record ComputedContentTypeHeader,
content_type : String?,
charset : String?
# :nodoc:
def self.content_type_and_charset(headers)
content_type = headers["Content-Type"]?
return ComputedContentTypeHeader.new(nil, nil) unless content_type
# Avoid allocating an array for the split if there's no ';'
if content_type.index(';')
pieces = content_type.split(';')
content_type = pieces[0].strip
(1...pieces.size).each do |i|
piece = pieces[i]
eq_index = piece.index('=')
if eq_index
key = piece[0...eq_index].strip
if key == "charset"
value = piece[eq_index + 1..-1].strip
# For the case of a quoted charset like charset="utf-8"
if value.starts_with?('"') && value.ends_with?('"')
value = value[1...-1].strip
end
return ComputedContentTypeHeader.new(content_type, value)
end
end
end
else
content_type = content_type.strip
end
ComputedContentTypeHeader.new(content_type.strip, nil)
end
# Parse a time string using the formats specified by [RFC 2616](https://tools.ietf.org/html/rfc2616#section-3.3.1)
#
# ```
# HTTP.parse_time("Sun, 14 Feb 2016 21:00:00 GMT") # => "2016-02-14 21:00:00 UTC"
# HTTP.parse_time("Sunday, 14-Feb-16 21:00:00 GMT") # => "2016-02-14 21:00:00 UTC"
# HTTP.parse_time("Sun Feb 14 21:00:00 2016") # => "2016-02-14 21:00:00 UTC"
# ```
#
# Uses `Time::Format::HTTP_DATE` as parser.
def self.parse_time(time_str : String) : Time?
Time::Format::HTTP_DATE.parse(time_str)
rescue Time::Format::Error
end
# Format a `Time` object as a `String` using the format specified as `sane-cookie-date`
# by [RFC 6265](https://tools.ietf.org/html/rfc6265#section-4.1.1) which is
# according to [RFC 2616](https://tools.ietf.org/html/rfc2616#section-3.3.1) a
# [RFC 1123](https://tools.ietf.org/html/rfc1123#page-55) format with explicit
# timezone `GMT` (interpreted as `UTC`).
#
# ```
# HTTP.format_time(Time.utc(2016, 2, 15)) # => "Mon, 15 Feb 2016 00:00:00 GMT"
# ```
#
# Uses `Time::Format::HTTP_DATE` as formatter.
def self.format_time(time : Time) : String
Time::Format::HTTP_DATE.format(time)
end
# Dequotes an [RFC 2616](https://tools.ietf.org/html/rfc2616#page-17)
# quoted-string.
#
# ```
# quoted = %q(\"foo\\bar\")
# HTTP.dequote_string(quoted) # => %q("foo\bar")
# ```
def self.dequote_string(str)
data = str.to_slice
quoted_pair_index = data.index('\\'.ord)
return str unless quoted_pair_index
String.build do |io|
while quoted_pair_index
io.write(data[0, quoted_pair_index])
io << data[quoted_pair_index + 1].chr
data += quoted_pair_index + 2
quoted_pair_index = data.index('\\'.ord)
end
io.write(data)
end
end
# Encodes a string to an [RFC 2616](https://tools.ietf.org/html/rfc2616#page-17)
# quoted-string. Encoded string is written to *io*. May raise when *string*
# contains an invalid character.
#
# ```
# string = %q("foo\ bar")
# io = IO::Memory.new
# HTTP.quote_string(string, io)
# io.rewind
# io.gets_to_end # => %q(\"foo\\\ bar\")
# ```
def self.quote_string(string, io)
# Escaping rules: https://evolvis.org/pipermail/evolvis-platfrm-discuss/2014-November/000675.html
string.each_byte do |byte|
case byte
when '\t'.ord, ' '.ord, '"'.ord, '\\'.ord
io << '\\'
when 0x00..0x1F, 0x7F
raise ArgumentError.new("String contained invalid character #{byte.chr.inspect}")
end
io.write_byte byte
end
end
# Encodes a string to an [RFC 2616](https://tools.ietf.org/html/rfc2616#page-17)
# quoted-string. May raise when *string* contains an invalid character.
#
# ```
# string = %q("foo\ bar")
# HTTP.quote_string(string) # => %q(\"foo\\\ bar\")
# ```
def self.quote_string(string)
String.build do |io|
quote_string(string, io)
end
end
# Returns the default status message of the given HTTP status code.
#
# Based on [Hypertext Transfer Protocol (HTTP) Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml)
#
# Last Updated 2017-04-14
#
# HTTP Status Codes (source: [http-status-codes-1.csv](https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv))
#
# * 1xx: Informational - Request received, continuing process
# * 2xx: Success - The action was successfully received, understood, and accepted
# * 3xx: Redirection - Further action must be taken in order to complete the request
# * 4xx: Client Error - The request contains bad syntax or cannot be fulfilled
# * 5xx: Server Error - The server failed to fulfill an apparently valid request
#
def self.default_status_message_for(status_code : Int) : String
case status_code
when 100 then "Continue"
when 101 then "Switching Protocols"
when 102 then "Processing"
when 200 then "OK"
when 201 then "Created"
when 202 then "Accepted"
when 203 then "Non-Authoritative Information"
when 204 then "No Content"
when 205 then "Reset Content"
when 206 then "Partial Content"
when 207 then "Multi-Status"
when 208 then "Already Reported"
when 226 then "IM Used"
when 300 then "Multiple Choices"
when 301 then "Moved Permanently"
when 302 then "Found"
when 303 then "See Other"
when 304 then "Not Modified"
when 305 then "Use Proxy"
when 307 then "Temporary Redirect"
when 308 then "Permanent Redirect"
when 400 then "Bad Request"
when 401 then "Unauthorized"
when 402 then "Payment Required"
when 403 then "Forbidden"
when 404 then "Not Found"
when 405 then "Method Not Allowed"
when 406 then "Not Acceptable"
when 407 then "Proxy Authentication Required"
when 408 then "Request Timeout"
when 409 then "Conflict"
when 410 then "Gone"
when 411 then "Length Required"
when 412 then "Precondition Failed"
when 413 then "Payload Too Large"
when 414 then "URI Too Long"
when 415 then "Unsupported Media Type"
when 416 then "Range Not Satisfiable"
when 417 then "Expectation Failed"
when 421 then "Misdirected Request"
when 422 then "Unprocessable Entity"
when 423 then "Locked"
when 424 then "Failed Dependency"
when 426 then "Upgrade Required"
when 428 then "Precondition Required"
when 429 then "Too Many Requests"
when 431 then "Request Header Fields Too Large"
when 451 then "Unavailable For Legal Reasons"
when 500 then "Internal Server Error"
when 501 then "Not Implemented"
when 502 then "Bad Gateway"
when 503 then "Service Unavailable"
when 504 then "Gateway Timeout"
when 505 then "HTTP Version Not Supported"
when 506 then "Variant Also Negotiates"
when 507 then "Insufficient Storage"
when 508 then "Loop Detected"
when 510 then "Not Extended"
when 511 then "Network Authentication Required"
else ""
end
end
end
require "./request"
require "./client/response"
require "./headers"
require "./content"
require "./cookie"