dalli 5.2.7 → 5.2.9

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: 7f2cea6074db3fcade9ffdc5277b26cddb9752ee9a4229536e2a883755d4137e
4
- data.tar.gz: 0f4294f047e670e18a2c97c0c7187e84449096a5e230faf7956547e634c996e9
3
+ metadata.gz: 2e1086cdd8b9a7bac4828786bfb089d1b046c5b1e61cd5074c795c5a2bc81acf
4
+ data.tar.gz: 3a3987346678ee792c0ce367ff3141122fcd9ac9c35eeb203e22f7e22d1cc4ea
5
5
  SHA512:
6
- metadata.gz: af2703898196c9ea24497f5777061d90b6797acb39faec3fc82b6206d2beb02668420d318bb519728b1f72383e66c05af465592ab0726e3703f5944b93a78c32
7
- data.tar.gz: a59742b1c0c146cd2b36f0d36d55fc94c4491353d364a1c8a3f216452ba293b801d79fb7c34dc3ffa85bbe3aea0d72f82621f67dad3aada23579a5e50048e312
6
+ metadata.gz: aae2272b110f5d4aa579884fecd7b090b76fa66f3014ad60b9481c1567d1ec1bdadaf2804e593e58d3d46614dba6d2b327628367708094f1c07a26f0d0ce108d
7
+ data.tar.gz: 2f773864672599adfb9b1f75bb66ff032d235f8d2e771020e48fe3b569d6d6ab6ffcd00c37043220bf850d36c999d454cdc4e283b90168d0abe531a9456b07bc
data/CHANGELOG.md CHANGED
@@ -1,6 +1,21 @@
1
1
  Dalli Changelog
2
2
  =====================
3
3
 
4
+ 5.2.9
5
+ ==========
6
+
7
+ Security:
8
+
9
+ - Bound memcached reply headers, incoming value sizes, and response counts, and enforce TLS timeouts for blocking operations (GHSA-5wpc-45jc-6ccc)
10
+
11
+ 5.2.8
12
+ ==========
13
+
14
+ Bug fixes:
15
+
16
+ - `set_multi` and `delete_multi` on more than one server retried forever, hanging the caller, when a server accepted their writes and then closed the connection before replying. Each quiet write reset the server's failure count, so it never reached `socket_max_failures`. Only a request whose reply is read resets it now, and the server is marked down and `Dalli::NetworkError` raised, as for `get`
17
+ - A signal arriving while `Dalli::Compressor` or `Dalli::GzipCompressor` was compressing or decompressing could make Ruby's zlib return before it had finished (ruby/zlib#49). Depending on the Ruby and zlib gem versions, that raised `Zlib::BufError` or `Zlib::DataError`, or stored a truncated value that later failed to decompress. Both compressors now keep finishing the stream until zlib reports its end. `GzipCompressor` no longer goes through `GzipWriter` and `GzipReader`, so it now always returns decompressed values as binary strings, as `Compressor` does (#1299)
18
+
4
19
  5.2.7
5
20
  ==========
6
21
 
data/README.md CHANGED
@@ -70,6 +70,8 @@ Dalli::Client.new('localhost:11211', value_max_bytes: 2 * 1024 * 1024)
70
70
 
71
71
  memcached's limit covers the whole item, so Dalli checks the stored (serialized and compressed) value plus the key plus 63 bytes of per-item overhead against `value_max_bytes`, and raises `Dalli::ValueOverMaxSize` before sending anything larger. With the defaults, the largest value you can store under a 10-byte key is 1,048,576 - 10 - 63 = 1,048,503 bytes.
72
72
 
73
+ Dalli also limits the size of values it reads to `value_max_bytes`. If another client writes larger items that this client needs to read, set `max_response_bytes` explicitly. Keep it no higher than the largest item size you intend to accept from the server.
74
+
73
75
  ### Deferred Draining
74
76
 
75
77
  By default, a `quiet` (or `multi`) block ends by waiting for the replies memcached still sends for its quiet requests, one round trip for each server the block wrote to. With `defer_drain: true`, the block returns without waiting:
data/lib/dalli/client.rb CHANGED
@@ -39,6 +39,8 @@ module Dalli
39
39
  # memcached, Dalli counts the key and 63 bytes of item overhead against this limit along
40
40
  # with the (serialized, compressed) value, so the largest value that can be stored is
