1 # -*- encoding: binary -*-
7 # This class is highly experimental (even more so than the rest of Unicorn)
8 # and has never run anything other than cgit.
9 class ExecCgi < Struct.new(:args)
29 ).map { |x| x.freeze } # frozen strings are faster for Hash assignments
31 # Intializes the app, example of usage in a config.ru
33 # run Unicorn::App::ExecCgi.new("/path/to/cgit.cgi")
38 raise ArgumentError, "need path to executable"
39 first[0] == ?/ or args[0] = ::File.expand_path(first)
40 File.executable?(args[0]) or
41 raise ArgumentError, "#{args[0]} is not executable"
46 out, err = Unicorn::Util.tmpio, Unicorn::Util.tmpio
47 inp = force_file_input(env)
48 pid = fork { run_child(inp, out, err, env) }
50 pid, status = Process.waitpid2(pid)
51 write_errors(env, err, status) if err.stat.size > 0
54 return parse_output!(out) if status.success?
56 [ 500, { 'Content-Length' => '0', 'Content-Type' => 'text/plain' }, [] ]
61 def run_child(inp, out, err, env)
62 PASS_VARS.each do |key|
63 val = env[key] or next
66 ENV['SCRIPT_NAME'] = args[0]
67 ENV['GATEWAY_INTERFACE'] = 'CGI/1.1'
68 env.keys.grep(/^HTTP_/) { |key| ENV[key] = env[key] }
70 a = IO.new(0).reopen(inp)
71 b = IO.new(1).reopen(out)
72 c = IO.new(2).reopen(err)
76 # Extracts headers from CGI out, will change the offset of out.
77 # This returns a standard Rack-compatible return value:
78 # [ 200, HeadersHash, body ]
79 def parse_output!(out)
82 head = out.sysread(CHUNK_SIZE)
84 head, body = head.split(/\n\n/, 2)
86 head, body = head.split(/\r\n\r\n/, 2)
91 # Allows +out+ to be used as a Rack body.
92 out.instance_eval { class << self; self; end }.instance_eval {
93 define_method(:each) { |&blk|
96 # don't use a preallocated buffer for sysread since we can't
97 # guarantee an actual socket is consuming the yielded string
98 # (or if somebody is pushing to an array for eventual concatenation
100 blk.call(sysread(CHUNK_SIZE))
109 headers = Rack::Utils::HeaderHash.new
110 head.split(/\r?\n/).each do |line|
112 when /^([A-Za-z0-9-]+):\s*(.*)$/ then headers[prev = $1] = $2
113 when /^[ \t]/ then headers[prev] << "\n#{line}" if prev
116 headers['Content-Length'] = size.to_s
117 [ 200, headers, out ]
120 # ensures rack.input is a file handle that we can redirect stdin to
121 def force_file_input(env)
122 inp = env['rack.input']
123 # inp could be a StringIO or StringIO-like object
124 if inp.respond_to?(:size) && inp.size == 0
125 ::File.open('/dev/null', 'rb')
127 tmp = Unicorn::Util.tmpio
129 buf = inp.read(CHUNK_SIZE)
132 end while inp.read(CHUNK_SIZE, buf)
138 # rack.errors this may not be an IO object, so we couldn't
139 # just redirect the CGI executable to that earlier.
140 def write_errors(env, err, status)
142 dst = env['rack.errors']
144 dst.write("#{pid}: #{args.inspect} status=#{status} stderr:\n")
145 err.each_line { |line| dst.write("#{pid}: #{line}") }