dalli 5.3.2 → 5.3.4

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: 01e6a1f1483a28b5913847f35280e7c4cf2f490f01ddda3607ba1cf7687e3081
4
- data.tar.gz: 0a4c8e31094f2d0fabc9a17062765d7e5293ec29ed338fabca6c93076d4ea224
3
+ metadata.gz: bcdbff6c85bb9b36e985afe7760f3a30b347e7e9cac5ab91220d1df40fbe9321
4
+ data.tar.gz: cd31ee942d757acd20c3dd6686bfb16ce8f5ace3246df87d3bb8d0152f9bd140
5
5
  SHA512:
6
- metadata.gz: 1fa29fe92cc42e648f5752c79a185466e24614283d0ebed7f8a12a5b3ab2f98806065c1989c403144b10809ad33baaa4033c66f140e80500c4ecb9c3a6b6a41b
7
- data.tar.gz: be9a46942962a98dc2d14d9058f48c0b78c22c245b447e7578b030aa941e286a67941516e0d8a9d377167fd9fcbb3960865c3c118e2f3e8ba88ba1aece683914
6
+ metadata.gz: e617006601c20a575781cb74c2393b79fe4b06d4179f44bf2cc87a150396843fbf57181e91040d8060f0e572a7bd27d7de82bf748da125eaadcdfb2c5ae25a38
7
+ data.tar.gz: 1981431f621ca9f4ad053d0df4bd712bdddd0c4e5847545cfe7bee03446a70b3c3ecd472eda799a1c33e3c61331b6114ee497b699d85431c0152a969536693ee
data/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ Dalli Changelog
4
4
  Unreleased
5
5
  ==========
6
6
 
7
+ 5.3.4
8
+ ==========
9
+
10
+ Bug fixes:
11
+
12
+ - `Client#with`, which lets a bare client stand in for a connection pool, now accepts and ignores the arguments `ConnectionPool#with` takes, such as `timeout:`. Before, passing any raised `ArgumentError` (#1323, @byroot)
13
+ - A request larger than the socket buffers no longer stalls until `socket_timeout` and marks the server down. memcached stops reading a connection while its replies go unread, so a large `get_multi`, `get_multi_cas`, `get_multi_with_metadata` or `delete_multi` (whose missing keys each get a reply) waited on the server. Over a Unix socket, whose buffer doesn't grow, this started at about 1,000 keys for `get_multi_cas`. Replies that arrive while a request is being sent are now read and held, checked as they arrive against what the requests sent could get back (#1328, based on #1326 by @edcarvio)
14
+
15
+ 5.3.3
16
+ ==========
17
+
18
+ Security:
19
+
20
+ - Bound memcached reply headers, incoming value sizes, and response counts, and enforce TLS timeouts for blocking operations (GHSA-5wpc-45jc-6ccc)
21
+
7
22
  5.3.2
8
23
  ==========
9
24
 
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
@@ -794,7 +796,7 @@ module Dalli
794
796
  end
795
797
 
796
798
  # Stub method so a bare Dalli client can pretend to be a connection pool.
797
- def with
799
+ def with(...)
798
800
  yield self
799
801
  end
800
802
 
@@ -247,6 +247,17 @@ module Dalli
247
247
  def servers_with_response(servers, timeout)
248
248
  return [] if servers.empty?
249
249
 
250
+ # A bounded read can stop while OpenSSL still holds decrypted bytes,
251
+ # and replies that arrived while the requests were sent are held by the
252
+ # connection. IO.select only sees the underlying socket, so process
253
+ # those bytes before waiting for another network event.
254
+ buffered = nil
255
+ servers.each do |server|
256
+ sock = server.sock
257
+ (buffered ||= []) << server if server.held_replies? || (sock.respond_to?(:pending_data?) && sock.pending_data?)
258
+ end
259
+ return buffered if buffered
260
+
250
261
  sockets = servers.map(&:sock)
251
262
  readable, = IO.select(sockets, nil, nil, timeout)
252
263
  return [] if readable.nil?
@@ -47,6 +47,7 @@ module Dalli
47
47
  @verify_reply_keys = client_options[:verify_reply_keys] ? true : false
48
48
  @value_marshaller = @raw_mode ? StringMarshaller.new(@options) : ValueMarshaller.new(@options)
49
49
  @connection_manager = ConnectionManager.new(hostname, port, socket_type, @options)
50
+ @connection_manager.max_reply_value_bytes = @value_marshaller.max_response_bytes
50
51
  end
51
52
 
52
53
  # Returns true if client is in raw mode (no serialization/compression).
@@ -185,6 +186,9 @@ module Dalli
185
186
  # to the noop at the end of the pipeline
186
187
  finish_pipeline && break if status && key.nil?
187
188
 
189
+ @pipeline_response_count += 1
190
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
191
+
188
192
  # A key that wasn't requested means the replies are out of step
189
193
  # (see expect_reply_keys): keep what was read so far, drop the rest
190
194
  if unexpected_reply_key?(key)
@@ -251,6 +255,12 @@ module Dalli
251
255
  !response_buffer.in_progress?
252
256
  end
253
257
 
258
+ # Replies that arrived while the request was sent, which IO.select
259
+ # can't see (see ConnectionManager#send_while_reading)
260
+ def held_replies?
261
+ @connection_manager.held_replies?
262
+ end
263
+
254
264
  def quiet?
255
265
  Thread.current[::Dalli::QUIET]
256
266
  end
@@ -484,8 +494,8 @@ module Dalli
484
494
  def drain_pipeline_responses(results)
485
495
  return unless connected?
486
496
 
487
- # Non-blocking check if socket has data available
488
- return unless sock.wait_readable(0)
497
+ # Replies held while this chunk was sent first, then the socket
498
+ return unless @connection_manager.held_replies? || sock.wait_readable(0)
489
499
 
490
500
  # Read available data without blocking
491
501
  response_buffer.read
@@ -495,6 +505,9 @@ module Dalli
495
505
  status, cas, key, value = response_buffer.process_single_getk_response
496
506
  break if status.nil? # No complete response available
497
507
 
508
+ @pipeline_response_count += 1
509
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
510
+
498
511
  # Handled by the next pipeline_next_responses, once sending is done
499
512
  if unexpected_reply_key?(key)
500
513
  @pipeline_out_of_step = true
@@ -528,6 +541,8 @@ module Dalli
528
541
  # other clients created, on memcached versions with the behavior.
529
542
  def expect_reply_keys(keys)
530
543
  @pipeline_out_of_step = false
544
+ @expected_response_count = keys.size
545
+ @pipeline_response_count = 0
531
546
  @expected_reply_keys = (keys.to_set { |k| reply_key_form(k) } if @verify_reply_keys)
532
547
  end
533
548
 
@@ -578,6 +593,8 @@ module Dalli
578
593
  response_buffer.clear
579
594
  @pipeline_out_of_step = false
580
595
  @expected_reply_keys = nil
596
+ @expected_response_count = nil
597
+ @pipeline_response_count = nil
581
598
  end
582
599
 
583
600
  # The single-server set_multi path passes its whole pairs hash as the
@@ -33,6 +33,13 @@ module Dalli
33
33
  # cleared with the write buffer whenever the connection closes.
34
34
  attr_writer :response_buffer
35
35
 
36
+ # The largest value a reply held during a send may declare: the
37
+ # protocol's max_response_bytes (see HeldReplies). Kept in options, as
38
+ # each instance variable here costs every request a little.
39
+ def max_reply_value_bytes=(bytes)
40
+ @options[:max_reply_value_bytes] = bytes
41
+ end
42
+
36
43
  def initialize(hostname, port, socket_type, client_options)
37
44
  @hostname = hostname
38
45
  @port = port
@@ -46,6 +53,11 @@ module Dalli
46
53
  @write_buffer = []
47
54
  @write_buffer_bytes = 0
48
55
  @response_buffer = nil
56
+ # Replies that arrived while a request was being sent, read before the
57
+ # socket while @held (see #send_while_reading)
58
+ @held_replies = nil
59
+ @held = false
60
+ @unanswered_bytes = 0
49
61
 
50
62
  @fail_count = 0
51
63
  reset_down_info
@@ -128,6 +140,9 @@ module Dalli
128
140
  reconnect_on_fork if fork_detected?
129
141
  return if @sock.nil? || @quiet_responses_pending
130
142
 
143
+ # Held replies with no request waiting for them were never asked for
144
+ return close if @held
145
+
131
146
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond)
132
147
  idle = now - @last_used_at
