dalli 3.2.17 → 4.0.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 85605d05fac6cb78fd5b6a3505bf92bb3df72f80a8aecd1fc581896e0bb6bcf5
4
- data.tar.gz: 3e1d6612ea7c0c8987bc573bc3686d0d29d184b6af2edbd737f14ec6619fc6f0
3
+ metadata.gz: 86e39b2869b7c916472e88e6cbbfb6aa1f6533aa35c9e1f1c704cffcbc680f8a
4
+ data.tar.gz: bf2e56610c6bae187d561ccf09105e6f5b4a29eed1308d089745ef22cf5b673b
5
5
  SHA512:
6
- metadata.gz: 6c037ec54baa774897ada2bbfce9a99f927eca9e9d7655bdfec55b56118939d6ba212057ebcaada26dc7d6761a5e2926dcbe2b018e3eb0ba249bb650a1f864ce
7
- data.tar.gz: 2cc9822465193504397dc0af9130eabf49b08887a77ca4dd37c86160e9043b6611eb4c3eddc91275dc4a341330d4d3430bff04a7087c4272c89da5c0e31a9270
6
+ metadata.gz: e2faab814abb4b25a53d87048f7e4e81e49c609bd64725cb18607670110da3d5b8038544598c44575831b9038500f9d8220a56ec28c16b9517a21d442212d12b
7
+ data.tar.gz: 3e5a7c326c908d72d2d8ce2211b27f67acebbbf97c279c5faf3ba2914ec7409df7f259a9082d82903cc9ae6b6716a137994aba849321546b8d3d3a35f8f7f5af
data/CHANGELOG.md CHANGED
@@ -1,119 +1,30 @@
1
1
  Dalli Changelog
2
2
  =====================
3
3
 