41
41
  # value_max_bytes - key bytesize - 63. Larger values raise Dalli::ValueOverMaxSize.
42
+ # - :max_response_bytes - largest value accepted from a server. Defaults to :value_max_bytes (1MB by default).
43
+ # Set this explicitly when reading larger items written by another client.
42
44
  # - :serializer - defaults to Marshal
43
45
  # - :compressor - defaults to Dalli::Compressor, a Zlib-based implementation
44
46
  # - :cache_nils - defaults to false, if true Dalli will not treat cached nil values as 'not found' for
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'zlib'
4
- require 'stringio'
5
4
 
6
5
  module Dalli
7
6
  ##
@@ -10,7 +9,7 @@ module Dalli
10
9
  ##
11
10
  class Compressor
12
11
  def self.compress(data)
13
- Zlib::Deflate.deflate(data)
12
+ deflate_fully(Zlib::Deflate.new, data)
14
13
  end
15
14
 
16
15
  # DEFLATE can't expand data by more than about 1032:1
@@ -24,11 +23,51 @@ module Dalli
24
23
  # as the output passes it, so a small compressed value can't expand into
25
24
  # gigabytes of memory.
26
25
  def self.decompress(data, max_bytes: nil)
27
- return Zlib::Inflate.inflate(data) unless may_exceed?(data, max_bytes)
26
+ return inflate_fully(Zlib::Inflate.new, data) unless may_exceed?(data, max_bytes)
28
27
 
29
28
  inflate_within_limit(Zlib::Inflate.new, data, max_bytes)
30
29
  end
31
30
 
31
+ # Ruby's zlib extension can return from a call before zlib has finished
32
+ # when a signal interrupts it (ruby/zlib#49). One-shot calls like
33
+ # Zlib::Deflate.deflate then raise or, with zlib 3.2.4, return truncated
34
+ # output, so these call finish until the stream has ended.
35
+ def self.deflate_fully(deflater, data)
36
+ finish_stream(deflater, deflater.deflate(data, Zlib::FINISH))
37
+ ensure
38
+ deflater.close
39
+ end
40
+
41
+ def self.inflate_fully(inflater, data)
42
+ finish_stream(inflater, feed(inflater, data) || String.new(encoding: Encoding::BINARY))
43
+ ensure
44
+ inflater.close
45
+ end
46
+
47
+ # zlib gem 3.2.3 and earlier retry an interrupted inflate even when it has
48
+ # used up its input, and raise the Z_BUF_ERROR zlib returns for that. The
49
+ # output so far stays in the stream, and finish raises for input that is
50
+ # truly truncated.
51
+ def self.feed(inflater, data, &)
52
+ inflater.inflate(data, &)
53
+ rescue Zlib::BufError
54
+ nil
55
+ end
56
+
57
+ def self.finish_stream(stream, out)
58
+ out << next_chunk(stream) until stream.finished?
59
+ out
60
+ end
61
+
62
+ # Each finish makes progress, so one that returns nothing means the
63
+ # stream can't end: the compressed input is truncated
64
+ def self.next_chunk(stream)
65
+ chunk = stream.finish
66
+ raise Zlib::BufError, 'buffer error' if chunk.empty?
67
+
68
+ chunk
69
+ end
70
+
32
71
  # False when even the largest possible expansion stays within max_bytes,
33
72
  # so the value can be inflated in one step
34
73
  def self.may_exceed?(data, max_bytes)
@@ -43,16 +82,15 @@ module Dalli
43
82
  # with Zlib::Inflate.inflate; finish would return it as output
44
83
  break if inflater.finished?
45
84
  end
46
- return out if inflater.finished?
47
-
48
- append_within_limit(out, inflater.finish, max_bytes)
85
+ append_within_limit(out, next_chunk(inflater), max_bytes) until inflater.finished?
86
+ out
49
87
  ensure
50
88
  inflater.close
51
89
  end
52
90
 
53
91
  # Both yielded and returned output count toward the limit
54
92
  def self.inflate_slice(inflater, slice, out, max_bytes)
55
- rest = inflater.inflate(slice) { |chunk| append_within_limit(out, chunk, max_bytes) }
93
+ rest = feed(inflater, slice) { |chunk| append_within_limit(out, chunk, max_bytes) }
56
94
  append_within_limit(out, rest, max_bytes)
57
95
  end
58
96
 
