dalli 5.1.1 → 5.1.3

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: 1cb62e15948a7d649e178bcfc9aa03de998be618f4fa7d08c988f874006c941f
4
- data.tar.gz: 0b2d3d9d1a7a73276a6fa22e2015805a306bab7c0e53616a9531eccff7979c33
3
+ metadata.gz: bf1d386c0e4bbde88c4dcafcd1babe51ffa12eaa173e105019bdcce2f7a2acfa
4
+ data.tar.gz: 07463ea0880be455439262d77dc8255562a0ed7035e5ec29ee07888612d844a2
5
5
  SHA512:
6
- metadata.gz: eaab609ed368a7f8f2fa129eab6177894cfc7548ea25002b30bae4ee13d22daaa6470241f97ba6e01a5b457820587e5c08e4426b948f889f6921c556dbdd8438
7
- data.tar.gz: 78d2faea9492b9f18bf7a0f5a0459a785319d0261c81f32c9fd218bb837b73550b79af8bd94373abc17f6e94db8b049a515308de2475905fda004a66de4cacc6
6
+ metadata.gz: 98f088e6d7c01b13b912a18f4c870587d02db32ebb3b6ec471359f97bf15324261468b7d62186f1ffc03bfe66ff175884c18f551fd457cf6a80dc2aef1774608
7
+ data.tar.gz: b3919430e8b9ed967e52495d626013b54a4c8a8b62c8a3042224569d6594b455188ff5d0ceb2342810994e5dc419dea780bf969c9cfa918395387127758a1b96
data/CHANGELOG.md CHANGED
@@ -4,6 +4,55 @@ Dalli Changelog
4
4
  Unreleased
5
5
  ==========
6
6
 
7
+ 5.1.3
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
+ 5.1.2
41
+ ==========
42
+
43
+ Bug fixes:
44
+
45
+ - Fix multi-server `get_multi` stopping at an empty value (#1170)
46
+ - 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
47
+ - 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
48
+ - An empty value is now returned as `''`, like a single-key `get` and single-server `get_multi`
49
+ - Affects the meta protocol since 3.2.0 (the default since 5.0.0)
50
+ - Thanks to Julian Richard Contreras for this contribution
51
+
52
+ Development:
53
+
54
+ - Add property tests for request building and fuzz tests for the reply parsers
55
+
7
56
  5.1.1
8
57
  ==========
9
58
 
data/README.md CHANGED
@@ -54,9 +54,13 @@ The separator must be a single non-alphanumeric character. Valid examples: `:`,
54
54
  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:
55
55
 
56
56
  ```ruby
57
- Dalli::Client.new('localhost:11211', serializer: JSON)
57
+ Dalli::Client.new('localhost:11211', serializer: Dalli::JSONSerializer)
58
58
  ```
59
59
 
60
+ `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.
61
+
62
+ 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`).
63
+
60
64
  See the [5.0-Upgrade.md](5.0-Upgrade.md) guide for upgrade information.
61
65
 
62
66
  ## OpenTelemetry Tracing
data/lib/dalli/client.rb CHANGED
@@ -821,7 +821,7 @@ module Dalli
821
821
  # check means unwinding through Protocol::Base#request, which logs the
822
822
  # failure as unexpected and closes the connection -- a caller passing a
823
823
  # bad token should get a clean ArgumentError and keep its connection.
824
- ROUTING_TOKEN_FORBIDDEN = /[\r\n\0]/
824
+ ROUTING_TOKEN_FORBIDDEN = /[\x00-\x20\x7F]/
825
825
  private_constant :ROUTING_TOKEN_FORBIDDEN
826
826
 
827
827
  def validate_routing_tokens!(req_options)
@@ -837,7 +837,9 @@ module Dalli
837
837
  # here (it would also excuse [] / {} from the type check below).
838
838
  return if value.nil? || (value.is_a?(String) && value.empty?)
839
839
  raise ArgumentError, "#{name} must be a String, got #{value.class}" unless value.is_a?(String)
