rack 2.2.8 → 3.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rack might be problematic. Click here for more details.

Files changed (84) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +138 -89
  3. data/CONTRIBUTING.md +53 -47
  4. data/MIT-LICENSE +1 -1
  5. data/README.md +287 -0
  6. data/Rakefile +40 -7
  7. data/SPEC.rdoc +166 -125
  8. data/contrib/LICENSE.md +7 -0
  9. data/contrib/logo.webp +0 -0
  10. data/lib/rack/auth/abstract/handler.rb +3 -1
  11. data/lib/rack/auth/abstract/request.rb +3 -1
  12. data/lib/rack/auth/digest/md5.rb +1 -131
  13. data/lib/rack/auth/digest/nonce.rb +1 -54
  14. data/lib/rack/auth/digest/params.rb +1 -54
  15. data/lib/rack/auth/digest/request.rb +1 -43
  16. data/lib/rack/auth/digest.rb +256 -0
  17. data/lib/rack/body_proxy.rb +3 -1
  18. data/lib/rack/builder.rb +60 -42
  19. data/lib/rack/cascade.rb +2 -0
  20. data/lib/rack/chunked.rb +16 -13
  21. data/lib/rack/common_logger.rb +23 -18
  22. data/lib/rack/conditional_get.rb +18 -15
  23. data/lib/rack/constants.rb +62 -0
  24. data/lib/rack/content_length.rb +12 -16
  25. data/lib/rack/content_type.rb +8 -5
  26. data/lib/rack/deflater.rb +40 -26
  27. data/lib/rack/directory.rb +9 -3
  28. data/lib/rack/etag.rb +14 -23
  29. data/lib/rack/events.rb +4 -0
  30. data/lib/rack/file.rb +2 -0
  31. data/lib/rack/files.rb +15 -17
  32. data/lib/rack/head.rb +9 -8
  33. data/lib/rack/headers.rb +154 -0
  34. data/lib/rack/lint.rb +740 -649
  35. data/lib/rack/lock.rb +2 -5
  36. data/lib/rack/logger.rb +2 -0
  37. data/lib/rack/media_type.rb +1 -1
  38. data/lib/rack/method_override.rb +5 -1
  39. data/lib/rack/mime.rb +8 -0
  40. data/lib/rack/mock.rb +1 -271
  41. data/lib/rack/mock_request.rb +166 -0
  42. data/lib/rack/mock_response.rb +124 -0
  43. data/lib/rack/multipart/generator.rb +7 -5
  44. data/lib/rack/multipart/parser.rb +123 -79
  45. data/lib/rack/multipart/uploaded_file.rb +4 -0
  46. data/lib/rack/multipart.rb +20 -40
  47. data/lib/rack/null_logger.rb +9 -0
  48. data/lib/rack/query_parser.rb +76 -44
  49. data/lib/rack/recursive.rb +2 -0
  50. data/lib/rack/reloader.rb +0 -2
  51. data/lib/rack/request.rb +189 -91
  52. data/lib/rack/response.rb +131 -61
  53. data/lib/rack/rewindable_input.rb +24 -5
  54. data/lib/rack/runtime.rb +7 -6
  55. data/lib/rack/sendfile.rb +30 -25
  56. data/lib/rack/show_exceptions.rb +15 -2
  57. data/lib/rack/show_status.rb +17 -7
  58. data/lib/rack/static.rb +8 -8
  59. data/lib/rack/tempfile_reaper.rb +15 -4
  60. data/lib/rack/urlmap.rb +4 -2
  61. data/lib/rack/utils.rb +208 -194
  62. data/lib/rack/version.rb +9 -4
  63. data/lib/rack.rb +5 -76
  64. data/rack.gemspec +6 -6
  65. metadata +19 -31
  66. data/README.rdoc +0 -320
  67. data/bin/rackup +0 -5
  68. data/contrib/rack.png +0 -0
  69. data/contrib/rack.svg +0 -150
  70. data/contrib/rack_logo.svg +0 -164
  71. data/lib/rack/core_ext/regexp.rb +0 -14
  72. data/lib/rack/handler/cgi.rb +0 -59
  73. data/lib/rack/handler/fastcgi.rb +0 -100
  74. data/lib/rack/handler/lsws.rb +0 -61
  75. data/lib/rack/handler/scgi.rb +0 -71
  76. data/lib/rack/handler/thin.rb +0 -36
  77. data/lib/rack/handler/webrick.rb +0 -129
  78. data/lib/rack/handler.rb +0 -104
  79. data/lib/rack/lobster.rb +0 -70
  80. data/lib/rack/server.rb +0 -466
  81. data/lib/rack/session/abstract/id.rb +0 -523
  82. data/lib/rack/session/cookie.rb +0 -204
  83. data/lib/rack/session/memcache.rb +0 -10
  84. data/lib/rack/session/pool.rb +0 -85
data/lib/rack/lint.rb CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  require 'forwardable'
4
4
 
5
+ require_relative 'constants'
6
+ require_relative 'utils'
7
+
5
8
  module Rack
6
9
  # Rack::Lint validates your application and the requests and
7
10
  # responses according to the Rack spec.
@@ -9,787 +12,875 @@ module Rack
9
12
  class Lint
10
13
  def initialize(app)
11
14
  @app = app
12
- @content_length = nil
13
15
  end
14
16
 
15
17
  # :stopdoc:
16
18
 
17
19
  class LintError < RuntimeError; end
18
- module Assertion
19
- def assert(message)
20
- unless yield
21
- raise LintError, message
22
- end
23
- end
24
- end
25
- include Assertion
26
-
27
- ## This specification aims to formalize the Rack protocol. You
20
+ # AUTHORS: n.b. The trailing whitespace between paragraphs is important and
21
+ # should not be removed. The whitespace creates paragraphs in the RDoc
22
+ # output.
23
+ #
24
+ ## This specification aims to formalize the Rack protocol. You
28
25
  ## can (and should) use Rack::Lint to enforce it.
29
26
  ##
30
27
  ## When you develop middleware, be sure to add a Lint before and
31
28
  ## after to catch all mistakes.
32
-
29
+ ##
33
30
  ## = Rack applications
34
-
31
+ ##
35
32
  ## A Rack application is a Ruby object (not a class) that
36
33
  ## responds to +call+.
37
34
  def call(env = nil)
38
- dup._call(env)
35
+ Wrapper.new(@app, env).response
39
36
  end
40
37
 
41
- def _call(env)
42
- ## It takes exactly one argument, the *environment*
43
- raise LintError, "No env given" unless env
44
- check_env env
38
+ class Wrapper
39
+ def initialize(app, env)
40
+ @app = app
41
+ @env = env
42
+ @response = nil
43
+ @head_request = false
44
+
45
+ @status = nil
46
+ @headers = nil
47
+ @body = nil
48
+ @invoked = nil
49
+ @content_length = nil
50
+ @closed = false
51
+ @size = 0
52
+ end
45
53
 
46
- env[RACK_INPUT] = InputWrapper.new(env[RACK_INPUT])
47
- env[RACK_ERRORS] = ErrorWrapper.new(env[RACK_ERRORS])
54
+ def response
55
+ ## It takes exactly one argument, the *environment*
56
+ raise LintError, "No env given" unless @env
57
+ check_environment(@env)
48
58
 
49
- ## and returns an Array of exactly three values:
50
- ary = @app.call(env)
51
- raise LintError, "response is not an Array, but #{ary.class}" unless ary.kind_of? Array
52
- raise LintError, "response array has #{ary.size} elements instead of 3" unless ary.size == 3
59
+ @env[RACK_INPUT] = InputWrapper.new(@env[RACK_INPUT])
60
+ @env[RACK_ERRORS] = ErrorWrapper.new(@env[RACK_ERRORS])
53
61
 
54
- status, headers, @body = ary
55
- ## The *status*,
56
- check_status status
57
- ## the *headers*,
58
- check_headers headers
62
+ ## and returns a non-frozen Array of exactly three values:
63
+ @response = @app.call(@env)
64
+ raise LintError, "response is not an Array, but #{@response.class}" unless @response.kind_of? Array
65
+ raise LintError, "response is frozen" if @response.frozen?
66
+ raise LintError, "response array has #{@response.size} elements instead of 3" unless @response.size == 3
59
67
 
60
- hijack_proc = check_hijack_response headers, env
61
- if hijack_proc && headers.is_a?(Hash)
62
- headers[RACK_HIJACK] = hijack_proc
63
- end
68
+ @status, @headers, @body = @response
69
+ ## The *status*,
70
+ check_status(@status)
64
71
 
65
- ## and the *body*.
66
- check_content_type status, headers
67
- check_content_length status, headers
68
- @head_request = env[REQUEST_METHOD] == HEAD
69
- [status, headers, self]
70
- end
72
+ ## the *headers*,
73
+ check_headers(@headers)
71
74
 
