app/exec_cgi: fix 1.9 compatibility
[unicorn.git] / lib / unicorn / app / exec_cgi.rb
blobd0b31f8753e2615a1f8a697eea94e09310c828f6
1 require 'unicorn'
2 require 'rack'
4 module Unicorn::App
6   # This class is highly experimental (even more so than the rest of Unicorn)
7   # and has never run anything other than cgit.
8   class ExecCgi < Struct.new(:args)
10     CHUNK_SIZE = 16384
11     PASS_VARS = %w(
12       CONTENT_LENGTH
13       CONTENT_TYPE
14       GATEWAY_INTERFACE
15       AUTH_TYPE
16       PATH_INFO
17       PATH_TRANSLATED
18       QUERY_STRING
19       REMOTE_ADDR
20       REMOTE_HOST
21       REMOTE_IDENT
22       REMOTE_USER
23       REQUEST_METHOD
24       SERVER_NAME
25       SERVER_PORT
26       SERVER_PROTOCOL
27       SERVER_SOFTWARE
28     ).map { |x| x.freeze }.freeze # frozen strings are faster for Hash lookups
30     # Intializes the app, example of usage in a config.ru
31     #   map "/cgit" do
32     #     run Unicorn::App::ExecCgi.new("/path/to/cgit.cgi")
33     #   end
34     def initialize(*args)
35       self.args = args
36       first = args[0] or
37         raise ArgumentError, "need path to executable"
38       first[0..0] == "/" or args[0] = ::File.expand_path(first)
39       File.executable?(args[0]) or
40         raise ArgumentError, "#{args[0]} is not executable"
41     end
43     # Calls the app
44     def call(env)
45       out, err = Unicorn::Util.tmpio, Unicorn::Util.tmpio
46       inp = force_file_input(env)
47       pid = fork { run_child(inp, out, err, env) }
48       inp.close
49       pid, status = Process.waitpid2(pid)
50       write_errors(env, err, status) if err.stat.size > 0
51       err.close
53       return parse_output!(out) if status.success?
54       out.close
55       [ 500, { 'Content-Length' => '0', 'Content-Type' => 'text/plain' }, [] ]
56     end
58     private
60     def run_child(inp, out, err, env)
61       PASS_VARS.each do |key|
62         val = env[key] or next
63         ENV[key] = val
64       end
65       ENV['SCRIPT_NAME'] = args[0]
66       ENV['GATEWAY_INTERFACE'] = 'CGI/1.1'
67       env.keys.grep(/^HTTP_/) { |key| ENV[key] = env[key] }
69       a = IO.new(0).reopen(inp)
70       b = IO.new(1).reopen(out)
71       c = IO.new(2).reopen(err)
72       exec(*args)
73     end
75     # Extracts headers from CGI out, will change the offset of out.
76     # This returns a standard Rack-compatible return value:
77     #   [ 200, HeadersHash, body ]
78     def parse_output!(out)
79       size = out.stat.size
80       out.sysseek(0)
81       head = out.sysread(CHUNK_SIZE)
82       offset = 2
83       head, body = head.split(/\n\n/, 2)
84       if body.nil?
85         head, body = head.split(/\r\n\r\n/, 2)
86         offset = 4
87       end
88       offset += head.length
90       # Allows +out+ to be used as a Rack body.
91       out.instance_eval { class << self; self; end }.instance_eval {
92         define_method(:each) { |&blk|
93           sysseek(offset)
95           # don't use a preallocated buffer for sysread since we can't
96           # guarantee an actual socket is consuming the yielded string
97           # (or if somebody is pushing to an array for eventual concatenation
98           begin
99             blk.call(sysread(CHUNK_SIZE))
100           rescue EOFError
101             break
102           end while true
103         }
104       }
106       size -= offset
107       prev = nil
108       headers = Rack::Utils::HeaderHash.new
109       head.split(/\r?\n/).each do |line|
110         case line
111         when /^([A-Za-z0-9-]+):\s*(.*)$/ then headers[prev = $1] = $2
112         when /^[ \t]/ then headers[prev] << "\n#{line}" if prev
113         end
114       end
115       headers['Content-Length'] = size.to_s
116       [ 200, headers, out ]
117     end
119     # ensures rack.input is a file handle that we can redirect stdin to
120     def force_file_input(env)
121       inp = env['rack.input']
122       if inp.size == 0 # inp could be a StringIO or StringIO-like object
123         ::File.open('/dev/null', 'rb')
124       else
125         tmp = Unicorn::Util.tmpio
127         buf = Unicorn::Z.dup
128         while inp.read(CHUNK_SIZE, buf)
129           tmp.syswrite(buf)
130         end
131         tmp.sysseek(0)
132         tmp
133       end
134     end
136     # rack.errors this may not be an IO object, so we couldn't
137     # just redirect the CGI executable to that earlier.
138     def write_errors(env, err, status)
139       err.seek(0)
140       dst = env['rack.errors']
141       pid = status.pid
142       dst.write("#{pid}: #{args.inspect} status=#{status} stderr:\n")
143       err.each_line { |line| dst.write("#{pid}: #{line}") }
144       dst.flush
145     end
147   end