840
- raise ArgumentError, "#{name} must not contain CRLF or null bytes" if value.match?(ROUTING_TOKEN_FORBIDDEN)
840
+ return unless value.match?(ROUTING_TOKEN_FORBIDDEN)
841
+
842
+ raise ArgumentError, "#{name} must not contain whitespace or control characters"
841
843
  end
842
844
 
843
845
  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)
@@ -51,6 +51,14 @@ module Dalli
51
51
  @raw_mode
52
52
  end
53
53
 
54
+ # True when values should come back as stored: the client is in raw mode,
55
+ # or this request passed raw: true. Retrieval paths use it to skip
56
+ # requesting flags, so a stored value is never deserialized or
57
+ # decompressed for a caller who asked for raw bytes.
58
+ def raw_request?(options)
59
+ raw_mode? || (options.is_a?(Hash) && options[:raw]) ? true : false
60
+ end
61
+
54
62
  # Chokepoint method for error handling and ensuring liveness
55
63
  def request(opkey, *args)
56
64
  verify_state(opkey)
@@ -142,7 +150,15 @@ module Dalli
142
150
  reconnect_on_pipeline_complete!
143
151
  values = nil
144
152
 
145
- response_buffer.read
153
+ # Only the read is socket I/O. The caller's block runs below, outside
154
+ # this rescue, so an Errno or Timeout::Error it raises reaches the
155
+ # caller instead of being mistaken for a network failure (which closed
156
+ # the connection and retried the whole get_multi, yielding keys twice).
157
+ begin
158
+ response_buffer.read
159
+ rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
160
+ @connection_manager.error_on_request!(e)
161
+ end
146
162
 
147
163
  status, cas, key, value = response_buffer.process_single_getk_response
148
164
  # status is not nil only if we have a full response to parse
@@ -168,8 +184,6 @@ module Dalli
168
184
  end
169
185
 
170
186
  values || {}
171
- rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
172
- @connection_manager.error_on_request!(e)
173
187
  end
174
188
  # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
175
189
 
@@ -35,7 +35,10 @@ module Dalli
35
35
  @request_in_progress = false
36
36
  @sock = nil
37
37
  @pid = nil
38
+ @write_buffer = []
39
+ @write_buffer_bytes = 0
38
40
 
41
+ @fail_count = 0
39
42
  reset_down_info
40
43
  end
41
44
 
@@ -51,7 +54,8 @@ module Dalli
51
54
  Dalli.logger.debug { "Dalli::Server#connect #{name}" }
52
55
 
53
56
  @sock = memcached_socket
54
- @sock.sync = false # Enable buffered I/O for better performance
57
+ # Writes are buffered in @write_buffer instead; see WRITE_BUFFER_FLUSH_BYTES
58
+ @sock.sync = true
55
59
  @pid = Process.pid
56
60
  @request_in_progress = false
57
61
  rescue SystemCallError, *TIMEOUT_ERRORS, EOFError, SocketError => e
@@ -83,6 +87,8 @@ module Dalli
83
87
  def down!
84
88
  close
85
89
  log_down_detected
90
+ # Once down_retry_delay passes, the server gets a full set of attempts
91
+ @fail_count = 0
86
92
 
87
93
  @error = $ERROR_INFO&.class&.name
88
94
  @msg ||= $ERROR_INFO&.message
@@ -112,7 +118,7 @@ module Dalli
112
118
  return unless @sock
113
119
 
114
120
  begin
115
- @sock.close
121
+ close_socket
116
122
  rescue StandardError
117
123
  nil
118
124
  ensure
@@ -123,10 +129,18 @@ module Dalli
123
129
  # @request_in_progress == true.
124
130
  @sock = nil
125
131
  @pid = nil
132
+ discard_write_buffer
126
133
  abort_request!
127
134
  end
128
135
  end
129
136
 