72
- ## == The Environment
73
- def check_env(env)
74
- ## The environment must be an unfrozen instance of Hash that includes
75
- ## CGI-like headers. The application is free to modify the
76
- ## environment.
77
- raise LintError, "env #{env.inspect} is not a Hash, but #{env.class}" unless env.kind_of? Hash
78
- raise LintError, "env should not be frozen, but is" if env.frozen?
79
-
80
- ##
81
- ## The environment is required to include these variables
82
- ## (adopted from PEP333), except when they'd be empty, but see
83
- ## below.
84
-
85
- ## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
86
- ## "GET" or "POST". This cannot ever
87
- ## be an empty string, and so is
88
- ## always required.
89
-
90
- ## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
91
- ## URL's "path" that corresponds to the
92
- ## application object, so that the
93
- ## application knows its virtual
94
- ## "location". This may be an empty
95
- ## string, if the application corresponds
96
- ## to the "root" of the server.
97
-
98
- ## <tt>PATH_INFO</tt>:: The remainder of the request URL's
99
- ## "path", designating the virtual
100
- ## "location" of the request's target
101
- ## within the application. This may be an
102
- ## empty string, if the request URL targets
103
- ## the application root and does not have a
104
- ## trailing slash. This value may be
105
- ## percent-encoded when originating from
106
- ## a URL.
107
-
108
- ## <tt>QUERY_STRING</tt>:: The portion of the request URL that
109
- ## follows the <tt>?</tt>, if any. May be
110
- ## empty, but is always required!
111
-
112
- ## <tt>SERVER_NAME</tt>:: When combined with <tt>SCRIPT_NAME</tt> and
113
- ## <tt>PATH_INFO</tt>, these variables can be
114
- ## used to complete the URL. Note, however,
115
- ## that <tt>HTTP_HOST</tt>, if present,
116
- ## should be used in preference to
117
- ## <tt>SERVER_NAME</tt> for reconstructing
118
- ## the request URL.
119
- ## <tt>SERVER_NAME</tt> can never be an empty
120
- ## string, and so is always required.
121
-
122
- ## <tt>SERVER_PORT</tt>:: An optional +Integer+ which is the port the
123
- ## server is running on. Should be specified if
124
- ## the server is running on a non-standard port.
125
-
126
- ## <tt>HTTP_</tt> Variables:: Variables corresponding to the
127
- ## client-supplied HTTP request
128
- ## headers (i.e., variables whose
129
- ## names begin with <tt>HTTP_</tt>). The
130
- ## presence or absence of these
131
- ## variables should correspond with
132
- ## the presence or absence of the
133
- ## appropriate HTTP header in the
134
- ## request. See
135
- ## {RFC3875 section 4.1.18}[https://tools.ietf.org/html/rfc3875#section-4.1.18]
136
- ## for specific behavior.
137
-
138
- ## In addition to this, the Rack environment must include these
139
- ## Rack-specific variables:
140
-
141
- ## <tt>rack.version</tt>:: The Array representing this version of Rack
142
- ## See Rack::VERSION, that corresponds to
143
- ## the version of this SPEC.
144
-
145
- ## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the
146
- ## request URL.
147
-
148
- ## <tt>rack.input</tt>:: See below, the input stream.
149
-
150
- ## <tt>rack.errors</tt>:: See below, the error stream.
151
-
152
- ## <tt>rack.multithread</tt>:: true if the application object may be
153
- ## simultaneously invoked by another thread
154
- ## in the same process, false otherwise.
155
-
156
- ## <tt>rack.multiprocess</tt>:: true if an equivalent application object
157
- ## may be simultaneously invoked by another
158
- ## process, false otherwise.
159
-
160
- ## <tt>rack.run_once</tt>:: true if the server expects
161
- ## (but does not guarantee!) that the
162
- ## application will only be invoked this one
163
- ## time during the life of its containing
164
- ## process. Normally, this will only be true
165
- ## for a server based on CGI
166
- ## (or something similar).
167
-
168
- ## <tt>rack.hijack?</tt>:: present and true if the server supports
169
- ## connection hijacking. See below, hijacking.
170
-
171
- ## <tt>rack.hijack</tt>:: an object responding to #call that must be
172
- ## called at least once before using
173
- ## rack.hijack_io.
174
- ## It is recommended #call return rack.hijack_io
175
- ## as well as setting it in env if necessary.
176
-
177
- ## <tt>rack.hijack_io</tt>:: if rack.hijack? is true, and rack.hijack
178
- ## has received #call, this will contain
179
- ## an object resembling an IO. See hijacking.
180
-
181
- ## Additional environment specifications have approved to
182
- ## standardized middleware APIs. None of these are required to
183
- ## be implemented by the server.
184
-
185
- ## <tt>rack.session</tt>:: A hash like interface for storing
186
- ## request session data.
187
- ## The store must implement:
188
- if session = env[RACK_SESSION]
189
- ## store(key, value) (aliased as []=);
190
- unless session.respond_to?(:store) && session.respond_to?(:[]=)
191
- raise LintError, "session #{session.inspect} must respond to store and []="
192
- end
193
-
194
- ## fetch(key, default = nil) (aliased as []);
195
- unless session.respond_to?(:fetch) && session.respond_to?(:[])
196
- raise LintError, "session #{session.inspect} must respond to fetch and []"
197
- end
198
-
199
- ## delete(key);
200
- unless session.respond_to?(:delete)
201
- raise LintError, "session #{session.inspect} must respond to delete"
202
- end
203
-
204
- ## clear;
205
- unless session.respond_to?(:clear)
206
- raise LintError, "session #{session.inspect} must respond to clear"
75
+ hijack_proc = check_hijack_response(@headers, @env)
76
+ if hijack_proc
77
+ @headers[RACK_HIJACK] = hijack_proc
207
78
  end
208
-
209
- ## to_hash (returning unfrozen Hash instance);
210
- unless session.respond_to?(:to_hash) && session.to_hash.kind_of?(Hash) && !session.to_hash.frozen?
211
- raise LintError, "session #{session.inspect} must respond to to_hash and return unfrozen Hash instance"
79
+
80
+ ## and the *body*.
81
+ check_content_type(@status, @headers)
82
+ check_content_length(@status, @headers)
83
+ @head_request = @env[REQUEST_METHOD] == HEAD
84
+
85
+ @lint = (@env['rack.lint'] ||= []) << self
86
+
87
+ if (@env['rack.lint.body_iteration'] ||= 0) > 0
88
+ raise LintError, "Middleware must not call #each directly"
212
89
  end
90
+
91
+ return [@status, @headers, self]
213
92
  end
214
93
 
