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