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)
28 ).map { |x| x.freeze }.freeze # frozen strings are faster for Hash lookups
30 # Intializes the app, example of usage in a config.ru
32 # run Unicorn::App::ExecCgi.new("/path/to/cgit.cgi")
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"
45 out, err = Unicorn::Util.tmpio, Unicorn::Util.tmpio
46 inp = force_file_input(env)
47 pid = fork { run_child(inp, out, err, env) }
49 pid, status = Process.waitpid2(pid)
50 write_errors(env, err, status) if err.stat.size > 0
53 return parse_output!(out) if status.success?
55 [ 500, { 'Content-Length' => '0', 'Content-Type' => 'text/plain' }, [] ]
60 def run_child(inp, out, err, env)
61 PASS_VARS.each do |key|
62 val = env[key] or next
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)
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)
81 head = out.sysread(CHUNK_SIZE)
83 head, body = head.split(/\n\n/, 2)
85 head, body = head.split(/\r\n\r\n/, 2)
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|
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
99 blk.call(sysread(CHUNK_SIZE))
108 headers = Rack::Utils::HeaderHash.new
109 head.split(/\r?\n/).each do |line|
111 when /^([A-Za-z0-9-]+):\s*(.*)$/ then headers[prev = $1] = $2
112 when /^[ \t]/ then headers[prev] << "\n#{line}" if prev
115 headers['Content-Length'] = size.to_s
116 [ 200, headers, out ]
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')
125 tmp = Unicorn::Util.tmpio
128 while inp.read(CHUNK_SIZE, buf)
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)
140 dst = env['rack.errors']
142 dst.write("#{pid}: #{args.inspect} status=#{status} stderr:\n")
143 err.each_line { |line| dst.write("#{pid}: #{line}") }