puma 8.1.3-java → 8.2.0.pre1-java

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +4 -4
  2. data/History.md +120 -0
  3. data/README.md +4 -3
  4. data/docs/GLOSSARY.md +160 -0
  5. data/docs/architecture.md +41 -42
  6. data/docs/binding.md +3 -0
  7. data/docs/cluster_mode.md +21 -21
  8. data/docs/control_server.md +4 -4
  9. data/docs/deployment/nginx.md +2 -0
  10. data/docs/deployment/systemd.md +15 -0
  11. data/docs/puma_support.md +12 -0
  12. data/docs/restart.md +2 -2
  13. data/docs/signals.md +3 -3
  14. data/docs/ssl.md +65 -0
  15. data/docs/upgrading/5.0-Upgrade.md +1 -1
  16. data/docs/upgrading/6.0-Upgrade.md +1 -1
  17. data/docs/upgrading/7.0-Upgrade.md +1 -1
  18. data/docs/upgrading/8.0-Upgrade.md +1 -1
  19. data/lib/puma/app/status.rb +22 -7
  20. data/lib/puma/binder.rb +0 -1
  21. data/lib/puma/cli.rb +1 -3
  22. data/lib/puma/client.rb +133 -57
  23. data/lib/puma/client_env.rb +9 -11
  24. data/lib/puma/cluster/worker.rb +0 -6
  25. data/lib/puma/cluster.rb +3 -14
  26. data/lib/puma/cluster_accept_loop_delay.rb +18 -7
  27. data/lib/puma/commonlogger.rb +3 -4
  28. data/lib/puma/configuration.rb +4 -1
  29. data/lib/puma/const.rb +5 -5
  30. data/lib/puma/control_cli.rb +5 -7
  31. data/lib/puma/detect.rb +1 -1
  32. data/lib/puma/dsl.rb +70 -14
  33. data/lib/puma/http_parser_error.rb +8 -0
  34. data/lib/puma/launcher/bundle_pruner.rb +3 -21
  35. data/lib/puma/launcher.rb +55 -25
  36. data/lib/puma/minissl/context_builder.rb +3 -2
  37. data/lib/puma/minissl.rb +12 -16
  38. data/lib/puma/plugin/systemd.rb +69 -3
  39. data/lib/puma/puma_http11.jar +0 -0
  40. data/lib/puma/rack/urlmap.rb +2 -2
  41. data/lib/puma/reactor.rb +138 -25
  42. data/lib/puma/response.rb +65 -38
  43. data/lib/puma/runner.rb +4 -1
  44. data/lib/puma/sd_notify.rb +21 -0
  45. data/lib/puma/server.rb +14 -14
  46. data/lib/puma/server_plugin_control.rb +2 -1
  47. data/lib/puma/single.rb +0 -1
  48. data/lib/puma/thread_pool.rb +87 -14
  49. data/lib/puma/util.rb +5 -16
  50. data/lib/puma.rb +22 -5
  51. data/lib/rack/handler/puma.rb +1 -5
  52. metadata +5 -2
