edgar-rack 1.2.1

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