215
- ## <tt>rack.logger</tt>:: A common object interface for logging messages.
216
- ## The object must implement:
217
- if logger = env[RACK_LOGGER]
218
- ## info(message, &block)
219
- unless logger.respond_to?(:info)
220
- raise LintError, "logger #{logger.inspect} must respond to info"
94
+ ##
95
+ ## == The Environment
96
+ ##
97
+ def check_environment(env)
98
+ ## The environment must be an unfrozen instance of Hash that includes
99
+ ## CGI-like headers. The Rack application is free to modify the
100
+ ## environment.
101
+ raise LintError, "env #{env.inspect} is not a Hash, but #{env.class}" unless env.kind_of? Hash
102
+ raise LintError, "env should not be frozen, but is" if env.frozen?
103
+
104
+ ##
105
+ ## The environment is required to include these variables
106
+ ## (adopted from {PEP 333}[https://peps.python.org/pep-0333/]), except when they'd be empty, but see
107
+ ## below.
108
+
109
+ ## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
110
+ ## "GET" or "POST". This cannot ever
111
+ ## be an empty string, and so is
112
+ ## always required.
113
+
114
+ ## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
115
+ ## URL's "path" that corresponds to the
116
+ ## application object, so that the
117
+ ## application knows its virtual
118
+ ## "location". This may be an empty
119
+ ## string, if the application corresponds
120
+ ## to the "root" of the server.
121
+
122
+ ## <tt>PATH_INFO</tt>:: The remainder of the request URL's
123
+ ## "path", designating the virtual
124
+ ## "location" of the request's target
125
+ ## within the application. This may be an
126
+ ## empty string, if the request URL targets
127
+ ## the application root and does not have a
128
+ ## trailing slash. This value may be
129
+ ## percent-encoded when originating from
130
+ ## a URL.
131
+
132
+ ## <tt>QUERY_STRING</tt>:: The portion of the request URL that
133
+ ## follows the <tt>?</tt>, if any. May be
134
+ ## empty, but is always required!
135
+
136
+ ## <tt>SERVER_NAME</tt>:: When combined with <tt>SCRIPT_NAME</tt> and
137
+ ## <tt>PATH_INFO</tt>, these variables can be
138
+ ## used to complete the URL. Note, however,
139
+ ## that <tt>HTTP_HOST</tt>, if present,
140
+ ## should be used in preference to
141
+ ## <tt>SERVER_NAME</tt> for reconstructing
142
+ ## the request URL.
143
+ ## <tt>SERVER_NAME</tt> can never be an empty
144
+ ## string, and so is always required.
145
+
146
+ ## <tt>SERVER_PORT</tt>:: An optional +Integer+ which is the port the
147
+ ## server is running on. Should be specified if
148
+ ## the server is running on a non-standard port.
149
+
150
+ ## <tt>SERVER_PROTOCOL</tt>:: A string representing the HTTP version used
151
+ ## for the request.
152
+
153
+ ## <tt>HTTP_</tt> Variables:: Variables corresponding to the
154
+ ## client-supplied HTTP request
155
+ ## headers (i.e., variables whose
156
+ ## names begin with <tt>HTTP_</tt>). The
157
+ ## presence or absence of these
158
+ ## variables should correspond with
159
+ ## the presence or absence of the
160
+ ## appropriate HTTP header in the
161
+ ## request. See
162
+ ## {RFC3875 section 4.1.18}[https://tools.ietf.org/html/rfc3875#section-4.1.18]
163
+ ## for specific behavior.
164
+
165
+ ## In addition to this, the Rack environment must include these
166
+ ## Rack-specific variables:
167
+
168
+ ## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the
169
+ ## request URL.
170
+
171
+ ## <tt>rack.input</tt>:: See below, the input stream.
172
+
173
+ ## <tt>rack.errors</tt>:: See below, the error stream.
174
+
175
+ ## <tt>rack.hijack?</tt>:: See below, if present and true, indicates
176
+ ## that the server supports partial hijacking.
177
+
178
+ ## <tt>rack.hijack</tt>:: See below, if present, an object responding
179
+ ## to +call+ that is used to perform a full
180
+ ## hijack.
181
+
182
+ ## Additional environment specifications have approved to
183
+ ## standardized middleware APIs. None of these are required to
184
+ ## be implemented by the server.
185
+
186
+ ## <tt>rack.session</tt>:: A hash-like interface for storing
187
+ ## request session data.
188
+ ## The store must implement:
189
+ if session = env[RACK_SESSION]
190
+ ## store(key, value) (aliased as []=);
191
+ unless session.respond_to?(:store) && session.respond_to?(:[]=)
192
+ raise LintError, "session #{session.inspect} must respond to store and []="
193
+ end
194
+
195
+ ## fetch(key, default = nil) (aliased as []);
196
+ unless session.respond_to?(:fetch) && session.respond_to?(:[])
197
+ raise LintError, "session #{session.inspect} must respond to fetch and []"
198
+ end
199
+
200
+ ## delete(key);
201
+ unless session.respond_to?(:delete)
202
+ raise LintError, "session #{session.inspect} must respond to delete"
203
+ end
204
+
205
+ ## clear;
206
+ unless session.respond_to?(:clear)
207
+ raise LintError, "session #{session.inspect} must respond to clear"
208
+ end
209
+
210
+ ## to_hash (returning unfrozen Hash instance);
211
+ unless session.respond_to?(:to_hash) && session.to_hash.kind_of?(Hash) && !session.to_hash.frozen?
212
+ raise LintError, "session #{session.inspect} must respond to to_hash and return unfrozen Hash instance"
213
+ end
221
214
  end
222
215
 
223
- ## debug(message, &block)
224
- unless logger.respond_to?(:debug)
225
- raise LintError, "logger #{logger.inspect} must respond to debug"
216
+ ## <tt>rack.logger</tt>:: A common object interface for logging messages.
217
+ ## The object must implement:
218
+ if logger = env[RACK_LOGGER]
219
+ ## info(message, &block)
220
+ unless logger.respond_to?(:info)
221
+ raise LintError, "logger #{logger.inspect} must respond to info"
222
+ end
223
+
224
+ ## debug(message, &block)
225
+ unless logger.respond_to?(:debug)
226
+ raise LintError, "logger #{logger.inspect} must respond to debug"
227
+ end
228
+
229
+ ## warn(message, &block)
230
+ unless logger.respond_to?(:warn)
231
+ raise LintError, "logger #{logger.inspect} must respond to warn"
232
+ end
233
+
234
+ ## error(message, &block)
235
+ unless logger.respond_to?(:error)
236
+ raise LintError, "logger #{logger.inspect} must respond to error"
237
+ end
238
+
239
+ ## fatal(message, &block)
240
+ unless logger.respond_to?(:fatal)
241
+ raise LintError, "logger #{logger.inspect} must respond to fatal"
242
+ end
226
243
  end
227
244
 
228
- ## warn(message, &block)
229
- unless logger.respond_to?(:warn)
230
- raise LintError, "logger #{logger.inspect} must respond to warn"
245
+ ## <tt>rack.multipart.buffer_size</tt>:: An Integer hint to the multipart parser as to what chunk size to use for reads and writes.
246
+ if bufsize = env[RACK_MULTIPART_BUFFER_SIZE]
247
+ unless bufsize.is_a?(Integer) && bufsize > 0
248
+ raise LintError, "rack.multipart.buffer_size must be an Integer > 0 if specified"
249
+ end
231
250
  end
232
251
 
233
- ## error(message, &block)
234
- unless logger.respond_to?(:error)
235
- raise LintError, "logger #{logger.inspect} must respond to error"
252
+ ## <tt>rack.multipart.tempfile_factory</tt>:: An object responding to #call with two arguments, the filename and content_type given for the multipart form field, and returning an IO-like object that responds to #<< and optionally #rewind. This factory will be used to instantiate the tempfile for each multipart form file upload field, rather than the default class of Tempfile.
253
+ if tempfile_factory = env[RACK_MULTIPART_TEMPFILE_FACTORY]
254
+ raise LintError, "rack.multipart.tempfile_factory must respond to #call" unless tempfile_factory.respond_to?(:call)
255
+ env[RACK_MULTIPART_TEMPFILE_FACTORY] = lambda do |filename, content_type|
256
+ io = tempfile_factory.call(filename, content_type)
257
+ raise LintError, "rack.multipart.tempfile_factory return value must respond to #<<" unless io.respond_to?(:<<)
258
+ io
259
+ end
236
260
  end
237
261
 
238
- ## fatal(message, &block)
239
- unless logger.respond_to?(:fatal)
240
- raise LintError, "logger #{logger.inspect} must respond to fatal"
262
+ ## The server or the application can store their own data in the
263
+ ## environment, too. The keys must contain at least one dot,
264
+ ## and should be prefixed uniquely. The prefix <tt>rack.</tt>
265
+ ## is reserved for use with the Rack core distribution and other
266
+ ## accepted specifications and must not be used otherwise.
267
+ ##
268
+
269
+ %w[REQUEST_METHOD SERVER_NAME QUERY_STRING SERVER_PROTOCOL
270
+ rack.input rack.errors].each { |header|
271
+ raise LintError, "env missing required key #{header}" unless env.include? header
272
+ }
273
+
274
+ ## The <tt>SERVER_PORT</tt> must be an Integer if set.
275
+ server_port = env["SERVER_PORT"]
276
+ unless server_port.nil? || (Integer(server_port) rescue false)
277
+ raise LintError, "env[SERVER_PORT] is not an Integer"
241
278
  end
242
- end
243
279
 
244
- ## <tt>rack.multipart.buffer_size</tt>:: An Integer hint to the multipart parser as to what chunk size to use for reads and writes.
245
- if bufsize = env[RACK_MULTIPART_BUFFER_SIZE]
246
- unless bufsize.is_a?(Integer) && bufsize > 0
247
- raise LintError, "rack.multipart.buffer_size must be an Integer > 0 if specified"
280
+ ## The <tt>SERVER_NAME</tt> must be a valid authority as defined by RFC7540.
281
+ unless (URI.parse("http://#{env[SERVER_NAME]}/") rescue false)
282
+ raise LintError, "#{env[SERVER_NAME]} must be a valid authority"
248
283
  end
249
- end
250
284
 
251
- ## <tt>rack.multipart.tempfile_factory</tt>:: An object responding to #call with two arguments, the filename and content_type given for the multipart form field, and returning an IO-like object that responds to #<< and optionally #rewind. This factory will be used to instantiate the tempfile for each multipart form file upload field, rather than the default class of Tempfile.
252
- if tempfile_factory = env[RACK_MULTIPART_TEMPFILE_FACTORY]
253
- raise LintError, "rack.multipart.tempfile_factory must respond to #call" unless tempfile_factory.respond_to?(:call)
254
- env[RACK_MULTIPART_TEMPFILE_FACTORY] = lambda do |filename, content_type|
255
- io = tempfile_factory.call(filename, content_type)
256
- raise LintError, "rack.multipart.tempfile_factory return value must respond to #<<" unless io.respond_to?(:<<)
257
- io
285
+ ## The <tt>HTTP_HOST</tt> must be a valid authority as defined by RFC7540.
286
+ unless (URI.parse("http://#{env[HTTP_HOST]}/") rescue false)
287
+ raise LintError, "#{env[HTTP_HOST]} must be a valid authority"
258
288
  end
