dalli 5.2.0 → 5.2.1

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: 23a3890b1ca95b3668eea5b0f2f6eabfb3ad6062daebf5723e5b99c2c7a74854
4
- data.tar.gz: 4f0c1775badbf133dab91d32a19f84ffafab7f1c0a6c9d7c195f968bed01c089
3
+ metadata.gz: 42431b1f305b3fe3d3923c2b66f3d1edfb402da378c434a587bb2c85d6688055
4
+ data.tar.gz: 39bc473979fb49cd488853d39a64675884ce89951e96a7b5925dc88c8307219a
5
5
  SHA512:
6
- metadata.gz: b1624d8d1024956e90ab86a5d5b7f56833d9d195b95d2e8f7ed92774775eebb5ae19baf798773e17ce8fdb7b8fa5abf728a5899d085ecd11335fe11daac52bdb
7
- data.tar.gz: 76c4e96a6ac88ec7ce86d213d58bf4f709f6ebc52e747ffa05661343173c654696e6e2625090b14d31874f160f3778a750e9cd524cb4f8985ea86716f267793e
6
+ metadata.gz: 810da4f09ea75bfa616471a48686cb0804b820b3a629c1ec53c3ecc7146c76d94e7afa729ce3361287ccafaa71d97a0ed5053f0b6adc0d8cea91c5de81070231
7
+ data.tar.gz: c18a6a1f3d1dac3fcf5f640c8714ff68e70e07dc8d154d1471fc62c9ccb5ee6a970a3d079b042d4c5337ad11f39090e69022ef6eb34dac281906e9834863b285
data/CHANGELOG.md CHANGED
@@ -4,6 +4,53 @@ Dalli Changelog
4
4
  Unreleased
5
5
  ==========
6
6
 