133
148
  @last_used_at = now
@@ -180,6 +195,9 @@ module Dalli
180
195
  @pid = nil
181
196
  @quiet_responses_pending = false
182
197
  discard_write_buffer
198
+ discard_held
199
+ @held_replies&.reset_accounting
200
+ @unanswered_bytes = 0
183
201
  @response_buffer&.clear
184
202
  abort_request!
185
203
  end
@@ -232,6 +250,9 @@ module Dalli
232
250
  # accepts connections but never answers would otherwise reset it on
233
251
  # every retry and never reach socket_max_failures.
234
252
  @fail_count = 0
253
+ # The server has read everything sent so far: it answered the last of it
254
+ @unanswered_bytes = 0
255
+ @held_replies.reset_accounting if @held_replies&.counting?
235
256
  end
236
257
 
237
258
  # Ends a request whose reply isn't read with it: a quiet write, or one of
@@ -265,13 +286,21 @@ module Dalli
265
286
  # never sends CRLF can't grow the read buffer without bound.
266
287
  MAX_LINE_BYTES = 8 * 1024
267
288
 
289
+ # TruffleRuby's gets with a limit doesn't find a two-byte separator whose
290
+ # bytes arrive in separate reads: it waits for more, or returns the line
291
+ # without them. Every reply line ends in CRLF, checked after the read,
292
+ # so reading to the LF finds the same lines.
293
+ LINE_SEPARATOR = RUBY_ENGINE == 'truffleruby' ? "\n" : "\r\n"
294
+
268
295
  def read_line
296
+ return held_line if @held
297
+
269
298
  flush_write_buffer
