rack 2.2.7 → 3.1.8

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