support for Rack hijack in request and response
[unicorn.git] / lib / unicorn / http_response.rb
blob083951c2229aebe54b46ed374cbf781a10285179
1 # -*- encoding: binary -*-
2 # :enddoc:
3 # Writes a Rack response to your client using the HTTP/1.1 specification.
4 # You use it by simply doing:
6 #   status, headers, body = rack_app.call(env)
7 #   http_response_write(socket, status, headers, body)
9 # Most header correctness (including Content-Length and Content-Type)
10 # is the job of Rack, with the exception of the "Date" and "Status" header.
11 module Unicorn::HttpResponse
13   # Every standard HTTP code mapped to the appropriate message.
14   CODES = Rack::Utils::HTTP_STATUS_CODES.inject({}) { |hash,(code,msg)|
15     hash[code] = "#{code} #{msg}"
16     hash
17   }
18   CRLF = "\r\n"
20   def err_response(code, response_start_sent)
21     "#{response_start_sent ? '' : 'HTTP/1.1 '}#{CODES[code]}\r\n\r\n"
22   end
24   # writes the rack_response to socket as an HTTP response
25   def http_response_write(socket, status, headers, body,
26                           response_start_sent=false)
27     status = CODES[status.to_i] || status
28     hijack = nil
30     http_response_start = response_start_sent ? '' : 'HTTP/1.1 '
31     if headers
32       buf = "#{http_response_start}#{status}\r\n" \
33             "Date: #{httpdate}\r\n" \
34             "Status: #{status}\r\n" \
35             "Connection: close\r\n"
36       headers.each do |key, value|
37         case key
38         when %r{\A(?:Date\z|Connection\z)}i
39           next
40         when "rack.hijack"
41           # this was an illegal key in Rack < 1.5, so it should be
42           # OK to silently discard it for those older versions
43           hijack = hijack_prepare(value)
44         else
45           if value =~ /\n/
46             # avoiding blank, key-only cookies with /\n+/
47             buf << value.split(/\n+/).map! { |v| "#{key}: #{v}\r\n" }.join
48           else
49             buf << "#{key}: #{value}\r\n"
50           end
51         end
52       end
53       socket.write(buf << CRLF)
54     end
56     if hijack
57       body = nil # ensure we do not close body
58       hijack.call(socket)
59     else
60       body.each { |chunk| socket.write(chunk) }
61     end
62   ensure
63     body.respond_to?(:close) and body.close
64   end
66   # Rack 1.5.0 (protocol version 1.2) adds response hijacking support
67   if ((Rack::VERSION[0] << 8) | Rack::VERSION[1]) >= 0x0102
68     def hijack_prepare(value)
69       value
70     end
71   else
72     def hijack_prepare(_)
73     end
74   end
75 end