270
- data = @sock.gets("\r\n", MAX_LINE_BYTES)
299
+ data = timed_tls_operation { @sock.gets(LINE_SEPARATOR, MAX_LINE_BYTES) }
271
300
  error_on_request!('EOF in read_line') if data.nil?
272
301
  # Without its CRLF the line either ran past MAX_LINE_BYTES or was cut
273
302
  # short by EOF; either way the connection is out of step
274
- error_on_request!("Reply line without CRLF in the first #{MAX_LINE_BYTES} bytes") unless data.end_with?("\r\n")
303
+ line_too_long! unless data.end_with?("\r\n")
275
304
  data
276
305
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
277
306
  error_on_request!(e)
@@ -292,6 +321,8 @@ module Dalli
292
321
 
293
322
  if RUBY_ENGINE == 'jruby'
294
323
  def read(count)
324
+ return held_read(count) if @held
325
+
295
326
  check_read_size!(count)
296
327
  flush_write_buffer
297
328
  @sock.readfull(count)
@@ -300,6 +331,8 @@ module Dalli
300
331
  end
301
332
  else
302
333
  def read(count)
334
+ return held_read(count) if @held
335
+
303
336
  check_read_size!(count)
304
337
  flush_write_buffer
305
338
  read_bytes(count)
@@ -321,6 +354,16 @@ module Dalli
321
354
  # is sent once it grows past this size, or when a reply is read.
322
355
  WRITE_BUFFER_FLUSH_BYTES = 64 * 1024
323
356
 
357
+ # Less than any socket send buffer: 8 KiB is the smallest default
358
+ # (Unix sockets on macOS), and Linux doubles a requested SO_SNDBUF from
359
+ # a minimum of 2,304 bytes
360
+ BLOCKING_WRITE_BYTES = 4 * 1024
361
+
362
+ # jruby-openssl won't read while it has encrypted bytes it couldn't send,
363
+ # and they can't go until the server reads, which it won't while its
364
+ # replies go unread. On JRuby a TLS request is sent as before.
365
+ HALF_DUPLEX_TLS = RUBY_ENGINE == 'jruby'
366
+
324
367
  def write(bytes)
325
368
  @write_buffer << bytes
326
369
  @write_buffer_bytes += bytes.bytesize
@@ -345,12 +388,20 @@ module Dalli
345
388
  end
346
389
 
347
390
  # Non-blocking read. Here to support the operation
348
- # of the get_multi operation
391
+ # of the get_multi operation. Held replies come first.
349
392
  def read_available(...)
393
+ return take_held(@held_replies.bytesize) if @held
394
+
350
395
  flush_write_buffer
351
396
  @sock.read_available(...)
352
397
  end
353
398
 
399
+ # Whether replies that arrived during a send are waiting to be read.
400
+ # IO.select can't see them, so a caller waiting for replies checks first.
401
+ def held_replies?
402
+ @held
403
+ end
404
+
354
405
  def max_allowed_failures
355
406
  @max_allowed_failures ||= @options[:socket_max_failures] || 2
356
407
  end
@@ -434,18 +485,152 @@ module Dalli
434
485
 
435
486
  private
436
487
 
488
+ # Ruby 3.3's default OpenSSL can block past IO#timeout= on the TCP
489
+ # socket. Bound the blocking TLS call itself; error_on_request! closes
490
+ # the connection after the Timeout::Error, so a partial reply or write
491
+ # is never reused.
492
+ def timed_tls_operation(&)
493
+ return yield unless @sock.is_a?(Dalli::Socket::SSLSocket)
494
+
495
+ Timeout.timeout(socket_timeout, &)
496
+ end
497
+
437
498
  # One write per flush. A TLS socket sends each argument of
438
499
  # write(*parts) as its own record and system call, so the parts are
439
500
  # joined first.
501
+ #
502
+ # A write blocks while the socket's send buffer is full. memcached stops
503
+ # reading a connection while its replies go unread, so once the requests
504
+ # it hasn't answered are more than the buffers hold, a blocking write
505
+ # and the server wait on each other until socket_timeout. Up to
506
+ # BLOCKING_WRITE_BYTES unanswered, the write fits whatever the server
507
+ # is doing; past that, #send_while_reading takes the replies off the
508
+ # socket while it sends.
440
509
  def flush_write_buffer
441
510
  return if @write_buffer.empty?
442
511
 
443
512
  # Set before writing: a write that fails may still have sent some bytes
444
513
  @request_sent = true if @request_in_progress
445
- @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer)
514
+ data = @write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer
515
+ @unanswered_bytes += data.bytesize
516
+ if @unanswered_bytes <= BLOCKING_WRITE_BYTES
517
+ write_blocking(data)
518
+ else
519
+ send_while_reading(data)
520
+ end
446
521
  discard_write_buffer
447
522
  end
448
523
 
