eac-rack 1.1.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (111) hide show
  1. data/COPYING +18 -0
  2. data/KNOWN-ISSUES +21 -0
  3. data/README +399 -0
  4. data/bin/rackup +4 -0
  5. data/contrib/rack_logo.svg +111 -0
  6. data/example/lobster.ru +4 -0
  7. data/example/protectedlobster.rb +14 -0
  8. data/example/protectedlobster.ru +8 -0
  9. data/lib/rack.rb +92 -0
  10. data/lib/rack/adapter/camping.rb +22 -0
  11. data/lib/rack/auth/abstract/handler.rb +37 -0
  12. data/lib/rack/auth/abstract/request.rb +37 -0
  13. data/lib/rack/auth/basic.rb +58 -0
  14. data/lib/rack/auth/digest/md5.rb +124 -0
  15. data/lib/rack/auth/digest/nonce.rb +51 -0
  16. data/lib/rack/auth/digest/params.rb +55 -0
  17. data/lib/rack/auth/digest/request.rb +40 -0
  18. data/lib/rack/builder.rb +80 -0
  19. data/lib/rack/cascade.rb +41 -0
  20. data/lib/rack/chunked.rb +49 -0
  21. data/lib/rack/commonlogger.rb +49 -0
  22. data/lib/rack/conditionalget.rb +47 -0
  23. data/lib/rack/config.rb +15 -0
  24. data/lib/rack/content_length.rb +29 -0
  25. data/lib/rack/content_type.rb +23 -0
  26. data/lib/rack/deflater.rb +96 -0
  27. data/lib/rack/directory.rb +157 -0
  28. data/lib/rack/etag.rb +23 -0
  29. data/lib/rack/file.rb +90 -0
  30. data/lib/rack/handler.rb +88 -0
  31. data/lib/rack/handler/cgi.rb +61 -0
  32. data/lib/rack/handler/evented_mongrel.rb +8 -0
  33. data/lib/rack/handler/fastcgi.rb +89 -0
  34. data/lib/rack/handler/lsws.rb +63 -0
  35. data/lib/rack/handler/mongrel.rb +90 -0
  36. data/lib/rack/handler/scgi.rb +62 -0
  37. data/lib/rack/handler/swiftiplied_mongrel.rb +8 -0
  38. data/lib/rack/handler/thin.rb +18 -0
  39. data/lib/rack/handler/webrick.rb +69 -0
  40. data/lib/rack/head.rb +19 -0
  41. data/lib/rack/lint.rb +575 -0
  42. data/lib/rack/lobster.rb +65 -0
  43. data/lib/rack/lock.rb +16 -0
  44. data/lib/rack/logger.rb +20 -0
  45. data/lib/rack/methodoverride.rb +27 -0
  46. data/lib/rack/mime.rb +206 -0
  47. data/lib/rack/mock.rb +189 -0
  48. data/lib/rack/nulllogger.rb +18 -0
  49. data/lib/rack/recursive.rb +57 -0
  50. data/lib/rack/reloader.rb +109 -0
  51. data/lib/rack/request.rb +271 -0
  52. data/lib/rack/response.rb +149 -0
  53. data/lib/rack/rewindable_input.rb +100 -0
  54. data/lib/rack/runtime.rb +27 -0
  55. data/lib/rack/sendfile.rb +142 -0
  56. data/lib/rack/server.rb +212 -0
  57. data/lib/rack/session/abstract/id.rb +140 -0
  58. data/lib/rack/session/cookie.rb +90 -0
  59. data/lib/rack/session/memcache.rb +119 -0
  60. data/lib/rack/session/pool.rb +100 -0
  61. data/lib/rack/showexceptions.rb +349 -0
  62. data/lib/rack/showstatus.rb +106 -0
  63. data/lib/rack/static.rb +38 -0
  64. data/lib/rack/urlmap.rb +56 -0
  65. data/lib/rack/utils.rb +614 -0
  66. data/rack.gemspec +38 -0
  67. data/test/spec_rack_auth_basic.rb +73 -0
  68. data/test/spec_rack_auth_digest.rb +226 -0
  69. data/test/spec_rack_builder.rb +84 -0
  70. data/test/spec_rack_camping.rb +51 -0
  71. data/test/spec_rack_cascade.rb +48 -0
  72. data/test/spec_rack_cgi.rb +89 -0
  73. data/test/spec_rack_chunked.rb +62 -0
  74. data/test/spec_rack_commonlogger.rb +61 -0
  75. data/test/spec_rack_conditionalget.rb +41 -0
  76. data/test/spec_rack_config.rb +24 -0
  77. data/test/spec_rack_content_length.rb +43 -0
  78. data/test/spec_rack_content_type.rb +30 -0
  79. data/test/spec_rack_deflater.rb +127 -0
  80. data/test/spec_rack_directory.rb +61 -0
  81. data/test/spec_rack_etag.rb +17 -0
  82. data/test/spec_rack_fastcgi.rb +89 -0
  83. data/test/spec_rack_file.rb +75 -0
  84. data/test/spec_rack_handler.rb +43 -0
  85. data/test/spec_rack_head.rb +30 -0
  86. data/test/spec_rack_lint.rb +528 -0
  87. data/test/spec_rack_lobster.rb +45 -0
  88. data/test/spec_rack_lock.rb +38 -0
  89. data/test/spec_rack_logger.rb +21 -0
  90. data/test/spec_rack_methodoverride.rb +60 -0
  91. data/test/spec_rack_mock.rb +243 -0
  92. data/test/spec_rack_mongrel.rb +189 -0
  93. data/test/spec_rack_nulllogger.rb +13 -0
  94. data/test/spec_rack_recursive.rb +77 -0
  95. data/test/spec_rack_request.rb +545 -0
  96. data/test/spec_rack_response.rb +221 -0
  97. data/test/spec_rack_rewindable_input.rb +118 -0
  98. data/test/spec_rack_runtime.rb +35 -0
  99. data/test/spec_rack_sendfile.rb +86 -0
  100. data/test/spec_rack_session_cookie.rb +73 -0
  101. data/test/spec_rack_session_memcache.rb +273 -0
  102. data/test/spec_rack_session_pool.rb +172 -0
  103. data/test/spec_rack_showexceptions.rb +21 -0
  104. data/test/spec_rack_showstatus.rb +72 -0
  105. data/test/spec_rack_static.rb +37 -0
  106. data/test/spec_rack_thin.rb +91 -0
  107. data/test/spec_rack_urlmap.rb +215 -0
  108. data/test/spec_rack_utils.rb +554 -0
  109. data/test/spec_rack_webrick.rb +130 -0
  110. data/test/spec_rackup.rb +154 -0
  111. metadata +311 -0