259
- end
260
289
 
261
- ## The server or the application can store their own data in the
262
- ## environment, too. The keys must contain at least one dot,
263
- ## and should be prefixed uniquely. The prefix <tt>rack.</tt>
264
- ## is reserved for use with the Rack core distribution and other
265
- ## accepted specifications and must not be used otherwise.
266
- ##
290
+ ## The <tt>SERVER_PROTOCOL</tt> must match the regexp <tt>HTTP/\d(\.\d)?</tt>.
291
+ server_protocol = env['SERVER_PROTOCOL']
292
+ unless %r{HTTP/\d(\.\d)?}.match?(server_protocol)
293
+ raise LintError, "env[SERVER_PROTOCOL] does not match HTTP/\\d(\\.\\d)?"
294
+ end
267
295
 
268
- %w[REQUEST_METHOD SERVER_NAME QUERY_STRING
269
- rack.version rack.input rack.errors
270
- rack.multithread rack.multiprocess rack.run_once].each { |header|
271
- raise LintError, "env missing required key #{header}" unless env.include? header
272
- }
296
+ ## If the <tt>HTTP_VERSION</tt> is present, it must equal the <tt>SERVER_PROTOCOL</tt>.
297
+ if env['HTTP_VERSION'] && env['HTTP_VERSION'] != server_protocol
298
+ raise LintError, "env[HTTP_VERSION] does not equal env[SERVER_PROTOCOL]"
299
+ end
273
300
 
274
- ## The <tt>SERVER_PORT</tt> must be an Integer if set.
275
- server_port = env["SERVER_PORT"]
276
- unless server_port.nil? || (Integer(server_port) rescue false)
277
- raise LintError, "env[SERVER_PORT] is not an Integer"
278
- end
301
+ ## The environment must not contain the keys
302
+ ## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
303
+ ## (use the versions without <tt>HTTP_</tt>).
304
+ %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
305
+ if env.include? header
306
+ raise LintError, "env contains #{header}, must use #{header[5, -1]}"
307
+ end
308
+ }
279
309
 
280
- ## The <tt>SERVER_NAME</tt> must be a valid authority as defined by RFC7540.
281
- unless (URI.parse("http://#{env[SERVER_NAME]}/") rescue false)
282
- raise LintError, "#{env[SERVER_NAME]} must be a valid authority"
283
- end
310
+ ## The CGI keys (named without a period) must have String values.
311
+ ## If the string values for CGI keys contain non-ASCII characters,
312
+ ## they should use ASCII-8BIT encoding.
313
+ env.each { |key, value|
314
+ next if key.include? "." # Skip extensions
315
+ unless value.kind_of? String
316
+ raise LintError, "env variable #{key} has non-string value #{value.inspect}"
317
+ end
318
+ next if value.encoding == Encoding::ASCII_8BIT
319
+ unless value.b !~ /[\x80-\xff]/n
320
+ raise LintError, "env variable #{key} has value containing non-ASCII characters and has non-ASCII-8BIT encoding #{value.inspect} encoding: #{value.encoding}"
321
+ end
322
+ }
284
323
 
285
- ## The <tt>HTTP_HOST</tt> must be a valid authority as defined by RFC7540.
286
- unless (URI.parse("http://#{env[HTTP_HOST]}/") rescue false)
287
- raise LintError, "#{env[HTTP_HOST]} must be a valid authority"
288
- end
324
+ ## There are the following restrictions:
289
325
 
290
- ## The environment must not contain the keys
291
- ## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
292
- ## (use the versions without <tt>HTTP_</tt>).
293
- %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
294
- if env.include? header
295
- raise LintError, "env contains #{header}, must use #{header[5, -1]}"
326
+ ## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
327
+ unless %w[http https].include?(env[RACK_URL_SCHEME])
328
+ raise LintError, "rack.url_scheme unknown: #{env[RACK_URL_SCHEME].inspect}"
296
329
  end
297
- }
298
330
 
299
- ## The CGI keys (named without a period) must have String values.
300
- ## If the string values for CGI keys contain non-ASCII characters,
301
- ## they should use ASCII-8BIT encoding.
302
- env.each { |key, value|
303
- next if key.include? "." # Skip extensions
304
- unless value.kind_of? String
305
- raise LintError, "env variable #{key} has non-string value #{value.inspect}"
306
- end
307
- next if value.encoding == Encoding::ASCII_8BIT
308
- unless value.b !~ /[\x80-\xff]/n
309
- raise LintError, "env variable #{key} has value containing non-ASCII characters and has non-ASCII-8BIT encoding #{value.inspect} encoding: #{value.encoding}"
331
+ ## * There must be a valid input stream in <tt>rack.input</tt>.
332
+ check_input env[RACK_INPUT]
333
+ ## * There must be a valid error stream in <tt>rack.errors</tt>.
334
+ check_error env[RACK_ERRORS]
335
+ ## * There may be a valid hijack callback in <tt>rack.hijack</tt>
336
+ check_hijack env
337
+
338
+ ## * The <tt>REQUEST_METHOD</tt> must be a valid token.
339
+ unless env[REQUEST_METHOD] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
340
+ raise LintError, "REQUEST_METHOD unknown: #{env[REQUEST_METHOD].dump}"
310
341
  end
311
- }
312
342
 
313
- ## There are the following restrictions:
343
+ ## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
344
+ if env.include?(SCRIPT_NAME) && env[SCRIPT_NAME] != "" && env[SCRIPT_NAME] !~ /\A\//
345
+ raise LintError, "SCRIPT_NAME must start with /"
346
+ end
347
+ ## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
348
+ if env.include?(PATH_INFO) && env[PATH_INFO] != "" && env[PATH_INFO] !~ /\A\//
349
+ raise LintError, "PATH_INFO must start with /"
350
+ end
351
+ ## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
352
+ if env.include?("CONTENT_LENGTH") && env["CONTENT_LENGTH"] !~ /\A\d+\z/
353
+ raise LintError, "Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}"
354
+ end
314
355
 
315
- ## * <tt>rack.version</tt> must be an array of Integers.
316
- unless env[RACK_VERSION].kind_of? Array
317
- raise LintError, "rack.version must be an Array, was #{env[RACK_VERSION].class}"
356
+ ## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
357
+ ## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
358
+ ## <tt>SCRIPT_NAME</tt> is empty.
359
+ unless env[SCRIPT_NAME] || env[PATH_INFO]
360
+ raise LintError, "One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)"
361
+ end
362
+ ## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
363
+ unless env[SCRIPT_NAME] != "/"
364
+ raise LintError, "SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'"
365
+ end
318
366
  end
319
- ## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
320
- unless %w[http https].include?(env[RACK_URL_SCHEME])
321
- raise LintError, "rack.url_scheme unknown: #{env[RACK_URL_SCHEME].inspect}"
367
+
368
+ ##
369
+ ## === The Input Stream
370
+ ##
371
+ ## The input stream is an IO-like object which contains the raw HTTP
372
+ ## POST data.
373
+ def check_input(input)
374
+ ## When applicable, its external encoding must be "ASCII-8BIT" and it
375
+ ## must be opened in binary mode, for Ruby 1.9 compatibility.
376
+ if input.respond_to?(:external_encoding) && input.external_encoding != Encoding::ASCII_8BIT
377
+ raise LintError, "rack.input #{input} does not have ASCII-8BIT as its external encoding"
378
+ end
379
+ if input.respond_to?(:binmode?) && !input.binmode?
380
+ raise LintError, "rack.input #{input} is not opened in binary mode"
381
+ end
382
+
383
+ ## The input stream must respond to +gets+, +each+, and +read+.
384
+ [:gets, :each, :read].each { |method|
385
+ unless input.respond_to? method
386
+ raise LintError, "rack.input #{input} does not respond to ##{method}"
387
+ end
388
+ }
322
389
  end
323
390
 
324
- ## * There must be a valid input stream in <tt>rack.input</tt>.
325
- check_input env[RACK_INPUT]
326
- ## * There must be a valid error stream in <tt>rack.errors</tt>.
327
- check_error env[RACK_ERRORS]
328
- ## * There may be a valid hijack stream in <tt>rack.hijack_io</tt>
329
- check_hijack env
391
+ class InputWrapper
392
+ def initialize(input)
393
+ @input = input
394
+ end
330
395
 