524
+ # The write every request makes, kept free of a block outside TLS: a
525
+ # block here measurably slowed each request
526
+ def write_blocking(data)
527
+ return @sock.write(data) unless @sock.is_a?(Dalli::Socket::SSLSocket)
528
+
529
+ Timeout.timeout(socket_timeout) { @sock.write(data) }
530
+ end
531
+
532
+ # Sends without blocking, holding the replies that arrive meanwhile (see
533
+ # HeldReplies). Fails after socket_timeout with nothing sent, as a
534
+ # blocking write does, or when a held reply isn't one the requests sent
535
+ # could get.
536
+ def send_while_reading(data)
537
+ return write_blocking(data) if HALF_DUPLEX_TLS && @sock.is_a?(OpenSSL::SSL::SSLSocket)
538
+
539
+ total = data.bytesize
540
+ sent = 0
541
+ deadline = nil
542
+ counted = false
543
+ while sent < total
544
+ rest = sent.zero? ? data : data.byteslice(sent, total - sent)
545
+ result = @sock.write_nonblock(rest, exception: false)
546
+ if result.is_a?(Integer)
547
+ sent += result
548
+ deadline = nil
549
+ else
550
+ # Replies can only be held from here, so the lines are counted now
551
+ counted ||= (@held_replies ||= HeldReplies.new(max_reply_value_bytes)).count_lines(data)
552
+ deadline ||= write_deadline
553
+ wait_to_send(result, deadline)
554
+ end
555
+ end
556
+ end
557
+
558
+ # Waits until the socket takes more, holding any replies that arrive.
559
+ # TLS can need the other direction first, and the socket is ready for
560
+ # the direction it doesn't need, so waiting on that too would return at
561
+ # once: a write can need to read (:wait_readable), and a read can need
562
+ # to write (:wait_writable).
563
+ def wait_to_send(wait_for, deadline)
564
+ readable, = wait_until(deadline, [@sock], wait_for == :wait_writable ? [@sock] : nil)
565
+ return if readable.empty?
566
+
567
+ wait_until(deadline, nil, [@sock]) if hold_arrived_replies == :wait_writable
568
+ end
569
+
570
+ def wait_until(deadline, readers, writers)
571
+ wait = deadline && (deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC))
572
+ raise Timeout::Error, "IO timeout writing to #{name}" if wait && wait <= 0
573
+
574
+ IO.select(readers, writers, nil, wait) or raise Timeout::Error, "IO timeout writing to #{name}"
575
+ end
576
+
577
+ def write_deadline
578
+ socket_timeout && (Process.clock_gettime(Process::CLOCK_MONOTONIC) + socket_timeout)
579
+ end
580
+
581
+ def max_reply_value_bytes
582
+ @options.fetch(:max_reply_value_bytes, MAX_READ_BYTES - 2)
583
+ end
584
+
585
+ # Returns what read_nonblock did when nothing was held
586
+ def hold_arrived_replies
587
+ result = @held_replies.read_from(@sock, @unanswered_bytes)
588
+ @held = true if result.nil?
589
+ result
590
+ rescue HeldReplies::Invalid => e
591
+ error_on_request!("#{name} sent #{e.message}")
592
+ end
593
+
594
+ # A held reply line. One that continues on the socket is finished from
595
+ # there. A CR that ends the held bytes may be the first half of its CRLF,
596
+ # which gets wouldn't find across the two.
597
+ def held_line
598
+ length, whole = @held_replies.next_line_length
599
+ line_too_long! if length > MAX_LINE_BYTES
600
+ return take_held(length) if whole
601
+
602
+ line = take_held(length)
603
+ line << read(1) while line.end_with?("\r") && line.bytesize <= MAX_LINE_BYTES
604
+ line << read_line unless line.end_with?("\r\n")
605
+ line_too_long! if line.bytesize > MAX_LINE_BYTES
606
+ line
607
+ end
608
+
609
+ # count bytes, the held ones first
610
+ def held_read(count)
611
+ check_read_size!(count)
612
+ held = @held_replies.bytesize
613
+ return take_held(count) if held >= count
614
+
615
+ value = take_held(held)
616
+ value << read(count - held)
617
+ end
618
+
619
+ def take_held(count)
620
+ part = @held_replies.take(count)
621
+ @held = false if @held_replies.empty?
622
+ part
623
+ end
624
+
625
+ def discard_held
626
+ @held = false
627
+ @held_replies&.clear
628
+ end
629
+
630
+ def line_too_long!
631
+ error_on_request!("Reply line without CRLF in the first #{MAX_LINE_BYTES} bytes")
632
+ end
633
+
449
634
  # Joined as bytes: requests can mix UTF-8 and binary strings, which
450
635
  # String#<< refuses to combine when both hold non-ASCII bytes
451
636
  if String.method_defined?(:append_as_bytes)
@@ -475,7 +660,7 @@ module Dalli
475
660
  # error_on_request!, which closes the dirty socket for a retry on a fresh
476
661
  # connection (and preserves the $ERROR_INFO context down! relies on).
477
662
  def read_bytes(count)
478
- buffer = @sock.read(count)
663
+ buffer = timed_tls_operation { @sock.read(count) }
479
664
  return buffer if buffer && buffer.bytesize == count
480
665
 
481
666
  raise EOFError, "EOF reading #{count} bytes; received #{buffer ? buffer.bytesize : 0}"
@@ -499,7 +684,8 @@ module Dalli
499
684
  flush_write_buffer
500
685
  if @awaiting_reply
501
686
  @awaiting_reply = false