@@ -70,19 +108,18 @@ module Dalli
70
108
  # entry.
71
109
  ##
72
110
  class GzipCompressor
111
+ # MAX_WBITS + 16 makes zlib write and read the gzip format (and check its CRC)
112
+ WINDOW_BITS = Zlib::MAX_WBITS + 16
113
+
73
114
  def self.compress(data)
74
- io = StringIO.new(+'', 'w')
75
- gz = Zlib::GzipWriter.new(io)
76
- gz.write(data)
77
- gz.close
78
- io.string
115
+ Compressor.deflate_fully(Zlib::Deflate.new(Zlib::DEFAULT_COMPRESSION, WINDOW_BITS), data)
79
116
  end
80
117
 
81
118
  def self.decompress(data, max_bytes: nil)
82
- return Zlib::GzipReader.new(StringIO.new(data, 'rb')).read unless Compressor.may_exceed?(data, max_bytes)
119
+ inflater = Zlib::Inflate.new(WINDOW_BITS)
120
+ return Compressor.inflate_fully(inflater, data) unless Compressor.may_exceed?(data, max_bytes)
83
121
 
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)
122
+ Compressor.inflate_within_limit(inflater, data, max_bytes)
86
123
  end
87
124
  end
88
125
  end
@@ -228,6 +228,16 @@ module Dalli
228
228
  def servers_with_response(servers, timeout)
229
229
  return [] if servers.empty?
230
230
 
231
+ # A bounded read can stop while OpenSSL still holds decrypted bytes.
232
+ # IO.select only sees the underlying socket, so process those bytes
233
+ # before waiting for another network event.
234
+ buffered = nil
235
+ servers.each do |server|
236
+ sock = server.sock
237
+ (buffered ||= []) << server if sock.respond_to?(:pending_data?) && sock.pending_data?
238
+ end
239
+ return buffered if buffered
240
+
231
241
  sockets = servers.map(&:sock)
232
242
  readable, = IO.select(sockets, nil, nil, timeout)
233
243
  return [] if readable.nil?
@@ -71,13 +71,7 @@ module Dalli
71
71
  @connection_manager.start_request!
72
72
  drain_pending_quiet_responses(opkey)
73
73
  response = send(opkey, *args)
74
- # Quiet requests can leave replies on the socket; remember that so the
75
- # end of the quiet block knows this server needs draining
76
- @connection_manager.mark_quiet_responses_pending! if quiet? && opkey != :noop
77
-
78
- # pipelined_get/pipelined_get_interleaved emit query but don't read the response(s)
79
- @connection_manager.finish_request! unless %i[pipelined_get pipelined_get_interleaved].include?(opkey)
80
-
74
+ finish_request(opkey)
81
75
  request_completed = true
82
76
  response
83
77
  rescue Dalli::MarshalError, Dalli::ValueOverMaxSize => e
@@ -183,6 +177,9 @@ module Dalli
183
177
  # to the noop at the end of the pipeline
184
178
  finish_pipeline && break if status && key.nil?
185
179
 
180
+ @pipeline_response_count += 1
181
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
182
+
186
183
  # A key that wasn't requested means the replies are out of step
187
184
  # (see expect_reply_keys): keep what was read so far, drop the rest
188
185
  if unexpected_reply_key?(key)
@@ -223,6 +220,8 @@ module Dalli
223
220
  response_buffer.clear
224
221
  @pipeline_out_of_step = false
225
222
  @expected_reply_keys = nil
223
+ @expected_response_count = nil
224
+ @pipeline_response_count = nil
226
225
  @connection_manager.abort_request!
227
226
  return true unless connected?
228
227
 
@@ -260,6 +259,27 @@ module Dalli
260
259
  Dalli.logger.warn(URI_CREDENTIAL_WARNING)
261
260
  end
262
261
 
262
+ # Only a request whose reply was read resets the failure count. Otherwise
263
+ # a server that takes set_multi's writes, then drops the connection before
264
+ # the noop's reply, would be back at zero on every retry, never reach
265
+ # socket_max_failures, and be retried forever.
266
+ def finish_request(opkey)
267
+ case opkey
268
+ # Finished by finish_pipeline, once the replies are read
269
+ when :pipelined_get, :pipelined_get_interleaved then nil
270
+ when :pipelined_set, :pipelined_delete then @connection_manager.finish_unanswered_request!
271
+ else
272
+ if quiet? && opkey != :noop
273
+ # Its reply is left on the socket; the end of the quiet block, or
274
+ # the next non-quiet request, reads it
275
+ @connection_manager.mark_quiet_responses_pending!
276
+ @connection_manager.finish_unanswered_request!
277
+ else
278
+ @connection_manager.finish_request!
279
+ end
280
+ end
281
+ end
282
+
263
283
  ALLOWED_QUIET_OPS = %i[add replace set delete incr decr append prepend flush noop].freeze
