Class: Itsi::HttpRequest

Inherits:
Object
  • Object
show all
Includes:
ResponseStatusShortcodes, Server::TypedHandlers::ParamParser
Defined in:
lib/itsi/http_request.rb,
lib/itsi/http_request/response_status_shortcodes.rb

Defined Under Namespace

Modules: ResponseStatusShortcodes

Constant Summary collapse

EMPTY_IO =
StringIO.new("").tap { |io| io.set_encoding(Encoding::ASCII_8BIT) }
RACK_HEADER_MAP =
StandardHeaders::ALL.map do |header|
  rack_form = \
    if header == "content-type"
      "CONTENT_TYPE"
    elsif header == "content-length"
      "CONTENT_LENGTH"
    else
      "HTTP_#{header.upcase.gsub(/-/, "_")}"
    end
  [header, rack_form]
end.to_h
SPECIAL_RACK_HEADER_MAP =
{
  "content-type" => "CONTENT_TYPE",
  "content-length" => "CONTENT_LENGTH",
  "accept" => "HTTP_ACCEPT",
  "accept-encoding" => "HTTP_ACCEPT_ENCODING",
  "accept-language" => "HTTP_ACCEPT_LANGUAGE",
  "user-agent" => "HTTP_USER_AGENT",
  "referer" => "HTTP_REFERER",
  "origin" => "HTTP_ORIGIN",
  "cookie" => "HTTP_COOKIE",
  "authorization" => "HTTP_AUTHORIZATION",
  "x-forwarded-for" => "HTTP_X_FORWARDED_FOR",
  "x-forwarded-proto" => "HTTP_X_FORWARDED_PROTO"
}.freeze
HTTP_09 =
"HTTP/0.9"
HTTP_09_ARR =
["HTTP/0.9"].freeze
HTTP_10 =
"HTTP/1.0"
HTTP_10_ARR =
["HTTP/1.0"].freeze
HTTP_11 =
"HTTP/1.1"
HTTP_11_ARR =
["HTTP/1.1"].freeze
HTTP_20 =
"HTTP/2.0"
HTTP_20_ARR =
["HTTP/2.0"].freeze
HTTP_30 =
"HTTP/3.0"
HTTP_30_ARR =
["HTTP/3.0"].freeze

Constants included from ResponseStatusShortcodes

ResponseStatusShortcodes::HTTP_STATUS_CODES, ResponseStatusShortcodes::HTTP_STATUS_NAME_TO_CODE_MAP

Constants included from Server::TypedHandlers::ParamParser

Server::TypedHandlers::ParamParser::CONVERSION_MAP

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Server::TypedHandlers::ParamParser

#apply_schema!, #cast_value!, #format_path, #processed_schema

Instance Attribute Details

#hijackedObject

Returns the value of attribute hijacked.



12
13
14
# File 'lib/itsi/http_request.rb', line 12

def hijacked
  @hijacked
end

Instance Method Details

#bodyObject



153
154
155
# File 'lib/itsi/http_request.rb', line 153

def body
  @body ||= build_input_io
end

#build_input_ioObject



157
158
159
160
161
162
163
164
# File 'lib/itsi/http_request.rb', line 157

def build_input_io
  case body_parts
  when nil then EMPTY_IO
  when String then StringIO.new(body_parts).tap { |io| io.set_encoding(Encoding::ASCII_8BIT) }
  when Array then File.open(body_parts.first, "rb").tap { |io| io.set_encoding(Encoding::ASCII_8BIT) }
  else body_parts
  end
end

#callObject

Rack expects env to respond to #call.



149
150
151
# File 'lib/itsi/http_request.rb', line 149

def call
  hijack
end

#clean_temp_files(params) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
# File 'lib/itsi/http_request.rb', line 219

def clean_temp_files(params)
  case params
  when Hash
    if params.key?(:tempfile)
      params[:tempfile].unlink
    else
      params.each_value { |v| clean_temp_files(v) }
    end
  when Array then params.each { |v| clean_temp_files(v) }
  end
end

#hijackObject



137
138
139
140
141
142
143
144
145
146
# File 'lib/itsi/http_request.rb', line 137

def hijack
  self.hijacked = true
  UNIXSocket.pair.yield_self do |(server_sock, app_sock)|
    server_sock.autoclose = false
    response.hijack(server_sock.fileno)
    server_sock.sync = true
    app_sock.sync = true
    app_sock
  end
end

#params(schema = nil) ⇒ Object



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
# File 'lib/itsi/http_request.rb', line 170