502
- wait_readable! unless @sock.is_a?(::OpenSSL::SSL::SSLSocket)
687
+ # A reply held while the request was sent has already arrived
688
+ wait_readable! unless @held || @sock.is_a?(::OpenSSL::SSL::SSLSocket)
503
689
  end
504
690
  super
505
691
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dalli
4
+ module Protocol
5
+ ##
6
+ # Replies that arrived while a request was being sent (see
7
+ # ConnectionManager#send_while_reading), held until the request's reader
8
+ # gets to them. Created only once a send has had to wait, so connections
9
+ # that never send a large request don't carry its state.
10
+ #
11
+ # Held bytes are checked as they arrive, so that what's held is never more
12
+ # than the requests sent could get back: whole reply lines of up to
13
+ # ConnectionManager::MAX_LINE_BYTES, no more replies than request lines
14
+ # sent, and values no larger than max_response_bytes. Anything else raises
15
+ # Invalid as soon as it's read.
16
+ ##
17
+ class HeldReplies
18
+ class Invalid < StandardError; end
19
+
20
+ # Read per wakeup: enough to empty a Unix socket's send buffer (208 KiB
21
+ # by default on Linux)
22
+ READ_BYTES = 256 * 1024
23
+
24
+ def initialize(max_value_bytes)
25
+ @max_value_bytes = max_value_bytes
26
+ @buffer = ''.b
27
+ @offset = 0
28
+ @chunk = nil
29
+ @line = ''.b
30
+ reset_accounting
31
+ end
32
+
33
+ # Whether lines were counted since the server last answered everything
34
+ def counting?
35
+ @counting
36
+ end
37
+
38
+ # Each request line can get one reply. Only the lines of a send that had
39
+ # to wait are counted: the socket took the others at once, as it does a
40
+ # blocking write's, and each of their bytes is allowed one.
41
+ def count_lines(data)
42
+ @counting = true
43
+ @counted_bytes += data.bytesize
44
+ @lines += data.count("\n")
45
+ true
46
+ end
47
+
48
+ # The server has answered everything sent so far
49
+ def reset_accounting
50
+ @counting = false
51
+ @counted_bytes = 0
52
+ @lines = 0
53
+ @replies = 0
54
+ @value_left = 0
55
+ @line.clear
56
+ end
57
+
58
+ # Moves the replies that have arrived on sock into the buffer, reading
59
+ # into it directly when it's empty, then checks them. Returns nil once
60
+ # bytes are held, or what read_nonblock returned when none were.
61
+ # unanswered_bytes is everything sent since the server last answered.
62
+ def read_from(sock, unanswered_bytes)
63
+ if empty?
64
+ @offset = 0
65
+ from = 0
66
+ result = sock.read_nonblock(READ_BYTES, @buffer, exception: false)
67
+ else
68
+ compact
69
+ from = @buffer.bytesize
70
+ result = sock.read_nonblock(READ_BYTES, @chunk ||= ''.b, exception: false)
71
+ @buffer << result if result.is_a?(String)
72
+ end
73
+ raise EOFError, 'EOF while sending' if result.nil?
74
+ # Nothing held: TLS read a handshake record, or nothing had arrived
75
+ return result unless result.is_a?(String)
76
+
77
+ check(from, unanswered_bytes)
78
+ nil
79
+ end
80
+
81
+ def empty?
82
+ @offset == @buffer.bytesize
83
+ end
84
+
85
+ def bytesize
86
+ @buffer.bytesize - @offset
87
+ end
88
+
89
+ # The length of the next line, CRLF included, and whether its CRLF is
90
+ # held. Without it, the line runs to the end of what's held.
91
+ def next_line_length
92
+ eol = @buffer.byteindex("\r\n", @offset)
93
+ eol ? [eol + 2 - @offset, true] : [bytesize, false]
94
+ end
95
+
96
+ # The next count bytes. Bytes that reach the end are copied: a byteslice
97
+ # there would share the buffer's memory and keep it all allocated.
98
+ def take(count)
99
+ if @offset + count < @buffer.bytesize
100
+ part = @buffer.byteslice(@offset, count)
101
+ @offset += count
102
+ else
103
+ part = String.new(capacity: count, encoding: Encoding::BINARY)
104
+ part.bytesplice(0, 0, @buffer, @offset, count)
105
+ clear
106
+ end
107
+ part
108
+ end
109
+
110
+ def clear
111
+ @buffer.clear
112
+ @offset = 0
113
+ end
114
+
115
+ private
116
+
117
+ def compact
118
+ return unless @offset > COMPACT_THRESHOLD && @offset > (@buffer.bytesize / 2)
119
+
120
+ @buffer.bytesplice(0, @offset, '')
121
+ @offset = 0
122
+ end
123
+
124
+ # Checks the held bytes from pos, keeping its place in a line or value
125
+ # that continues in the next read
126
+ def check(pos, unanswered_bytes)
127
+ size = @buffer.bytesize
128
+ while pos < size
129
+ if @value_left.positive?
130
+ step = [@value_left, size - pos].min
131
+ @value_left -= step
132
+ pos += step
133
+ next
134
+ end
135
+
136
+ eol = @buffer.byteindex("\n", pos)
137
+ @line << @buffer.byteslice(pos, (eol ? eol + 1 : size) - pos)
138
+ line_too_long! if @line.bytesize > ConnectionManager::MAX_LINE_BYTES
139
+ return unless eol
140
+
141
+ pos = eol + 1
142
+ check_reply(@line, unanswered_bytes)
143
+ @line.clear
144
+ end
145
+ end
146
+
147
+ def check_reply(line, unanswered_bytes)
148
+ line_too_long! unless line.end_with?("\r\n")
149
+
150
+ @replies += 1
151
+ if @replies > unanswered_bytes - @counted_bytes + @lines
152
+ raise Invalid, 'more replies than requests while they were being sent'
153
+ end
154
+ return unless line.start_with?('VA ')
155
+
156
+ size = line[/\AVA (\d+)[ \r]/, 1]&.to_i
157
+ unless size && size <= @max_value_bytes
158
+ raise Invalid, 'a value larger than max_response_bytes while a request was being sent'
159
+ end
160
+
161
+ @value_left = size + 2
162
+ end
163
+
164
+ def line_too_long!
165
+ raise Invalid, "a reply line without CRLF in the first #{ConnectionManager::MAX_LINE_BYTES} bytes"
166
+ end
167
+ end
168
+ end
169
+ end
@@ -238,7 +238,7 @@ module Dalli
238
238
 