137
+ # A forked child shares the parent's connection, so it closes only its
138
+ # own file descriptor. Closing the TLS socket itself would send
139
+ # close_notify and end the parent's TLS session.
140
+ def close_socket
141
+ fork_detected? ? @sock.to_io.close : @sock.close
142
+ end
143
+
130
144
  def connected?
131
145
  !@sock.nil?
132
146
  end
@@ -145,6 +159,11 @@ module Dalli
145
159
  raise '[Dalli] No request in progress. This may be a bug in Dalli.' unless @request_in_progress
146
160
 
147
161
  @request_in_progress = false
162
+ # A completed request is what proves the server healthy again, so the
163
+ # failure count resets here rather than on reconnect: a server that
164
+ # accepts connections but never answers would otherwise reset it on
165
+ # every retry and never reach socket_max_failures.
166
+ @fail_count = 0
148
167
  end
149
168
 
150
169
  def abort_request!
@@ -152,6 +171,7 @@ module Dalli
152
171
  end
153
172
 
154
173
  def read_line
174
+ flush_write_buffer
155
175
  data = @sock.gets("\r\n")
156
176
  error_on_request!('EOF in read_line') if data.nil?
157
177
  data
@@ -161,14 +181,29 @@ module Dalli
161
181
 
162
182
  # JRuby doesn't support IO#timeout=, so use custom readfull implementation
163
183
  # CRuby 3.3+ has IO#timeout= which makes IO#read work with timeouts
184
+ # memcached can't store an item larger than 1 GiB (its -I maximum), so a
185
+ # reply claiming more (or a negative size) is malformed or hostile.
186
+ # IO#read allocates the full count up front, so check before reading.
187
+ MAX_READ_BYTES = (1024 * 1024 * 1024) + 2 # plus the value's trailing "\r\n"
188
+
189
+ def check_read_size!(count)
190
+ return if count.between?(0, MAX_READ_BYTES)
191
+
192
+ raise Dalli::DalliError, "Reply size #{count} from #{name} is out of range"
193
+ end
194
+
164
195
  if RUBY_ENGINE == 'jruby'
165
196
  def read(count)
197
+ check_read_size!(count)
198
+ flush_write_buffer
166
199
  @sock.readfull(count)
167
200
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
168
201
  error_on_request!(e)
169
202
  end
170
203
  else
171
204
  def read(count)
205
+ check_read_size!(count)
206
+ flush_write_buffer
172
207
  read_bytes(count)
173
208
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
174
209
  error_on_request!(e)
@@ -179,22 +214,34 @@ module Dalli
179
214
  # at the call site.
180
215
  alias read_exact read
181
216
 
217
+ # Requests are buffered here rather than in the socket's own IO buffer
218
+ # (the socket is sync). Ruby flushes an IO's write buffer when any process
219
+ # holding it closes or finalizes the IO, so after a fork a child could
220
+ # send bytes the parent had buffered but not sent yet: a quiet write would
221
+ # run twice, or the parent's replies would shift onto the wrong requests.
222
+ # A forked child discards this buffer instead. Like IO's own buffer, it
223
+ # is sent once it grows past this size, or when a reply is read.
224
+ WRITE_BUFFER_FLUSH_BYTES = 64 * 1024
225
+
182
226
  def write(bytes)
183
- @sock.write(bytes)
227
+ @write_buffer << bytes
228
+ @write_buffer_bytes += bytes.bytesize
229
+ flush_write_buffer if @write_buffer_bytes >= WRITE_BUFFER_FLUSH_BYTES
230
+ bytes.bytesize
184
231
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
185
232
  error_on_request!(e)
186
233
  end
187
234
 
188
235
  def flush
189
- @sock.flush
236
+ flush_write_buffer
190
237
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
191
238
  error_on_request!(e)
192
239
  end
193
240
 
194
241
  def flushed_write(bytes)
195
- written = @sock.write(bytes)
196
- @sock.flush
197
- written
242
+ @write_buffer << bytes
243
+ flush_write_buffer
244
+ bytes.bytesize
198
245
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
199
246
  error_on_request!(e)