@@ -68,6 +68,21 @@ See
68
68
  [systemd.exec](https://www.freedesktop.org/software/systemd/man/systemd.exec.html)
69
69
  for additional details.
70
70
 
71
+ ### Startup timeout extension
72
+
73
+ If boot time varies too much for a fixed `TimeoutStartSec`, set
74
+ `PUMA_EXTEND_TIMEOUT_SEC`. Until `READY=1`, Puma keeps asking systemd for that
75
+ many more seconds. `PUMA_EXTEND_TIMEOUT_MAX_SEC` optionally caps the total,
76
+ counted from when Puma loads its systemd plugin.
77
+
78
+ ~~~~ ini
79
+ Environment=PUMA_EXTEND_TIMEOUT_SEC=30
80
+ Environment=PUMA_EXTEND_TIMEOUT_MAX_SEC=600
81
+ ~~~~
82
+
83
+ Extensions start after Puma reads its config, so `ExecStartPre=` and config
84
+ loading must still fit in `TimeoutStartSec`.
85
+
71
86
  ## Socket Activation
72
87
 
73
88
  systemd and Puma also support socket activation, where systemd opens the
data/docs/puma_support.md CHANGED
@@ -20,6 +20,8 @@ CI aims for the most coverage with the fewest jobs.
20
20
 
21
21
  Every OS and architecture runs the oldest supported Ruby on its oldest runner image, and the newest Ruby on its newest image.
22
22
 
23
+ "Runner images" means every standard GitHub-hosted runner image currently listed in [GitHub's runner docs](https://docs.github.com/en/actions/reference/runners/github-hosted-runners#supported-runners-and-hardware-resources), not only the images CI already uses.
24
+
23
25
  On x64, a few more jobs fill in the gaps:
24
26
 
25
27
  - The newest Ubuntu image that can build every supported Ruby runs all of them.
@@ -28,6 +30,14 @@ On x64, a few more jobs fill in the gaps:
28
30
  - The oldest Ubuntu and Windows images also run the oldest Ruby without SSL.
29
31
  - The oldest Ubuntu image also runs the oldest Ruby with the oldest supported Rack.
30
32
 
33
+ ## Versioning
34
+
35
+ Puma follows [SemVer 2.0](https://semver.org/). Puma's public API is its HTTP serving behavior over the socket and its configuration. All of Puma's other Ruby APIs are private and may change in any release.
36
+
37
+ Puma is an HTTP/1.1 server, so any deviation from the relevant RFCs is a bug, which we may fix in a patch release.
38
+
39
+ PRs labeled `breaking change` are strong evidence that a major release is needed.
40
+
31
41
  ## Puma release support policy
32
42
 
33
43
  By default, Puma supports one release version, the latest release. That means if there is a bug in 3.2.1 (made-up numbers for example only), but the latest release is 4.3.2, the bug must be reproduced in 4.3.2 to qualify for support.
@@ -36,6 +46,8 @@ When a new major (and sometimes minor) version is released, Puma maintainers wil
36
46
 
37
47
  If a bug report cannot be reproduced with the latest Puma version, it may be closed.
38
48
 
49
+ Security fixes follow a separate policy; see [SECURITY.md](../governance/SECURITY.md#supported-versions).
50
+
39
51
  ## Ruby version support policy
40
52
 
41
53
  "Ruby version" refers to the https://github.com/ruby/ruby implementation. Puma also supports other Ruby implementations (the origin of Puma involves an alternate Ruby implementation, Rubinius); see below.
data/docs/restart.md CHANGED
@@ -15,7 +15,7 @@ If the new process is unable to load, it will simply exit. You should therefore
15
15
  Any of the following will cause a Puma server to perform a hot restart:
16
16
 
17
17
  * Send the `puma` process the `SIGUSR2` signal
18
- * Issue a `GET` request to the Puma status/control server with the path `/restart`
18
+ * Issue a `GET` request to the Puma control server with the path `/restart`
19
19
  * Issue `pumactl restart` (this uses the control server method if available, otherwise sends the `SIGUSR2` signal to the process)
20
20
 
21
21
  ### Supported configurations
@@ -45,7 +45,7 @@ Phased restarts replace all running workers in a Puma cluster. This is a useful
45
45
  Any of the following will cause a Puma server to perform a phased restart:
46
46
 
47
47
  * Send the `puma` process the `SIGUSR1` signal
48
- * Issue a `GET` request to the Puma status/control server with the path `/phased-restart`
48
+ * Issue a `GET` request to the Puma control server with the path `/phased-restart`
49
49
  * Issue `pumactl phased-restart` (this uses the control server method if available, otherwise sends the `SIGUSR1` signal to the process)
50
50
 
51
51
  ### Supported configurations
data/docs/signals.md CHANGED
@@ -38,11 +38,11 @@ Puma cluster responds to these signals:
38
38
  - `TTIN`: Increment the worker count by 1.
39
39
  - `TTOU`: Decrement the worker count by 1.
40
40
  - `TERM`: Send `TERM` to worker. The worker will attempt to finish then exit.
41
- - `USR2`: Restart workers. This also reloads the Puma configuration file, if there is one.
42
- - `USR1`: Restart workers in phases, a rolling restart. This will not reload the configuration file.
41
+ - `USR2`: Perform a [hot restart](restart.md#hot-restart). This also reloads the Puma configuration file, if there is one.
42
+ - `USR1`: Restart workers one at a time, a [phased restart](restart.md#phased-restart). This will not reload the configuration file.
43
43
  - `HUP`: Reopen log files defined in `stdout_redirect` configuration parameter. If there is no `stdout_redirect` option provided, it will behave like `INT`.
44
44
  - `INT`: Equivalent of sending Ctrl-C to cluster. Puma will attempt to finish then exit.
45
- - `CHLD`: Reap zombie child processes and wake event loop in `fork_worker` and `mold_worker` modes.
45
+ - `CHLD`: Reap zombie child processes and wake the master in `fork_worker` and `mold_worker` modes.
46
46
  - `URG`: Refork workers in phases from worker 0 if `fork_worker` option is enabled, or from a newly promoted mold if `mold_worker` option is enabled.
47
47
  - `INFO` (or `PWR` for systems without `INFO`) print backtraces of all puma threads (if supported on your platform).
48
48
 
data/docs/ssl.md ADDED
@@ -0,0 +1,65 @@
1
+ # HTTPS with Puma
2
+
3
+ There are two common setups:
4
+
5
+ 1. **TLS terminates at a reverse proxy** (nginx, a load balancer, a CDN). The proxy holds the certificate and talks plain HTTP to Puma over TCP or a Unix socket. Puma needs no SSL configuration.
6
+ 2. **TLS terminates in Puma** with an `ssl://` bind or `ssl_bind`. Useful for local HTTPS, or when nothing sits in front of Puma.
7
+
8
+ ## TLS at a reverse proxy
9
+
10
+ Bind Puma to a plain socket:
11
+
12
+ ```ruby
13
+ # config/puma.rb
14
+ bind 'unix:///myapp/tmp/puma.sock'
15
+ # Or, when the proxy cannot share a filesystem with Puma (for example, separate containers):
16
+ # bind 'tcp://0.0.0.0:9292'
17
+ ```
18
+
19
+ Terminate TLS in nginx and tell the app the original request was HTTPS:
20
+
21
+ ```nginx
22
+ upstream myapp {
23
+ server unix:///myapp/tmp/puma.sock;
24
+ }
25
+
26
+ server {
27
+ listen 443 ssl;
28
+ server_name myapp.com;
29
+
30
+ ssl_certificate /etc/nginx/certs/cert.pem;
31
+ ssl_certificate_key /etc/nginx/certs/key.pem;
32
+
33
+ location / {
34
+ proxy_pass http://myapp;
35
+ proxy_set_header Host $host;
36
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
37
+ proxy_set_header X-Forwarded-Proto https;
38
+ }
39
+ }
40
+ ```
41
+
42
+ Puma passes `X-Forwarded-Proto` through to the Rack env, and frameworks such as Rails use it to treat the request as HTTPS. If your proxy cannot set the header, `rack_url_scheme 'https'` in the Puma config sets `env['rack.url_scheme']` instead.
43
+
44
+ ## TLS in Puma
45
+
46
+ From the command line:
47
+
48
+ ```
49
+ $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert'
50
+ ```
51
+
52
+ Or in `config/puma.rb`:
53
+
54
+ ```ruby
55
+ ssl_bind '127.0.0.1', '9292', {
56
+ key: 'path_to_key',
57
+ cert: 'path_to_cert'
58
+ }
59
+ ```
60
+
61
+ Bind URLs name a socket type, not an HTTP scheme, so use `ssl://`. Puma accepts `tcp://`, `unix://`, and `ssl://`; `https://` is not a valid bind.
62
+
63
+ `verify_mode` controls client certificates, not whether HTTPS is on. The default, `none`, is right for an ordinary HTTPS server. `peer` and `force_peer` are for mutual TLS, usually together with `ca`.
64
+
65
+ See [`Puma::DSL#ssl_bind`](../lib/puma/dsl.rb) for every option, and [Binding TCP / Sockets and SSL](binding.md) for self-signed development certificates, cipher suites, and encrypted keys.
@@ -10,7 +10,7 @@ Puma 5 brings new experimental performance features, a few quality-of-life featu
10
10
  2. Upgrade to version 5.0 in your Gemfile and deploy.
11
11
  3. Try the new performance experiments outlined below and report your results back to the Puma issue tracker.
12
12
 
13
- Puma 5 was named Spoony Bard by our newest supercontributor, [@wjordan](https://github.com/puma/puma/commits?author=wjordan). Will brought you one of our new perf features for this release, as well as [many other fixes and refactors.](https://github.com/puma/puma/commits?author=wjordan) If you'd like to name a Puma release in the future, take a look at [CONTRIBUTING.md](../../CONTRIBUTING.md) and get started helping us out :)
13
+ Puma 5 was named Spoony Bard by our newest supercontributor, [@wjordan](https://github.com/puma/puma/commits?author=wjordan). Will brought you one of our new perf features for this release, as well as [many other fixes and refactors.](https://github.com/puma/puma/commits?author=wjordan) If you'd like to name a Puma release in the future, take a look at [CONTRIBUTING.md](../../governance/CONTRIBUTING.md) and get started helping us out :)
14
14
 
15
15
  Puma 5 also welcomes [@MSP-Greg](https://github.com/puma/puma/commits?author=MSP-Greg) as our newest committer. Greg has been instrumental in improving our CI setup and SSL features. Greg also [named our 4.3.0 release](https://github.com/puma/puma/releases/tag/v4.3.0): Mysterious Traveller.
16
16
 
@@ -9,7 +9,7 @@ Here's what you should do:
9
9
  1. Review the Upgrade section below to look for breaking changes that could affect you.
10
10
  2. Upgrade to version 6.0 in your Gemfile and deploy.
11
11
  3. Open up a new bug issue if you find any problems.
12
- 4. Join us in building Puma! We welcome first-timers. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
12
+ 4. Join us in building Puma! We welcome first-timers. See [CONTRIBUTING.md](../../governance/CONTRIBUTING.md).
13
13
 
14
14
  For a complete list of changes, see [History.md](../../History.md).
15
15
 
@@ -7,7 +7,7 @@ Here's what you should do:
7
7
  1. Review the Upgrade section below to look for breaking changes that could affect you.
8
8
  2. Upgrade to version 7.0 in your Gemfile and deploy.
9
9
  3. Open up a new bug issue if you find any problems.
10
- 4. Join us in building Puma! We welcome first-timers. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
10
+ 4. Join us in building Puma! We welcome first-timers. See [CONTRIBUTING.md](../../governance/CONTRIBUTING.md).
11
11
 
12
12
  For a complete list of changes, see [History.md](../../History.md).
13
13
 
@@ -7,7 +7,7 @@ Here's what you should do:
7
7
  1. Review the Upgrade section below to look for breaking changes that could affect you.
8
8
  2. Upgrade to version 8.0 in your Gemfile and deploy.
9
9
  3. Open up a new bug issue if you find any problems.
10
- 4. Join us in building Puma! We welcome first-timers. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
10
+ 4. Join us in building Puma! We welcome first-timers. See [CONTRIBUTING.md](../../governance/CONTRIBUTING.md).
11
11
 
12
12
  For a complete list of changes, see [History.md](../../History.md).
13
13
 
@@ -12,23 +12,31 @@ module Puma
12
12
  # @param launcher [::Puma::Launcher]
13
13
  # @param token [String, nil] the token used for authentication
14
14
  # @param data_only [Boolean] if true, restrict to read-only data commands
15
+ # @param data_token [String, Symbol, nil] optional token (or 'none' / :none) for read-only data commands
15
16
  #
16
- def initialize(launcher, token: nil, data_only: false)
17
+ def initialize(launcher, token: nil, data_only: false, data_token: nil)
17
18
  @launcher = launcher
18
19
  @auth_token = token
19
20
  @enabled_commands = READ_ONLY_COMMANDS if data_only
21
+ @data_token =
22
+ case data_token
23
+ when '' then nil
24
+ when 'none' then :none
25
+ else data_token
26
+ end
20
27
  end
21
28
 
22
29
  # most commands call methods in `::Puma::Launcher` based on command in
23
30
  # `env['PATH_INFO']`
24
31
  def call(env)
25
- unless authenticate(env)
26
- return rack_response(403, 'Invalid auth token', 'text/plain')
27
- end
28
-
29
32
  # resp_type is processed by following case statement, return
30
33
  # is a number (status) or a string used as the body of a 200 response
31
34
  command = env['PATH_INFO'][/\/([^\/]+)$/, 1]
35
+
36
+ unless authenticate(env, command)
37
+ return rack_response(403, 'Invalid auth token', 'text/plain')
38
+ end
39
+
32
40
  if @enabled_commands && !@enabled_commands.include?(command)
33
41
  return rack_response(404, "Command #{command.inspect} unavailable", 'text/plain')
34
42
  end
@@ -86,9 +94,16 @@ module Puma
86
94
 
87
95
  private
88
96
 
89
- def authenticate(env)
97
+ def authenticate(env, command)
90
98
  return true unless @auth_token
91
- env['QUERY_STRING'].to_s.split(/[&;]/).include? "token=#{@auth_token}"
99
+ return true if token_matches?(env, @auth_token)
100
+ return false unless @data_token && READ_ONLY_COMMANDS.include?(command)
101
+
102
+ @data_token == :none || token_matches?(env, @data_token)
103
+ end
104
+
105
+ def token_matches?(env, token)
106
+ env['QUERY_STRING'].to_s.split(/[&;]/).include?("token=#{token}")
92
107
  end
93
108
 
94
109
  def rack_response(status, body, content_type='application/json')
data/lib/puma/binder.rb CHANGED
@@ -234,7 +234,6 @@ module Puma
234
234
  # If key and certs are not defined and localhost gem is required.
235
235
  # localhost gem will be used for self signed
236
236
  # Load localhost authority if not loaded.
237
- # Ruby 3 `values_at` accepts an array, earlier do not
238
237
  if params.values_at(*cert_key).all? { |v| v.to_s.empty? }
239
238
  ctx = localhost_authority && localhost_authority_context(params)
240
239
  end
data/lib/puma/cli.rb CHANGED
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'optparse'
4
- require 'uri'
5
4
 
6
5
  require_relative '../puma'
7
6
  require_relative 'configuration'
@@ -25,7 +24,6 @@ module Puma
25
24
  # arguments.
26
25
  #
27
26
  def initialize(argv, log_writer = LogWriter.stdio, events = Events.new, env: ENV)
28
- @debug = false
29
27
  @argv = argv.dup
30
28
  @log_writer = log_writer
31
29
  @events = events
@@ -92,7 +90,7 @@ module Puma
92
90
 
93
91
  def setup_options(env = ENV)
94
92
  @conf = Configuration.new({}, { events: @events }, env) do |user_config, file_config|
95
- @parser = OptionParser.new do |o|
93
+ OptionParser.new do |o|
96
94
  o.on "-b", "--bind URI", "URI to bind to (tcp://, unix://, ssl://)" do |arg|
97
95
  user_config.bind arg
98
96
  end
data/lib/puma/client.rb CHANGED
@@ -3,16 +3,10 @@
3
3
  require_relative 'detect'
4
4
  require_relative 'io_buffer'
5
5
  require_relative 'client_env'
6
+ require_relative 'http_parser_error'
6
7
  require_relative 'null_io'
7
8
  require 'tempfile'
8
9
 
9
- if Puma::IS_JRUBY
10
- # We have to work around some OpenSSL buffer/io-readiness bugs
11
- # so we pull it in regardless of if the user is binding
12
- # to an SSL socket
13
- require 'openssl'
14
- end
15
-
16
10
  module Puma
17
11
 
18
12
  class ConnectionError < RuntimeError; end
@@ -57,10 +51,16 @@ module Puma
57
51
  # this tests all values but the last, which must be chunked
58
52
  ALLOWED_TRANSFER_ENCODING = %w[compress deflate gzip].freeze
59
53
 
60
- # chunked body validation
54
+ # chunked body validation (RFC 9112 §7.1, §7.1.1)
61
55
  CHUNK_SIZE_VALID = /\A\h+\z/.freeze
56
+ CHUNK_EXT_TCHAR = /[!#$%&'*+\-.^_`|~0-9A-Za-z]/.freeze
57
+ CHUNK_EXT_TOKEN = /#{CHUNK_EXT_TCHAR}+/.freeze
58
+ CHUNK_EXT_QUOTED = /"(?:[\t \x21\x23-\x5B\x5D-\x7E\x80-\xFF]|\\[\t \x21-\x7E\x80-\xFF])*"/n.freeze
59
+ CHUNK_EXT_VALID = /\A(?:[ \t]*;[ \t]*#{CHUNK_EXT_TOKEN}(?:[ \t]*=[ \t]*(?:#{CHUNK_EXT_TOKEN}|#{CHUNK_EXT_QUOTED}))?)+\z/n.freeze
62
60
  CHUNK_VALID_ENDING = Const::LINE_END
63
61
  CHUNK_VALID_ENDING_SIZE = CHUNK_VALID_ENDING.bytesize
62
+ BARE_LF = /(?<!\r)\n/.freeze
63
+ private_constant :CHUNK_EXT_TCHAR, :CHUNK_EXT_TOKEN, :CHUNK_EXT_QUOTED, :CHUNK_EXT_VALID, :BARE_LF
64
64
 
65
65
  # The maximum number of bytes we'll buffer looking for a valid
66
66
  # chunk header, and the maximum size of a trailer section.
@@ -94,27 +94,30 @@ module Puma
94
94
  :allow_underscore_headers, :continue_callback
95
95
 
96
96
  attr_accessor :remote_addr_header, :listener, :env_set_http_version,
97
- :reactor_error
97
+ :reactor_error, :empty_rack_input
98
98
 
99
- def initialize(io, env=nil)
99
+ def initialize(io, env=nil, http_parser: nil)
100
100
  @io = io
101
101
  @to_io = io.to_io
102
102
  @io_buffer = IOBuffer.new
103
103
  @proto_env = env
104
104
  @env = env&.dup
105
105
 
106
- @parser = HttpParser.new
106
+ http_parser ||= Puma.default_http_parser
107
+ @parser = http_parser.respond_to?(:call) ? http_parser.call : http_parser.new
107
108
  @parsed_bytes = 0
108
109
  @read_header = true
109
110
  @read_proxy = false
110
111
  @ready = false
111
112
 
112
113
  @body = nil
114
+ @empty_rack_input = EmptyBody
113
115
  @body_read_start = nil
114
116
  @buffer = nil
115
117
  @tempfile = nil
116
118
 
117
119
  @timeout_at = nil
120
+ @header_deadline = nil
118
121
 
119
122
  @requests_served = 0
120
123
  @hijacked = false
@@ -142,7 +145,6 @@ module Puma
142
145
  @read_buffer = String.new # rubocop: disable Performance/UnfreezeString
143
146
  end
144
147
 
145
- # Remove in Puma 7?
146
148
  def closed?
147
149
  @to_io.closed?
148
150
  end
@@ -174,6 +176,14 @@ module Puma
174
176
  @timeout_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) + val
175
177
  end
176
178
 
179
+ def set_read_timeout(val)
180
+ set_timeout(val)
181
+ return if in_data_phase
182
+
183
+ @header_deadline ||= @timeout_at
184
+ @timeout_at = @header_deadline
185
+ end
186
+
177
187
  # Number of seconds until the timeout elapses.
178
188
  # @!attribute [r] timeout
179
189
  def timeout
@@ -193,6 +203,7 @@ module Puma
193
203
  @in_last_chunk = false
194
204
  @http_content_length_limit_exceeded = nil
195
205
  @error_status_code = nil
206
+ @header_deadline = nil
196
207
  end
197
208
 
198
209
  # only used with back-to-back requests contained in the buffer
@@ -318,12 +329,13 @@ module Puma
318
329
 
319
330
  def finish(timeout, &deadline)
320
331
  return if @ready
321
- set_timeout timeout
332
+ set_read_timeout timeout
322
333
  read = @bytes_read
323
334
  until try_to_finish(&deadline)
324
335
  if @bytes_read > read
325
- set_timeout timeout
336
+ set_read_timeout timeout
326
337
  read = @bytes_read
338
+ timeout! if !in_data_phase && self.timeout == 0
327
339
  elsif self.timeout == 0
328
340
  timeout!
329
341
  end
@@ -360,6 +372,12 @@ module Puma
360
372
  def parser_execute
361
373
  ret = @parser.execute(@env, @buffer, @parsed_bytes)
362
374
 
375
+ if (proto = @env[SERVER_PROTOCOL]) && proto != HTTP_11 && !proto.start_with?('HTTP/1.')
376
+ @error_status_code = 505
377
+ @env[HTTP_CONNECTION] = CLOSE
378
+ raise HttpParserError, "HTTP Version Not Supported: #{proto}"
379
+ end
380
+
363
381
  if @env[REQUEST_METHOD] && @supported_http_methods != :any && !@supported_http_methods.key?(@env[REQUEST_METHOD])
364
382
  raise HttpParserError501, "#{@env[REQUEST_METHOD]} method is not supported"
365
383
  end
@@ -392,10 +410,12 @@ module Puma
392
410
  # protocol is bad
393
411
  text = request_line[/[^ ]*\z/]
394
412
  raise HttpParserError, "Invalid HTTP format, parsing fails. Bad protocol #{text}"
395
- elsif !headers.empty?
413
+ elsif headers && !headers.empty?
396
414
  # headers are bad
397
415
  hdrs = headers.split("\r\n").map { |h| h.gsub "\n", '\n'}.join "\n"
398
416
  raise HttpParserError, "Invalid HTTP format, parsing fails. Bad headers\n#{hdrs}"
417
+ else
418
+ raise e
399
419
  end
400
420
  end
401
421
 
@@ -525,19 +545,20 @@ module Puma
525
545
 
526
546
  @body_read_start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
527
547
 
528
- if @env[HTTP_EXPECT] == CONTINUE
529
- if @continue_callback && (response = @continue_callback.call(@env))
530
- reject_continue response
531
- end
532
- write_interim HTTP_11_100
533
- end
534
-
535
- @read_header = false
536
-
537
- parser_body = @parser.body
538
-
539
548
  te = @env[TRANSFER_ENCODING2]
549
+ cl = @env[CONTENT_LENGTH]
550
+
540
551
  if te
552
+ if @env.key?(CONTENT_LENGTH)
553
+ @error_status_code = 400
554
+ @env[HTTP_CONNECTION] = CLOSE
555
+ raise HttpParserError, "#{TE_ERR_MSG}, cannot be combined with Content-Length"
556
+ end
557
+ if te.empty?
558
+ @error_status_code = 400
559
+ @env[HTTP_CONNECTION] = CLOSE
560
+ raise HttpParserError, "#{TE_ERR_MSG}, empty value"
561
+ end
541
562
  te_lwr = te.downcase
542
563
  if te.include? ','
543
564
  te_ary = te_lwr.split(',').each { |te| te.gsub!(STRIP_OWS, "") }
@@ -550,30 +571,38 @@ module Puma
550
571
  elsif !te_valid
551
572
  raise HttpParserError501, "#{TE_ERR_MSG}, unknown value: '#{te}'"
552
573
  end
553
- @env.delete TRANSFER_ENCODING2
554
- return setup_chunked_body parser_body
555
- elsif te_lwr == CHUNKED
556
- @env.delete TRANSFER_ENCODING2
557
- return setup_chunked_body parser_body
558
- elsif ALLOWED_TRANSFER_ENCODING.include? te_lwr
559
- raise HttpParserError , "#{TE_ERR_MSG}, single value must be chunked: '#{te}'"
560
- else
561
- raise HttpParserError501 , "#{TE_ERR_MSG}, unknown value: '#{te}'"
574
+ elsif te_lwr != CHUNKED
575
+ if ALLOWED_TRANSFER_ENCODING.include? te_lwr
576
+ raise HttpParserError , "#{TE_ERR_MSG}, single value must be chunked: '#{te}'"
577
+ else
578
+ raise HttpParserError501, "#{TE_ERR_MSG}, unknown value: '#{te}'"
579
+ end
562
580
  end
581
+ elsif cl && (CONTENT_LENGTH_VALUE_INVALID.match?(cl) || cl.empty?)
582
+ @error_status_code = 400
583
+ @env[HTTP_CONNECTION] = 'close'
584
+ raise HttpParserError, "Invalid Content-Length: #{cl.inspect}"
563
585
  end
564
586
 
565
- @chunked_body = false
587
+ if @env[HTTP_EXPECT] == CONTINUE && @env[SERVER_PROTOCOL] != HTTP_10
588
+ if @continue_callback && (response = @continue_callback.call(@env))
589
+ reject_continue response
590
+ end
591
+ write_interim HTTP_11_100
592
+ end
566
593
 
567
- cl = @env[CONTENT_LENGTH]
594
+ @read_header = false
568
595
 
569
- if cl
570
- # cannot contain characters that are not \d, or be empty
571
- if CONTENT_LENGTH_VALUE_INVALID.match?(cl) || cl.empty?
572
- @error_status_code = 400
573
- @env[HTTP_CONNECTION] = 'close'
574
- raise HttpParserError, "Invalid Content-Length: #{cl.inspect}"
575
- end
576
- else
596
+ parser_body = @parser.body
597
+
598
+ if te
599
+ @env.delete TRANSFER_ENCODING2
600
+ return setup_chunked_body parser_body
601
+ end
602
+
603
+ @chunked_body = false
604
+
605
+ unless cl
577
606
  @buffer = parser_body.empty? ? nil : parser_body
578
607
  @body = EmptyBody
579
608
  set_ready
@@ -710,13 +739,13 @@ module Puma
710
739
  @partial_part_left = 0
711
740
  @prev_chunk = ""
712
741
  @excess_cr = 0
713
-
714
- @body = Tempfile.create(Const::PUMA_TMP_BASE)
715
- File.unlink @body.path unless IS_WINDOWS
716
- @body.binmode
717
- @tempfile = @body
742
+ @tempfile = nil
718
743
  @chunked_content_length = 0
719
744
 
745
+ # The body[0,0] trick is to get an empty string in the same
746
+ # encoding as body.
747
+ @body = StringIO.new body[0,0]
748
+
720
749
  if decode_chunk(body)
721
750
  @env[CONTENT_LENGTH] = @chunked_content_length.to_s
722
751
  return true
@@ -725,17 +754,41 @@ module Puma
725
754
 
726
755
  # @version 5.0.0
727
756
  def write_chunk(str)
728
- if @http_content_length_limit&.< @chunked_content_length + str.bytesize
757
+ remain = @chunked_content_length + str.bytesize
758
+
759
+ if @http_content_length_limit&.< remain
729
760
  raise_above_http_content_limit
730
761
  end
731
762
 
763
+ # The length of a chunked body is unknown up front, so it starts in memory
764
+ # and moves to a Tempfile once it grows past MAX_BODY, similar to Content-Length.
765
+ if @tempfile.nil? && remain > MAX_BODY
766
+ @tempfile = Tempfile.create(Const::PUMA_TMP_BASE)
767
+ File.unlink @tempfile.path unless IS_WINDOWS
768
+ @tempfile.binmode
769
+ @tempfile.write @body.string
770
+ @body = @tempfile
771
+ @env[RACK_INPUT] = @body
772
+ end
773
+
732
774
  @chunked_content_length += @body.write(str)
733
775
  end
734
776
 
777
+ def check_chunk_ending(str, left)
778
+ (left - CHUNK_VALID_ENDING_SIZE...left).each do |i|
779
+ next if i < 0 || i >= str.bytesize
780
+
781
+ unless str.getbyte(i) == CHUNK_VALID_ENDING.getbyte(i - left + CHUNK_VALID_ENDING_SIZE)
782
+ raise HttpParserError, "Chunk size mismatch"
783
+ end
784
+ end
785
+ end
786
+
735
787
  def decode_chunk(chunk)
736
788
  return finish_last_chunk(@prev_chunk + chunk) if @in_last_chunk
737
789
 
738
790
  if @partial_part_left > 0
791
+ check_chunk_ending(chunk, @partial_part_left)
739
792
  if @partial_part_left <= chunk.size
740
793
  if @partial_part_left > 2
741
794
  write_chunk(chunk[0..(@partial_part_left-3)]) # skip the \r\n
@@ -767,11 +820,19 @@ module Puma
767
820
  while !io.eof?
768
821
  line = io.gets
769
822
  if line.end_with?(CHUNK_VALID_ENDING)
770
- # Puma doesn't process chunk extensions, but should parse if they're
771
- # present, which is the reason for the semicolon regex
772
- chunk_hex = line.strip[/\A[^;]+/]
773
- unless CHUNK_SIZE_VALID.match? chunk_hex
774
- err_msg = chunk_hex && !chunk_hex.empty? ?
823
+ header = line.b.byteslice(0, line.bytesize - CHUNK_VALID_ENDING_SIZE)
824
+ if semi = header.index(';')
825
+ chunk_hex = header.byteslice(0, semi).sub(/[ \t]+\z/, '')
826
+ chunk_ext = header.byteslice(semi, header.bytesize - semi)
827
+ unless CHUNK_EXT_VALID.match?(chunk_ext)
828
+ raise HttpParserError, "Invalid chunk extension"
829
+ end
830
+ else
831
+ chunk_hex = header
832
+ end
833
+
834
+ unless CHUNK_SIZE_VALID.match?(chunk_hex)
835
+ err_msg = !chunk_hex.empty? ?
775
836
  "Invalid chunk size: '#{chunk_hex}'" :
776
837
  "Chunk size cannot be empty or nil"
777
838
  raise HttpParserError, err_msg
@@ -800,7 +861,8 @@ module Puma
800
861
 
801
862
  len += 2
802
863
 
803
- part = io.read(len)
864
+ # StringIO#read takes a C long, so don't ask for more than is buffered
865
+ part = io.read([len, io.size].min)
804
866
 
805
867
  unless part
806
868
  @partial_part_left = len
@@ -821,9 +883,12 @@ module Puma
821
883
  write_chunk(part)
822
884
  @partial_part_left = len - part.size
823
885
  when got == len - 1 # edge where we get just \r but not \n
886
+ check_chunk_ending(part, len)
824
887
  write_chunk(part[0..-2])
825
888
  @partial_part_left = len - part.size
826
889
  end
890
+ elsif line.end_with?("\n")
891
+ raise HttpParserError, "Invalid chunk header: bare LF"
827
892
  else
828
893
  if @prev_chunk.size + line.size >= MAX_CHUNK_HEADER_SIZE
829
894
  raise HttpParserError, "maximum size of chunk header exceeded"
@@ -842,10 +907,21 @@ module Puma
842
907
  # CRLF*2. Puma does not surface trailers, so we skip past them. Bytes
843
908
  # past the terminator belong to the next pipelined request.
844
909
  def finish_last_chunk(rest)
910
+ rest = rest.b
845
911
  if rest.start_with?(CHUNK_VALID_ENDING)
846
912
  trailer_end = CHUNK_VALID_ENDING_SIZE
913
+ elsif rest.start_with?("\n")
914
+ @env[HTTP_CONNECTION] = CLOSE
915
+ raise HttpParserError, "Invalid chunk trailer: bare LF"
847
916
  elsif idx = rest.index(CHUNK_VALID_ENDING * 2)
917
+ if BARE_LF.match?(rest.byteslice(0, idx))
918
+ @env[HTTP_CONNECTION] = CLOSE
919
+ raise HttpParserError, "Invalid chunk trailer: bare LF"
920
+ end
848
921
  trailer_end = idx + CHUNK_VALID_ENDING_SIZE * 2
922
+ elsif BARE_LF.match?(rest)
923
+ @env[HTTP_CONNECTION] = CLOSE
924
+ raise HttpParserError, "Invalid chunk trailer: bare LF"
849
925
  elsif rest.bytesize < MAX_CHUNK_HEADER_SIZE
850
926
  @prev_chunk = rest
851
927
  return false