239
239
  def finish_pipelined_delete(sent)
240
240
  write_noop
241
- sent - response_processor.pipelined_delete_non_deletions
241
+ sent - response_processor.pipelined_delete_non_deletions(sent)
242
242
  end
243
243
 
244
244
  # Arithmetic Commands
@@ -373,8 +373,13 @@ module Dalli
373
373
  expect_reply_keys(keys)
374
374
  hash = {}
375
375
  unmarshal_error = nil
376
+ replies = 0
376
377
  while (line = @connection_manager.read_line)
377
378
  break if line.start_with?('MN')
379
+
380
+ replies += 1
381
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
382
+
378
383
  next unless line.start_with?('VA ')
379
384
 
380
385
  tokens = line.chomp!(TERMINATOR).split
@@ -408,8 +413,13 @@ module Dalli
408
413
  expect_reply_keys(keys)
409
414
  hash = {}
410
415
  unmarshal_error = nil
416
+ replies = 0
411
417
  while (line = @connection_manager.read_line)
412
418
  break if line.start_with?('MN')
419
+
420
+ replies += 1
421
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
422
+
413
423
  next unless line.start_with?('VA ')
414
424
 
415
425
  begin
@@ -467,7 +477,7 @@ module Dalli
467
477
  buffer = RequestFormatter.multi_meta_set(entries, ttl: ttl, **routing_token_kwargs(req_options))
468
478
  flushed_write(buffer)
469
479
  buffer.clear
470
- response_processor.consume_all_responses_until_mn
480
+ response_processor.consume_all_responses_until_mn(entries.size)
471
481
  end
472
482
  raise value_error if value_error
473
483
  end
@@ -479,7 +489,7 @@ module Dalli
479
489
  **routing_token_kwargs(req_options))
480
490
  flushed_write(buffer)
481
491
  buffer.clear
482
- keys.size - response_processor.pipelined_delete_non_deletions
492
+ keys.size - response_processor.pipelined_delete_non_deletions(keys.size)
483
493
  end
484
494
 
485
495
  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'
@@ -176,7 +178,11 @@ module Dalli
176
178
  def stats
177
179
  tokens = error_on_unexpected!(T_END_TOKEN_STAT)
178
180
  values = {}
181
+ replies = 0
179
182
  while tokens.first != END_TOKEN
183
+ replies += 1
184
+ raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
185
+
180
186
  values[tokens[1]] = tokens[2]
181
187
  tokens = next_line_to_tokens
182
188
  end
@@ -200,10 +206,16 @@ module Dalli
200
206
  tokens.last
201
207
  end
202
208
 
203
- def consume_all_responses_until_mn
209
+ def consume_all_responses_until_mn(max_responses = MAX_QUIET_RESPONSES)
204
210
  tokens = next_line_to_tokens
205
211
 
206
- tokens = next_line_to_tokens while tokens.first != MN
212
+ replies = 0
213
+ while tokens.first != MN
214
+ replies += 1
215
+ raise Dalli::DalliError, 'Too many quiet replies' if replies > max_responses
216
+
217
+ tokens = next_line_to_tokens
218
+ end
207
219
  true
208
220
  end
209
221
 
@@ -214,11 +226,13 @@ module Dalli
214
226
  # was NOT deleted -- a miss (NF) or an error. Returns that count so
215
227
  # callers can derive the number of successful deletes as
216
228
  # (keys_sent - non_deletions).
217
- def pipelined_delete_non_deletions
229
+ def pipelined_delete_non_deletions(max_responses = MAX_QUIET_RESPONSES)
218
230
  non_deletions = 0
219
231
  tokens = next_line_to_tokens
220
232
  until tokens.first == MN
221
233
  non_deletions += 1
234
+ raise Dalli::DalliError, 'Too many delete replies' if non_deletions > max_responses
235
+
222
236
  tokens = next_line_to_tokens