200
247
  end
@@ -202,6 +249,7 @@ module Dalli
202
249
  # Non-blocking read. Here to support the operation
203
250
  # of the get_multi operation
204
251
  def read_available(...)
252
+ flush_write_buffer
205
253
  @sock.read_available(...)
206
254
  end
207
255
 
@@ -228,8 +276,9 @@ module Dalli
228
276
  raise Dalli::RetryableNetworkError, message
229
277
  end
230
278
 
279
+ # Called on connect. Deliberately leaves @fail_count alone; see
280
+ # finish_request!.
231
281
  def reset_down_info
232
- @fail_count = 0
233
282
  @down_at = nil
234
283
  @last_down_at = nil
235
284
  @msg = nil
@@ -254,7 +303,8 @@ module Dalli
254
303
  def reconnect_on_fork
255
304
  message = 'Fork detected, re-connecting child process...'
256
305
  Dalli.logger.info { message }
257
- # Close socket on a fork and reconnect immediately
306
+ # Drops anything the parent had buffered, closes the inherited socket
307
+ # without touching the parent's connection, and reconnects immediately
258
308
  close
259
309
  establish_connection
260
310
  end
@@ -284,6 +334,18 @@ module Dalli
284
334
 
285
335
  private
286
336
 
337
+ def flush_write_buffer
338
+ return if @write_buffer.empty?
339
+
340
+ @sock.write(*@write_buffer)
341
+ discard_write_buffer
342
+ end
343
+
344
+ def discard_write_buffer
345
+ @write_buffer.clear
346
+ @write_buffer_bytes = 0
347
+ end
348
+
287
349
  # Reads exactly `count` bytes. IO#read(count) on a blocking socket blocks
288
350
  # until it has `count` bytes, accumulating across TCP chunks internally,
289
351
  # 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],
@@ -266,7 +267,7 @@ module Dalli
266
267
  # response parsing to minimize per-key overhead. Avoids the PipelinedGetter
267
268
  # machinery (IO.select, response buffering, server grouping).
268
269
  def read_multi_req(keys, options = nil)
269
- is_raw = raw_mode?
270
+ is_raw = raw_request?(options)
270
271
  buffer = RequestFormatter.multi_meta_get(keys, skip_flags: is_raw, **routing_token_kwargs(options))
271
272
  flushed_write(buffer)
272
273
  buffer.clear
@@ -282,7 +283,7 @@ module Dalli
282
283
  # Shared by both the single-server fast path and PipelinedGetter's
283
284
  # per-server-group request, so this one change covers both routes.
284
285
  def read_multi_with_metadata_req(keys, options = nil)
285
- is_raw = raw_mode?
286
+ is_raw = raw_request?(options)
286
287
  buffer = RequestFormatter.multi_meta_get(keys, skip_flags: is_raw, return_cas: true,
287
288
  **routing_token_kwargs(options))
288
289
  flushed_write(buffer)
@@ -200,11 +200,11 @@ module Dalli
200
200
  # specifications to a proxy or router inbetween a client and a
201
201
  # memcached daemon."
202
202
  #
203
- # Empty / nil tokens are treated as no-ops. CRLF and null bytes are
204
- # rejected with ArgumentError to prevent the token from being used as a
205
- # wire-protocol injection vector (e.g. "foo\r\nflush_all\r\n" would
206
- # otherwise be parsed as a second command by memcached or any
207
- # intermediate proxy/LB).
203
+ # Empty / nil tokens are treated as no-ops. Whitespace and control
204
+ # characters are rejected with ArgumentError so a token can't be used
205
+ # for wire-protocol injection: CRLF would add a second command (e.g.
206
+ # "foo\r\nflush_all\r\n"), and a space would add meta flags to this one
207
+ # (e.g. "foo T1" changing an item's TTL on a read).
208
208
  def routing_tokens(p_token: nil, l_token: nil)
209
209
  # Only an empty *String* is a no-op. Checking respond_to?(:empty?)