264
284
  private_constant :ALLOWED_QUIET_OPS
265
285
 
@@ -407,7 +427,7 @@ module Dalli
407
427
  # Non-blocking read and processing of any available pipeline responses.
408
428
  # Used during interleaved pipelined gets to prevent buffer deadlock.
409
429
  # Populates the provided results hash directly to avoid allocation overhead.
410
- def drain_pipeline_responses(results)
430
+ def drain_pipeline_responses(results) # rubocop:disable Metrics/CyclomaticComplexity
411
431
  return unless connected?
412
432
 
413
433
  # Non-blocking check if socket has data available
@@ -421,6 +441,9 @@ module Dalli
421
441
  status, cas, key, value = response_buffer.process_single_getk_response
422
442
  break if status.nil? # No complete response available
423
443
 
444
+ @pipeline_response_count += 1
445
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
446
+
424
447
  # Handled by the next pipeline_next_responses, once sending is done
425
448
  if unexpected_reply_key?(key)
426
449
  @pipeline_out_of_step = true
@@ -454,6 +477,8 @@ module Dalli
454
477
  # other clients created, on memcached versions with the behavior.
455
478
  def expect_reply_keys(keys)
456
479
  @pipeline_out_of_step = false
480
+ @expected_response_count = keys.size
481
+ @pipeline_response_count = 0
457
482
  @expected_reply_keys = (keys.to_set { |k| reply_key_form(k) } if @verify_reply_keys)
458
483
  end
459
484
 
@@ -189,6 +189,15 @@ module Dalli
189
189
  @fail_count = 0
190
190
  end
191
191
 
192
+ # Ends a request whose reply isn't read with it: a quiet write, or one of
193
+ # set_multi's or delete_multi's writes. The server hasn't answered, so the
194
+ # failure count stays; the noop that reads the replies resets it.
195
+ def finish_unanswered_request!
196
+ raise '[Dalli] No request in progress. This may be a bug in Dalli.' unless @request_in_progress
197
+
198
+ @request_in_progress = false
199
+ end
200
+
192
201
  def abort_request!
193
202
  @request_in_progress = false
194
203
  end
@@ -204,7 +213,7 @@ module Dalli
204
213
 
205
214
  def read_line
206
215
  flush_write_buffer
207
- data = @sock.gets("\r\n", MAX_LINE_BYTES)
216
+ data = timed_tls_operation { @sock.gets("\r\n", MAX_LINE_BYTES) }
208
217
  error_on_request!('EOF in read_line') if data.nil?
209
218
  # Without its CRLF the line either ran past MAX_LINE_BYTES or was cut
210
219
  # short by EOF; either way the connection is out of step
@@ -369,13 +378,23 @@ module Dalli
369
378
 
370
379
  private
371
380
 
381
+ # Ruby 3.3's default OpenSSL can block past IO#timeout= on the TCP
382
+ # socket. Bound the blocking TLS call itself; error_on_request! closes
383
+ # the connection after the Timeout::Error, so a partial reply or write
384
+ # is never reused.
385
+ def timed_tls_operation(&)
386
+ return yield unless @sock.is_a?(Dalli::Socket::SSLSocket)
387
+
388
+ Timeout.timeout(socket_timeout, &)
389
+ end
390
+
372
391
  # One write per flush. A TLS socket sends each argument of
373
392
  # write(*parts) as its own record and system call, so the parts are
374
393
  # joined first.
375
394
  def flush_write_buffer
376
395
  return if @write_buffer.empty?
377
396
 
378
- @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer)
397
+ timed_tls_operation { @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer) }
379
398
  discard_write_buffer
380
399
  end
381
400
 
@@ -408,7 +427,7 @@ module Dalli
408
427
  # error_on_request!, which closes the dirty socket for a retry on a fresh
409
428
  # connection (and preserves the $ERROR_INFO context down! relies on).
