Merged updates from trunk into stable branch
[feedcatcher.git] / vendor / rails / actionpack / lib / action_controller / vendor / rack-1.0 / rack / handler / fastcgi.rb
1 require 'fcgi'
2 require 'socket'
3 require 'rack/content_length'
4
5 module Rack
6 module Handler
7 class FastCGI
8 def self.run(app, options={})
9 file = options[:File] and STDIN.reopen(UNIXServer.new(file))
10 port = options[:Port] and STDIN.reopen(TCPServer.new(port))
11 FCGI.each { |request|
12 serve request, app
13 }
14 end
15
16 module ProperStream # :nodoc:
17 def each # This is missing by default.
18 while line = gets
19 yield line
20 end
21 end
22
23 def read(*args)
24 if args.empty?
25 super || "" # Empty string on EOF.
26 else
27 super
28 end
29 end
30 end
31
32 def self.serve(request, app)
33 app = Rack::ContentLength.new(app)
34
35 env = request.env
36 env.delete "HTTP_CONTENT_LENGTH"
37
38 request.in.extend ProperStream
39
40 env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
41
42 env.update({"rack.version" => [0,1],
43 "rack.input" => request.in,
44 "rack.errors" => request.err,
45
46 "rack.multithread" => false,
47 "rack.multiprocess" => true,
48 "rack.run_once" => false,
49
50 "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
51 })
52
53 env["QUERY_STRING"] ||= ""
54 env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
55 env["REQUEST_PATH"] ||= "/"
56 env.delete "PATH_INFO" if env["PATH_INFO"] == ""
57 env.delete "CONTENT_TYPE" if env["CONTENT_TYPE"] == ""
58 env.delete "CONTENT_LENGTH" if env["CONTENT_LENGTH"] == ""
59
60 status, headers, body = app.call(env)
61 begin
62 send_headers request.out, status, headers
63 send_body request.out, body
64 ensure
65 body.close if body.respond_to? :close
66 request.finish
67 end
68 end
69
70 def self.send_headers(out, status, headers)
71 out.print "Status: #{status}\r\n"
72 headers.each { |k, vs|
73 vs.split("\n").each { |v|
74 out.print "#{k}: #{v}\r\n"
75 }
76 }
77 out.print "\r\n"
78 out.flush
79 end
80
81 def self.send_body(out, body)
82 body.each { |part|
83 out.print part
84 out.flush
85 }
86 end
87 end
88 end
89 end