210
210
  # instead would also swallow p_token: [] / {} before the type check
@@ -261,15 +261,18 @@ module Dalli
261
261
 
262
262
  private
263
263
 
264
- # Disallowed bytes: CR, LF, NUL. Any of these embedded in a routing
265
- # token would let the caller inject a second wire-protocol command.
266
- ROUTING_TOKEN_FORBIDDEN = /[\r\n\0]/
264
+ # Disallowed bytes: whitespace and control characters. CR, LF or NUL
265
+ # would let a token inject a second command; a space would let it add
266
+ # meta flags (T, N, I, q, ...) to the request it rides on.
267
+ ROUTING_TOKEN_FORBIDDEN = /[\x00-\x20\x7F]/
267
268
  private_constant :ROUTING_TOKEN_FORBIDDEN
268
269
 
269
270
  def validate_routing_token!(name, value)
270
271
  return if value.nil?
271
272
  raise ArgumentError, "#{name} must be a String, got #{value.class}" unless value.is_a?(String)
272
- raise ArgumentError, "#{name} must not contain CRLF or null bytes" if value.match?(ROUTING_TOKEN_FORBIDDEN)
273
+ return unless value.match?(ROUTING_TOKEN_FORBIDDEN)
274
+
275
+ raise ArgumentError, "#{name} must not contain whitespace or control characters"
273
276
  end
274
277
 
275
278
  # 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
  FLAGS_TOKEN_PREFIX = ' f'
28
30
  BYTE_B = 'b'.ord
29
31
  BYTE_C = 'c'.ord
@@ -236,12 +238,16 @@ module Dalli
236
238
  end
237
239
  body_len = flag_int(size, 's')
238
240
 
239
- # We have a complete response that has no body.
240
- # This is either the response to the terminating
241
- # noop or, if the status is not MN, an intermediate
242
- # error response that needs to be discarded.
243
- return [true, header_len] if body_len.zero?
241
+ # A complete response with no body. Only the terminating noop's MN
242
+ # ends the pipeline. Any other bodyless reply (CLIENT_ERROR,
243
+ # SERVER_ERROR, ...) answers one key's request: report it with a
244
+ # false status so the caller skips it and keeps reading. Treating it
245
+ # as the end would leave the remaining replies on the connection for
246
+ # later commands to read as their own. A hit on an empty value (VA 0)
247
+ # still has a body -- just its terminator -- so it's parsed below.
248
+ return [tokens.first == MN, header_len] if body_len.zero? && tokens.first != VA
244
249
 
250
+ check_value_size!(body_len)
245
251
  resp_size = header_len + body_len + TERMINATOR.length
246
252
  # The header is in the buffer, but the body is not. As we don't have
247
253
  # a complete response, don't advance the buffer
@@ -344,6 +350,14 @@ module Dalli
344
350
  end
345
351
  end
346
352
 
353
+ # A pipelined reply claiming an impossible size would otherwise have the
354
+ # buffer wait for (and accumulate) that many bytes
355
+ def check_value_size!(size)
356
+ return if size.between?(0, MAX_VALUE_BYTES)
357
+
358
+ raise Dalli::DalliError, "Reply value size #{size} is out of range"
359
+ end
360
+
347
361
  def read_line
348
362
  @io_source.read_line&.chomp!(TERMINATOR)
349
363
  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.1.1'
4
+ VERSION = '5.1.3'
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/client'
67
68
  require_relative 'dalli/key_manager'
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.1.1
4
+ version: 5.1.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Peter M. Goldstein
@@ -42,6 +42,7 @@ files:
42
42
  - lib/dalli/compressor.rb
43
43
  - lib/dalli/flags.rb
44
44
  - lib/dalli/instrumentation.rb
45
+ - lib/dalli/json_serializer.rb
45
46
  - lib/dalli/key_manager.rb
46
47
  - lib/dalli/options.rb
47
48
  - lib/dalli/pipelined_deleter.rb