410
429
  def read_bytes(count)
411
- buffer = @sock.read(count)
430
+ buffer = timed_tls_operation { @sock.read(count) }
412
431
  return buffer if buffer && buffer.bytesize == count
413
432
 
414
433
  raise EOFError, "EOF reading #{count} bytes; received #{buffer ? buffer.bytesize : 0}"
@@ -229,7 +229,7 @@ module Dalli
229
229
 
230
230
  def finish_pipelined_delete(sent)
231
231
  write_noop
232
- sent - response_processor.pipelined_delete_non_deletions
232
+ sent - response_processor.pipelined_delete_non_deletions(sent)
233
233
  end
234
234
 
235
235
  # Arithmetic Commands
@@ -363,8 +363,13 @@ module Dalli
363
363
  def read_multi_metadata_responses(is_raw, keys)
364
364
  expect_reply_keys(keys)
365
365
  hash = {}
366
+ replies = 0
366
367
  while (line = @connection_manager.read_line)
367
368
  break if line.start_with?('MN')
369
+
370
+ replies += 1
371
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
372
+
368
373
  next unless line.start_with?('VA ')
369
374
 
370
375
  tokens = line.chomp!(TERMINATOR).split
@@ -387,8 +392,13 @@ module Dalli
387
392
  def read_multi_get_responses(is_raw, keys)
388
393
  expect_reply_keys(keys)
389
394
  hash = {}
395
+ replies = 0
390
396
  while (line = @connection_manager.read_line)
391
397
  break if line.start_with?('MN')
398
+
399
+ replies += 1
400
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
401
+
392
402
  next unless line.start_with?('VA ')
393
403
 
394
404
  key, value = parse_multi_get_value(line, is_raw)
@@ -439,7 +449,7 @@ module Dalli
439
449
  buffer = RequestFormatter.multi_meta_set(entries, ttl: ttl, **routing_token_kwargs(req_options))
440
450
  flushed_write(buffer)
441
451
  buffer.clear
442
- response_processor.consume_all_responses_until_mn
452
+ response_processor.consume_all_responses_until_mn(entries.size)
443
453
  end
444
454
  raise value_error if value_error
445
455
  end
@@ -451,7 +461,7 @@ module Dalli
451
461
  **routing_token_kwargs(req_options))
452
462
  flushed_write(buffer)
453
463
  buffer.clear
454
- keys.size - response_processor.pipelined_delete_non_deletions
464
+ keys.size - response_processor.pipelined_delete_non_deletions(keys.size)
455
465
  end
456
466
 
457
467
  require_relative 'key_regularizer'
@@ -26,6 +26,8 @@ module Dalli
26
26
  VA_PREFIX = 'VA '
27
27
  # memcached can't store an item larger than 1 GiB (its -I maximum)
28
28
  MAX_VALUE_BYTES = 1024 * 1024 * 1024
29
+ MAX_STATS_ENTRIES = 10_000
30
+ MAX_QUIET_RESPONSES = 100_000
29
31
  HD_PREFIX = 'HD '
30
32
  FLAGS_TOKEN_PREFIX = ' f'
31
33
  CAS_TOKEN_PREFIX = ' c'
@@ -174,7 +176,11 @@ module Dalli
174
176
  def stats
175
177
  tokens = error_on_unexpected!(T_END_TOKEN_STAT)
176
178
  values = {}
179
+ replies = 0
177
180
  while tokens.first != END_TOKEN
181
+ replies += 1
182
+ raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
183
+
178
184
  values[tokens[1]] = tokens[2]
179
185
  tokens = next_line_to_tokens
180
186
  end
@@ -198,10 +204,16 @@ module Dalli
198
204
  tokens.last
199
205
  end
200
206
 
201
- def consume_all_responses_until_mn
207
+ def consume_all_responses_until_mn(max_responses = MAX_QUIET_RESPONSES)
202
208
  tokens = next_line_to_tokens
203
209
 
204
- tokens = next_line_to_tokens while tokens.first != MN
210
+ replies = 0
211
+ while tokens.first != MN
212
+ replies += 1
213
+ raise Dalli::DalliError, 'Too many quiet replies' if replies > max_responses
214
+
215
+ tokens = next_line_to_tokens
216
+ end
205
217
  true
206
218
  end
207
219
 