4
- 3.2.17
5
- ==========
6
-
7
- Security:
8
-
9
- - Security fixes; details will follow in the advisory.
10
-
11
- 3.2.16
12
- ==========
13
-
14
- Security:
15
-
16
- - Bound memcached reply headers, incoming value sizes, and response counts, and enforce TLS timeouts for blocking operations (GHSA-5wpc-45jc-6ccc)
17
-
18
- 3.2.15
19
- ==========
20
-
21
- - Keep a connection shared by several threads or fibers in step during a `quiet` block (GHSA-5xvx-r8rg-5qm2)
22
- - A `quiet` (or `multi`) block is quiet only for the thread or fiber that runs it. memcached still replies to a quiet request that fails (for example an `add` of a key that exists), and another thread or fiber using the same client while the block was open read that reply as its own, so its later requests could return another key's value. A non-quiet request now reads any pending quiet replies first
23
- - Affects every supported line, with both protocols; with the binary protocol the connection stayed out of step after the block ended. Fixed in 5.2.4, 5.1.6, 5.0.12, 4.3.9 and 3.2.15
24
- - With `protocol: :meta`, read values by their size instead of up to the first CRLF (GHSA-5xvx-r8rg-5qm2)
25
- - `get`, `gat` and `cas` read a value as one line, so a value containing CR/LF was cut short and the rest was parsed as the next reply. A stored value containing a crafted reply was then returned for a later read of a different key, with flags that could cause it to be deserialized
26
- - Affects 3.2.0 to 3.2.14 with `protocol: :meta`; fixed in 3.2.15. The binary protocol (3.2's default) and 4.0 and later aren't affected
27
- - A per-request `raw: true` write no longer compresses the value (backport of #1213)
28
- - Values at or above the compression threshold (4 KB by default) were compressed and flagged even with `raw: true`. Raw reads ignore flags, so reading them back with `raw: true` returned the compressed bytes
29
- - Raw values are now stored exactly as given. Callers that pass `raw: true` without `compress: false` store large values uncompressed; Rails' `MemCacheStore` passes `compress: false` and isn't affected
30
- - Handle failed TLS handshakes like other connection failures, and warn when TLS verification is off (backport of #1215)
31
- - A failed or timed-out handshake left the TCP socket open until GC and raised `OpenSSL::SSL::SSLError` directly, so the server was never marked down. The socket is now closed, and the error goes through the usual retry and `socket_max_failures` handling, raising `Dalli::NetworkError` (or `Dalli::RingError` once no server is available)
32
- - Certificate and hostname checks come only from the `ssl_context` you pass, and a bare `OpenSSL::SSL::SSLContext.new` checks neither. Dalli now logs a warning once per process when `verify_mode` doesn't include `VERIFY_PEER` or `verify_hostname` is false; see the new TLS section in the README
33
- - A reply line longer than 8 KiB without a CRLF, or one cut short by the connection closing, is now a network error that closes the connection. Before, the line had no length limit (backport of #1216)
34
-
35
- 3.2.14
36
- ==========
37
-
38
- - Don't rely on memcached's auto-create for keys that need base64 encoding (GHSA-r47x-6p6r-mvcp)
39
- - memcached stores an item made by auto-create (`ma` with `N`/`J`, or `mg` with `N`) for a base64-encoded key without its binary-key flag, and later replies name the item by its raw key bytes. A key containing spaces or CR/LF could then make a multi-get read the replies after it as different ones
40
- - `incr` and `decr` with an initial value now create such counters with an add instead. Return values are unchanged
41
- - The new `verify_reply_keys` option makes `get_multi` ignore replies for keys they didn't request, which guards against items created by older Dalli versions or other clients until memcached is upgraded. It's off by default, since it costs a multi-get about 15%
42
- - Affects `protocol: :meta` since 3.2.0; fixed in 5.2.3, 5.1.5, 5.0.11, 4.3.8 and 3.2.14. memcached 1.6.45 and earlier still name these items by their raw key bytes
43
-
44
- 3.2.13
45
- ==========
46
-
47
- - Complete the fix for per-request `raw: true` on reads (GHSA-wr87-m4jw-29x5)
48
- - `cas` and `cas!` accepted `raw: true` but didn't pass it to the read, so the value was still deserialized. They now honor it, in both protocols
49
- - Affects 3.2.12 and earlier; fixed in 5.2.2, 5.1.4, 5.0.10, 4.3.7 and 3.2.13
50
- - Complete the fork-safety fix (GHSA-w39f-xq2m-4g8x)
51
- - Fork detection used a pid cache refreshed by a `Process._fork` hook. When another library's fork hook ran first in the child (connection_pool, loaded before Dalli as in Rails, closes its connections there), Dalli didn't know it was in a forked child and ended the parent's TLS session. It now checks `Process.pid`
52
- - Fixed in 4.3.7 and 3.2.13
53
-
54
- - Fix a regression in 3.2.12: a `get_multi` that didn't finish within `socket_timeout` counted toward `socket_max_failures`, so two slow `get_multi` calls in a row marked a healthy server down. It now just closes the connection
55
- - Handle malformed pipelined replies from a broken or hostile server or proxy: a hit with no key, or with no `s` flag, could leave the connection out of step or raise an error
56
- - With `decompressed_max_bytes` in effect, data after the end of a compressed value's stream was returned as part of the value. It's now ignored, as without the limit
57
- - With a `digest_class` whose digests aren't short hex strings, shortening a long key could loop forever. It now raises `ArgumentError`
58
-
59
- - Run the Tests and RuboCop workflows on pushes to `main` and the `*-stable` branches only, so a pull request's branch isn't tested twice (backport of #1198)
60
-
61
- 3.2.12
62
- ==========
63
-
64
- - Fix pipelined `get_multi` returning one key's value for another after an error reply (GHSA-p6pm-ch9v-44vx)
65
- - The pipelined reply parser took any reply without a body for the end of the batch. An error reply for one key (`CLIENT_ERROR`, `SERVER_ERROR`, or `EN` from a proxy) ended it early, and the replies still on the connection were read as the replies to later commands, so a `get` could return another key's value
66
- - Keys are now measured in bytes as sent (after base64 encoding when the meta protocol needs it). A key under 250 characters but over 250 bytes, for example one with many non-ASCII characters, passed validation:
67
- - with the meta protocol, memcached rejected it with the error reply above
68
- - with the binary protocol, memcached dropped the connection, and `get` or `get_multi` with that key retried forever
69
- - Such keys are now truncated like other long keys; keys that worked before are unchanged
70
- - The reply parser affects `protocol: :meta` since 3.2.0; the key length affects both protocols; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
71
- - Stop retrying an unresponsive server forever (GHSA-4qp6-2jcr-596v)
72
- - A server that accepted connections but never answered (or dropped the connection on a request) was retried forever, hanging the caller, because each successful reconnect reset the failure count. Requests now fail after `socket_max_failures` attempts and the server is marked down, as when it can't be reached at all; it gets a full set of attempts again after `down_retry_delay`
73
- - Affects all versions; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
74
- - Limit decompressed and reply value sizes (GHSA-3553-vcg5-72jw)
75
- - Values flagged as compressed were inflated without limit, so a small stored value could expand to gigabytes on read, whatever the client's `compress` or `serializer` settings. The new `decompressed_max_bytes` option (default 128 MiB; `nil` disables it) makes a read that would pass it raise `Dalli::UnmarshalError`. Custom compressors whose `decompress` takes only the data keep working, without the limit
76
- - The value size in a reply (a meta `VA` size or a binary body length) was used to read or buffer that many bytes, so a malicious server could make the client allocate gigabytes. Sizes over 1 GiB, memcached's largest item, now raise `Dalli::DalliError` before reading
77
- - Affects all versions; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
78
- - Honor per-request `raw: true` on reads, and add `Dalli::JSONSerializer` (GHSA-wr87-m4jw-29x5)
79
- - `get`, `gat` and `fetch` ignored a per-request `raw: true` and deserialized the value according to its stored flags, so a caller who asked for raw bytes could still have `Marshal.load` run on data someone else wrote to memcached. They now return the stored bytes
80
- - The `raw` part affects all versions
81
- - `serializer: JSON` reads values with `JSON.load`, which on json gem versions before 3.0 creates an object of the class named in a stored `json_class` key when the json additions are loaded. The new `Dalli::JSONSerializer` reads with `JSON.parse` and only returns plain JSON types. The README now recommends it; `serializer: JSON` itself is unchanged
82
- - The `serializer: JSON` part affects any version used with the json gem before 3.0
83
- - Keep a forked child from closing the parent's TLS session (GHSA-w39f-xq2m-4g8x)
84
- - With TLS, a forked child that closed the client (or reconnected after detecting the fork) sent a TLS close on the connection the parent was still using, ending the parent's session. A forked child now closes only its own copy of the socket
85
- - Affects all versions with TLS; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
86
-
87
- - Fix three flaky tests: the `KeyManager` namespace key-length test, the Rack session freshness test, and `MemcachedManager`'s start and stop handling (backport of #1141, #1183)
88
- - Fix flaky failover tests: move their ports out of Linux's ephemeral port range, and wait for memcached to accept connections after starting it (backport of #1184)
89
-
90
- 3.2.11
91
- ==========
92
-
93
- - Fix multi-server `get_multi` stopping at an empty value (#1170)
94
- - The pipelined reply parser took a hit on a zero-length value (`VA 0`) for the terminating `MN`, so that server's remaining keys were silently missing from the result
95
- - Its value terminator and any replies not yet parsed stayed on the connection and were read as the replies to later commands on it. Those commands could fail with `Dalli::DalliError: Response error`, or a single-key `get` could silently return another key's value
96
- - An empty value is now returned as `''`, like a single-key `get` and single-server `get_multi`
97
- - Affects only clients using `protocol: :meta`; the default binary protocol is not affected
98
- - Thanks to Julian Richard Contreras for this contribution
99
-
100
- 3.2.10
101
- ==========
102
-
103
- - Fix `Rack::Session::Dalli` with connection_pool 3.x, which only accepts keyword arguments (backport of #1051)
104
- - Add `logger` as a runtime dependency, since it is no longer a default gem as of Ruby 4.0 (backport of #1010, olleolleolle)
105
- - CI: patch memcached 1.5.22 so it builds on ubuntu-22.04, and run tests there (backport of #1033)
106
-
107
- 3.2.9
108
- ==========
109
-
110
- Security:
111
-
112
- - Fix memcached command injection through the `incr`/`decr` default with the meta protocol (GHSA-6wmv-xq9m-fmp7)
113
- - With `protocol: :meta`, the `default` argument of `incr`/`decr` was written into the command without conversion, so a String containing CRLF injected additional memcached commands (e.g. `set`, `flush_all`) on the connection. The default binary protocol is not affected
114
- - `default` must now be an Integer, or a String of decimal digits; anything else raises `ArgumentError` before a request is sent
115
- - As defense in depth, the meta `RequestFormatter` now converts every numeric flag it writes (`D`, `J`, `N`, `T`) to an Integer
116
- - Thanks to oss-security-shop for the report
4
+ 4.0.0
5
+ ==========
6
+
7
+ BREAKING CHANGES:
8
+
9
+ - Require Ruby 3.1+ (dropped support for Ruby 2.6, 2.7, and 3.0)
10
+ - Removed `Dalli::Server` deprecated alias - use `Dalli::Protocol::Binary` instead
11
+ - Removed `:compression` option - use `:compress` instead
12
+ - Removed `close_on_fork` method - use `reconnect_on_fork` instead
13
+
14
+ Other changes:
15
+
16
+ - Add security warning when using default Marshal serializer (silence with `silence_marshal_warning: true`)
17
+ - Add defense-in-depth input validation for stats command arguments
18
+ - Add `string_fastpath` option to skip serialization for simple strings (byroot)
19
+ - Meta protocol set performance improvement (danmayer)
20
+ - Fix connection_pool 3.0 compatibility for Rack session store
21
+ - Fix session recovery after deletion (stengineering0)
22
+ - Fix cannot read response data included terminator `\r\n` when use meta protocol (matsubara0507)
23
+ - Support SERVER_ERROR response from Memcached as per the [memcached spec](https://github.com/memcached/memcached/blob/e43364402195c8e822bb8f88755a60ab8bbed62a/doc/protocol.txt#L172) (grcooper)
24
+ - Update Socket timeout handling to use Socket#timeout= when available (nickamorim)
25
+ - Serializer: reraise all .load errors as UnmarshalError (olleolleolle)
26
+ - Reconnect gracefully when a fork is detected instead of crashing (PatrickTulskie)
27
+ - Update CI to test against memcached 1.6.40
117
28
 
118
29
  3.2.8
119
30
  ==========
data/Gemfile CHANGED
@@ -5,7 +5,9 @@ source 'https://rubygems.org'
5
5
  gemspec
6
6
 
7
7
  group :development, :test do
8
+ gem 'cgi'
8
9
  gem 'connection_pool'
10
+ gem 'debug' unless RUBY_PLATFORM == 'java'
9
11
  gem 'minitest', '~> 5'
10
12
  gem 'rack', '~> 2.0', '>= 2.2.0'
11
13
  gem 'rake', '~> 13.0'
data/README.md CHANGED
@@ -25,47 +25,6 @@ The name is a variant of Salvador Dali for his famous painting [The Persistence
25
25
  * [Forum](https://github.com/petergoldstein/dalli/discussions/categories/q-a) - If you have questions about Dalli, please post them here.
26
26
  * [Client API](https://www.rubydoc.info/gems/dalli) - Ruby documentation for the `Dalli::Client` API
27
27
 
28
- ## Security Note
29
-
30
- Incoming values are limited to `value_max_bytes` (1 MB by default). Set `max_response_bytes` to a positive byte count if an existing memcached deployment stores larger values:
31
-
32
- ```ruby
33
- Dalli::Client.new('localhost:11211', max_response_bytes: 2 * 1024 * 1024)
34
- ```
35
-
36
- By default, Dalli uses Ruby's Marshal for serialization. Deserializing untrusted data with Marshal can lead to remote code execution. If you cache user-controlled data, or your memcached server could be written to by someone else, consider using a safer serializer:
37
-
38
- ```ruby
39
- Dalli::Client.new('localhost:11211', serializer: Dalli::JSONSerializer)
40
- ```
41
-
42
- `Dalli::JSONSerializer` reads values with `JSON.parse`, so it only ever returns plain hashes, arrays, strings, numbers, booleans and `nil`. Passing the `JSON` module itself (`serializer: JSON`) reads values with `JSON.load`, which can create objects of other classes from a stored `json_class` key and is not recommended for data an attacker might write.
43
-
44
- Per-request `raw: true` returns the stored bytes without deserializing or decompressing them, on every read method that accepts it (`get` and `fetch`).
45
-
46
- ### Counters and verify_reply_keys
47
-
48
- memcached names an item made by auto-create for a base64-encoded key (one with whitespace, control or non-ASCII characters) by its raw key bytes in later replies (with `protocol: :meta`). Since 3.2.14, Dalli creates counters for such keys with an add rather than auto-create. Items created before then, or by other clients, can still be named that way until memcached releases a fix (1.6.45 and earlier behave this way). If keys passed to `incr` or `decr` with an initial value can contain untrusted input, set `verify_reply_keys: true` until then: multi-gets then ignore replies for keys they didn't request, at a cost of about 15% per multi-get.
49
-
50
- ## TLS
51
-
52
- Pass an `OpenSSL::SSL::SSLContext` as `ssl_context:` to connect over TLS. Certificate and hostname verification come only from that context: Dalli adds no checks of its own. A bare `OpenSSL::SSL::SSLContext.new` verifies nothing, so it accepts any certificate from any server. Configure the context to verify both:
53
-
54
- ```ruby
55
- ssl_context = OpenSSL::SSL::SSLContext.new
56
- ssl_context.set_params(
57
- verify_mode: OpenSSL::SSL::VERIFY_PEER,
58
- verify_hostname: true,
59
- ca_file: '/path/to/ca.crt' # omit to use the system's trusted certificates
60
- )
61
-
62
- Dalli::Client.new('memcached.example.com:11211', ssl_context: ssl_context)
63
- ```
64
-
65
- Dalli logs a warning once per process when the context's `verify_mode` is `VERIFY_NONE`, or when it is `VERIFY_PEER` but `verify_hostname` is false.
66
-
67
- A failed TLS handshake counts as a failed connection attempt, like a refused connection: once `socket_max_failures` attempts have failed, the server is marked down and requests fail over to the other servers.
68
-
69
28
  ## Development
70
29
 
71
30
  After checking out the repo, run `bin/setup` to install dependencies. You can run `bin/console` for an interactive prompt that will allow you to experiment.
data/lib/dalli/client.rb CHANGED
@@ -28,7 +28,6 @@ module Dalli
28
28
  # the server configuration.
29
29
  #
30
30
  # Options:
31
- # - :max_response_bytes - largest value accepted from a server. Defaults to :value_max_bytes (1 MB by default).
32
31
  # - :namespace - prepend each key with this value to provide simple namespacing.
33
32
  # - :failover - if a server is down, look for and store values on another server in the ring. Default: true.
34
33
  # - :threadsafe - ensure that only one thread is actively using a socket at a time. Default: true.
@@ -46,11 +45,6 @@ module Dalli
46
45
  # useful for injecting a FIPS compliant hash object.
47
46
  # - :protocol - one of either :binary or :meta, defaulting to :binary. This sets the protocol that Dalli uses
48
47
  # to communicate with memcached.
49
- # - :verify_reply_keys - defaults to false. When true, get_multi only accepts replies for the keys it requested;
50
- # after a reply naming another key, the rest of that server's replies are treated as misses.
51
- # With the meta protocol, memcached can name an item by its raw key bytes when the item was
52
- # created by auto-create from a base64-encoded key, which Dalli no longer does. Costs a
53
- # multi-get about 15%.
54
48
  #
55
49
  def initialize(servers = nil, options = {})
56
50
  @normalized_servers = ::Dalli::ServersArgNormalizer.normalize_servers(servers)
@@ -161,8 +155,8 @@ module Dalli
161
155
  # - nil if the key did not exist.
162
156
  # - false if the value was changed by someone else.
163
157
  # - true if the value was successfully updated.
164
- def cas(key, ttl = nil, req_options = nil, &block)
165
- cas_core(key, false, ttl, req_options, &block)
158
+ def cas(key, ttl = nil, req_options = nil, &)
159
+ cas_core(key, false, ttl, req_options, &)
166
160
  end
167
161
 
168
162
  ##
@@ -172,8 +166,8 @@ module Dalli
172
166
  # Returns:
173
167
  # - false if the value was changed by someone else.
174
168
  # - true if the value was successfully updated.
175
- def cas!(key, ttl = nil, req_options = nil, &block)
176
- cas_core(key, true, ttl, req_options, &block)
169
+ def cas!(key, ttl = nil, req_options = nil, &)
170
+ cas_core(key, true, ttl, req_options, &)
177
171
  end
178
172
 
179
173
  ##
@@ -193,11 +187,6 @@ module Dalli
193
187
  # Any error replies will be discarded at the end of the block, and
194
188
  # Dalli client methods invoked inside the block will not
195
189
  # have return values
196
- #
197
- # The block is quiet only for the thread or fiber that runs it. Another
198
- # thread or fiber sharing this client can make requests meanwhile; a
199
- # non-quiet one first reads the block's pending replies with a noop and
200
- # discards them, so it reads only its own.
201
190
  def quiet
202
191
  old = Thread.current[::Dalli::QUIET]
203
192
  Thread.current[::Dalli::QUIET] = true
@@ -268,8 +257,6 @@ module Dalli
268
257
  ##
269
258
  # Incr adds the given amount to the counter on the memcached server.
270
259
  # Amt must be a positive integer value.
271
- # Default, if given, must be an Integer (or a String of decimal digits);
272
- # anything else raises ArgumentError.
273
260
  #
274
261
  # If default is nil, the counter must already exist or the operation
275
262
  # will fail and will return nil. Otherwise this method will return
@@ -282,7 +269,6 @@ module Dalli
282
269
  # If the value already exists, it must have been set with raw: true
283
270
  def incr(key, amt = 1, ttl = nil, default = nil)
284
271
  check_positive!(amt)
285
- validate_integer!(:default, default)
286
272
 
287
273
  perform(:incr, key, amt.to_i, ttl_or_default(ttl), default)
288
274
  end
@@ -290,8 +276,6 @@ module Dalli
290
276
  ##
291
277
  # Decr subtracts the given amount from the counter on the memcached server.
292
278
  # Amt must be a positive integer value.
293
- # Default, if given, must be an Integer (or a String of decimal digits);
294
- # anything else raises ArgumentError.
295
279
  #
296
280
  # memcached counters are unsigned and cannot hold negative values. Calling
297
281
  # decr on a counter which is 0 will just return 0.
@@ -307,7 +291,6 @@ module Dalli
307
291
  # If the value already exists, it must have been set with raw: true
308
292
  def decr(key, amt = 1, ttl = nil, default = nil)
309
293
  check_positive!(amt)
310
- validate_integer!(:default, default)
311
294
 
312
295
  perform(:decr, key, amt.to_i, ttl_or_default(ttl), default)
313
296
  end
@@ -390,17 +373,8 @@ module Dalli
390
373
  raise ArgumentError, "Positive values only: #{amt}" if amt.negative?
391
374
  end
392
375
 
393
- # Numeric arguments that become meta protocol flags (GHSA-6wmv-xq9m-fmp7).
394
- # Checked before the request starts so a bad value raises a clean
395
- # ArgumentError, instead of Protocol::Base#request logging it as
396
- # unexpected and closing the connection.
397
- def validate_integer!(name, value)
398
- Dalli::Protocol::Meta::RequestFormatter.integer_flag(name, value) unless value.nil?
399
- end
400
-
401
376
  def cas_core(key, always_set, ttl = nil, req_options = nil)
402
- # req_options reaches the read too, so raw: true returns the stored bytes
403
- (value, cas) = perform(:cas, key, req_options)
377
+ (value, cas) = perform(:cas, key)
404
378
  return if value.nil? && !always_set
405
379
 
406
380
  newvalue = yield(value)
@@ -13,54 +13,8 @@ module Dalli
13
13
  Zlib::Deflate.deflate(data)
14
14
  end
15
15
 
16
- # DEFLATE can't expand data by more than about 1032:1
17
- MAX_EXPANSION = 1032
18
- # Compressed input is fed to zlib this many bytes at a time. MRI's zlib
19
- # yields the output in small chunks; one that returns it instead still
20
- # produces at most MAX_EXPANSION times this per step.
21
- INFLATE_SLICE_BYTES = 64 * 1024
22
-
23
- # max_bytes caps the decompressed size; inflating stops and raises as soon
24
- # as the output passes it, so a small compressed value can't expand into
25
- # gigabytes of memory.
26
- def self.decompress(data, max_bytes: nil)
27
- return Zlib::Inflate.inflate(data) unless may_exceed?(data, max_bytes)
28
-
29
- inflate_within_limit(Zlib::Inflate.new, data, max_bytes)
30
- end
31
-
32
- # False when even the largest possible expansion stays within max_bytes,
33
- # so the value can be inflated in one step
34
- def self.may_exceed?(data, max_bytes)
35
- max_bytes ? data.bytesize * MAX_EXPANSION > max_bytes : false
36
- end
37
-
38
- def self.inflate_within_limit(inflater, data, max_bytes)
39
- out = String.new(encoding: Encoding::BINARY)
40
- 0.step(data.bytesize - 1, INFLATE_SLICE_BYTES) do |pos|
41
- inflate_slice(inflater, data.byteslice(pos, INFLATE_SLICE_BYTES), out, max_bytes)
42
- # Anything after the end of the stream isn't part of the value, as
43
- # with Zlib::Inflate.inflate; finish would return it as output
44
- break if inflater.finished?
45
- end
46
- return out if inflater.finished?
47
-
48
- append_within_limit(out, inflater.finish, max_bytes)
49
- ensure
50
- inflater.close
51
- end
52
-
53
- # Both yielded and returned output count toward the limit
54
- def self.inflate_slice(inflater, slice, out, max_bytes)
55
- rest = inflater.inflate(slice) { |chunk| append_within_limit(out, chunk, max_bytes) }
56
- append_within_limit(out, rest, max_bytes)
57
- end
58
-
59
- def self.append_within_limit(out, chunk, max_bytes)
60
- out << chunk if chunk
61
- return out if out.bytesize <= max_bytes
62
-
63
- raise Dalli::UnmarshalError, "Decompressed value exceeds #{max_bytes} bytes (decompressed_max_bytes)"
16
+ def self.decompress(data)
17
+ Zlib::Inflate.inflate(data)
64
18
  end
65
19
  end
66
20
 
@@ -78,11 +32,9 @@ module Dalli
78
32
  io.string
79
33
  end
80
34
 
81
- def self.decompress(data, max_bytes: nil)
82
- return Zlib::GzipReader.new(StringIO.new(data, 'rb')).read unless Compressor.may_exceed?(data, max_bytes)
83
-
84
- # MAX_WBITS + 16 makes zlib read the gzip format (and check its CRC)
85
- Compressor.inflate_within_limit(Zlib::Inflate.new(Zlib::MAX_WBITS + 16), data, max_bytes)
35
+ def self.decompress(data)
36
+ io = StringIO.new(data, 'rb')
37
+ Zlib::GzipReader.new(io).read
86
38
  end
87
39
  end
88
40
  end
@@ -30,13 +30,10 @@ module Dalli
30
30
 
31
31
  def initialize(client_options)
32
32
  @key_options =
33
- DEFAULTS.merge(client_options.select { |k, _| OPTIONS.include?(k) })
33
+ DEFAULTS.merge(client_options.slice(*OPTIONS))
34
34
  validate_digest_class_option(@key_options)
35
35
 
36
36
  @namespace = namespace_from_options
37
- # The meta protocol base64-encodes keys with whitespace or non-ASCII
38
- # characters, so their length on the wire differs from their length here
39
- @meta_protocol = client_options[:protocol]&.to_s == 'meta'
40
37
  end
41
38
 
42
39
  ##
@@ -54,7 +51,7 @@ module Dalli
54
51
  raise ArgumentError, 'key cannot be blank' unless key&.length&.positive?
55
52
 
56
53
  key = key_with_namespace(key)
57
- wire_length(key) > MAX_KEY_LENGTH ? truncated_key(key) : key
54
+ key.length > MAX_KEY_LENGTH ? truncated_key(key) : key
58
55
  end
59
56
 
60
57
  ##
@@ -80,7 +77,7 @@ module Dalli
80
77
  def namespace_regexp
81
78
  return /\A#{Regexp.escape(evaluate_namespace)}:/ if namespace.is_a?(Proc)
82
79
 
83
- @namespace_regexp ||= /\A#{Regexp.escape(namespace)}:/.freeze unless namespace.nil?
80
+ @namespace_regexp ||= /\A#{Regexp.escape(namespace)}:/ unless namespace.nil?
84
81
  end
85
82
 
86
83
  def validate_digest_class_option(opts)
@@ -110,30 +107,7 @@ module Dalli
110
107
  ##
111
108
  def truncated_key(key)
112
109
  digest = digest_class.hexdigest(key)
113
- prefix = key[0, [prefix_length(digest), 0].max]
114
- truncated = "#{prefix}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
115
- # A prefix with whitespace or non-ASCII characters sends the whole key
116
- # base64-encoded, which can still be too long on the wire; shorten it.
117
- while wire_length(truncated) > MAX_KEY_LENGTH && !prefix.empty?
118
- prefix = prefix[0...-1]
119
- truncated = "#{prefix}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
120
- end
121
- return truncated if wire_length(truncated) <= MAX_KEY_LENGTH
122
-
123
- # Only possible with a digest_class whose digests aren't short hex strings
124
- raise ArgumentError, "#{digest_class} digests are too long to fit in a truncated key"
125
- end
126
-
127
- # memcached's key limit applies to the key as sent: in bytes, and, with
128
- # the meta protocol, after base64 encoding when the key needs it. A key
129
- # within the limit in characters can still be too long. With the meta
130
- # protocol memcached rejects it with a CLIENT_ERROR that must never reach
131
- # a pipelined get; with the binary protocol it drops the connection.
132
- def wire_length(key)
133
- return key.bytesize unless @meta_protocol
134
-
135
- encoded, = Dalli::Protocol::Meta::KeyRegularizer.encode(key)
136
- encoded.bytesize
110
+ "#{key[0, prefix_length(digest)]}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
137
111
  end
138
112
 
139
113
  def prefix_length(digest)
@@ -147,9 +147,6 @@ module Dalli
147
147
  def servers_with_response(servers, timeout)
148
148
  return [] if servers.empty?
149
149
 
150
- buffered = pending_tls_servers(servers)
151
- return buffered unless buffered.empty?
152
-
153
150
  # TODO: - This is a bit challenging. Essentially the PipelinedGetter
154
151
  # is a reactor, but without the benefit of a Fiber or separate thread.
155
152
  # My suspicion is that we may want to try and push this down into the
@@ -164,10 +161,6 @@ module Dalli
164
161
  readable.map { |sock| server_map[sock] }
165
162
  end
166
163
 
167
- def pending_tls_servers(servers)
168
- servers.select { |server| server.sock.respond_to?(:pending_data?) && server.sock.pending_data? }
169
- end
170
-
171
164
  def groups_for_keys(*keys)
172
165
  keys.flatten!
173
166
  keys.map! { |a| @key_manager.validate_key(a.to_s) }
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'forwardable'
4
- require 'set'
5
4
  require 'socket'
6
5
  require 'timeout'
7
6
 
@@ -24,28 +23,17 @@ module Dalli
24
23
  def initialize(attribs, client_options = {})
25
24
  hostname, port, socket_type, @weight, user_creds = ServerConfigParser.parse(attribs)
26
25
  @options = client_options.merge(user_creds)
27
- @verify_reply_keys = client_options[:verify_reply_keys] ? true : false
28
26
  @value_marshaller = ValueMarshaller.new(@options)
29
27
  @connection_manager = ConnectionManager.new(hostname, port, socket_type, @options)
30
28
  end
31
29
 
32
- # True when this request passed raw: true. A stored value is then
33
- # returned as stored, never deserialized or decompressed.
34
- def raw_request?(options)
35
- options.is_a?(Hash) && options[:raw] ? true : false
36
- end
37
-
38
30
  # Chokepoint method for error handling and ensuring liveness
39
31
  def request(opkey, *args)
40
32
  verify_state(opkey)
41
33
 
42
34
  begin
43
35
  @connection_manager.start_request!
44
- drain_pending_quiet_responses(opkey)
45
36
  response = send(opkey, *args)
46
- # Quiet requests can leave replies on the socket; remember that so a
47
- # later non-quiet request knows to read them first
48
- @connection_manager.quiet_responses_pending = true if quiet? && opkey != :noop
49
37
 
50
38
  # pipelined_get emit query but doesn't read the response(s)
51
39
  @connection_manager.finish_request! unless opkey == :pipelined_get
@@ -109,11 +97,9 @@ module Dalli
109
97
  # to the noop at the end of the pipeline
110
98
  finish_pipeline && break if status && key.nil?
111
99
 
112
- check_pipeline_response_count!
113
-
114
100
  # If the status is ok and the key is not nil, then this is a
115
101
  # getkq response with a value that we want to set in the response hash
116
- break unless keep_reading?(values, key, value, cas)
102
+ values[key] = [value, cas] unless key.nil?
117
103
 
118
104
  # Get the next response from the buffer
119
105
  status, cas, key, value = response_buffer.process_single_getk_response
@@ -132,16 +118,13 @@ module Dalli
132
118
  def pipeline_abort
133
119
  response_buffer.clear
134
120
  @connection_manager.abort_request!
135
- return unless connected?
136
-
137
- # Closes the connection, which ensures that our connection is in a
138
- # clean state for future requests. The get_multi ran out of time
139
- # overall rather than hitting a socket error, so it doesn't count
140
- # toward socket_max_failures: two slow get_multis in a row would
141
- # otherwise mark a healthy server down.
142
- Dalli.logger.warn { "#{name} didn't finish a get_multi within socket_timeout; closing the connection" }
143
- @connection_manager.close
144
- nil
121
+ return true unless connected?
122
+
123
+ # Closes the connection, which ensures that our connection
124
+ # is in a clean state for future requests
125
+ @connection_manager.error_on_request!('External timeout')
126
+ rescue NetworkError
127
+ true
145
128
  end
146
129
 
147
130
  # Did the last call to #pipeline_response_setup complete successfully?
@@ -171,17 +154,7 @@ module Dalli
171
154
  private
172
155
 
173
156
  ALLOWED_QUIET_OPS = %i[add replace set delete incr decr append prepend flush noop].freeze
174
-
175
- # Reads the replies still pending from quiet requests before any
176
- # non-quiet request, which reads a reply of its own. A quiet block reads
177
- # them at its end, but the connection is shared: another thread or fiber
178
- # (quiet? is fiber-local) can make a request while the block is still
179
- # open, and would otherwise read the block's replies as its own.
180
- def drain_pending_quiet_responses(opkey)
181
- return unless @connection_manager.quiet_responses_pending? && opkey != :noop && !quiet?
182
-
183
- noop
184
- end
157
+ private_constant :ALLOWED_QUIET_OPS
185
158
 
186
159
  def verify_allowed_quiet!(opkey)
187
160
  return if ALLOWED_QUIET_OPS.include?(opkey)
@@ -240,7 +213,6 @@ module Dalli
240
213
  end
241
214
 
242
215
  def pipelined_get(keys)
243
- expect_reply_keys(keys)
244
216
  req = +''
245
217
  keys.each do |key|
246
218
  req << quiet_get_request(key)
@@ -253,59 +225,6 @@ module Dalli
253
225
  @response_buffer ||= ResponseBuffer.new(@connection_manager, response_processor)
254
226
  end
255
227
 
256
- # A multi-get only accepts replies for the keys it asked for. With the
257
- # meta protocol, memcached names an item created by auto-create (ma or mg
258
- # with N) for a base64-encoded key by its raw bytes, without the b flag;
259
- # such a key can contain spaces or CR/LF, which split the reply header and
260
- # make the replies after it parse as different ones. A key that wasn't
261
- # requested is how that shows up. Only with the verify_reply_keys option,
262
- # since building the set costs a multi-get about 15%.
263
- def expect_reply_keys(keys)
264
- @expected_response_count = keys.size
265
- @pipeline_response_count = 0
266
- @expected_reply_keys = (keys.to_set { |k| reply_key_form(k) } if @verify_reply_keys)
267
- end
268
-
269
- def check_pipeline_response_count!
270
- @pipeline_response_count += 1
271
- return if @pipeline_response_count <= @expected_response_count
272
-
273
- raise Dalli::DalliError, 'Too many get_multi replies'
274
- end
275
-
276
- # Stores a getkq reply's value and returns true, unless its key wasn't
277
- # requested: then the replies are out of step, so what was read so far is
278
- # kept, the rest dropped, and false returned to stop reading
279
- def keep_reading?(values, key, value, cas)
280
- return true if key.nil?
281
-
282
- if unexpected_reply_key?(key)
283
- abandon_pipeline
284
- return false
285
- end
286
-
287
- values[key] = [value, cas]
288
- true
289
- end
290
-
291
- def unexpected_reply_key?(key)
292
- !key.nil? && @expected_reply_keys && !@expected_reply_keys.include?(reply_key_form(key))
293
- end
294
-
295
- # Keys compared as bytes; ASCII keys compare equal in any encoding as is
296
- def reply_key_form(key)
297
- key.ascii_only? ? key : key.b
298
- end
299
-
300
- # Drops the rest of this server's replies and closes the connection so
301
- # nothing unread is left on it. Not a socket failure, so it doesn't count
302
- # toward socket_max_failures; the keys not read are simply missing.
303
- def abandon_pipeline
304
- Dalli.logger.warn { "#{name} replied to a get_multi with a key that wasn't requested; closing the connection" }
305
- response_buffer.clear
306
- @connection_manager.close
307
- end
308
-
309
228
  # Called after the noop response is received at the end of a set
310
229
  # of pipelined gets
311
230
  def finish_pipeline