Class: Nitro::Cgi
Overview
Nitro CGI (Common Gateway Interface) methods. Typically handles HTTP Request parsing and HTTP Response generation.
Constant Summary
Constants included from Http
Http::CR, Http::CRLF, Http::EOL, Http::LF, Http::STATUS_AUTH_REQUIRED, Http::STATUS_BAD_GATEWAY, Http::STATUS_BAD_REQUEST, Http::STATUS_FORBIDDEN, Http::STATUS_LENGTH_REQUIRED, Http::STATUS_METHOD_NOT_ALLOWED, Http::STATUS_MOVED, Http::STATUS_NOT_ACCEPTABLE, Http::STATUS_NOT_FOUND, Http::STATUS_NOT_IMPLEMENTED, Http::STATUS_NOT_MODIFIED, Http::STATUS_OK, Http::STATUS_PARTIAL_CONTENT, Http::STATUS_PRECONDITION_FAILED, Http::STATUS_REDIRECT, Http::STATUS_SEE_OTHER, Http::STATUS_SEE_OTHER_307, Http::STATUS_SERVER_ERROR, Http::STATUS_STRINGS, Http::STATUS_VARIANT_ALSO_VARIES
Class Method Summary collapse
-
.parse_cookies(context) ⇒ Object
Parse the HTTP_COOKIE header and returns the cookies as a key->value hash.
-
.parse_multipart(context, boundary) ⇒ Object
Parse a multipart request.
-
.parse_params(context) ⇒ Object
Initialize the request params.
-
.parse_query_string(query_string) ⇒ Object
Returns a hash with the pairs from the query string.
-
.process(server, cgi, inp, out) ⇒ Object
Process a CGI request.
-
.response_headers(context, proto = false) ⇒ Object
Build the response headers for the context.
-
.structure_param(params, key, val) ⇒ Object
push a parameter into the params hash.
Class Method Details
.parse_cookies(context) ⇒ Object
Parse the HTTP_COOKIE header and returns the cookies as a key->value hash. For efficiency no cookie objects are created.
context
-
The context
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/nitro/cgi.rb', line 121 def self.(context) env = context.env # FIXME: dont precreate? context. = {} #if env.has_key?('HTTP_COOKIE') or env.has_key?('COOKIE') if env['HTTP_COOKIE'] or env['COOKIE'] (env['HTTP_COOKIE'] or env['COOKIE']).split(/; /).each do |c| key, val = c.split(/=/, 2) val ||= "" key = CGI.unescape(key) val = val.split(/&/).collect{|v| CGI::unescape(v)}.join("\0") if context..include?(key) context.[key] += "\0" + val else context.[key] = val end end end end |
.parse_multipart(context, boundary) ⇒ Object
Parse a multipart request. Adapted from Ruby’s cgi.rb – TODO: optimize and rationalize this. ++
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 |
# File 'lib/nitro/cgi.rb', line 210 def self.parse_multipart(context, boundary) input = context.in content_length = context.content_length env_table = context.env params = Hash.new() boundary = "--" + boundary quoted_boundary = Regexp.quote(boundary, "n") buf = "" boundary_end="" # start multipart/form-data input.binmode if defined? input.binmode boundary_size = boundary.size + EOL.size content_length -= boundary_size status = input.read(boundary_size) if nil == status raise EOFError, "no content body" elsif boundary + EOL != status raise EOFError, "bad content body" end loop do head = nil if 10240 < content_length body = Tempfile.new("CGI") else begin require "stringio" body = StringIO.new rescue LoadError body = Tempfile.new("CGI") end end body.binmode if defined? body.binmode until head and /#{quoted_boundary}(?:#{EOL}|--)/n.match(buf) if (not head) and /#{EOL}#{EOL}/n.match(buf) buf = buf.sub(/\A((?:.|\n)*?#{EOL})#{EOL}/n) do head = $1.dup "" end next end if head and ( (EOL + boundary + EOL).size < buf.size ) body.print buf[0 ... (buf.size - (EOL + boundary + EOL).size)] buf[0 ... (buf.size - (EOL + boundary + EOL).size)] = "" end c = if Cgi.buffer_size < content_length input.read(Cgi.buffer_size) else input.read(content_length) end if c.nil? || c.empty? raise EOFError, "bad content body" end buf.concat(c) content_length -= c.size end buf = buf.sub(/\A((?:.|\n)*?)(?:[\r\n]{1,2})?#{quoted_boundary}([\r\n]{1,2}|--)/n) do body.print $1 if "--" == $2 content_length = -1 end boundary_end = $2.dup "" end body.rewind /Content-Disposition:.* filename="?([^\";]*)"?/ni.match(head) filename = ($1 or "") if /Mac/ni.match(env_table['HTTP_USER_AGENT']) and /Mozilla/ni.match(env_table['HTTP_USER_AGENT']) and (not /MSIE/ni.match(env_table['HTTP_USER_AGENT'])) filename = CGI::unescape(filename) end /Content-Type: (.*)/ni.match(head) content_type = ($1 or "") (class << body; self; end).class_eval do alias local_path path define_method(:original_filename) { filename.dup.taint } define_method(:content_type) { content_type.dup.taint } # gmosx: this hides the performance hit!! define_method(:to_s) { str = read; rewind; return str} end /Content-Disposition:.* name="?([^\";]*)"?/ni.match(head) name = $1.dup params = self.structure_param(params, name, body) break if buf.size == 0 break if content_length === -1 end raise EOFError, "bad boundary end of body" unless boundary_end =~ /--/ return params end |
.parse_params(context) ⇒ Object
Initialize the request params. Handles multipart forms (in particular, forms that involve file uploads). Reads query parameters in the @params field, and cookies into @cookies.
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/nitro/cgi.rb', line 184 def self.parse_params(context) method = context.method if (:post == method) and %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n.match(context.headers['CONTENT_TYPE']) boundary = $1.dup context.params = parse_multipart(context, boundary) # Also include the URL parameters. context.params.update(Cgi.parse_query_string(context.query_string)) else case method when :get, :head context.params = Cgi.parse_query_string(context.query_string) when :post context.in.binmode if defined?(context.in.binmode) context.params = Cgi.parse_query_string(context.in.read(context.content_length) || '') end end end |
.parse_query_string(query_string) ⇒ Object
Returns a hash with the pairs from the query string. The implicit hash construction that is done in parse_request_params is not done here.
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
# File 'lib/nitro/cgi.rb', line 96 def self.parse_query_string(query_string) params = Dictionary.new # gmosx, THINK: better return nil here? return params if (query_string.nil? or query_string.empty?) query_string.split(/[&;]/).each do |p| key, val = p.split('=') key = CGI.unescape(key) unless key.nil? val = CGI.unescape(val) unless val.nil? params = self.structure_param(params, key, val) end return params end |
.process(server, cgi, inp, out) ⇒ Object
Process a CGI request. This is a general method reused by many adapters. – A CGI request is process-based so there is no need for Og connection cleanup. ++
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 |
# File 'lib/nitro/cgi.rb', line 31 def self.process(server, cgi, inp, out) context = Context.new(server) unless inp.respond_to?(:rewind) # The module Request#raw_body requires a rewind method, # so if the input stream doesn't have one, *cough* FCgi, # we convert it to a StringIO. inp = StringIO.new(inp.read.to_s) # if read returns nil, to_s makes it "" end context.in = inp context.headers = cgi.env #-- # gmosx: only handle nitro requests. #++ # gmosx: QUERY_STRING is sometimes not populated. if context.query_string.empty? and context.uri =~ /\?/ context.headers['QUERY_STRING'] = context.uri.split('?').last end Cgi.parse_params(context) Cgi.(context) context.render(context.path) out.print(Cgi.response_headers(context)) if context.out.is_a?(IO) begin while buf = context.out.read(4096) out.write(buf) end ensure context.out.close end else out.print(context.out) end $autoreload_dirty = false context.close end |
.response_headers(context, proto = false) ⇒ Object
Build the response headers for the context.
context
-
The context of the response.
proto
-
If true emmit the protocol line. Useful for MOD_RUBY.
– FIXME: return the correct protocol from env. TODO: Perhaps I can optimize status calc. ++
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
# File 'lib/nitro/cgi.rb', line 156 def self.response_headers(context, proto = false) reason = STATUS_STRINGS[context.status] if proto buf = "HTTP/1.1 #{context.status} #{reason}#{EOL}Date: #{CGI::rfc1123_date(Time.now)}#{EOL}" else buf = "Status: #{context.status} #{reason}#{EOL}" end context.response_headers.each do |key, value| tmp = key.gsub(/\bwww|^te$|\b\w/) { |s| s.upcase } buf << "#{tmp}: #{value}" << EOL end context..each do || buf << "Set-Cookie: " << .to_s << EOL end if context. buf << EOL return buf end |
.structure_param(params, key, val) ⇒ Object
push a parameter into the params hash
79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/nitro/cgi.rb', line 79 def self.structure_param(params, key, val) if key =~ /(.+)\[(.+)\]$/ or key =~ /([^\.]+)\.(.+)$/ params[$1] ||= Dictionary.new params[$1] = structure_param(params[$1], $2, val) elsif key =~ /(.+)\[\]$/ params[$1] ||= Array.new params[$1] << val.to_s else params[key] = val.nil? ? nil : val end return params end |