331
- ## * The <tt>REQUEST_METHOD</tt> must be a valid token.
332
- unless env[REQUEST_METHOD] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
333
- raise LintError, "REQUEST_METHOD unknown: #{env[REQUEST_METHOD].dump}"
334
- end
396
+ ## * +gets+ must be called without arguments and return a string,
397
+ ## or +nil+ on EOF.
398
+ def gets(*args)
399
+ raise LintError, "rack.input#gets called with arguments" unless args.size == 0
400
+ v = @input.gets
401
+ unless v.nil? or v.kind_of? String
402
+ raise LintError, "rack.input#gets didn't return a String"
403
+ end
404
+ v
405
+ end
335
406
 
336
- ## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
337
- if env.include?(SCRIPT_NAME) && env[SCRIPT_NAME] != "" && env[SCRIPT_NAME] !~ /\A\//
338
- raise LintError, "SCRIPT_NAME must start with /"
339
- end
340
- ## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
341
- if env.include?(PATH_INFO) && env[PATH_INFO] != "" && env[PATH_INFO] !~ /\A\//
342
- raise LintError, "PATH_INFO must start with /"
343
- end
344
- ## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
345
- if env.include?("CONTENT_LENGTH") && env["CONTENT_LENGTH"] !~ /\A\d+\z/
346
- raise LintError, "Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}"
347
- end
407
+ ## * +read+ behaves like IO#read.
408
+ ## Its signature is <tt>read([length, [buffer]])</tt>.
409
+ ##
410
+ ## If given, +length+ must be a non-negative Integer (>= 0) or +nil+,
411
+ ## and +buffer+ must be a String and may not be nil.
412
+ ##
413
+ ## If +length+ is given and not nil, then this method reads at most
414
+ ## +length+ bytes from the input stream.
415
+ ##
416
+ ## If +length+ is not given or nil, then this method reads
417
+ ## all data until EOF.
418
+ ##
419
+ ## When EOF is reached, this method returns nil if +length+ is given
420
+ ## and not nil, or "" if +length+ is not given or is nil.
421
+ ##
422
+ ## If +buffer+ is given, then the read data will be placed
423
+ ## into +buffer+ instead of a newly created String object.
424
+ def read(*args)
425
+ unless args.size <= 2
426
+ raise LintError, "rack.input#read called with too many arguments"
427
+ end
428
+ if args.size >= 1
429
+ unless args.first.kind_of?(Integer) || args.first.nil?
430
+ raise LintError, "rack.input#read called with non-integer and non-nil length"
431
+ end
432
+ unless args.first.nil? || args.first >= 0
433
+ raise LintError, "rack.input#read called with a negative length"
434
+ end
435
+ end
436
+ if args.size >= 2
437
+ unless args[1].kind_of?(String)
438
+ raise LintError, "rack.input#read called with non-String buffer"
439
+ end
440
+ end
348
441
 
349
- ## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
350
- ## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
351
- ## <tt>SCRIPT_NAME</tt> is empty.
352
- unless env[SCRIPT_NAME] || env[PATH_INFO]
353
- raise LintError, "One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)"
354
- end
355
- ## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
356
- unless env[SCRIPT_NAME] != "/"
357
- raise LintError, "SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'"
358
- end
359
- end
442
+ v = @input.read(*args)
360
443
 
361
- ## === The Input Stream
362
- ##
363
- ## The input stream is an IO-like object which contains the raw HTTP
364
- ## POST data.
365
- def check_input(input)
366
- ## When applicable, its external encoding must be "ASCII-8BIT" and it
367
- ## must be opened in binary mode, for Ruby 1.9 compatibility.
368
- if input.respond_to?(:external_encoding) && input.external_encoding != Encoding::ASCII_8BIT
369
- raise LintError, "rack.input #{input} does not have ASCII-8BIT as its external encoding"
444
+ unless v.nil? or v.kind_of? String
445
+ raise LintError, "rack.input#read didn't return nil or a String"
446
+ end
447
+ if args[0].nil?
448
+ unless !v.nil?
449
+ raise LintError, "rack.input#read(nil) returned nil on EOF"
450
+ end
451
+ end
452
+
453
+ v
454
+ end
455
+
456
+ ## * +each+ must be called without arguments and only yield Strings.
457
+ def each(*args)
458
+ raise LintError, "rack.input#each called with arguments" unless args.size == 0
459
+ @input.each { |line|
460
+ unless line.kind_of? String
461
+ raise LintError, "rack.input#each didn't yield a String"
462
+ end
463
+ yield line
464
+ }
465
+ end
466
+
467
+ ## * +close+ must never be called on the input stream.
468
+ def close(*args)
469
+ raise LintError, "rack.input#close must not be called"
470
+ end
370
471
  end
371
- if input.respond_to?(:binmode?) && !input.binmode?
372
- raise LintError, "rack.input #{input} is not opened in binary mode"
472
+
473
+ ##
474
+ ## === The Error Stream
475
+ ##
476
+ def check_error(error)
477
+ ## The error stream must respond to +puts+, +write+ and +flush+.
478
+ [:puts, :write, :flush].each { |method|
479
+ unless error.respond_to? method
480
+ raise LintError, "rack.error #{error} does not respond to ##{method}"
481
+ end
482
+ }
373
483
  end
374
484
 
375
- ## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
376
- [:gets, :each, :read, :rewind].each { |method|
377
- unless input.respond_to? method
378
- raise LintError, "rack.input #{input} does not respond to ##{method}"
485
+ class ErrorWrapper
486
+ def initialize(error)
487
+ @error = error
379
488
  end
380
- }
381
- end
382
489
 
383
- class InputWrapper
384
- include Assertion
490
+ ## * +puts+ must be called with a single argument that responds to +to_s+.
491
+ def puts(str)
492
+ @error.puts str
493
+ end
385
494
 
386
- def initialize(input)
387
- @input = input
388
- end
495
+ ## * +write+ must be called with a single argument that is a String.
496
+ def write(str)
497
+ raise LintError, "rack.errors#write not called with a String" unless str.kind_of? String
498
+ @error.write str
499
+ end
500
+
501
+ ## * +flush+ must be called without arguments and must be called
502
+ ## in order to make the error appear for sure.
503
+ def flush
504
+ @error.flush
505
+ end
389
506
 
390
- ## * +gets+ must be called without arguments and return a string,
391
- ## or +nil+ on EOF.
392
- def gets(*args)
393
- raise LintError, "rack.input#gets called with arguments" unless args.size == 0
394
- v = @input.gets
395
- unless v.nil? or v.kind_of? String
396
- raise LintError, "rack.input#gets didn't return a String"
507
+ ## * +close+ must never be called on the error stream.
508
+ def close(*args)
509
+ raise LintError, "rack.errors#close must not be called"
397
510
  end
398
- v
399
511
  end
400
512
 
401
- ## * +read+ behaves like IO#read.
402
- ## Its signature is <tt>read([length, [buffer]])</tt>.
403
513
  ##
404
- ## If given, +length+ must be a non-negative Integer (>= 0) or +nil+,
405
- ## and +buffer+ must be a String and may not be nil.
514
+ ## === Hijacking
406
515
  ##
407
- ## If +length+ is given and not nil, then this method reads at most
408
- ## +length+ bytes from the input stream.
516
+ ## The hijacking interfaces provides a means for an application to take
517
+ ## control of the HTTP connection. There are two distinct hijack
518
+ ## interfaces: full hijacking where the application takes over the raw
519
+ ## connection, and partial hijacking where the application takes over
520
+ ## just the response body stream. In both cases, the application is
521
+ ## responsible for closing the hijacked stream.
409
522
  ##
410
- ## If +length+ is not given or nil, then this method reads
411
- ## all data until EOF.
523
+ ## Full hijacking only works with HTTP/1. Partial hijacking is functionally
524
+ ## equivalent to streaming bodies, and is still optionally supported for
525
+ ## backwards compatibility with older Rack versions.
412
526
  ##
413
- ## When EOF is reached, this method returns nil if +length+ is given
414
- ## and not nil, or "" if +length+ is not given or is nil.
527
+ ## ==== Full Hijack
415
528
  ##
416
- ## If +buffer+ is given, then the read data will be placed
417
- ## into +buffer+ instead of a newly created String object.
418
- def read(*args)
419
- unless args.size <= 2
420
- raise LintError, "rack.input#read called with too many arguments"
421
- end
422
- if args.size >= 1
423
- unless args.first.kind_of?(Integer) || args.first.nil?
424
- raise LintError, "rack.input#read called with non-integer and non-nil length"
425
- end
426
- unless args.first.nil? || args.first >= 0
427
- raise LintError, "rack.input#read called with a negative length"
428
- end
429
- end
430
- if args.size >= 2
431
- unless args[1].kind_of?(String)
432
- raise LintError, "rack.input#read called with non-String buffer"
433
- end
434
- end
529
+ ## Full hijack is used to completely take over an HTTP/1 connection. It
530
+ ## occurs before any headers are written and causes the request to
531
+ ## ignores any response generated by the application.
532
+ ##
533
+ ## It is intended to be used when applications need access to raw HTTP/1
534
+ ## connection.
535
+ ##
536
+ def check_hijack(env)
537
+ ## If +rack.hijack+ is present in +env+, it must respond to +call+
538
+ if original_hijack = env[RACK_HIJACK]
539
+ raise LintError, "rack.hijack must respond to call" unless original_hijack.respond_to?(:call)
435
540
 