223
237
  end
224
238
  non_deletions
@@ -239,6 +253,13 @@ module Dalli
239
253
  def getk_response_from_buffer(buf, offset = 0, raw: false)
240
254
  # Find the header terminator starting from offset
241
255
  term_idx = buf.byteindex(TERMINATOR, offset)
256
+ max_line_bytes = ConnectionManager::MAX_LINE_BYTES
257
+ header_too_long = if term_idx
258
+ term_idx - offset + TERMINATOR.bytesize > max_line_bytes
259
+ else
260
+ buf.bytesize - offset >= max_line_bytes
261
+ end
262
+ raise Dalli::DalliError, "Reply line without CRLF in the first #{max_line_bytes} bytes" if header_too_long
242
263
  return [0] unless term_idx
243
264
 
244
265
  if buf.byteslice(offset, VA_PREFIX.bytesize) == VA_PREFIX
@@ -488,9 +509,11 @@ module Dalli
488
509
  end
489
510
 
490
511
  def check_value_size!(size)
491
- return if size.between?(0, MAX_VALUE_BYTES)
512
+ limit = @value_marshaller.max_response_bytes
513
+ return if size >= 0 && size <= MAX_VALUE_BYTES && size <= limit # rubocop:disable Style/ComparableBetween
492
514
 
493
- raise Dalli::DalliError, "Reply value size #{size} is out of range"
515
+ effective_limit = [MAX_VALUE_BYTES, limit].min
516
+ raise Dalli::DalliError, "Reply value size #{size} exceeds the #{effective_limit}-byte response limit"
494
517
  end
495
518
 
496
519
  # A value is read by its declared size, so check the CRLF that should
@@ -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
 
@@ -251,13 +267,15 @@ module Dalli
251
267
 
252
268
  # Closes the TCP socket if the handshake fails or times out, so a failed
253
269
  # attempt doesn't hold a file descriptor until GC.
254
- def self.wrapping_ssl_socket(tcp_socket, host, ssl_context)
270
+ def self.wrapping_ssl_socket(tcp_socket, host, ssl_context, timeout = nil)
255
271
  warn_if_unverified(ssl_context)
256
272
  connected = false
257
273
  ssl_socket = Dalli::Socket::SSLSocket.new(tcp_socket, ssl_context)
258
274
  ssl_socket.hostname = host
259
275
  ssl_socket.sync_close = true
260
- ssl_socket.connect
276
+ # The underlying TCP socket's IO#timeout= does not reliably bound
277
+ # OpenSSL's blocking handshake on Ruby 3.3.
278
+ Timeout.timeout(timeout) { ssl_socket.connect }
261
279
  connected = true
262
280
  ssl_socket
263
281
  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.3.2'
4
+ VERSION = '5.3.4'
5
5
 
6
6
  MIN_SUPPORTED_MEMCACHED_VERSION = '1.6.27'
7
7
  end
data/lib/dalli.rb CHANGED
@@ -91,6 +91,7 @@ require_relative 'dalli/ring'
91
91
  require_relative 'dalli/protocol'
92
92
  require_relative 'dalli/protocol/base'
93
93
  require_relative 'dalli/protocol/connection_manager'
94
+ require_relative 'dalli/protocol/held_replies'
94
95
  require_relative 'dalli/protocol/meta'
95
96
  require_relative 'dalli/protocol/response_buffer'
96
97
  require_relative 'dalli/protocol/server_config_parser'
metadata CHANGED
@@ -1,96 +1,101 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: dalli
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.3.2
4
+ version: 5.3.4
5
5
  platform: ruby
6
6
  authors:
7
- - Peter M. Goldstein
8
- - Mike Perham
7
+ - Peter M. Goldstein
8
+ - Mike Perham
9
9
  bindir: bin
10
10
  cert_chain: []
11
11
  date: 1980-01-02 00:00:00.000000000 Z
12
12
  dependencies:
13
- - !ruby/object:Gem::Dependency
14
- name: logger
15
- requirement: !ruby/object:Gem::Requirement
16
- requirements:
17
- - - ">="
18
- - !ruby/object:Gem::Version
19
- version: '0'
20
- type: :runtime
21
- prerelease: false
22
- version_requirements: !ruby/object:Gem::Requirement
23
- requirements:
24
- - - ">="
25
- - !ruby/object:Gem::Version
26
- version: '0'
13
+ - !ruby/object:Gem::Dependency
14
+ name: logger
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ -
18
+ - ">="
19
+ - !ruby/object:Gem::Version
20
+ version: "0"
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ -
26
+ - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: "0"
27
29
  description: High performance memcached client for Ruby
28
30
  email:
29
- - peter.m.goldstein@gmail.com
30
- - mperham@gmail.com
31
+ - peter.m.goldstein@gmail.com
32
+ - mperham@gmail.com
31
33
  executables: []
32
34
  extensions: []
33
35
  extra_rdoc_files: []
34
36
  files:
35
- - CHANGELOG.md
36
- - Gemfile
37
- - LICENSE
38
- - README.md
39
- - lib/dalli.rb
40
- - lib/dalli/cache_result.rb
41
- - lib/dalli/cas/client.rb
42
- - lib/dalli/client.rb
43
- - lib/dalli/compressor.rb
44
- - lib/dalli/flags.rb
45
- - lib/dalli/instrumentation.rb
46
- - lib/dalli/json_serializer.rb
47
- - lib/dalli/key_grouping.rb
48
- - lib/dalli/key_manager.rb
49
- - lib/dalli/options.rb
50
- - lib/dalli/pipelined_deleter.rb
51
- - lib/dalli/pipelined_getter.rb
52
- - lib/dalli/pipelined_setter.rb
53
- - lib/dalli/protocol.rb
54
- - lib/dalli/protocol/base.rb
55
- - lib/dalli/protocol/connection_manager.rb
56
- - lib/dalli/protocol/key_regularizer.rb
57
- - lib/dalli/protocol/meta.rb
58
- - lib/dalli/protocol/request_formatter.rb
59
- - lib/dalli/protocol/response_buffer.rb
60
- - lib/dalli/protocol/response_processor.rb
61
- - lib/dalli/protocol/server_config_parser.rb
62
- - lib/dalli/protocol/string_marshaller.rb
63
- - lib/dalli/protocol/ttl_sanitizer.rb
64
- - lib/dalli/protocol/value_compressor.rb
65
- - lib/dalli/protocol/value_marshaller.rb
66
- - lib/dalli/protocol/value_serializer.rb
67
- - lib/dalli/ring.rb
68
- - lib/dalli/servers_arg_normalizer.rb
69
- - lib/dalli/socket.rb
70
- - lib/dalli/version.rb
71
- - lib/rack/session/dalli.rb
72
- homepage: https://github.com/petergoldstein/dalli
37
+ - CHANGELOG.md
38
+ - Gemfile
39
+ - LICENSE
40
+ - README.md
41
+ - lib/dalli.rb
42
+ - lib/dalli/cache_result.rb
43
+ - lib/dalli/cas/client.rb
44
+ - lib/dalli/client.rb
45
+ - lib/dalli/compressor.rb
46
+ - lib/dalli/flags.rb
47
+ - lib/dalli/instrumentation.rb
48
+ - lib/dalli/json_serializer.rb
49
+ - lib/dalli/key_grouping.rb
50
+ - lib/dalli/key_manager.rb
51
+ - lib/dalli/options.rb
52
+ - lib/dalli/pipelined_deleter.rb
53
+ - lib/dalli/pipelined_getter.rb
54
+ - lib/dalli/pipelined_setter.rb
55
+ - lib/dalli/protocol.rb
56
+ - lib/dalli/protocol/base.rb
57
+ - lib/dalli/protocol/connection_manager.rb
58
+ - lib/dalli/protocol/held_replies.rb
59
+ - lib/dalli/protocol/key_regularizer.rb
60
+ - lib/dalli/protocol/meta.rb
61
+ - lib/dalli/protocol/request_formatter.rb
62
+ - lib/dalli/protocol/response_buffer.rb
63
+ - lib/dalli/protocol/response_processor.rb
64
+ - lib/dalli/protocol/server_config_parser.rb
65
+ - lib/dalli/protocol/string_marshaller.rb
66
+ - lib/dalli/protocol/ttl_sanitizer.rb
67
+ - lib/dalli/protocol/value_compressor.rb
68
+ - lib/dalli/protocol/value_marshaller.rb
69
+ - lib/dalli/protocol/value_serializer.rb
70
+ - lib/dalli/ring.rb
71
+ - lib/dalli/servers_arg_normalizer.rb
72
+ - lib/dalli/socket.rb
73
+ - lib/dalli/version.rb
74
+ - lib/rack/session/dalli.rb
75
+ homepage: "https://github.com/petergoldstein/dalli"
73
76
  licenses:
74
- - MIT
77
+ - MIT
75
78
  metadata:
76
- bug_tracker_uri: https://github.com/petergoldstein/dalli/issues
77
- changelog_uri: https://github.com/petergoldstein/dalli/blob/main/CHANGELOG.md
78
- rubygems_mfa_required: 'true'
79
+ bug_tracker_uri: "https://github.com/petergoldstein/dalli/issues"
80
+ changelog_uri: "https://github.com/petergoldstein/dalli/blob/main/CHANGELOG.md"
81
+ rubygems_mfa_required: "true"
79
82
  rdoc_options: []
80
83
  require_paths:
81
- - lib
84
+ - lib
82
85
  required_ruby_version: !ruby/object:Gem::Requirement
83
86
  requirements:
84
- - - ">="
85
- - !ruby/object:Gem::Version
86
- version: '3.3'
87
+ -
88
+ - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: "3.3"
87
91
  required_rubygems_version: !ruby/object:Gem::Requirement
88
92
  requirements:
89
- - - ">="
90
- - !ruby/object:Gem::Version
91
- version: '0'
93
+ -
94
+ - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: "0"
92
97
  requirements: []
93
- rubygems_version: 4.0.24
98
+ rubygems_version: 4.1.0
94
99
  specification_version: 4
95
100
  summary: High performance memcached client for Ruby
96
101
  test_files: []