@@ -212,11 +224,13 @@ module Dalli
212
224
  # was NOT deleted -- a miss (NF) or an error. Returns that count so
213
225
  # callers can derive the number of successful deletes as
214
226
  # (keys_sent - non_deletions).
215
- def pipelined_delete_non_deletions
227
+ def pipelined_delete_non_deletions(max_responses = MAX_QUIET_RESPONSES)
216
228
  non_deletions = 0
217
229
  tokens = next_line_to_tokens
218
230
  until tokens.first == MN
219
231
  non_deletions += 1
232
+ raise Dalli::DalliError, 'Too many delete replies' if non_deletions > max_responses
233
+
220
234
  tokens = next_line_to_tokens
221
235
  end
222
236
  non_deletions
@@ -237,6 +251,13 @@ module Dalli
237
251
  def getk_response_from_buffer(buf, offset = 0, raw: false)
238
252
  # Find the header terminator starting from offset
239
253
  term_idx = buf.byteindex(TERMINATOR, offset)
254
+ max_line_bytes = ConnectionManager::MAX_LINE_BYTES
255
+ header_too_long = if term_idx
256
+ term_idx - offset + TERMINATOR.bytesize > max_line_bytes
257
+ else
258
+ buf.bytesize - offset >= max_line_bytes
259
+ end
260
+ raise Dalli::DalliError, "Reply line without CRLF in the first #{max_line_bytes} bytes" if header_too_long
240
261
  return [0] unless term_idx
241
262
 
242
263
  if buf.byteslice(offset, VA_PREFIX.bytesize) == VA_PREFIX
@@ -456,9 +477,11 @@ module Dalli
456
477
  end
457
478
 
458
479
  def check_value_size!(size)
459
- return if size.between?(0, MAX_VALUE_BYTES)
480
+ limit = @value_marshaller.max_response_bytes
481
+ return if size >= 0 && size <= MAX_VALUE_BYTES && size <= limit # rubocop:disable Style/ComparableBetween
460
482
 
461
- raise Dalli::DalliError, "Reply value size #{size} is out of range"
483
+ effective_limit = [MAX_VALUE_BYTES, limit].min
484
+ raise Dalli::DalliError, "Reply value size #{size} exceeds the #{effective_limit}-byte response limit"
462
485
  end
463
486
 
464
487
  def read_line
@@ -15,12 +15,14 @@ module Dalli
15
15
  value_max_bytes: 1024 * 1024
16
16
  }.freeze
17
17
 
18
- attr_reader :value_max_bytes
18
+ attr_reader :value_max_bytes, :max_response_bytes
19
19
 
20
20
  def initialize(client_options)
21
21
  @value_max_bytes = client_options.fetch(:value_max_bytes) do
22
22
  DEFAULTS.fetch(:value_max_bytes)
23
23
  end.to_i
24
+ @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, @value_max_bytes))
25
+ raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
24
26
  end
25
27
 
26
28
  def store(key, value, _options = nil)
@@ -47,6 +47,8 @@ module Dalli
47
47
  @marshal_options =
48
48
  DEFAULTS.merge(client_options.slice(*OPTIONS))
49
49
  @marshal_options[:value_max_bytes] = @marshal_options[:value_max_bytes].to_i
50
+ @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, value_max_bytes))
51
+ raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
50
52
  end
51
53
 
52
54
  def store(key, value, options = nil)
@@ -67,6 +69,8 @@ module Dalli
67
69
  @marshal_options[:value_max_bytes]
68
70
  end
69
71
 
72
+ attr_reader :max_response_bytes
73
+
70
74
  def error_if_over_max_value_bytes(key, value)
71
75
  self.class.error_if_over_max_value_bytes(key, value, value_max_bytes)
72
76
  end
data/lib/dalli/socket.rb CHANGED
@@ -19,6 +19,10 @@ module Dalli
19
19
  ##
20
20
  module InstanceMethods
21
21
  READ_CHUNK_SIZE = 8196
22
+ # Give the response parser control between bounded socket reads. In
23
+ # particular, a peer continuously sending a header without CRLF must
24
+ # not keep this method appending forever.
25
+ MAX_AVAILABLE_BYTES = READ_CHUNK_SIZE * 8
22
26
 
23
27
  # Reads whatever is available without blocking. A read that returns less
24
28
  # than a full chunk means the socket was drained, so we stop there rather