@@ -0,0 +1,63 @@
1
+ require 'lsapi'
2
+ require 'rack/content_length'
3
+ require 'rack/rewindable_input'
4
+
5
+ module Rack
6
+ module Handler
7
+ class LSWS
8
+ def self.run(app, options=nil)
9
+ while LSAPI.accept != nil
10
+ serve app
11
+ end
12
+ end
13
+ def self.serve(app)
14
+ app = Rack::ContentLength.new(app)
15
+
16
+ env = ENV.to_hash
17
+ env.delete "HTTP_CONTENT_LENGTH"
18
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
19
+
20
+ rack_input = RewindableInput.new($stdin.read.to_s)
21
+
22
+ env.update(
23
+ "rack.version" => [1,1],
24
+ "rack.input" => rack_input,
25
+ "rack.errors" => $stderr,
26
+ "rack.multithread" => false,
27
+ "rack.multiprocess" => true,
28
+ "rack.run_once" => false,
29
+ "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
30
+ )
31
+
32
+ env["QUERY_STRING"] ||= ""
33
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
34
+ env["REQUEST_PATH"] ||= "/"
35
+ status, headers, body = app.call(env)
36
+ begin
37
+ send_headers status, headers
38
+ send_body body
39
+ ensure
40
+ body.close if body.respond_to? :close
41
+ end
42
+ ensure
43
+ rack_input.close
44
+ end
45
+ def self.send_headers(status, headers)
46
+ print "Status: #{status}\r\n"
47
+ headers.each { |k, vs|
48
+ vs.split("\n").each { |v|
49
+ print "#{k}: #{v}\r\n"
50
+ }
51
+ }
52
+ print "\r\n"
53
+ STDOUT.flush
54
+ end
55
+ def self.send_body(body)
56
+ body.each { |part|
57
+ print part
58
+ STDOUT.flush
59
+ }
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,90 @@
1
+ require 'mongrel'
2
+ require 'stringio'
3
+ require 'rack/content_length'
4
+ require 'rack/chunked'
5
+
6
+ module Rack
7
+ module Handler
8
+ class Mongrel < ::Mongrel::HttpHandler
9
+ def self.run(app, options={})
10
+ server = ::Mongrel::HttpServer.new(
11
+ options[:Host] || '0.0.0.0',
12
+ options[:Port] || 8080,
13
+ options[:num_processors] || 950,
14
+ options[:throttle] || 0,
15
+ options[:timeout] || 60)
16
+ # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods.
17
+ # Use is similar to #run, replacing the app argument with a hash of
18
+ # { path=>app, ... } or an instance of Rack::URLMap.
19
+ if options[:map]
20
+ if app.is_a? Hash
21
+ app.each do |path, appl|
22
+ path = '/'+path unless path[0] == ?/
23
+ server.register(path, Rack::Handler::Mongrel.new(appl))
24
+ end
25
+ elsif app.is_a? URLMap
26
+ app.instance_variable_get(:@mapping).each do |(host, path, appl)|
27
+ next if !host.nil? && !options[:Host].nil? && options[:Host] != host
28
+ path = '/'+path unless path[0] == ?/
29
+ server.register(path, Rack::Handler::Mongrel.new(appl))
30
+ end
31
+ else
32
+ raise ArgumentError, "first argument should be a Hash or URLMap"
33
+ end
34
+ else
35
+ server.register('/', Rack::Handler::Mongrel.new(app))
36
+ end
37
+ yield server if block_given?
38
+ server.run.join
39
+ end
40
+
41
+ def initialize(app)
42
+ @app = Rack::Chunked.new(Rack::ContentLength.new(app))
43
+ end
44
+
45
+ def process(request, response)
46
+ env = {}.replace(request.params)
47
+ env.delete "HTTP_CONTENT_TYPE"
48
+ env.delete "HTTP_CONTENT_LENGTH"
49
+
50
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
51
+
52
+ rack_input = request.body || StringIO.new('')
53
+ rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding)
54
+
55
+ env.update({"rack.version" => [1,1],
56
+ "rack.input" => rack_input,
57
+ "rack.errors" => $stderr,
58
+
59
+ "rack.multithread" => true,
60
+ "rack.multiprocess" => false, # ???
61
+ "rack.run_once" => false,
62
+
63
+ "rack.url_scheme" => "http",
64
+ })
65
+ env["QUERY_STRING"] ||= ""
66
+
67
+ status, headers, body = @app.call(env)
68
+
69
+ begin
70
+ response.status = status.to_i
71
+ response.send_status(nil)
72
+
73
+ headers.each { |k, vs|
74
+ vs.split("\n").each { |v|
75
+ response.header[k] = v
76
+ }
77
+ }
78
+ response.send_header
79
+
80
+ body.each { |part|
81
+ response.write part
82
+ response.socket.flush
83
+ }
84
+ ensure
85
+ body.close if body.respond_to? :close
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,62 @@
1
+ require 'scgi'
2
+ require 'stringio'
3
+ require 'rack/content_length'
4
+ require 'rack/chunked'
5
+
6
+ module Rack
7
+ module Handler
8
+ class SCGI < ::SCGI::Processor
9
+ attr_accessor :app
10
+
11
+ def self.run(app, options=nil)
12
+ new(options.merge(:app=>app,
13
+ :host=>options[:Host],
14
+ :port=>options[:Port],
15
+ :socket=>options[:Socket])).listen
16
+ end
17
+
18
+ def initialize(settings = {})
19
+ @app = Rack::Chunked.new(Rack::ContentLength.new(settings[:app]))
20
+ @log = Object.new
21
+ def @log.info(*args); end
22
+ def @log.error(*args); end
23
+ super(settings)
24
+ end
25
+
26
+ def process_request(request, input_body, socket)
27
+ env = {}.replace(request)
28
+ env.delete "HTTP_CONTENT_TYPE"
29
+ env.delete "HTTP_CONTENT_LENGTH"
30
+ env["REQUEST_PATH"], env["QUERY_STRING"] = env["REQUEST_URI"].split('?', 2)
31
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
32
+ env["PATH_INFO"] = env["REQUEST_PATH"]
33
+ env["QUERY_STRING"] ||= ""
34
+ env["SCRIPT_NAME"] = ""
35
+
36
+ rack_input = StringIO.new(input_body)
37
+ rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding)
38
+
39
+ env.update({"rack.version" => [1,1],
40
+ "rack.input" => rack_input,
41
+ "rack.errors" => $stderr,
42
+ "rack.multithread" => true,
43
+ "rack.multiprocess" => true,
44
+ "rack.run_once" => false,
45
+
46
+ "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
47
+ })
48
+ status, headers, body = app.call(env)
49
+ begin
50
+ socket.write("Status: #{status}\r\n")
51
+ headers.each do |k, vs|
52
+ vs.split("\n").each { |v| socket.write("#{k}: #{v}\r\n")}
53
+ end
54
+ socket.write("\r\n")
55
+ body.each {|s| socket.write(s)}
56
+ ensure
57
+ body.close if body.respond_to? :close
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,8 @@
1
+ require 'swiftcore/swiftiplied_mongrel'
2
+
3
+ module Rack
4
+ module Handler
5
+ class SwiftipliedMongrel < Handler::Mongrel
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,18 @@
1
+ require "thin"
2
+ require "rack/content_length"
3
+ require "rack/chunked"
4
+
5
+ module Rack
6
+ module Handler
7
+ class Thin
8
+ def self.run(app, options={})
9
+ app = Rack::Chunked.new(Rack::ContentLength.new(app))
10
+ server = ::Thin::Server.new(options[:Host] || '0.0.0.0',
11
+ options[:Port] || 8080,
12
+ app)
13
+ yield server if block_given?
14
+ server.start
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,69 @@
1
+ require 'webrick'
2
+ require 'stringio'
3
+ require 'rack/content_length'
4
+
5
+ module Rack
6
+ module Handler
7
+ class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet
8
+ def self.run(app, options={})
9
+ options[:BindAddress] = options.delete(:Host) if options[:Host]
10
+ server = ::WEBrick::HTTPServer.new(options)
11
+ server.mount "/", Rack::Handler::WEBrick, app
12
+ trap(:INT) { server.shutdown }
13
+ yield server if block_given?
14
+ server.start
15
+ end
16
+
17
+ def initialize(server, app)
18
+ super server
19
+ @app = Rack::ContentLength.new(app)
20
+ end
21
+
22
+ def service(req, res)
23
+ env = req.meta_vars
24
+ env.delete_if { |k, v| v.nil? }
25
+
26
+ rack_input = StringIO.new(req.body.to_s)
27
+ rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding)
28
+
29
+ env.update({"rack.version" => [1,1],
30
+ "rack.input" => rack_input,
31
+ "rack.errors" => $stderr,
32
+
33
+ "rack.multithread" => true,
34
+ "rack.multiprocess" => false,
35
+ "rack.run_once" => false,
36
+
37
+ "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
38
+ })
39
+
40
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
41
+ env["QUERY_STRING"] ||= ""
42
+ env["REQUEST_PATH"] ||= "/"
43
+ unless env["PATH_INFO"] == ""
44
+ path, n = req.request_uri.path, env["SCRIPT_NAME"].length
45
+ env["PATH_INFO"] = path[n, path.length-n]
46
+ end
47
+
48
+ status, headers, body = @app.call(env)
49
+ begin
50
+ res.status = status.to_i
51
+ headers.each { |k, vs|
52
+ if k.downcase == "set-cookie"
53
+ res.cookies.concat vs.split("\n")
54
+ else
55
+ vs.split("\n").each { |v|
56
+ res[k] = v
57
+ }
58
+ end
59
+ }
60
+ body.each { |part|
61
+ res.body << part
62
+ }
63
+ ensure
64
+ body.close if body.respond_to? :close
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,19 @@
1
+ module Rack
2
+
3
+ class Head
4
+ def initialize(app)
5
+ @app = app
6
+ end
7
+
8
+ def call(env)
9
+ status, headers, body = @app.call(env)
10
+
11
+ if env["REQUEST_METHOD"] == "HEAD"
12
+ [status, headers, []]
13
+ else
14
+ [status, headers, body]
15
+ end
16
+ end
17
+ end
18
+
19
+ end
@@ -0,0 +1,575 @@
1
+ require 'rack/utils'
2
+
3
+ module Rack
4
+ # Rack::Lint validates your application and the requests and
5
+ # responses according to the Rack spec.
6
+
7
+ class Lint
8
+ def initialize(app)
9
+ @app = app
10
+ end
11
+
12
+ # :stopdoc:
13
+
14
+ class LintError < RuntimeError; end
15
+ module Assertion
16
+ def assert(message, &block)
17
+ unless block.call
18
+ raise LintError, message
19
+ end
20
+ end
21
+ end
22
+ include Assertion
23
+
24
+ ## This specification aims to formalize the Rack protocol. You
25
+ ## can (and should) use Rack::Lint to enforce it.
26
+ ##
27
+ ## When you develop middleware, be sure to add a Lint before and
28
+ ## after to catch all mistakes.
29
+
30
+ ## = Rack applications
31
+
32
+ ## A Rack application is an Ruby object (not a class) that
33
+ ## responds to +call+.
34
+ def call(env=nil)
35
+ dup._call(env)
36
+ end
37
+
38
+ def _call(env)
39
+ ## It takes exactly one argument, the *environment*
40
+ assert("No env given") { env }
41
+ check_env env
42
+
43
+ env['rack.input'] = InputWrapper.new(env['rack.input'])
44
+ env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
45
+
46
+ ## and returns an Array of exactly three values:
47
+ status, headers, @body = @app.call(env)
48
+ ## The *status*,
49
+ check_status status
50
+ ## the *headers*,
51
+ check_headers headers
52
+ ## and the *body*.
53
+ check_content_type status, headers
54
+ check_content_length status, headers, env
55
+ [status, headers, self]
56
+ end
57
+
58
+ ## == The Environment
59
+ def check_env(env)
60
+ ## The environment must be an true instance of Hash (no
61
+ ## subclassing allowed) that includes CGI-like headers.
62
+ ## The application is free to modify the environment.
63
+ assert("env #{env.inspect} is not a Hash, but #{env.class}") {
64
+ env.kind_of? Hash
65
+ }
66
+
67
+ ##
68
+ ## The environment is required to include these variables
69
+ ## (adopted from PEP333), except when they'd be empty, but see
70
+ ## below.
71
+
72
+ ## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
73
+ ## "GET" or "POST". This cannot ever
74
+ ## be an empty string, and so is
75
+ ## always required.
76
+
77
+ ## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
78
+ ## URL's "path" that corresponds to the
79
+ ## application object, so that the
80
+ ## application knows its virtual
81
+ ## "location". This may be an empty
82
+ ## string, if the application corresponds
83
+ ## to the "root" of the server.
84
+
85
+ ## <tt>PATH_INFO</tt>:: The remainder of the request URL's
86
+ ## "path", designating the virtual
87
+ ## "location" of the request's target
88
+ ## within the application. This may be an
89
+ ## empty string, if the request URL targets
90
+ ## the application root and does not have a
91
+ ## trailing slash. This value may be
92
+ ## percent-encoded when I originating from
93
+ ## a URL.
94
+
95
+ ## <tt>QUERY_STRING</tt>:: The portion of the request URL that
96
+ ## follows the <tt>?</tt>, if any. May be
97
+ ## empty, but is always required!
98
+
99
+ ## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>:: When combined with <tt>SCRIPT_NAME</tt> and <tt>PATH_INFO</tt>, these variables can be used to complete the URL. Note, however, that <tt>HTTP_HOST</tt>, if present, should be used in preference to <tt>SERVER_NAME</tt> for reconstructing the request URL. <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt> can never be empty strings, and so are always required.
100
+
101
+ ## <tt>HTTP_</tt> Variables:: Variables corresponding to the
102
+ ## client-supplied HTTP request
103
+ ## headers (i.e., variables whose
104
+ ## names begin with <tt>HTTP_</tt>). The
105
+ ## presence or absence of these
106
+ ## variables should correspond with
107
+ ## the presence or absence of the
108
+ ## appropriate HTTP header in the
109
+ ## request.
110
+
111
+ ## In addition to this, the Rack environment must include these
112
+ ## Rack-specific variables:
113
+
114
+ ## <tt>rack.version</tt>:: The Array [1,1], representing this version of Rack.
115
+ ## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the request URL.
116
+ ## <tt>rack.input</tt>:: See below, the input stream.
117
+ ## <tt>rack.errors</tt>:: See below, the error stream.
118
+ ## <tt>rack.multithread</tt>:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
119
+ ## <tt>rack.multiprocess</tt>:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
120
+ ## <tt>rack.run_once</tt>:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
121
+ ##
122
+
123
+ ## Additional environment specifications have approved to
124
+ ## standardized middleware APIs. None of these are required to
125
+ ## be implemented by the server.
126
+
127
+ ## <tt>rack.session</tt>:: A hash like interface for storing request session data.
128
+ ## The store must implement:
129
+ if session = env['rack.session']
130
+ ## store(key, value) (aliased as []=);
131
+ assert("session #{session.inspect} must respond to store and []=") {
132
+ session.respond_to?(:store) && session.respond_to?(:[]=)
133
+ }
134
+
135
+ ## fetch(key, default = nil) (aliased as []);
136
+ assert("session #{session.inspect} must respond to fetch and []") {
137
+ session.respond_to?(:fetch) && session.respond_to?(:[])
138
+ }
139
+
140
+ ## delete(key);
141
+ assert("session #{session.inspect} must respond to delete") {
142
+ session.respond_to?(:delete)
143
+ }
144
+
145
+ ## clear;
146
+ assert("session #{session.inspect} must respond to clear") {
147
+ session.respond_to?(:clear)
148
+ }
149
+ end
150
+
151
+ ## <tt>rack.logger</tt>:: A common object interface for logging messages.
152
+ ## The object must implement:
153
+ if logger = env['rack.logger']
154
+ ## info(message, &block)
155
+ assert("logger #{logger.inspect} must respond to info") {
156
+ logger.respond_to?(:info)
157
+ }
158
+
159
+ ## debug(message, &block)
160
+ assert("logger #{logger.inspect} must respond to debug") {
161
+ logger.respond_to?(:debug)
162
+ }
163
+
164
+ ## warn(message, &block)
165
+ assert("logger #{logger.inspect} must respond to warn") {
166
+ logger.respond_to?(:warn)
167
+ }
168
+
169
+ ## error(message, &block)
170
+ assert("logger #{logger.inspect} must respond to error") {
171
+ logger.respond_to?(:error)
172
+ }
173
+
174
+ ## fatal(message, &block)
175
+ assert("logger #{logger.inspect} must respond to fatal") {
176
+ logger.respond_to?(:fatal)
177
+ }
178
+ end
179
+
180
+ ## The server or the application can store their own data in the
181
+ ## environment, too. The keys must contain at least one dot,
182
+ ## and should be prefixed uniquely. The prefix <tt>rack.</tt>
183
+ ## is reserved for use with the Rack core distribution and other
184
+ ## accepted specifications and must not be used otherwise.
185
+ ##
186
+
187
+ %w[REQUEST_METHOD SERVER_NAME SERVER_PORT
188
+ QUERY_STRING
189
+ rack.version rack.input rack.errors
190
+ rack.multithread rack.multiprocess rack.run_once].each { |header|
191
+ assert("env missing required key #{header}") { env.include? header }
192
+ }
193
+
194
+ ## The environment must not contain the keys
195
+ ## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
196
+ ## (use the versions without <tt>HTTP_</tt>).
197
+ %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
198
+ assert("env contains #{header}, must use #{header[5,-1]}") {
199
+ not env.include? header
200
+ }
201
+ }
202
+
203
+ ## The CGI keys (named without a period) must have String values.
204
+ env.each { |key, value|
205
+ next if key.include? "." # Skip extensions
206
+ assert("env variable #{key} has non-string value #{value.inspect}") {
207
+ value.kind_of? String
208
+ }
209
+ }
210
+
211
+ ##
212
+ ## There are the following restrictions:
213
+
214
+ ## * <tt>rack.version</tt> must be an array of Integers.
215
+ assert("rack.version must be an Array, was #{env["rack.version"].class}") {
216
+ env["rack.version"].kind_of? Array
217
+ }
218
+ ## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
219
+ assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
220
+ %w[http https].include? env["rack.url_scheme"]
221
+ }
222
+
223
+ ## * There must be a valid input stream in <tt>rack.input</tt>.
224
+ check_input env["rack.input"]
225
+ ## * There must be a valid error stream in <tt>rack.errors</tt>.
226
+ check_error env["rack.errors"]
227
+
228
+ ## * The <tt>REQUEST_METHOD</tt> must be a valid token.
229
+ assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
230
+ env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
231
+ }
232
+
233
+ ## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
234
+ assert("SCRIPT_NAME must start with /") {
235
+ !env.include?("SCRIPT_NAME") ||
236
+ env["SCRIPT_NAME"] == "" ||
237
+ env["SCRIPT_NAME"] =~ /\A\//
238
+ }
239
+ ## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
240
+ assert("PATH_INFO must start with /") {
241
+ !env.include?("PATH_INFO") ||
242
+ env["PATH_INFO"] == "" ||
243
+ env["PATH_INFO"] =~ /\A\//
244
+ }
245
+ ## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
246
+ assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
247
+ !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
248
+ }
249
+
250
+ ## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
251
+ ## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
252
+ ## <tt>SCRIPT_NAME</tt> is empty.
253
+ assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
254
+ env["SCRIPT_NAME"] || env["PATH_INFO"]
255
+ }
256
+ ## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
257
+ assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
258
+ env["SCRIPT_NAME"] != "/"
259
+ }
260
+ end
261
+
262
+ ## === The Input Stream
263
+ ##
264
+ ## The input stream is an IO-like object which contains the raw HTTP
265
+ ## POST data.
266
+ def check_input(input)
267
+ ## When applicable, its external encoding must be "ASCII-8BIT" and it
268
+ ## must be opened in binary mode, for Ruby 1.9 compatibility.
269
+ assert("rack.input #{input} does not have ASCII-8BIT as its external encoding") {
270
+ input.external_encoding.name == "ASCII-8BIT"
271
+ } if input.respond_to?(:external_encoding)
272
+ assert("rack.input #{input} is not opened in binary mode") {
273
+ input.binmode?
274
+ } if input.respond_to?(:binmode?)
275
+
276
+ ## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
277
+ [:gets, :each, :read, :rewind].each { |method|
278
+ assert("rack.input #{input} does not respond to ##{method}") {
279
+ input.respond_to? method
280
+ }
281
+ }
282
+ end
283
+
284
+ class InputWrapper
285
+ include Assertion
286
+
287
+ def initialize(input)
288
+ @input = input
289
+ end
290
+
291
+ def size
292
+ @input.size
293
+ end
294
+
295
+ ## * +gets+ must be called without arguments and return a string,
296
+ ## or +nil+ on EOF.
297
+ def gets(*args)
298
+ assert("rack.input#gets called with arguments") { args.size == 0 }
299
+ v = @input.gets
300
+ assert("rack.input#gets didn't return a String") {
301
+ v.nil? or v.kind_of? String
302
+ }
303
+ v
304
+ end
305
+
306
+ ## * +read+ behaves like IO#read. Its signature is <tt>read([length, [buffer]])</tt>.
307
+ ## If given, +length+ must be an non-negative Integer (>= 0) or +nil+, and +buffer+ must
308
+ ## be a String and may not be nil. If +length+ is given and not nil, then this method
309
+ ## reads at most +length+ bytes from the input stream. If +length+ is not given or nil,
310
+ ## then this method reads all data until EOF.
311
+ ## When EOF is reached, this method returns nil if +length+ is given and not nil, or ""
312
+ ## if +length+ is not given or is nil.
313
+ ## If +buffer+ is given, then the read data will be placed into +buffer+ instead of a
314
+ ## newly created String object.
315
+ def read(*args)
316
+ assert("rack.input#read called with too many arguments") {
317
+ args.size <= 2
318
+ }
319
+ if args.size >= 1
320
+ assert("rack.input#read called with non-integer and non-nil length") {
321
+ args.first.kind_of?(Integer) || args.first.nil?
322
+ }
323
+ assert("rack.input#read called with a negative length") {
324
+ args.first.nil? || args.first >= 0
325
+ }
326
+ end
327
+ if args.size >= 2
328
+ assert("rack.input#read called with non-String buffer") {
329
+ args[1].kind_of?(String)
330
+ }
331
+ end
332
+
333
+ v = @input.read(*args)
334
+
335
+ assert("rack.input#read didn't return nil or a String") {
336
+ v.nil? or v.kind_of? String
337
+ }
338
+ if args[0].nil?
339
+ assert("rack.input#read(nil) returned nil on EOF") {
340
+ !v.nil?
341
+ }
342
+ end
343
+
344
+ v
345
+ end
346
+
347
+ ## * +each+ must be called without arguments and only yield Strings.
348
+ def each(*args)
349
+ assert("rack.input#each called with arguments") { args.size == 0 }
350
+ @input.each { |line|
351
+ assert("rack.input#each didn't yield a String") {
352
+ line.kind_of? String
353
+ }
354
+ yield line
355
+ }
356
+ end
357
+
358
+ ## * +rewind+ must be called without arguments. It rewinds the input
359
+ ## stream back to the beginning. It must not raise Errno::ESPIPE:
360
+ ## that is, it may not be a pipe or a socket. Therefore, handler
361
+ ## developers must buffer the input data into some rewindable object
362
+ ## if the underlying input stream is not rewindable.
363
+ def rewind(*args)
364
+ assert("rack.input#rewind called with arguments") { args.size == 0 }
365
+ assert("rack.input#rewind raised Errno::ESPIPE") {
366
+ begin
367
+ @input.rewind
368
+ true
369
+ rescue Errno::ESPIPE
370
+ false
371
+ end
372
+ }
373
+ end
374
+
375
+ ## * +close+ must never be called on the input stream.
376
+ def close(*args)
377
+ assert("rack.input#close must not be called") { false }
378
+ end
379
+ end
380
+
381
+ ## === The Error Stream
382
+ def check_error(error)
383
+ ## The error stream must respond to +puts+, +write+ and +flush+.
384
+ [:puts, :write, :flush].each { |method|
385
+ assert("rack.error #{error} does not respond to ##{method}") {
386
+ error.respond_to? method
387
+ }
388
+ }
389
+ end
390
+
391
+ class ErrorWrapper
392
+ include Assertion
393
+
394
+ def initialize(error)
395
+ @error = error
396
+ end
397
+
398
+ ## * +puts+ must be called with a single argument that responds to +to_s+.
399
+ def puts(str)
400
+ @error.puts str
401
+ end
402
+
403
+ ## * +write+ must be called with a single argument that is a String.
404
+ def write(str)
405
+ assert("rack.errors#write not called with a String") { str.kind_of? String }
406
+ @error.write str
407
+ end
408
+
409
+ ## * +flush+ must be called without arguments and must be called
410
+ ## in order to make the error appear for sure.
411
+ def flush
412
+ @error.flush
413
+ end
414
+
415
+ ## * +close+ must never be called on the error stream.
416
+ def close(*args)
417
+ assert("rack.errors#close must not be called") { false }
418
+ end
419
+ end
420
+
421
+ ## == The Response
422
+
423
+ ## === The Status
424
+ def check_status(status)
425
+ ## This is an HTTP status. When parsed as integer (+to_i+), it must be
426
+ ## greater than or equal to 100.
427
+ assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
428
+ end
429
+
430
+ ## === The Headers
431
+ def check_headers(header)
432
+ ## The header must respond to +each+, and yield values of key and value.
433
+ assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
434
+ header.respond_to? :each
435
+ }
436
+ header.each { |key, value|
437
+ ## The header keys must be Strings.
438
+ assert("header key must be a string, was #{key.class}") {
439
+ key.kind_of? String
440
+ }
441
+ ## The header must not contain a +Status+ key,
442
+ assert("header must not contain Status") { key.downcase != "status" }
443
+ ## contain keys with <tt>:</tt> or newlines in their name,
444
+ assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
445
+ ## contain keys names that end in <tt>-</tt> or <tt>_</tt>,
446
+ assert("header names must not end in - or _") { key !~ /[-_]\z/ }
447
+ ## but only contain keys that consist of
448
+ ## letters, digits, <tt>_</tt> or <tt>-</tt> and start with a letter.
449
+ assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
450
+
451
+ ## The values of the header must be Strings,
452
+ assert("a header value must be a String, but the value of " +
453
+ "'#{key}' is a #{value.class}") { value.kind_of? String }
454
+ ## consisting of lines (for multiple header values, e.g. multiple
455
+ ## <tt>Set-Cookie</tt> values) seperated by "\n".
456
+ value.split("\n").each { |item|
457
+ ## The lines must not contain characters below 037.
458
+ assert("invalid header value #{key}: #{item.inspect}") {
459
+ item !~ /[\000-\037]/
460
+ }
461
+ }
462
+ }
463
+ end
464
+
465
+ ## === The Content-Type
466
+ def check_content_type(status, headers)
467
+ headers.each { |key, value|
468
+ ## There must be a <tt>Content-Type</tt>, except when the
469
+ ## +Status+ is 1xx, 204 or 304, in which case there must be none
470
+ ## given.
471
+ if key.downcase == "content-type"
472
+ assert("Content-Type header found in #{status} response, not allowed") {
473
+ not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
474
+ }
475
+ return
476
+ end
477
+ }
478
+ assert("No Content-Type header found") {
479
+ Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
480
+ }
481
+ end
482
+
483
+ ## === The Content-Length
484
+ def check_content_length(status, headers, env)
485
+ headers.each { |key, value|
486
+ if key.downcase == 'content-length'
487
+ ## There must not be a <tt>Content-Length</tt> header when the
488
+ ## +Status+ is 1xx, 204 or 304.
489
+ assert("Content-Length header found in #{status} response, not allowed") {
490
+ not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
491
+ }
492
+
493
+ bytes = 0
494
+ string_body = true
495
+
496
+ if @body.respond_to?(:to_ary)
497
+ @body.each { |part|
498
+ unless part.kind_of?(String)
499
+ string_body = false
500
+ break
501
+ end
502
+
503
+ bytes += Rack::Utils.bytesize(part)
504
+ }
505
+
506
+ if env["REQUEST_METHOD"] == "HEAD"
507
+ assert("Response body was given for HEAD request, but should be empty") {
508
+ bytes == 0
509
+ }
510
+ else
511
+ if string_body
512
+ assert("Content-Length header was #{value}, but should be #{bytes}") {
513
+ value == bytes.to_s
514
+ }
515
+ end
516
+ end
517
+ end
518
+
519
+ return
520
+ end
521
+ }
522
+ end
523
+
524
+ ## === The Body
525
+ def each
526
+ @closed = false
527
+ ## The Body must respond to +each+
528
+ @body.each { |part|
529
+ ## and must only yield String values.
530
+ assert("Body yielded non-string value #{part.inspect}") {
531
+ part.kind_of? String
532
+ }
533
+ yield part
534
+ }
535
+ ##
536
+ ## The Body itself should not be an instance of String, as this will
537
+ ## break in Ruby 1.9.
538
+ ##
539
+ ## If the Body responds to +close+, it will be called after iteration.
540
+ # XXX howto: assert("Body has not been closed") { @closed }
541
+
542
+
543
+ ##
544
+ ## If the Body responds to +to_path+, it must return a String
545
+ ## identifying the location of a file whose contents are identical
546
+ ## to that produced by calling +each+; this may be used by the
547
+ ## server as an alternative, possibly more efficient way to
548
+ ## transport the response.
549
+
550
+ if @body.respond_to?(:to_path)
551
+ assert("The file identified by body.to_path does not exist") {
552
+ ::File.exist? @body.to_path
553
+ }
554
+ end
555
+
556
+ ##
557
+ ## The Body commonly is an Array of Strings, the application
558
+ ## instance itself, or a File-like object.
559
+ end
560
+
561
+ def close
562
+ @closed = true
563
+ @body.close if @body.respond_to?(:close)
564
+ end
565
+
566
+ # :startdoc:
567
+
568
+ end
569
+ end
570
+
571
+ ## == Thanks
572
+ ## Some parts of this specification are adopted from PEP333: Python
573
+ ## Web Server Gateway Interface
574
+ ## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
575
+ ## everyone involved in that effort.