tee_input: update documentation for Rack 1.2
[unicorn.git] / lib / unicorn / cgi_wrapper.rb
blobb6eeb338343edb531c29f3dc2cc7bd17980580e9
1 # -*- encoding: binary -*-
3 # This code is based on the original CGIWrapper from Mongrel
4 # Copyright (c) 2005 Zed A. Shaw
5 # Copyright (c) 2009 Eric Wong
6 # You can redistribute it and/or modify it under the same terms as Ruby.
8 # Additional work donated by contributors.  See CONTRIBUTORS for more info.
10 require 'cgi'
12 module Unicorn; end
14 # The beginning of a complete wrapper around Unicorn's internal HTTP
15 # processing system but maintaining the original Ruby CGI module.  Use
16 # this only as a crutch to get existing CGI based systems working.  It
17 # should handle everything, but please notify us if you see special
18 # warnings.  This work is still very alpha so we need testers to help
19 # work out the various corner cases.
20 class Unicorn::CGIWrapper < ::CGI
21   undef_method :env_table
22   attr_reader :env_table
23   attr_reader :body
25   # these are stripped out of any keys passed to CGIWrapper.header function
26   NPH = 'nph'.freeze # Completely ignored, Unicorn outputs the date regardless
27   CONNECTION = 'connection'.freeze # Completely ignored. Why is CGI doing this?
28   CHARSET = 'charset'.freeze # this gets appended to Content-Type
29   COOKIE = 'cookie'.freeze # maps (Hash,Array,String) to "Set-Cookie" headers
30   STATUS = 'status'.freeze # stored as @status
31   Status = 'Status'.freeze # code + human-readable text, Rails sets this
33   # some of these are common strings, but this is the only module
34   # using them and the reason they're not in Unicorn::Const
35   SET_COOKIE = 'Set-Cookie'.freeze
36   CONTENT_TYPE = 'Content-Type'.freeze
37   CONTENT_LENGTH = 'Content-Length'.freeze # this is NOT Const::CONTENT_LENGTH
38   RACK_INPUT = 'rack.input'.freeze
39   RACK_ERRORS = 'rack.errors'.freeze
41   # this maps CGI header names to HTTP header names
42   HEADER_MAP = {
43     'status' => Status,
44     'type' => CONTENT_TYPE,
45     'server' => 'Server'.freeze,
46     'language' => 'Content-Language'.freeze,
47     'expires' => 'Expires'.freeze,
48     'length' => CONTENT_LENGTH,
49   }
51   # Takes an a Rackable environment, plus any additional CGI.new
52   # arguments These are used internally to create a wrapper around the
53   # real CGI while maintaining Rack/Unicorn's view of the world.  This
54   # this will NOT deal well with large responses that take up a lot of
55   # memory, but neither does the CGI nor the original CGIWrapper from
56   # Mongrel...
57   def initialize(rack_env, *args)
58     @env_table = rack_env
59     @status = nil
60     @head = {}
61     @headv = Hash.new { |hash,key| hash[key] = [] }
62     @body = StringIO.new("")
63     super(*args)
64   end
66   # finalizes the response in a way Rack applications would expect
67   def rack_response
68     # @head[CONTENT_LENGTH] ||= @body.size
69     @headv[SET_COOKIE].concat(@output_cookies) if @output_cookies
70     @headv.each_pair do |key,value|
71       @head[key] ||= value.join("\n") unless value.empty?
72     end
74     # Capitalized "Status:", with human-readable status code (e.g. "200 OK")
75     @status ||= @head.delete(Status)
77     [ @status || 500, @head, [ @body.string ] ]
78   end
80   # The header is typically called to send back the header.  In our case we
81   # collect it into a hash for later usage.  This can be called multiple
82   # times to set different cookies.
83   def header(options = "text/html")
84     # if they pass in a string then just write the Content-Type
85     if String === options
86       @head[CONTENT_TYPE] ||= options
87     else
88       HEADER_MAP.each_pair do |from, to|
89         from = options.delete(from) or next
90         @head[to] = from.to_s
91       end
93       @head[CONTENT_TYPE] ||= "text/html"
94       if charset = options.delete(CHARSET)
95         @head[CONTENT_TYPE] << "; charset=#{charset}"
96       end
98       # lots of ways to set cookies
99       if cookie = options.delete(COOKIE)
100         set_cookies = @headv[SET_COOKIE]
101         case cookie
102         when Array
103           cookie.each { |c| set_cookies << c.to_s }
104         when Hash
105           cookie.each_value { |c| set_cookies << c.to_s }
106         else
107           set_cookies << cookie.to_s
108         end
109       end
110       @status ||= options.delete(STATUS) # all lower-case
112       # drop the keys we don't want anymore
113       options.delete(NPH)
114       options.delete(CONNECTION)
116       # finally, set the rest of the headers as-is, allowing duplicates
117       options.each_pair { |k,v| @headv[k] << v }
118     end
120     # doing this fakes out the cgi library to think the headers are empty
121     # we then do the real headers in the out function call later
122     ""
123   end
125   # The dumb thing is people can call header or this or both and in
126   # any order.  So, we just reuse header and then finalize the
127   # HttpResponse the right way.  This will have no effect if called
128   # the second time if the first "outputted" anything.
129   def out(options = "text/html")
130     header(options)
131     @body.size == 0 or return
132     @body << yield if block_given?
133   end
135   # Used to wrap the normal stdinput variable used inside CGI.
136   def stdinput
137     @env_table[RACK_INPUT]
138   end
140   # return a pointer to the StringIO body since it's STDOUT-like
141   def stdoutput
142     @body
143   end