@@ -26,7 +30,7 @@ module Dalli
26
30
  # Callers keep waiting on IO.select for anything that arrives later.
27
31
  def read_available(reusable_buffer = nil)
28
32
  if reusable_buffer
29
- value = read_nonblock(READ_CHUNK_SIZE, reusable_buffer, exception: false)
33
+ value = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES].min, reusable_buffer, exception: false)
30
34
  case value
31
35
  when :wait_writable, :wait_readable
32
36
  return reusable_buffer.clear
@@ -34,13 +38,15 @@ module Dalli
34
38
  raise Errno::ECONNRESET, "Connection reset: #{logged_options.inspect}"
35
39
  end
36
40
  return value if drained_after?(value)
41
+ return value if value.bytesize >= MAX_AVAILABLE_BYTES
37
42
  else
38
43
  value = ''.b
39
44
  end
40
45
 
41
46
  buffer = ''.b
42
47
  loop do
43
- result = read_nonblock(READ_CHUNK_SIZE, buffer, exception: false)
48
+ result = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES - value.bytesize].min,
49
+ buffer, exception: false)
44
50
  case result
45
51
  when :wait_writable, :wait_readable
46
52
  buffer.clear
@@ -50,6 +56,7 @@ module Dalli
50
56
  else
51
57
  value << result
52
58
  return value if drained_after?(result)
59
+ return value if value.bytesize >= MAX_AVAILABLE_BYTES
53
60
  end
54
61
  end
55
62
  end
@@ -114,13 +121,17 @@ module Dalli
114
121
  # jruby-openssl can take the next record off the socket during a short
115
122
  # read and hold it where neither pending nor IO.select sees it, so on
116
123
  # JRuby a read continues until the socket would block.
124
+ def pending_data?
125
+ pending.positive? || (@rbuffer && !@rbuffer.empty?)
126
+ end
127
+
117
128
  if RUBY_ENGINE == 'jruby'
118
129
  def buffered_data?
119
130
  true
120
131
  end
121
132
  else
122
133
  def buffered_data?
123
- pending.positive?
134
+ pending_data?
124
135
  end
125
136
  end
126
137
 
@@ -157,7 +168,12 @@ module Dalli
157
168
  sock.options = { host: host, port: port }.merge(options)
158
169
  init_socket_options(sock, options)
159
170
 
160
- options[:ssl_context] ? wrapping_ssl_socket(sock, host, options[:ssl_context]) : sock
171
+ if options[:ssl_context]
172
+ wrapping_ssl_socket(sock, host, options[:ssl_context],
173
+ options[:socket_timeout])
174
+ else
175
+ sock
176
+ end
161
177
  end
162
178
  end
163
179
 
@@ -248,13 +264,15 @@ module Dalli
248
264
 
249
265
  # Closes the TCP socket if the handshake fails or times out, so a failed
250
266
  # attempt doesn't hold a file descriptor until GC.
251
- def self.wrapping_ssl_socket(tcp_socket, host, ssl_context)
267
+ def self.wrapping_ssl_socket(tcp_socket, host, ssl_context, timeout = nil)
252
268
  warn_if_unverified(ssl_context)
253
269
  connected = false
254
270
  ssl_socket = Dalli::Socket::SSLSocket.new(tcp_socket, ssl_context)
255
271
  ssl_socket.hostname = host
256
272
  ssl_socket.sync_close = true
257
- ssl_socket.connect
273
+ # The underlying TCP socket's IO#timeout= does not reliably bound
274
+ # OpenSSL's blocking handshake on Ruby 3.3.
275
+ Timeout.timeout(timeout) { ssl_socket.connect }
258
276
  connected = true
259
277
  ssl_socket
260
278
  ensure
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.7'
4
+ VERSION = '5.2.9'
5
5
 
6
6
  MIN_SUPPORTED_MEMCACHED_VERSION = '1.6.27'
7
7
  end
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.7
4
+ version: 5.2.9
5
5
  platform: ruby
6
6
  authors:
7
7
  - Peter M. Goldstein
@@ -89,7 +89,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
89
89
  - !ruby/object:Gem::Version
90
90
  version: '0'
91
91
  requirements: []
92
- rubygems_version: 4.0.23
92
+ rubygems_version: 4.0.24
93
93
  specification_version: 4
94
94
  summary: High performance memcached client for Ruby
95
95
  test_files: []