def params(schema = nil)
  params = if url_encoded?
             URI.decode_www_form(build_input_io.read).to_h
           elsif json?
             JSON.parse(build_input_io.read)
           elsif multipart?
             Rack::Multipart::Parser.parse(
               build_input_io,
               content_length,
               content_type,
               Rack::Multipart::Parser::TEMPFILE_FACTORY,
               Rack::Multipart::Parser::BUFSIZE,
               Rack::Utils.default_query_parser
             ).params
           else
             {}
           end

  params.merge!(query_params).merge!(url_params)
  validated = schema ? apply_schema!(params, schema) : params
  if block_given?
    yield validated
  else
    raise "#params must take a block for multipart requests" if multipart?

    validated

  end
rescue ValidationError => e
  if response.json?
    respond(json: { error: e.message }, status: 400)
  else
    respond(e.message, 400)
  end
rescue StandardError => e
  Itsi.log_error e.message
  puts e.backtrace

  # Unexpected error.
  # Don't reveal potential sensitive information to client.
  if response.json?
    respond(json: { error: "Internal Server Error" }, status: 500)
  else
    respond("Internal Server Error", 500)
  end
ensure
  clean_temp_files(params)
end

#query_paramsObject



231
232
233
# File 'lib/itsi/http_request.rb', line 231

def query_params
  URI.decode_www_form(query_string).to_h
end

#respond(_body = nil, _status = 200, _headers = nil, json: nil, html: nil, text: nil, xml: nil, hijack: false, as: nil, status: _status, headers: _headers, body: _body, &blk) ⇒ Object



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
# File 'lib/itsi/http_request.rb', line 95

def respond(
  _body = nil, _status = 200, _headers = nil, # rubocop:disable Lint/UnderscorePrefixedVariableName
  json: nil,
  html: nil,
  text: nil,
  xml: nil,
  hijack: false,
  as: nil,
  status: _status,
  headers: _headers,
  body: _body,
  &blk
)
  if json
    if as
      begin
        validate!(json, as: as)
      rescue ValidationError => e
        json = { type: "error", message: "Validation Error: #{e.message}" }
        status = 400
      end
    end
    body = json.to_json
    headers ||= {}
    headers["Content-Type"] ||= "application/json"
  elsif html
    body = html
    headers ||= {}
    headers["Content-Type"] ||= "text/html"
  elsif xml
    body = xml
    headers ||= {}
    headers["Content-Type"] ||= "application/xml"
  elsif text
    body = text
    headers ||= {}
    headers["Content-Type"] ||= "text/plain"
  end

  response.respond(status: status, headers: headers, body: body, hijack: hijack, &blk)
end

#to_rack_envObject



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
# File 'lib/itsi/http_request.rb', line 56

def to_rack_env
  path = self.path
  host = self.host
  version = self.version
  env = RackEnvPool.checkout
  env["SCRIPT_NAME"] = script_name
  env["REQUEST_METHOD"] = request_method
  env["REQUEST_PATH"] = env["PATH_INFO"] = path
  env["QUERY_STRING"] = query_string
  env["REMOTE_ADDR"] = remote_addr
  env["SERVER_PORT"] = port.to_s
  env["HTTP_HOST"] = env["SERVER_NAME"] = host
  env["HTTP_VERSION"] = env["SERVER_PROTOCOL"] = version
  env["itsi.request"] = self
  env["itsi.response"] = response
  env["rack.version"] = \
    case version
    when HTTP_09 then HTTP_09_ARR
    when HTTP_10 then HTTP_10_ARR
    when HTTP_11 then HTTP_11_ARR
    when HTTP_20 then HTTP_20_ARR
    when HTTP_30 then HTTP_30_ARR
    end
  env["rack.url_scheme"] = scheme
  env["rack.input"] = build_input_io
  env["rack.hijack"] = self
  each_header do |k, v|
    rack_header = SPECIAL_RACK_HEADER_MAP[k] || RACK_HEADER_MAP[k]
    if k == "cookie" && env.key?(rack_header)
      # RFC 9113 allows HTTP/2 clients to split Cookie across fields. Rack
      # expects one HTTP_COOKIE value, joined with "; " rather than comma.
      env[rack_header] = "#{env[rack_header]}; #{v}"
    else
      env[rack_header] = v
    end
  end
  env
end

#validate!(params, as: nil) ⇒ Object



166
167
168
# File 'lib/itsi/http_request.rb', line 166

def validate!(params, as: nil)
  as ? apply_schema!(params, as) : params
end