436
- v = @input.read(*args)
541
+ env[RACK_HIJACK] = proc do
542
+ io = original_hijack.call
437
543
 
438
- unless v.nil? or v.kind_of? String
439
- raise LintError, "rack.input#read didn't return nil or a String"
440
- end
441
- if args[0].nil?
442
- unless !v.nil?
443
- raise LintError, "rack.input#read(nil) returned nil on EOF"
544
+ ## and return an +IO+ instance which can be used to read and write
545
+ ## to the underlying connection using HTTP/1 semantics and
546
+ ## formatting.
547
+ raise LintError, "rack.hijack must return an IO instance" unless io.is_a?(IO)
548
+
549
+ io
444
550
  end
445
551
  end
446
-
447
- v
448
552
  end
449
553
 
450
- ## * +each+ must be called without arguments and only yield Strings.
451
- def each(*args)
452
- raise LintError, "rack.input#each called with arguments" unless args.size == 0
453
- @input.each { |line|
454
- unless line.kind_of? String
455
- raise LintError, "rack.input#each didn't yield a String"
554
+ ##
555
+ ## ==== Partial Hijack
556
+ ##
557
+ ## Partial hijack is used for bi-directional streaming of the request and
558
+ ## response body. It occurs after the status and headers are written by
559
+ ## the server and causes the server to ignore the Body of the response.
560
+ ##
561
+ ## It is intended to be used when applications need bi-directional
562
+ ## streaming.
563
+ ##
564
+ def check_hijack_response(headers, env)
565
+ ## If +rack.hijack?+ is present in +env+ and truthy,
566
+ if env[RACK_IS_HIJACK]
567
+ ## an application may set the special response header +rack.hijack+
568
+ if original_hijack = headers[RACK_HIJACK]
569
+ ## to an object that responds to +call+,
570
+ unless original_hijack.respond_to?(:call)
571
+ raise LintError, 'rack.hijack header must respond to #call'
572
+ end
573
+ ## accepting a +stream+ argument.
574
+ return proc do |io|
575
+ original_hijack.call StreamWrapper.new(io)
576
+ end
577
+ end
578
+ ##
579
+ ## After the response status and headers have been sent, this hijack
580
+ ## callback will be invoked with a +stream+ argument which follows the
581
+ ## same interface as outlined in "Streaming Body". Servers must
582
+ ## ignore the +body+ part of the response tuple when the
583
+ ## +rack.hijack+ response header is present. Using an empty +Array+
584
+ ## instance is recommended.
585
+ else
586
+ ##
587
+ ## The special response header +rack.hijack+ must only be set
588
+ ## if the request +env+ has a truthy +rack.hijack?+.
589
+ if headers.key?(RACK_HIJACK)
590
+ raise LintError, 'rack.hijack header must not be present if server does not support hijacking'
456
591
  end
457
- yield line
458
- }
459
- end
460
-
461
- ## * +rewind+ must be called without arguments. It rewinds the input
462
- ## stream back to the beginning. It must not raise Errno::ESPIPE:
463
- ## that is, it may not be a pipe or a socket. Therefore, handler
464
- ## developers must buffer the input data into some rewindable object
465
- ## if the underlying input stream is not rewindable.
466
- def rewind(*args)
467
- raise LintError, "rack.input#rewind called with arguments" unless args.size == 0
468
- begin
469
- @input.rewind
470
- true
471
- rescue Errno::ESPIPE
472
- raise LintError, "rack.input#rewind raised Errno::ESPIPE"
473
592
  end
593
+
594
+ nil
474
595
  end
475
596
 
476
- ## * +close+ must never be called on the input stream.
477
- def close(*args)
478
- raise LintError, "rack.input#close must not be called"
597
+ ## == The Response
598
+ ##
599
+ ## === The Status
600
+ ##
601
+ def check_status(status)
602
+ ## This is an HTTP status. It must be an Integer greater than or equal to
603
+ ## 100.
604
+ unless status.is_a?(Integer) && status >= 100
605
+ raise LintError, "Status must be an Integer >=100"
606
+ end
479
607
  end
480
- end
481
608
 
482
- ## === The Error Stream
483
- def check_error(error)
484
- ## The error stream must respond to +puts+, +write+ and +flush+.
485
- [:puts, :write, :flush].each { |method|
486
- unless error.respond_to? method
487
- raise LintError, "rack.error #{error} does not respond to ##{method}"
609
+ ##
610
+ ## === The Headers
611
+ ##
612
+ def check_headers(headers)
613
+ ## The headers must be a unfrozen Hash.
614
+ unless headers.kind_of?(Hash)
615
+ raise LintError, "headers object should be a hash, but isn't (got #{headers.class} as headers)"
616
+ end
617
+
618
+ if headers.frozen?
619
+ raise LintError, "headers object should not be frozen, but is"
488
620
  end
489
- }
490
- end
491
621
 
492
- class ErrorWrapper
493
- include Assertion
622
+ headers.each do |key, value|
623
+ ## The header keys must be Strings.
624
+ unless key.kind_of? String
625
+ raise LintError, "header key must be a string, was #{key.class}"
626
+ end
494
627
 
495
- def initialize(error)
496
- @error = error
628
+ ## Special headers starting "rack." are for communicating with the
629
+ ## server, and must not be sent back to the client.
630
+ next if key.start_with?("rack.")
631
+
632
+ ## The header must not contain a +Status+ key.
633
+ raise LintError, "header must not contain status" if key == "status"
634
+ ## Header keys must conform to RFC7230 token specification, i.e. cannot
635
+ ## contain non-printable ASCII, DQUOTE or "(),/:;<=>?@[\]{}".
636
+ raise LintError, "invalid header name: #{key}" if key =~ /[\(\),\/:;<=>\?@\[\\\]{}[:cntrl:]]/
637
+ ## Header keys must not contain uppercase ASCII characters (A-Z).
638
+ raise LintError, "uppercase character in header name: #{key}" if key =~ /[A-Z]/
639
+
640
+ ## Header values must be either a String instance,
641
+ if value.kind_of?(String)
642
+ check_header_value(key, value)
643
+ elsif value.kind_of?(Array)
644
+ ## or an Array of String instances,
645
+ value.each{|value| check_header_value(key, value)}
646
+ else
647
+ raise LintError, "a header value must be a String or Array of Strings, but the value of '#{key}' is a #{value.class}"
648
+ end
649
+ end
497
650
  end
498
651
 
499
- ## * +puts+ must be called with a single argument that responds to +to_s+.
500
- def puts(str)
501
- @error.puts str
652
+ def check_header_value(key, value)
653
+ ## such that each String instance must not contain characters below 037.
654
+ if value =~ /[\000-\037]/
655
+ raise LintError, "invalid header value #{key}: #{value.inspect}"
656
+ end
502
657
  end
503
658
 
504
- ## * +write+ must be called with a single argument that is a String.
505
- def write(str)
506
- raise LintError, "rack.errors#write not called with a String" unless str.kind_of? String
507
- @error.write str
659
+ ##
660
+ ## === The content-type
661
+ ##
662
+ def check_content_type(status, headers)
663
+ headers.each { |key, value|
664
+ ## There must not be a <tt>content-type</tt> header key when the +Status+ is 1xx,
665
+ ## 204, or 304.
666
+ if key == "content-type"
667
+ if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i
668
+ raise LintError, "content-type header found in #{status} response, not allowed"
669
+ end
670
+ return
671
+ end
672
+ }
508
673
  end
509
674
 
510
- ## * +flush+ must be called without arguments and must be called
511
- ## in order to make the error appear for sure.
512
- def flush
513
- @error.flush
675
+ ##
676
+ ## === The content-length
677
+ ##
678
+ def check_content_length(status, headers)
679
+ headers.each { |key, value|
680
+ if key == 'content-length'
681
+ ## There must not be a <tt>content-length</tt> header key when the
682
+ ## +Status+ is 1xx, 204, or 304.
683
+ if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i
684
+ raise LintError, "content-length header found in #{status} response, not allowed"
685
+ end
686
+ @content_length = value
687
+ end
688
+ }
514
689
  end
515
690
 
516
- ## * +close+ must never be called on the error stream.
517
- def close(*args)
518
- raise LintError, "rack.errors#close must not be called"
691
+ def verify_content_length(size)
692
+ if @head_request
693
+ unless size == 0
694
+ raise LintError, "Response body was given for HEAD request, but should be empty"
695
+ end
696
+ elsif @content_length
697
+ unless @content_length == size.to_s
698
+ raise LintError, "content-length header was #{@content_length}, but should be #{size}"
699
+ end
700
+ end
519
701
  end
