rack 2.0.9.3 → 3.0.0

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