7
+ 5.2.1
8
+ ==========
9
+
10
+ Security:
11
+
12
+ - Fix pipelined `get_multi` returning one key's value for another after an error reply (GHSA-p6pm-ch9v-44vx)
13
+ - 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
14
+ - Keys are now measured in bytes as sent, after base64 encoding when the key needs it. A key under 250 characters but over 250 bytes on the wire (for example, one with many non-ASCII characters) was the easiest way to cause that error reply. Such keys are now truncated like other long keys; keys that worked before are unchanged
15
+ - Affects the meta protocol since 3.2.0 (the default since 5.0.0); fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
16
+ - Reject routing tokens that add meta flags, and stop retrying an unresponsive server forever (GHSA-4qp6-2jcr-596v)
17
+ - `p_token` and `l_token` now reject whitespace and control characters, not just CR, LF and NUL. A space let a token add meta flags to the request it was sent with: changing an item's TTL on a read, creating stub items on a miss, turning a delete into a stale tombstone, or reading a different key
18
+ - Affects 5.1.0 and later; fixed in 5.2.1 and 5.1.3
19
+ - 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`
20
+ - Affects all versions; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
21
+ - Limit decompressed and reply value sizes (GHSA-3553-vcg5-72jw)
22
+ - 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
23
+ - The value size in a reply 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
24
+ - Affects all versions; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
25
+ - Honor per-request `raw: true` on reads, and add `Dalli::JSONSerializer` (GHSA-wr87-m4jw-29x5)
26
+ - `get_multi`, `get_multi_cas`, `get_multi_with_metadata`, `get_cas` and `get_with_metadata` 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
27
+ - The `raw` part affects `get_with_metadata` since 4.2.0, and the other methods since they gained per-request options in 5.1.0
28
+ - `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 and the Marshal security warning now recommend it; `serializer: JSON` itself is unchanged
29
+ - The `serializer: JSON` part affects any version used with the json gem before 3.0
30
+ - Keep a forked child from writing to or closing the parent's connection (GHSA-w39f-xq2m-4g8x)
31
+ - A child forked while the parent had requests buffered but not yet sent, such as quiet writes inside a `quiet` block, sent them again when it closed the client or reconnected: quiet writes ran twice, and the parent's later replies could be read as the replies to other requests, returning one key's value for another. Dalli now buffers requests itself and a forked child discards them
32
+ - Affects 4.2.0 and later; fixed in 5.2.1, 5.1.3, 5.0.9 and 4.3.6
33
+ - 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
34
+ - Affects all versions with TLS; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
35
+
36
+ Bug fixes:
37
+
38
+ - An exception raised by a `get_multi` block (such as `Timeout::Error`) was treated as a network failure: swallowed, with the whole `get_multi` retried and keys yielded twice. It now reaches the caller
39
+
40
+ Notes:
41
+
42
+ - Document [Ruby bug 21195](https://bugs.ruby-lang.org/issues/21195), a VM crash (`[BUG] rb_sys_fail_path_in(io_fillbuf, ...) - errno == 0`) when a socket read using `IO#timeout` is interrupted by a signal, in the README (#1189)
43
+ - Affects Ruby 3.3.0–3.3.7 and 3.4.0–3.4.2; fixed in 3.3.8 and 3.4.3
44
+
45
+ Development:
46
+
47
+ - Add property tests for request building and fuzz tests for the reply parsers
48
+ - Add a security policy (`SECURITY.md`), give every workflow a least-privilege token, and pin third-party actions by commit SHA (#1190)
49
+ - Fix flaky failover tests (#1184)
50
+ - Their ports were inside Linux's ephemeral port range (32768-60999), so an earlier client connection could hold one as its local port. memcached then couldn't bind it on IPv4 and listened on IPv6 only, and the test's client marked that server down. They now use ports in the 26xxx range
51
+ - The test helper now waits until memcached accepts connections, instead of sleeping a fixed 0.1s after starting it
52
+ - Refresh apt's package index before installing libevent in CI, so a stale runner image can't break every memcached build (#1172)
53
+
7
54
  5.2.0
8
55
  ==========
9
56
 
data/README.md CHANGED
@@ -24,6 +24,16 @@ latest release. Earlier 1.6.x servers are not supported: the meta protocol
24
24
  rejects unknown flags outright, so features added after a server's release fail
25
25
  with `CLIENT_ERROR invalid flag` rather than degrading.
26
26
 
27
+ ### Known Ruby issue: crash on an interrupted socket read
28
+
29
+ Dalli sets socket timeouts with `IO#timeout`. Ruby 3.3.0–3.3.7 and 3.4.0–3.4.2 have a bug ([Ruby #21195](https://bugs.ruby-lang.org/issues/21195)) where a timed read interrupted by a signal aborts the whole process:
30
+
31
+ ```
32
+ [BUG] rb_sys_fail_path_in(io_fillbuf, fd:N ) - errno == 0
33
+ ```
34
+
35
+ The crash is inside Ruby itself, so it can't be rescued. It's fixed in Ruby 3.3.8 and 3.4.3. If you see this crash, upgrade to one of those versions or later.
36
+
27
37
  ## Configuration Options
28
38
 
29
39
  ### Namespace
@@ -80,9 +90,13 @@ end
80
90
  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, consider using a safer serializer:
81
91
 
82
92
  ```ruby
83
- Dalli::Client.new('localhost:11211', serializer: JSON)
93
+ Dalli::Client.new('localhost:11211', serializer: Dalli::JSONSerializer)
84
94
  ```
85
95
 
96
+ `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.
97
+
98
+ Per-request `raw: true` returns the stored bytes without deserializing or decompressing them, on every read method (`get`, `get_multi`, `get_cas`, `get_with_metadata` and `fetch`).
99
+
86
100
  See the [5.0-Upgrade.md](5.0-Upgrade.md) guide for upgrade information.
87
101
 
88
102
  ## OpenTelemetry Tracing
data/lib/dalli/client.rb CHANGED
@@ -881,7 +881,7 @@ module Dalli
881
881
  # check means unwinding through Protocol::Base#request, which logs the
882
882
  # failure as unexpected and closes the connection -- a caller passing a
883
883
  # bad token should get a clean ArgumentError and keep its connection.
884
- ROUTING_TOKEN_FORBIDDEN = /[\r\n\0]/
884
+ ROUTING_TOKEN_FORBIDDEN = /[\x00-\x20\x7F]/
885
885
  private_constant :ROUTING_TOKEN_FORBIDDEN
886
886
 
887
887
  def validate_routing_tokens!(req_options)
@@ -897,7 +897,9 @@ module Dalli
897
897
  # here (it would also excuse [] / {} from the type check below).
898
898
  return if value.nil? || (value.is_a?(String) && value.empty?)
899
899
  raise ArgumentError, "#{name} must be a String, got #{value.class}" unless value.is_a?(String)
900
- raise ArgumentError, "#{name} must not contain CRLF or null bytes" if value.match?(ROUTING_TOKEN_FORBIDDEN)
900
+ return unless value.match?(ROUTING_TOKEN_FORBIDDEN)
901
+
902
+ raise ArgumentError, "#{name} must not contain whitespace or control characters"
901
903
  end
902
904
 
903
905
  def cas_core(key, always_set, ttl = nil, req_options = nil)
@@ -13,8 +13,49 @@ module Dalli
13
13
  Zlib::Deflate.deflate(data)
14
14
  end
15
15
 
16
- def self.decompress(data)
17
- Zlib::Inflate.inflate(data)
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
+ end
43
+ append_within_limit(out, inflater.finish, max_bytes)
44
+ ensure
45
+ inflater.close
46
+ end
47
+
48
+ # Both yielded and returned output count toward the limit
49
+ def self.inflate_slice(inflater, slice, out, max_bytes)
50
+ rest = inflater.inflate(slice) { |chunk| append_within_limit(out, chunk, max_bytes) }
51
+ append_within_limit(out, rest, max_bytes)
52
+ end
53
+
54
+ def self.append_within_limit(out, chunk, max_bytes)
55
+ out << chunk if chunk
56
+ return out if out.bytesize <= max_bytes
57
+
58
+ raise Dalli::UnmarshalError, "Decompressed value exceeds #{max_bytes} bytes (decompressed_max_bytes)"
18
59
  end
19
60
  end
20
61
 
@@ -32,9 +73,11 @@ module Dalli
32
73
  io.string
33
74
  end
34
75
 
35
- def self.decompress(data)
36
- io = StringIO.new(data, 'rb')
37
- Zlib::GzipReader.new(io).read
76
+ def self.decompress(data, max_bytes: nil)
77
+ return Zlib::GzipReader.new(StringIO.new(data, 'rb')).read unless Compressor.may_exceed?(data, max_bytes)
78
+
79
+ # MAX_WBITS + 16 makes zlib read the gzip format (and check its CRC)
80
+ Compressor.inflate_within_limit(Zlib::Inflate.new(Zlib::MAX_WBITS + 16), data, max_bytes)
38
81
  end
39
82
  end
40
83
  end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Dalli
6
+ ##
7
+ # A serializer that stores values as JSON and never creates Ruby objects
8
+ # from what it reads.
9
+ #
10
+ # Passing the JSON module itself as the serializer (serializer: JSON) reads
11
+ # values back with JSON.load, which on json gem versions before 3.0 honors
12
+ # "json_class" and instantiates other classes when the json gem's additions
13
+ # are loaded. This serializer reads with JSON.parse, so a value written to
14
+ # memcached by someone else can only come back as plain hashes, arrays,
15
+ # strings, numbers, booleans and nil.
16
+ #
17
+ # Dalli::Client.new(servers, serializer: Dalli::JSONSerializer)
18
+ ##
19
+ module JSONSerializer
20
+ def self.dump(value)
21
+ JSON.generate(value)
22
+ end
23
+
24
+ def self.load(data)
25
+ JSON.parse(data)
26
+ end
27
+ end
28
+ end
@@ -58,7 +58,7 @@ module Dalli
58
58
  raise ArgumentError, 'key cannot be blank' unless key&.length&.positive?
59
59
 
60
60
  key = key_with_namespace(key)
61
- key.length > MAX_KEY_LENGTH ? truncated_key(key) : key
61
+ wire_length(key) > MAX_KEY_LENGTH ? truncated_key(key) : key
62
62
  end
63
63
 
64
64
  ##
@@ -122,7 +122,25 @@ module Dalli
122
122
  ##
123
123
  def truncated_key(key)
124
124
  digest = digest_class.hexdigest(key)
125
- "#{key[0, prefix_length(digest)]}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
125
+ prefix = key[0, prefix_length(digest)]
126
+ truncated = "#{prefix}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
127
+ # A prefix with whitespace or non-ASCII characters sends the whole key
128
+ # base64-encoded, which can still be too long on the wire; shorten it.
129
+ while wire_length(truncated) > MAX_KEY_LENGTH
130
+ prefix = prefix[0...-1]
131
+ truncated = "#{prefix}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
132
+ end
133
+ truncated
134
+ end
135
+
136
+ # memcached's key limit applies to the key as sent: in bytes, and after
137
+ # base64 encoding when the key needs it. A key can be within the limit in
138
+ # characters and still be rejected, and memcached's CLIENT_ERROR for it
139
+ # must never reach a pipelined get.
140
+ def wire_length(key)
141
+ return key.bytesize unless Dalli::Protocol::Meta::KeyRegularizer.required?(key)
142
+
143
+ ((key.bytesize + 2) / 3) * 4
126
144
  end
127
145
 
128
146
  def prefix_length(digest)
@@ -53,6 +53,14 @@ module Dalli
53
53
  @raw_mode
54
54
  end
55
55
 
56
+ # True when values should come back as stored: the client is in raw mode,
57
+ # or this request passed raw: true. Retrieval paths use it to skip
58
+ # requesting flags, so a stored value is never deserialized or
59
+ # decompressed for a caller who asked for raw bytes.
60
+ def raw_request?(options)
61
+ raw_mode? || (options.is_a?(Hash) && options[:raw]) ? true : false
62
+ end
63
+
56
64
  # Chokepoint method for error handling and ensuring liveness
57
65
  def request(opkey, *args)
58
66
  verify_state(opkey)
@@ -148,7 +156,15 @@ module Dalli
148
156
  reconnect_on_pipeline_complete!
149
157
  values = nil
150
158
 
151
- response_buffer.read
159
+ # Only the read is socket I/O. The caller's block runs below, outside
160
+ # this rescue, so an Errno or Timeout::Error it raises reaches the
161
+ # caller instead of being mistaken for a network failure (which closed
162
+ # the connection and retried the whole get_multi, yielding keys twice).
163
+ begin
164
+ response_buffer.read
165
+ rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
166
+ @connection_manager.error_on_request!(e)
167
+ end
152
168
 
153
169
  status, cas, key, value = response_buffer.process_single_getk_response
154
170
  # status is not nil only if we have a full response to parse
@@ -174,8 +190,6 @@ module Dalli
174
190
  end
175
191
 
176
192
  values || {}
177
- rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
178
- @connection_manager.error_on_request!(e)
179
193
  end
180
194
  # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
181
195
 
@@ -36,7 +36,10 @@ module Dalli
36
36
  @quiet_responses_pending = false
37
37
  @sock = nil
38
38
  @pid = nil
39
+ @write_buffer = []
40
+ @write_buffer_bytes = 0
39
41
 
42
+ @fail_count = 0
40
43
  reset_down_info
41
44
  end
42
45
 
@@ -52,7 +55,8 @@ module Dalli
52
55
  Dalli.logger.debug { "Dalli::Server#connect #{name}" }
53
56
 
54
57
  @sock = memcached_socket
55
- @sock.sync = false # Enable buffered I/O for better performance
58
+ # Writes are buffered in @write_buffer instead; see WRITE_BUFFER_FLUSH_BYTES
59
+ @sock.sync = true
56
60
  @pid = Process.pid
57
61
  @request_in_progress = false
58
62
  @quiet_responses_pending = false
@@ -85,6 +89,8 @@ module Dalli
85
89
  def down!
86
90
  close
87
91
  log_down_detected
92
+ # Once down_retry_delay passes, the server gets a full set of attempts
93
+ @fail_count = 0
88
94
 
89
95
  @error = $ERROR_INFO&.class&.name
90
96
  @msg ||= $ERROR_INFO&.message
@@ -114,7 +120,7 @@ module Dalli
114
120
  return unless @sock
115
121
 
116
122
  begin
117
- @sock.close
123
+ close_socket
118
124
  rescue StandardError
119
125
  nil
120
126
  ensure
@@ -126,10 +132,18 @@ module Dalli
126
132
  @sock = nil
127
133
  @pid = nil
128
134
  @quiet_responses_pending = false
135
+ discard_write_buffer
129
136
  abort_request!
130
137
  end
131
138
  end
132
139
 
140
+ # A forked child shares the parent's connection, so it closes only its
141
+ # own file descriptor. Closing the TLS socket itself would send
142
+ # close_notify and end the parent's TLS session.
143
+ def close_socket
144
+ fork_detected? ? @sock.to_io.close : @sock.close
145
+ end
146
+
133
147
  def connected?
134
148
  !@sock.nil?
135
149
  end
@@ -163,6 +177,11 @@ module Dalli
163
177
  raise '[Dalli] No request in progress. This may be a bug in Dalli.' unless @request_in_progress
164
178
 
165
179
  @request_in_progress = false
180
+ # A completed request is what proves the server healthy again, so the
181
+ # failure count resets here rather than on reconnect: a server that
182
+ # accepts connections but never answers would otherwise reset it on
183
+ # every retry and never reach socket_max_failures.
184
+ @fail_count = 0
166
185
  end
167
186
 
168
187
  def abort_request!
@@ -170,6 +189,7 @@ module Dalli
170
189
  end
171
190
 
172
191
  def read_line
192
+ flush_write_buffer
173
193
  data = @sock.gets("\r\n")
174
194
  error_on_request!('EOF in read_line') if data.nil?
175
195
  data
@@ -179,14 +199,29 @@ module Dalli
179
199
 
180
200
  # JRuby doesn't support IO#timeout=, so use custom readfull implementation
181
201
  # CRuby 3.3+ has IO#timeout= which makes IO#read work with timeouts
202
+ # memcached can't store an item larger than 1 GiB (its -I maximum), so a
203
+ # reply claiming more (or a negative size) is malformed or hostile.
204
+ # IO#read allocates the full count up front, so check before reading.
205
+ MAX_READ_BYTES = (1024 * 1024 * 1024) + 2 # plus the value's trailing "\r\n"
206
+
207
+ def check_read_size!(count)
208
+ return if count.between?(0, MAX_READ_BYTES)
209
+
210
+ raise Dalli::DalliError, "Reply size #{count} from #{name} is out of range"
211
+ end
212
+
182
213
  if RUBY_ENGINE == 'jruby'
183
214
  def read(count)
215
+ check_read_size!(count)
216
+ flush_write_buffer
184
217
  @sock.readfull(count)
185
218
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
186
219
  error_on_request!(e)
187
220
  end
188
221
  else
189
222
  def read(count)
223
+ check_read_size!(count)
224
+ flush_write_buffer
190
225
  read_bytes(count)
191
226
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
192
227
  error_on_request!(e)
@@ -197,22 +232,34 @@ module Dalli
197
232
  # at the call site.
198
233
  alias read_exact read
199
234
 
235
+ # Requests are buffered here rather than in the socket's own IO buffer
236
+ # (the socket is sync). Ruby flushes an IO's write buffer when any process
237
+ # holding it closes or finalizes the IO, so after a fork a child could
238
+ # send bytes the parent had buffered but not sent yet: a quiet write would
239
+ # run twice, or the parent's replies would shift onto the wrong requests.
240
+ # A forked child discards this buffer instead. Like IO's own buffer, it
241
+ # is sent once it grows past this size, or when a reply is read.
242
+ WRITE_BUFFER_FLUSH_BYTES = 64 * 1024
243
+
200
244
  def write(bytes)
201
- @sock.write(bytes)
245
+ @write_buffer << bytes
246
+ @write_buffer_bytes += bytes.bytesize
247
+ flush_write_buffer if @write_buffer_bytes >= WRITE_BUFFER_FLUSH_BYTES
248
+ bytes.bytesize
202
249
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
203
250
  error_on_request!(e)
204
251
  end
205
252
 
206
253
  def flush
207
- @sock.flush
254
+ flush_write_buffer
208
255
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
209
256
  error_on_request!(e)
210
257
  end
211
258
 
212
259
  def flushed_write(bytes)
213
- written = @sock.write(bytes)
214
- @sock.flush
215
- written
260
+ @write_buffer << bytes
261
+ flush_write_buffer
262
+ bytes.bytesize
216
263
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
217
264
  error_on_request!(e)
218
265
  end
@@ -220,6 +267,7 @@ module Dalli
220
267
  # Non-blocking read. Here to support the operation
221
268
  # of the get_multi operation
222
269
  def read_available(...)
270
+ flush_write_buffer
223
271
  @sock.read_available(...)
224
272
  end
225
273
 
@@ -246,8 +294,9 @@ module Dalli
246
294
  raise Dalli::RetryableNetworkError, message
247
295
  end
248
296
 
297
+ # Called on connect. Deliberately leaves @fail_count alone; see
298
+ # finish_request!.
249
299
  def reset_down_info
250
- @fail_count = 0
251
300
  @down_at = nil
252
301
  @last_down_at = nil
253
302
  @msg = nil
@@ -272,7 +321,8 @@ module Dalli
272
321
  def reconnect_on_fork
273
322
  message = 'Fork detected, re-connecting child process...'
274
323
  Dalli.logger.info { message }
275
- # Close socket on a fork and reconnect immediately
324
+ # Drops anything the parent had buffered, closes the inherited socket
325
+ # without touching the parent's connection, and reconnects immediately
276
326
  close
277
327
  establish_connection
278
328
  end
@@ -302,6 +352,18 @@ module Dalli
302
352
 
303
353
  private
304
354
 
355
+ def flush_write_buffer
356
+ return if @write_buffer.empty?
357
+
358
+ @sock.write(*@write_buffer)
359
+ discard_write_buffer
360
+ end
361
+
362
+ def discard_write_buffer
363
+ @write_buffer.clear
364
+ @write_buffer_bytes = 0
365
+ end
366
+
305
367
  # Reads exactly `count` bytes. IO#read(count) on a blocking socket blocks
306
368
  # until it has `count` bytes, accumulating across TCP chunks internally,
307
369
  # and only hands back a shorter (or nil) buffer when the stream hits EOF.
@@ -43,15 +43,15 @@ module Dalli
43
43
 
44
44
  def quiet_get_request(key, options = nil)
45
45
  # Skip bitflags in raw mode - saves 2 bytes per request and skips parsing
46
- RequestFormatter.meta_get(key: key, return_cas: true, quiet: true, skip_flags: raw_mode?,
46
+ RequestFormatter.meta_get(key: key, return_cas: true, quiet: true, skip_flags: raw_request?(options),
47
47
  **routing_token_kwargs(options))
48
48
  end
49
49
 
50
50
  # Same requests as quiet_get_request for each key, built in one pass
51
51
  # and without the trailing noop.
52
52
  def quiet_get_requests(keys, options = nil, return_cas: true)
53
- RequestFormatter.multi_meta_get(keys, skip_flags: raw_mode?, return_cas: return_cas, terminate: false,
54
- **routing_token_kwargs(options))
53
+ RequestFormatter.multi_meta_get(keys, skip_flags: raw_request?(options), return_cas: return_cas,
54
+ terminate: false, **routing_token_kwargs(options))
55
55
  end
56
56
 
57
57
  def gat(key, ttl, options = nil)
@@ -72,7 +72,8 @@ module Dalli
72
72
  # TODO: This is confusing, as there's a cas command in memcached
73
73
  # and this isn't it. Maybe rename? Maybe eliminate?
74
74
  def cas(key, options = nil)
75
- req = RequestFormatter.meta_get(key: key, value: true, return_cas: true, **routing_token_kwargs(options))
75
+ req = RequestFormatter.meta_get(key: key, value: true, return_cas: true, skip_flags: raw_request?(options),
76
+ **routing_token_kwargs(options))
76
77
  flushed_write(req)
77
78
  response_processor.meta_get_with_value_and_cas
78
79
  end
@@ -103,7 +104,7 @@ module Dalli
103
104
  # - :last_access - seconds since last access (only if return_last_access: true)
104
105
  def meta_get(key, options = {})
105
106
  req = RequestFormatter.meta_get(
106
- key: key, value: true, return_cas: true,
107
+ key: key, value: true, return_cas: true, skip_flags: raw_request?(options),
107
108
  vivify_ttl: options[:vivify_ttl], recache_ttl: options[:recache_ttl],
108
109
  return_hit_status: options[:return_hit_status],
109
110
  return_last_access: options[:return_last_access],
@@ -288,7 +289,7 @@ module Dalli
288
289
  # response parsing to minimize per-key overhead. Avoids the PipelinedGetter
289
290
  # machinery (IO.select, response buffering, server grouping).
290
291
  def read_multi_req(keys, options = nil)
291
- is_raw = raw_mode?
292
+ is_raw = raw_request?(options)
292
293
  buffer = RequestFormatter.multi_meta_get(keys, skip_flags: is_raw, **routing_token_kwargs(options))
293
294
  flushed_write(buffer)
294
295
  buffer.clear
@@ -304,7 +305,7 @@ module Dalli
304
305
  # Shared by both the single-server fast path and PipelinedGetter's
305
306
  # per-server-group request, so this one change covers both routes.
306
307
  def read_multi_with_metadata_req(keys, options = nil)
307
- is_raw = raw_mode?
308
+ is_raw = raw_request?(options)
308
309
  buffer = RequestFormatter.multi_meta_get(keys, skip_flags: is_raw, return_cas: true,
309
310
  **routing_token_kwargs(options))
310
311
  flushed_write(buffer)
@@ -218,11 +218,11 @@ module Dalli
218
218
  # specifications to a proxy or router inbetween a client and a
219
219
  # memcached daemon."
220
220
  #
221
- # Empty / nil tokens are treated as no-ops. CRLF and null bytes are
222
- # rejected with ArgumentError to prevent the token from being used as a
223
- # wire-protocol injection vector (e.g. "foo\r\nflush_all\r\n" would
224
- # otherwise be parsed as a second command by memcached or any
225
- # intermediate proxy/LB).
221
+ # Empty / nil tokens are treated as no-ops. Whitespace and control
222
+ # characters are rejected with ArgumentError so a token can't be used
223
+ # for wire-protocol injection: CRLF would add a second command (e.g.
224
+ # "foo\r\nflush_all\r\n"), and a space would add meta flags to this one
225
+ # (e.g. "foo T1" changing an item's TTL on a read).
226
226
  def routing_tokens(p_token: nil, l_token: nil)
227
227
  # Only an empty *String* is a no-op. Checking respond_to?(:empty?)
228
228
  # instead would also swallow p_token: [] / {} before the type check
@@ -279,15 +279,18 @@ module Dalli
279
279
 
280
280
  private
281
281
 
282
- # Disallowed bytes: CR, LF, NUL. Any of these embedded in a routing
283
- # token would let the caller inject a second wire-protocol command.
284
- ROUTING_TOKEN_FORBIDDEN = /[\r\n\0]/
282
+ # Disallowed bytes: whitespace and control characters. CR, LF or NUL
283
+ # would let a token inject a second command; a space would let it add
284
+ # meta flags (T, N, I, q, ...) to the request it rides on.
285
+ ROUTING_TOKEN_FORBIDDEN = /[\x00-\x20\x7F]/
285
286
  private_constant :ROUTING_TOKEN_FORBIDDEN
286
287
 
287
288
  def validate_routing_token!(name, value)
288
289
  return if value.nil?
289
290
  raise ArgumentError, "#{name} must be a String, got #{value.class}" unless value.is_a?(String)
290
- raise ArgumentError, "#{name} must not contain CRLF or null bytes" if value.match?(ROUTING_TOKEN_FORBIDDEN)
291
+ return unless value.match?(ROUTING_TOKEN_FORBIDDEN)
292
+
293
+ raise ArgumentError, "#{name} must not contain whitespace or control characters"
291
294
  end
292
295
 
293
296
  # Numeric flag values are written straight into the command line, so a
@@ -24,6 +24,8 @@ module Dalli
24
24
  SERVER_ERROR = 'SERVER_ERROR'
25
25
 
26
26
  VA_PREFIX = 'VA '
27
+ # memcached can't store an item larger than 1 GiB (its -I maximum)
28
+ MAX_VALUE_BYTES = 1024 * 1024 * 1024
27
29
  HD_PREFIX = 'HD '
28
30
  FLAGS_TOKEN_PREFIX = ' f'
29
31
  CAS_TOKEN_PREFIX = ' c'
@@ -256,14 +258,16 @@ module Dalli
256
258
  end
257
259
  body_len = flag_int(size, 's')
258
260
 
259
- # We have a complete response that has no body.
260
- # This is either the response to the terminating
261
- # noop or, if the status is not MN, an intermediate
262
- # error response that needs to be discarded. A hit
263
- # on an empty value (VA 0) still has a body -- just
264
- # its terminator -- so it's parsed below as a value.
265
- return [true, header_len] if body_len.zero? && tokens.first != VA
261
+ # A complete response with no body. Only the terminating noop's MN
262
+ # ends the pipeline. Any other bodyless reply (CLIENT_ERROR,
263
+ # SERVER_ERROR, ...) answers one key's request: report it with a
264
+ # false status so the caller skips it and keeps reading. Treating it
265
+ # as the end would leave the remaining replies on the connection for
266
+ # later commands to read as their own. A hit on an empty value (VA 0)
267
+ # still has a body -- just its terminator -- so it's parsed below.
268
+ return [tokens.first == MN, header_len] if body_len.zero? && tokens.first != VA
266
269
 
270
+ check_value_size!(body_len)
267
271
  resp_size = header_len + body_len + TERMINATOR.length
268
272
  # The header is in the buffer, but the body is not. As we don't have
269
273
  # a complete response, don't advance the buffer
@@ -300,6 +304,7 @@ module Dalli
300
304
  end
301
305
  return nil if size.nil? || size.zero?
302
306
 
307
+ check_value_size!(size)
303
308
  header_len = term_idx - offset + TERMINATOR.length
304
309
  resp_size = header_len + size + TERMINATOR.length
305
310
  return [0] unless buf.bytesize >= offset + resp_size
@@ -424,6 +429,14 @@ module Dalli
424
429
  end
425
430
  end
426
431
 
432
+ # A pipelined reply claiming an impossible size would otherwise have the
433
+ # buffer wait for (and accumulate) that many bytes
434
+ def check_value_size!(size)
435
+ return if size.between?(0, MAX_VALUE_BYTES)
436
+
437
+ raise Dalli::DalliError, "Reply value size #{size} is out of range"
438
+ end
439
+
427
440
  def read_line
428
441
  @io_source.read_line&.chomp!(TERMINATOR)
429
442
  end
@@ -15,11 +15,17 @@ module Dalli
15
15
  compress: true,
16
16
  compressor: ::Dalli::Compressor,
17
17
  # min byte size to attempt compression
18
- compression_min_size: 4 * 1024 # 4K
18
+ compression_min_size: 4 * 1024, # 4K
19
+ # max size a stored value may decompress to (nil: no limit). Guards
20
+ # against a small compressed value expanding into gigabytes on read.
21
+ decompressed_max_bytes: 128 * 1024 * 1024 # 128 MiB
19
22
  }.freeze
20
23
 
21
24
  OPTIONS = DEFAULTS.keys.freeze
22
25
 
26
+ KEYWORD_PARAMETER_TYPES = %i[key keyreq].freeze
27
+ private_constant :KEYWORD_PARAMETER_TYPES
28
+
23
29
  def initialize(client_options)
24
30
  @compression_options =
25
31
  DEFAULTS.merge(client_options.slice(*OPTIONS))
@@ -34,8 +40,16 @@ module Dalli
34
40
  end
35
41
 
36
42
  def retrieve(value, bitflags)
37
- compressed = bitflags.anybits?(Flags::COMPRESSED)
38
- compressed ? compressor.decompress(value) : value
43
+ return value unless bitflags.anybits?(Flags::COMPRESSED)
44
+
45
+ max_bytes = @compression_options[:decompressed_max_bytes]
46
+ # Custom compressors that only define decompress(data) keep working,
47
+ # without the limit
48
+ if max_bytes && compressor_accepts_max_bytes?
49
+ compressor.decompress(value, max_bytes: max_bytes)
50
+ else
51
+ compressor.decompress(value)
52
+ end
39
53
 
40
54
  # TODO: We likely want to move this rescue into the Dalli::Compressor / Dalli::GzipCompressor
41
55
  # itself, since not all compressors necessarily use Zlib. For now keep it here, so the behavior
@@ -44,6 +58,19 @@ module Dalli
44
58
  raise UnmarshalError, "Unable to uncompress value: #{$ERROR_INFO.message}"
45
59
  end
46
60
 
61
+ def compressor_accepts_max_bytes?
62
+ return @compressor_accepts_max_bytes if defined?(@compressor_accepts_max_bytes)
63
+
64
+ @compressor_accepts_max_bytes =
65
+ begin
66
+ compressor.method(:decompress).parameters.any? do |type, name|
67
+ name == :max_bytes && KEYWORD_PARAMETER_TYPES.include?(type)
68
+ end
69
+ rescue NameError # an object without a reflectable decompress method
70
+ false
71
+ end
72
+ end
73
+
47
74
  def compress_by_default?
48
75
  @compression_options[:compress]
49
76
  end
@@ -100,7 +100,7 @@ module Dalli
100
100
  Dalli.logger.warn 'SECURITY WARNING: Dalli is using Marshal for serialization. ' \
101
101
  'Marshal can execute arbitrary code during deserialization. ' \
102
102
  'If your memcached server could be compromised, consider using ' \
103
- 'a safer serializer like JSON: Dalli::Client.new(servers, serializer: JSON)'
103
+ 'a safer serializer: Dalli::Client.new(servers, serializer: Dalli::JSONSerializer)'
104
104
  @@marshal_warning_logged = true # rubocop:disable Style/ClassVars
105
105
  end
106
106
  end
data/lib/dalli/version.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Dalli
4
- VERSION = '5.2.0'
4
+ VERSION = '5.2.1'
5
5
 
6
6
  MIN_SUPPORTED_MEMCACHED_VERSION = '1.6.27'
7
7
  end
data/lib/dalli.rb CHANGED
@@ -62,6 +62,7 @@ require_relative 'dalli/version'
62
62
  require_relative 'dalli/instrumentation'
63
63
 
64
64
  require_relative 'dalli/flags'
65
+ require_relative 'dalli/json_serializer'
65
66
  require_relative 'dalli/compressor'
66
67
  require_relative 'dalli/cache_result'
67
68
  require_relative 'dalli/client'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: dalli
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.2.0
4
+ version: 5.2.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Peter M. Goldstein
@@ -43,6 +43,7 @@ files:
43
43
  - lib/dalli/compressor.rb
44
44
  - lib/dalli/flags.rb
45
45
  - lib/dalli/instrumentation.rb
46
+ - lib/dalli/json_serializer.rb
46
47
  - lib/dalli/key_manager.rb
47
48
  - lib/dalli/options.rb
48
49
  - lib/dalli/pipelined_deleter.rb