520
- end
521
-
522
- class HijackWrapper
523
- include Assertion
524
- extend Forwardable
525
702
 
526
- REQUIRED_METHODS = [
527
- :read, :write, :read_nonblock, :write_nonblock, :flush, :close,
528
- :close_read, :close_write, :closed?
529
- ]
703
+ ##
704
+ ## === The Body
705
+ ##
706
+ ## The Body is typically an +Array+ of +String+ instances, an enumerable
707
+ ## that yields +String+ instances, a +Proc+ instance, or a File-like
708
+ ## object.
709
+ ##
710
+ ## The Body must respond to +each+ or +call+. It may optionally respond
711
+ ## to +to_path+ or +to_ary+. A Body that responds to +each+ is considered
712
+ ## to be an Enumerable Body. A Body that responds to +call+ is considered
713
+ ## to be a Streaming Body.
714
+ ##
715
+ ## A Body that responds to both +each+ and +call+ must be treated as an
716
+ ## Enumerable Body, not a Streaming Body. If it responds to +each+, you
717
+ ## must call +each+ and not +call+. If the Body doesn't respond to
718
+ ## +each+, then you can assume it responds to +call+.
719
+ ##
720
+ ## The Body must either be consumed or returned. The Body is consumed by
721
+ ## optionally calling either +each+ or +call+.
722
+ ## Then, if the Body responds to +close+, it must be called to release
723
+ ## any resources associated with the generation of the body.
724
+ ## In other words, +close+ must always be called at least once; typically
725
+ ## after the web server has sent the response to the client, but also in
726
+ ## cases where the Rack application makes internal/virtual requests and
727
+ ## discards the response.
728
+ ##
729
+ def close
730
+ ##
731
+ ## After calling +close+, the Body is considered closed and should not
732
+ ## be consumed again.
733
+ @closed = true
530
734
 
531
- def_delegators :@io, *REQUIRED_METHODS
735
+ ## If the original Body is replaced by a new Body, the new Body must
736
+ ## also consume the original Body by calling +close+ if possible.
737
+ @body.close if @body.respond_to?(:close)
532
738
 
533
- def initialize(io)
534
- @io = io
535
- REQUIRED_METHODS.each do |meth|
536
- raise LintError, "rack.hijack_io must respond to #{meth}" unless io.respond_to? meth
739
+ index = @lint.index(self)
740
+ unless @env['rack.lint'][0..index].all? {|lint| lint.instance_variable_get(:@closed)}
741
+ raise LintError, "Body has not been closed"
537
742
  end
538
743
  end
539
- end
540
-
541
- ## === Hijacking
542
- #
543
- # AUTHORS: n.b. The trailing whitespace between paragraphs is important and
544
- # should not be removed. The whitespace creates paragraphs in the RDoc
545
- # output.
546
- #
547
- ## ==== Request (before status)
548
- def check_hijack(env)
549
- if env[RACK_IS_HIJACK]
550
- ## If rack.hijack? is true then rack.hijack must respond to #call.
551
- original_hijack = env[RACK_HIJACK]
552
- raise LintError, "rack.hijack must respond to call" unless original_hijack.respond_to?(:call)
553
- env[RACK_HIJACK] = proc do
554
- ## rack.hijack must return the io that will also be assigned (or is
555
- ## already present, in rack.hijack_io.
556
- io = original_hijack.call
557
- HijackWrapper.new(io)
558
- ##
559
- ## rack.hijack_io must respond to:
560
- ## <tt>read, write, read_nonblock, write_nonblock, flush, close,
561
- ## close_read, close_write, closed?</tt>
562
- ##
563
- ## The semantics of these IO methods must be a best effort match to
564
- ## those of a normal ruby IO or Socket object, using standard
565
- ## arguments and raising standard exceptions. Servers are encouraged
566
- ## to simply pass on real IO objects, although it is recognized that
567
- ## this approach is not directly compatible with SPDY and HTTP 2.0.
568
- ##
569
- ## IO provided in rack.hijack_io should preference the
570
- ## IO::WaitReadable and IO::WaitWritable APIs wherever supported.
571
- ##
572
- ## There is a deliberate lack of full specification around
573
- ## rack.hijack_io, as semantics will change from server to server.
574
- ## Users are encouraged to utilize this API with a knowledge of their
575
- ## server choice, and servers may extend the functionality of
576
- ## hijack_io to provide additional features to users. The purpose of
577
- ## rack.hijack is for Rack to "get out of the way", as such, Rack only
578
- ## provides the minimum of specification and support.
579
- env[RACK_HIJACK_IO] = HijackWrapper.new(env[RACK_HIJACK_IO])
580
- io
581
- end
582
- else
583
- ##
584
- ## If rack.hijack? is false, then rack.hijack should not be set.
585
- raise LintError, "rack.hijack? is false, but rack.hijack is present" unless env[RACK_HIJACK].nil?
586
- ##
587
- ## If rack.hijack? is false, then rack.hijack_io should not be set.
588
- raise LintError, "rack.hijack? is false, but rack.hijack_io is present" unless env[RACK_HIJACK_IO].nil?
589
- end
590
- end
591
744
 
592
- ## ==== Response (after headers)
593
- ## It is also possible to hijack a response after the status and headers
594
- ## have been sent.
595
- def check_hijack_response(headers, env)
596
-
597
- # this check uses headers like a hash, but the spec only requires
598
- # headers respond to #each
599
- headers = Rack::Utils::HeaderHash[headers]
600
-
601
- ## In order to do this, an application may set the special header
602
- ## <tt>rack.hijack</tt> to an object that responds to <tt>call</tt>
603
- ## accepting an argument that conforms to the <tt>rack.hijack_io</tt>
604
- ## protocol.
605
- ##
606
- ## After the headers have been sent, and this hijack callback has been
607
- ## called, the application is now responsible for the remaining lifecycle
608
- ## of the IO. The application is also responsible for maintaining HTTP
609
- ## semantics. Of specific note, in almost all cases in the current SPEC,
610
- ## applications will have wanted to specify the header Connection:close in
611
- ## HTTP/1.1, and not Connection:keep-alive, as there is no protocol for
612
- ## returning hijacked sockets to the web server. For that purpose, use the
613
- ## body streaming API instead (progressively yielding strings via each).
614
- ##
615
- ## Servers must ignore the <tt>body</tt> part of the response tuple when
616
- ## the <tt>rack.hijack</tt> response API is in use.
617
-
618
- if env[RACK_IS_HIJACK] && headers[RACK_HIJACK]
619
- unless headers[RACK_HIJACK].respond_to? :call
620
- raise LintError, 'rack.hijack header must respond to #call'
621
- end
622
- original_hijack = headers[RACK_HIJACK]
623
- proc do |io|
624
- original_hijack.call HijackWrapper.new(io)
625
- end
626
- else
745
+ def verify_to_path
627
746
  ##
628
- ## The special response header <tt>rack.hijack</tt> must only be set
629
- ## if the request env has <tt>rack.hijack?</tt> <tt>true</tt>.
630
- unless headers[RACK_HIJACK].nil?
631
- raise LintError, 'rack.hijack header must not be present if server does not support hijacking'
747
+ ## If the Body responds to +to_path+, it must return a +String+
748
+ ## path for the local file system whose contents are identical
749
+ ## to that produced by calling +each+; this may be used by the
750
+ ## server as an alternative, possibly more efficient way to
751
+ ## transport the response. The +to_path+ method does not consume
752
+ ## the body.
753
+ if @body.respond_to?(:to_path)
754
+ unless ::File.exist? @body.to_path
755
+ raise LintError, "The file identified by body.to_path does not exist"
756
+ end
632
757
  end
633
-
634
- nil
635
758
  end
636
- end
637
- ## ==== Conventions
638
- ## * Middleware should not use hijack unless it is handling the whole
639
- ## response.
640
- ## * Middleware may wrap the IO object for the response pattern.
641
- ## * Middleware should not wrap the IO object for the request pattern. The
642
- ## request pattern is intended to provide the hijacker with "raw tcp".
643
-
644
- ## == The Response
645
-
646
- ## === The Status
647
- def check_status(status)
648
- ## This is an HTTP status. When parsed as integer (+to_i+), it must be
649
- ## greater than or equal to 100.
650
- unless status.to_i >= 100
651
- raise LintError, "Status must be >=100 seen as integer"
652
- end
653
- end
654
759
 
655
- ## === The Headers
656
- def check_headers(header)
657
- ## The header must respond to +each+, and yield values of key and value.
658
- unless header.respond_to? :each
659
- raise LintError, "headers object should respond to #each, but doesn't (got #{header.class} as headers)"
660
- end
760
+ ##
761
+ ## ==== Enumerable Body
762
+ ##
763
+ def each
764
+ ## The Enumerable Body must respond to +each+.
765
+ raise LintError, "Enumerable Body must respond to each" unless @body.respond_to?(:each)
661
766
 
662
- header.each { |key, value|
663
- ## The header keys must be Strings.
664
- unless key.kind_of? String
665
- raise LintError, "header key must be a string, was #{key.class}"
666
- end
767
+ ## It must only be called once.
768
+ raise LintError, "Response body must only be invoked once (#{@invoked})" unless @invoked.nil?
667
769
 
668
- ## Special headers starting "rack." are for communicating with the
669
- ## server, and must not be sent back to the client.
670
- next if key =~ /^rack\..+$/
770
+ ## It must not be called after being closed.
771
+ raise LintError, "Response body is already closed" if @closed
671
772
 
672
- ## The header must not contain a +Status+ key.
673
- raise LintError, "header must not contain Status" if key.downcase == "status"
674
- ## The header must conform to RFC7230 token specification, i.e. cannot
675
- ## contain non-printable ASCII, DQUOTE or "(),/:;<=>?@[\]{}".
676
- raise LintError, "invalid header name: #{key}" if key =~ /[\(\),\/:;<=>\?@\[\\\]{}[:cntrl:]]/
773
+ @invoked = :each
677
774
 
678
- ## The values of the header must be Strings,
679
- unless value.kind_of? String
680
- raise LintError, "a header value must be a String, but the value of '#{key}' is a #{value.class}"
681
- end
682
- ## consisting of lines (for multiple header values, e.g. multiple
683
- ## <tt>Set-Cookie</tt> values) separated by "\\n".
684
- value.split("\n").each { |item|
685
- ## The lines must not contain characters below 037.
686
- if item =~ /[\000-\037]/
687
- raise LintError, "invalid header value #{key}: #{item.inspect}"
775
+ @body.each do |chunk|
776
+ ## and must only yield String values.
777
+ unless chunk.kind_of? String
778
+ raise LintError, "Body yielded non-string value #{chunk.inspect}"
688
779
  end
689
- }
690
- }
691
- end
692
780
 
693
- ## === The Content-Type
694
- def check_content_type(status, headers)
695
- headers.each { |key, value|
696
- ## There must not be a <tt>Content-Type</tt>, when the +Status+ is 1xx,
697
- ## 204 or 304.
698
- if key.downcase == "content-type"
699
- if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i
700
- raise LintError, "Content-Type header found in #{status} response, not allowed"
781
+ ##
782
+ ## The Body itself should not be an instance of String, as this will
783
+ ## break in Ruby 1.9.
784
+ ##
785
+ ## Middleware must not call +each+ directly on the Body.
786
+ ## Instead, middleware can return a new Body that calls +each+ on the
787
+ ## original Body, yielding at least once per iteration.
788
+ if @lint[0] == self
789
+ @env['rack.lint.body_iteration'] += 1
790
+ else
791
+ if (@env['rack.lint.body_iteration'] -= 1) > 0
792
+ raise LintError, "New body must yield at least once per iteration of old body"
793
+ end
701
794
  end
702
- return
703
- end
704
- }
705
- end
706
795
 
707
- ## === The Content-Length
708
- def check_content_length(status, headers)
709
- headers.each { |key, value|
710
- if key.downcase == 'content-length'
711
- ## There must not be a <tt>Content-Length</tt> header when the
712
- ## +Status+ is 1xx, 204 or 304.
713
- if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i
714
- raise LintError, "Content-Length header found in #{status} response, not allowed"
715
- end
716
- @content_length = value
796
+ @size += chunk.bytesize
797
+ yield chunk
717
798
  end
718
- }
719
- end
720
799
 
721
- def verify_content_length(bytes)
722
- if @head_request
723
- unless bytes == 0
724
- raise LintError, "Response body was given for HEAD request, but should be empty"
725
- end
726
- elsif @content_length
727
- unless @content_length == bytes.to_s
728
- raise LintError, "Content-Length header was #{@content_length}, but should be #{bytes}"
729
- end
730
- end
731
- end
800
+ verify_content_length(@size)
732
801
 
733
- ## === The Body
734
- def each
735
- @closed = false
736
- bytes = 0
802
+ verify_to_path
803
+ end
737
804
 
738
- ## The Body must respond to +each+
739
- unless @body.respond_to?(:each)
740
- raise LintError, "Response body must respond to each"
805
+ def respond_to?(name, *)
806
+ if name == :to_ary
807
+ @body.respond_to?(name)
808
+ else
809
+ super
810
+ end
741
811
  end
742
812
 
743
- @body.each { |part|
744
- ## and must only yield String values.
745
- unless part.kind_of? String
746
- raise LintError, "Body yielded non-string value #{part.inspect}"
813
+ ##
814
+ ## If the Body responds to +to_ary+, it must return an +Array+ whose
815
+ ## contents are identical to that produced by calling +each+.
816
+ ## Middleware may call +to_ary+ directly on the Body and return a new
817
+ ## Body in its place. In other words, middleware can only process the
818
+ ## Body directly if it responds to +to_ary+. If the Body responds to both
819
+ ## +to_ary+ and +close+, its implementation of +to_ary+ must call
820
+ ## +close+.
821
+ def to_ary
822
+ @body.to_ary.tap do |content|
823
+ unless content == @body.enum_for.to_a
824
+ raise LintError, "#to_ary not identical to contents produced by calling #each"
825
+ end
747
826
  end
748
- bytes += part.bytesize
749
- yield part
750
- }
751
- verify_content_length(bytes)
827
+ ensure
828
+ close
829
+ end
752
830
 
753
831
  ##
754
- ## The Body itself should not be an instance of String, as this will
755
- ## break in Ruby 1.9.
832
+ ## ==== Streaming Body
756
833
  ##
757
- ## If the Body responds to +close+, it will be called after iteration. If
758
- ## the body is replaced by a middleware after action, the original body
759
- ## must be closed first, if it responds to close.
760
- # XXX howto: raise LintError, "Body has not been closed" unless @closed
834
+ def call(stream)
835
+ ## The Streaming Body must respond to +call+.
836
+ raise LintError, "Streaming Body must respond to call" unless @body.respond_to?(:call)
761
837
 
838
+ ## It must only be called once.
839
+ raise LintError, "Response body must only be invoked once (#{@invoked})" unless @invoked.nil?
762
840
 
763
- ##
764
- ## If the Body responds to +to_path+, it must return a String
765
- ## identifying the location of a file whose contents are identical
766
- ## to that produced by calling +each+; this may be used by the
767
- ## server as an alternative, possibly more efficient way to
768
- ## transport the response.
841
+ ## It must not be called after being closed.
842
+ raise LintError, "Response body is already closed" if @closed
769
843
 
770
- if @body.respond_to?(:to_path)
771
- unless ::File.exist? @body.to_path
772
- raise LintError, "The file identified by body.to_path does not exist"
773
- end
844
+ @invoked = :call
845
+
846
+ ## It takes a +stream+ argument.
847
+ ##
848
+ ## The +stream+ argument must implement:
849
+ ## <tt>read, write, flush, close, close_read, close_write, closed?</tt>
850
+ ##
851
+ @body.call(StreamWrapper.new(stream))
774
852
  end
775
853
 
776
- ##
777
- ## The Body commonly is an Array of Strings, the application
778
- ## instance itself, or a File-like object.
779
- end
854
+ class StreamWrapper
855
+ extend Forwardable
780
856
 
781
- def close
782
- @closed = true
783
- @body.close if @body.respond_to?(:close)
784
- end
857
+ ## The semantics of these IO methods must be a best effort match to
858
+ ## those of a normal Ruby IO or Socket object, using standard arguments
859
+ ## and raising standard exceptions. Servers are encouraged to simply
860
+ ## pass on real IO objects, although it is recognized that this approach
861
+ ## is not directly compatible with HTTP/2.
862
+ REQUIRED_METHODS = [
863
+ :read, :write, :flush, :close,
864
+ :close_read, :close_write, :closed?
865
+ ]
785
866
 
786
- # :startdoc:
867
+ def_delegators :@stream, *REQUIRED_METHODS
787
868
 
869
+ def initialize(stream)
870
+ @stream = stream
871
+
872
+ REQUIRED_METHODS.each do |method_name|
873
+ raise LintError, "Stream must respond to #{method_name}" unless stream.respond_to?(method_name)
874
+ end
875
+ end
876
+ end
877
+
878
+ # :startdoc:
879
+ end
788
880
  end
789
881
  end
790
882
 
883
+ ##
791
884
  ## == Thanks
792
- ## Some parts of this specification are adopted from PEP333: Python
793
- ## Web Server Gateway Interface
794
- ## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
795
- ## everyone involved in that effort.
885
+ ## Some parts of this specification are adopted from {PEP 333 – Python Web Server Gateway Interface v1.0}[https://peps.python.org/pep-0333/]
886
+ ## I'd like to thank everyone involved in that effort.