net_tcp_client 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,8 +38,8 @@ module Net
38
38
  include SemanticLogger::Loggable if defined?(SemanticLogger::Loggable)
39
39
 
40
40
  attr_accessor :connect_timeout, :read_timeout, :write_timeout,
41
- :connect_retry_count, :connect_retry_interval, :retry_count,
42
- :policy, :close_on_error, :buffered, :ssl, :proxy_server, :keepalive
41
+ :connect_retry_count, :connect_retry_interval, :retry_count,
42
+ :policy, :close_on_error, :buffered, :ssl, :keepalive
43
43
  attr_reader :servers, :address, :socket, :ssl_handshake_timeout
44
44
 
45
45
  # Supports embedding user supplied data along with this connection
@@ -65,8 +65,8 @@ module Net
65
65
  # Return the array of errors that will result in an automatic connection retry
66
66
  # To add any additional errors to the standard list:
67
67
  # Net::TCPClient.reconnect_on_errors << Errno::EPROTO
68
- def self.reconnect_on_errors
69
- @reconnect_on_errors
68
+ class << self
69
+ attr_reader :reconnect_on_errors
70
70
  end
71
71
 
72
72
  # Create a connection, call the supplied block and close the connection on
@@ -81,19 +81,17 @@ module Net
81
81
  # connect_retry_count: 5
82
82
  # ) do |client|
83
83
  # client.retry_on_connection_failure do
84
- # client.send('Update the database')
84
+ # client.write('Update the database')
85
85
  # end
86
86
  # response = client.read(20)
87
87
  # puts "Received: #{response}"
88
88
  # end
89
89
  #
90
- def self.connect(params={})
91
- begin
92
- connection = self.new(params)
93
- yield(connection)
94
- ensure
95
- connection.close if connection
96
- end
90
+ def self.connect(params = {})
91
+ connection = new(**params)
92
+ yield(connection)
93
+ ensure
94
+ connection&.close
97
95
  end
98
96
 
99
97
  # Create a new TCP Client connection
@@ -103,6 +101,8 @@ module Net
103
101
  # URL of the server to connect to with port number
104
102
  # 'localhost:2000'
105
103
  # '192.168.1.10:80'
104
+ # '[2001:db8::1]:80' (An IPv6 address must be enclosed in square brackets)
105
+ # A host name is resolved to all of its IPv4 and IPv6 addresses, IPv4 first.
106
106
  #
107
107
  # :servers [Array of String]
108
108
  # Array of URL's of servers to connect to with port numbers
@@ -143,7 +143,7 @@ module Net
143
143
  # upon use instead of possibly taking considerable time to fail.
144
144
  # Default: true
145
145
  #
146
- # :connect_retry_count [Fixnum]
146
+ # :connect_retry_count [Integer]
147
147
  # Number of times to retry connecting when a connection fails
148
148
  # Default: 10
149
149
  #
@@ -151,7 +151,7 @@ module Net
151
151
  # Number of seconds between connection retry attempts after the first failed attempt
152
152
  # Default: 0.5
153
153
  #
154
- # :retry_count [Fixnum]
154
+ # :retry_count [Integer]
155
155
  # Number of times to retry when calling #retry_on_connection_failure
156
156
  # This is independent of :connect_retry_count which still applies with
157
157
  # connection failures. This retry controls upto how many times to retry the
@@ -193,10 +193,8 @@ module Net
193
193
  # This includes a Read Timeout
194
194
  # Default: true
195
195
  #
196
- # :proxy_server [String]
197
- # The host name and port in the form of 'host_name:1234' to forward
198
- # socket connections though.
199
- # Default: nil ( none )
196
+ # :proxy_server
197
+ # Not supported: raises ArgumentError. Connecting through a SOCKS proxy never worked.
200
198
  #
201
199
  # SSL Options
202
200
  # :ssl [true|false|Hash]
@@ -220,7 +218,7 @@ module Net
220
218
  # )
221
219
  #
222
220
  # client.retry_on_connection_failure do
223
- # client.send('Update the database')
221
+ # client.write('Update the database')
224
222
  # end
225
223
  #
226
224
  # # Read upto 20 characters from the server
@@ -247,11 +245,10 @@ module Net
247
245
  # }
248
246
  # )
249
247
  def initialize(server: nil, servers: nil,
250
- policy: :ordered, buffered: true, keepalive: true,
251
- connect_timeout: 10.0, read_timeout: 60.0, write_timeout: 60.0,
252
- connect_retry_count: 10, retry_count: 3, connect_retry_interval: 0.5, close_on_error: true,
253
- on_connect: nil, proxy_server: nil, ssl: nil
254
- )
248
+ policy: :ordered, buffered: true, keepalive: true,
249
+ connect_timeout: 10.0, read_timeout: 60.0, write_timeout: 60.0,
250
+ connect_retry_count: 10, retry_count: 3, connect_retry_interval: 0.5, close_on_error: true,
251
+ on_connect: nil, proxy_server: nil, ssl: nil)
255
252
  @read_timeout = read_timeout.to_f
256
253
  @write_timeout = write_timeout.to_f
257
254
  @connect_timeout = connect_timeout.to_f
@@ -261,9 +258,15 @@ module Net
261
258
  @retry_count = retry_count
262
259
  @connect_retry_interval = connect_retry_interval.to_f
263
260
  @on_connect = on_connect
264
- @proxy_server = proxy_server
265
261
  @policy = policy
266
262
  @close_on_error = close_on_error
263
+ if proxy_server
264
+ raise(
265
+ ArgumentError,
266
+ "proxy_server: is not supported. Net::TCPClient cannot connect through a SOCKS proxy. " \
267
+ "See https://github.com/reidmorrison/net_tcp_client/issues/7"
268
+ )
269
+ end
267
270
  if ssl
268
271
  @ssl = ssl == true ? {} : ssl
269
272
  @ssl_handshake_timeout = (@ssl.delete(:handshake_timeout) || @connect_timeout).to_f
@@ -271,7 +274,7 @@ module Net
271
274
  @servers = [server] if server
272
275
  @servers = servers if servers
273
276
 
274
- raise(ArgumentError, 'Missing mandatory :server or :servers') unless @servers
277
+ raise(ArgumentError, "Missing mandatory :server or :servers") unless @servers
275
278
 
276
279
  connect
277
280
  end
@@ -309,27 +312,33 @@ module Net
309
312
  begin
310
313
  connect_to_server(servers, policy)
311
314
  logger.info(message: "Connected to #{address}", duration: (Time.now - start_time) * 1000) if respond_to?(:logger)
312
- rescue ConnectionFailure, ConnectionTimeout => exception
313
- cause = exception.is_a?(ConnectionTimeout) ? exception : exception.cause
315
+ rescue ConnectionFailure, ConnectionTimeout => e
316
+ cause = e.is_a?(ConnectionTimeout) ? e : e.cause
314
317
  # Retry-able?
315
318
  if self.class.reconnect_on_errors.include?(cause.class) && (retries < connect_retry_count.to_i)
316
319
  retries += 1
317
- logger.warn "#connect Failed to connect to any of #{servers.join(',')}. Sleeping:#{connect_retry_interval}s. Retry: #{retries}" if respond_to?(:logger)
320
+ if respond_to?(:logger)
321
+ logger.warn "#connect Failed to connect to any of #{servers.join(',')}. Sleeping:#{connect_retry_interval}s. Retry: #{retries}"
322
+ end
318
323
  sleep(connect_retry_interval)
319
324
  retry
320
325
  else
321
- message = "#connect Failed to connect to any of #{servers.join(',')} after #{retries} retries. #{exception.class}: #{exception.message}"
322
- logger.benchmark_error(message, exception: exception, duration: (Time.now - start_time)) if respond_to?(:logger)
323
- raise ConnectionFailure.new(message, address.to_s, cause)
326
+ if respond_to?(:logger)
327
+ message = "#connect Failed to connect to any of #{servers.join(',')} after #{retries} retries"
328
+ # Not measure_error: it raises the exception it is given, which would make what #connect
329
+ # raises depend on the log level.
330
+ logger.error(message: message, exception: e, duration: (Time.now - start_time) * 1000)
331
+ end
332
+ raise e
324
333
  end
325
334
  end
326
335
  end
327
336
 
328
- # Send data to the server
337
+ # Write data to the server
329
338
  #
330
- # Use #with_retry to add resilience to the #send method
339
+ # Use #with_retry to add resilience to the #write method
331
340
  #
332
- # Raises Net::TCPClient::ConnectionFailure whenever the send fails
341
+ # Raises Net::TCPClient::ConnectionFailure whenever the write fails
333
342
  # For a description of the errors, see Socket#write
334
343
  #
335
344
  # Parameters
@@ -352,15 +361,15 @@ module Net
352
361
  payload = {timeout: timeout}
353
362
  # With trace level also log the sent data
354
363
  payload[:data] = data if logger.trace?
355
- logger.benchmark_debug('#write', payload: payload) do
364
+ logger.measure_debug("#write", payload: payload) do
356
365
  payload[:bytes] = socket_write(data, timeout)
357
366
  end
358
367
  else
359
368
  socket_write(data, timeout)
360
369
  end
361
- rescue Exception => exc
370
+ rescue Exception => e
362
371
  close if close_on_error
363
- raise exc
372
+ raise e
364
373
  end
365
374
 
366
375
  # Returns a response from the server
@@ -378,7 +387,7 @@ module Net
378
387
  # to read the response from the connection
379
388
  #
380
389
  # Parameters
381
- # length [Fixnum]
390
+ # length [Integer]
382
391
  # The number of bytes to return
383
392
  # #read will not return until 'length' bytes have been received from
384
393
  # the server
@@ -402,7 +411,7 @@ module Net
402
411
  def read(length, buffer = nil, timeout = read_timeout)
403
412
  if respond_to?(:logger)
404
413
  payload = {bytes: length, timeout: timeout}
405
- logger.benchmark_debug('#read', payload: payload) do
414
+ logger.measure_debug("#read", payload: payload) do
406
415
  data = socket_read(length, buffer, timeout)
407
416
  # With trace level also log the received data
408
417
  payload[:data] = data if logger.trace?
@@ -411,12 +420,12 @@ module Net
411
420
  else
412
421
  socket_read(length, buffer, timeout)
413
422
  end
414
- rescue Exception => exc
423
+ rescue Exception => e
415
424
  close if close_on_error
416
- raise exc
425
+ raise e
417
426
  end
418
427
 
419
- # Send and/or receive data with automatic retry on connection failure
428
+ # Write and/or receive data with automatic retry on connection failure
420
429
  #
421
430
  # On a connection failure, it will create a new connection and retry the block.
422
431
  # Returns immediately on exception Net::TCPClient::ReadTimeout
@@ -425,28 +434,28 @@ module Net
425
434
  # 1. Example of a resilient _readonly_ request:
426
435
  #
427
436
  # When reading data from a server that does not change state on the server
428
- # Wrap both the send and the read with #retry_on_connection_failure
429
- # since it is safe to send the same data twice to the server
437
+ # Wrap both the write and the read with #retry_on_connection_failure
438
+ # since it is safe to write the same data twice to the server
430
439
  #
431
- # # Since the send can be sent many times it is safe to also put the receive
440
+ # # Since the write can be sent many times it is safe to also put the receive
432
441
  # # inside the retry block
433
442
  # value = client.retry_on_connection_failure do
434
- # client.send("GETVALUE:count\n")
443
+ # client.write("GETVALUE:count\n")
435
444
  # client.read(20).strip.to_i
436
445
  # end
437
446
  #
438
447
  # 2. Example of a resilient request that _modifies_ data on the server:
439
448
  #
440
449
  # When changing state on the server, for example when updating a value
441
- # Wrap _only_ the send with #retry_on_connection_failure
450
+ # Wrap _only_ the write with #retry_on_connection_failure
442
451
  # The read must be outside the #retry_on_connection_failure since we must
443
- # not retry the send if the connection fails during the #read
452
+ # not retry the write if the connection fails during the #read
444
453
  #
445
454
  # value = 45
446
- # # Only the send is within the retry block since we cannot re-send once
447
- # # the send was successful since the server may have made the change
455
+ # # Only the write is within the retry block since we cannot re-write once
456
+ # # the write was successful since the server may have made the change
448
457
  # client.retry_on_connection_failure do
449
- # client.send("SETVALUE:#{count}\n")
458
+ # client.write("SETVALUE:#{count}\n")
450
459
  # end
451
460
  # # Server returns "SAVED" if the call was successful
452
461
  # result = client.read(20).strip
@@ -462,20 +471,22 @@ module Net
462
471
  begin
463
472
  connect if closed?
464
473
  yield(self)
465
- rescue ConnectionFailure => exception
466
- exc_str = exception.cause ? "#{exception.cause.class}: #{exception.cause.message}" : exception.message
474
+ rescue ConnectionFailure => e
475
+ exc_str = e.cause ? "#{e.cause.class}: #{e.cause.message}" : e.message
467
476
  # Re-raise exceptions that should not be retried
468
- if !self.class.reconnect_on_errors.include?(exception.cause.class)
477
+ if !self.class.reconnect_on_errors.include?(e.cause.class)
469
478
  logger.info "#retry_on_connection_failure not configured to retry: #{exc_str}" if respond_to?(:logger)
470
- raise exception
479
+ raise e
471
480
  elsif retries < @retry_count
472
481
  retries += 1
473
- logger.warn "#retry_on_connection_failure retry #{retries} due to #{exception.class}: #{exception.message}" if respond_to?(:logger)
482
+ logger.warn "#retry_on_connection_failure retry #{retries} due to #{e.class}: #{e.message}" if respond_to?(:logger)
474
483
  connect
475
484
  retry
476
485
  end
477
- logger.error "#retry_on_connection_failure Connection failure: #{exception.class}: #{exception.message}. Giving up after #{retries} retries" if respond_to?(:logger)
478
- raise ConnectionFailure.new("After #{retries} retries to host '#{server}': #{exc_str}", server, exception.cause)
486
+ if respond_to?(:logger)
487
+ logger.error "#retry_on_connection_failure Connection failure: #{e.class}: #{e.message}. Giving up after #{retries} retries"
488
+ end
489
+ raise ConnectionFailure.new("After #{retries} retries to any of #{servers.join(',')}': #{exc_str}", servers, e.cause)
479
490
  end
480
491
  end
481
492
 
@@ -487,14 +498,15 @@ module Net
487
498
  @socket = nil
488
499
  @address = nil
489
500
  true
490
- rescue IOError => exception
491
- logger.warn "IOError when attempting to close socket: #{exception.class}: #{exception.message}" if respond_to?(:logger)
501
+ rescue IOError => e
502
+ logger.warn "IOError when attempting to close socket: #{e.class}: #{e.message}" if respond_to?(:logger)
492
503
  false
493
504
  end
494
505
 
495
506
  def flush
496
507
  return unless socket
497
- respond_to?(:logger) ? logger.benchmark_debug('#flush') { socket.flush } : socket.flush
508
+
509
+ respond_to?(:logger) ? logger.measure_debug("#flush") { socket.flush } : socket.flush
498
510
  end
499
511
 
500
512
  def closed?
@@ -520,13 +532,17 @@ module Net
520
532
  # I.e. About 8.3 micro seconds per call
521
533
  def alive?
522
534
  return false if socket.nil? || closed?
535
+ return true unless IO.select([socket], nil, nil, 0)
523
536
 
524
- if IO.select([socket], nil, nil, 0)
525
- !socket.eof? rescue false
526
- else
527
- true
528
- end
529
- rescue IOError
537
+ # Something is waiting to be read: data, the end of the connection, or with SSL, records that
538
+ # carry no data, such as TLS 1.3 session tickets. socket.eof? would then block until the server
539
+ # sends data, so read a byte without blocking instead, and put it back for the next #read.
540
+ byte = socket.read_nonblock(1, exception: false)
541
+ return false if byte.nil?
542
+
543
+ socket.ungetc(byte) if byte.is_a?(String)
544
+ true
545
+ rescue StandardError
530
546
  false
531
547
  end
532
548
 
@@ -544,8 +560,8 @@ module Net
544
560
  Policy::Base.factory(policy, servers).each do |address|
545
561
  begin
546
562
  return connect_to_address(address)
547
- rescue ConnectionTimeout, ConnectionFailure => exception
548
- last_exception = exception
563
+ rescue ConnectionTimeout, ConnectionFailure => e
564
+ last_exception = e
549
565
  end
550
566
  end
551
567
 
@@ -559,12 +575,7 @@ module Net
559
575
  # Connect to the server at the supplied address
560
576
  # Returns the socket connection
561
577
  def connect_to_address(address)
562
- socket =
563
- if proxy_server
564
- ::SOCKSSocket.new("#{address.ip_address}:#{address.port}", proxy_server)
565
- else
566
- ::Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
567
- end
578
+ socket = ::Socket.new(address.family, Socket::SOCK_STREAM, 0)
568
579
  unless buffered
569
580
  socket.sync = true
570
581
  socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
@@ -577,7 +588,7 @@ module Net
577
588
  @address = address
578
589
 
579
590
  # Invoke user supplied Block every time a new connection has been established
580
- @on_connect.call(self) if @on_connect
591
+ @on_connect&.call(self)
581
592
  end
582
593
 
583
594
  # Connect to server
@@ -585,32 +596,39 @@ module Net
585
596
  # Raises Net::TCPClient::ConnectionTimeout when the connection timeout has been exceeded
586
597
  # Raises Net::TCPClient::ConnectionFailure
587
598
  def socket_connect(socket, address, timeout)
588
- socket_address = Socket.pack_sockaddr_in(address.port, address.ip_address)
599
+ socket_address = address.sockaddr
589
600
 
590
601
  # Timeout of -1 means wait forever for a connection
591
602
  return socket.connect(socket_address) if timeout == -1
592
603
 
593
604
  deadline = Time.now.utc + timeout
594
605
  begin
595
- non_blocking(socket, deadline) { socket.connect_nonblock(socket_address) }
606
+ if socket.connect_nonblock(socket_address, exception: false) == :wait_writable
607
+ raise NonBlockingTimeout unless IO.select(nil, [socket], nil, check_time_remaining(deadline))
608
+
609
+ # Once the socket is writable, SO_ERROR holds the outcome of the connect. Calling connect again
610
+ # instead is not portable: on some platforms it raises Errno::EISCONN after a refused connect.
611
+ error = socket.getsockopt(Socket::SOL_SOCKET, Socket::SO_ERROR).int
612
+ raise SystemCallError.new("connect(2) for #{address}", error) unless error.zero?
613
+ end
596
614
  rescue Errno::EISCONN
597
615
  # Connection was successful.
598
616
  rescue NonBlockingTimeout
599
- raise ConnectionTimeout.new("Timed out after #{timeout} seconds trying to connect to #{address}")
600
- rescue SystemCallError, IOError => exception
601
- message = "#connect Connection failure connecting to '#{address.to_s}': #{exception.class}: #{exception.message}"
617
+ raise ConnectionTimeout, "Timed out after #{timeout} seconds trying to connect to #{address}"
618
+ rescue SystemCallError, IOError => e
619
+ message = "#connect Connection failure connecting to '#{address}': #{e.class}: #{e.message}"
602
620
  logger.error message if respond_to?(:logger)
603
- raise ConnectionFailure.new(message, address.to_s, exception)
621
+ raise ConnectionFailure.new(message, address.to_s, e)
604
622
  end
605
623
  end
606
624
 
607
625
  # Write to the socket
608
626
  def socket_write(data, timeout)
609
- if timeout < 0
627
+ if timeout.negative?
610
628
  socket.write(data)
611
629
  else
612
- deadline = Time.now.utc + timeout
613
- length = data.bytesize
630
+ deadline = Time.now.utc + timeout
631
+ length = data.bytesize
614
632
  total_count = 0
615
633
  non_blocking(socket, deadline) do
616
634
  loop do
@@ -621,46 +639,64 @@ module Net
621
639
  end
622
640
  total_count += count
623
641
  return total_count if total_count >= length
642
+
624
643
  data = data.byteslice(count..-1)
625
644
  end
626
645
  end
627
646
  end
628
647
  rescue NonBlockingTimeout
629
648
  logger.warn "#write Timeout after #{timeout} seconds" if respond_to?(:logger)
630
- raise WriteTimeout.new("Timed out after #{timeout} seconds trying to write to #{address}")
631
- rescue SystemCallError, IOError => exception
632
- message = "#write Connection failure while writing to '#{address.to_s}': #{exception.class}: #{exception.message}"
649
+ raise WriteTimeout, "Timed out after #{timeout} seconds trying to write to #{address}"
650
+ rescue SystemCallError, IOError => e
651
+ message = "#write Connection failure while writing to '#{address}': #{e.class}: #{e.message}"
633
652
  logger.error message if respond_to?(:logger)
634
- raise ConnectionFailure.new(message, address.to_s, exception)
653
+ raise ConnectionFailure.new(message, address.to_s, e)
635
654
  end
636
655
 
637
656
  def socket_read(length, buffer, timeout)
638
657
  result =
639
- if timeout < 0
658
+ if timeout.negative?
640
659
  buffer.nil? ? socket.read(length) : socket.read(length, buffer)
641
660
  else
642
- deadline = Time.now.utc + timeout
643
- non_blocking(socket, deadline) do
644
- buffer.nil? ? socket.read_nonblock(length) : socket.read_nonblock(length, buffer)
645
- end
661
+ socket_read_nonblock(length, buffer, Time.now.utc + timeout)
646
662
  end
647
663
 
648
664
  # EOF before all the data was returned
649
- if result.nil? || (result.length < length)
665
+ if result.nil? || (result.bytesize < length)
650
666
  logger.warn "#read server closed the connection before #{length} bytes were returned" if respond_to?(:logger)
651
- raise ConnectionFailure.new('Connection lost while reading data', address.to_s, EOFError.new('end of file reached'))
667
+ raise ConnectionFailure.new("Connection lost while reading data", address.to_s, EOFError.new("end of file reached"))
652
668
  end
653
669
  result
654
670
  rescue NonBlockingTimeout
655
671
  logger.warn "#read Timeout after #{timeout} seconds" if respond_to?(:logger)
656
- raise ReadTimeout.new("Timed out after #{timeout} seconds trying to read from #{address}")
657
- rescue SystemCallError, IOError => exception
658
- message = "#read Connection failure while reading data from '#{address.to_s}': #{exception.class}: #{exception.message}"
672
+ raise ReadTimeout, "Timed out after #{timeout} seconds trying to read from #{address}"
673
+ rescue SystemCallError, IOError => e
674
+ message = "#read Connection failure while reading data from '#{address}': #{e.class}: #{e.message}"
659
675
  logger.error message if respond_to?(:logger)
660
- raise ConnectionFailure.new(message, address.to_s, exception)
676
+ raise ConnectionFailure.new(message, address.to_s, e)
661
677
  end
662
678
 
663
- class NonBlockingTimeout< ::SocketError
679
+ # Returns [String] the next length bytes from the socket, or fewer when the connection
680
+ # is closed before they all arrive.
681
+ #
682
+ # Raises NonBlockingTimeout when they have not all arrived by the deadline. The bytes read
683
+ # until then are put back, so that the next #read returns them.
684
+ def socket_read_nonblock(length, buffer, deadline)
685
+ result = buffer ? buffer.clear.force_encoding(Encoding::BINARY) : String.new(encoding: Encoding::BINARY)
686
+ begin
687
+ non_blocking(socket, deadline) do
688
+ result << socket.read_nonblock(length - result.bytesize) while result.bytesize < length
689
+ end
690
+ rescue NonBlockingTimeout
691
+ socket.ungetc(result) unless result.empty?
692
+ raise
693
+ rescue EOFError
694
+ # Fewer than length bytes: #socket_read reports the lost connection.
695
+ end
696
+ result
697
+ end
698
+
699
+ class NonBlockingTimeout < ::SocketError
664
700
  end
665
701
 
666
702
  def non_blocking(socket, deadline)
@@ -668,16 +704,19 @@ module Net
668
704
  rescue IO::WaitReadable
669
705
  time_remaining = check_time_remaining(deadline)
670
706
  raise NonBlockingTimeout unless IO.select([socket], nil, nil, time_remaining)
707
+
671
708
  retry
672
709
  rescue IO::WaitWritable
673
710
  time_remaining = check_time_remaining(deadline)
674
711
  raise NonBlockingTimeout unless IO.select(nil, [socket], nil, time_remaining)
712
+
675
713
  retry
676
714
  end
677
715
 
678
716
  def check_time_remaining(deadline)
679
717
  time_remaining = deadline - Time.now.utc
680
- raise NonBlockingTimeout if time_remaining < 0
718
+ raise NonBlockingTimeout if time_remaining.negative?
719
+
681
720
  time_remaining
682
721
  end
683
722
 
@@ -705,13 +744,13 @@ module Net
705
744
  rescue Errno::EISCONN
706
745
  # Connection was successful.
707
746
  rescue NonBlockingTimeout
708
- raise ConnectionTimeout.new("SSL handshake Timed out after #{timeout} seconds trying to connect to #{address.to_s}")
747
+ raise ConnectionTimeout, "SSL handshake Timed out after #{timeout} seconds trying to connect to #{address}"
709
748
  end
710
749
  end
711
- rescue SystemCallError, OpenSSL::SSL::SSLError, IOError => exception
712
- message = "#connect SSL handshake failure with '#{address.to_s}': #{exception.class}: #{exception.message}"
750
+ rescue SystemCallError, OpenSSL::SSL::SSLError, IOError => e
751
+ message = "#connect SSL handshake failure with '#{address}': #{e.class}: #{e.message}"
713
752
  logger.error message if respond_to?(:logger)
714
- raise ConnectionFailure.new(message, address.to_s, exception)
753
+ raise ConnectionFailure.new(message, address.to_s, e)
715
754
  end
716
755
 
717
756
  # Verify Peer certificate
@@ -721,20 +760,20 @@ module Net
721
760
 
722
761
  # Raises Net::TCPClient::ConnectionFailure if the peer certificate does not match its hostname
723
762
  def ssl_verify(ssl_socket, address)
724
- unless OpenSSL::SSL.verify_certificate_identity(ssl_socket.peer_cert, address.host_name)
725
- domains = extract_domains_from_cert(ssl_socket.peer_cert)
726
- ssl_socket.close
727
- message = "#connect SSL handshake failed due to a hostname mismatch. Request address was: '#{address.to_s}'" +
728
- " Certificate valid for hostnames: #{domains.map { |d| "'#{d}'"}.join(',')}"
729
- logger.error message if respond_to?(:logger)
730
- raise ConnectionFailure.new(message, address.to_s)
731
- end
763
+ return if OpenSSL::SSL.verify_certificate_identity(ssl_socket.peer_cert, address.host_name)
764
+
765
+ domains = extract_domains_from_cert(ssl_socket.peer_cert)
766
+ ssl_socket.close
767
+ message = "#connect SSL handshake failed due to a hostname mismatch. Request address was: '#{address}'" \
768
+ " Certificate valid for hostnames: #{domains.map { |d| "'#{d}'" }.join(',')}"
769
+ logger.error message if respond_to?(:logger)
770
+ raise ConnectionFailure.new(message, address.to_s)
732
771
  end
733
772
 
734
773
  def extract_domains_from_cert(cert)
735
- cert.subject.to_a.each{|oid, value|
774
+ cert.subject.to_a.each do |oid, value|
736
775
  return [value] if oid == "CN"
737
- }
776
+ end
738
777
  end
739
778
  end
740
779
  end
@@ -1,5 +1,5 @@
1
1
  module Net
2
- class TCPClient #:nodoc
3
- VERSION = '2.2.0'.freeze
2
+ class TCPClient
3
+ VERSION = "2.3.0".freeze
4
4
  end
5
5
  end
@@ -1,22 +1,22 @@
1
- require 'socket'
1
+ require "socket"
2
2
  # Load SemanticLogger if available
3
3
  begin
4
- require 'semantic_logger'
4
+ require "semantic_logger"
5
5
  rescue LoadError
6
6
  end
7
- require 'net/tcp_client/version'
8
- require 'net/tcp_client/address'
9
- require 'net/tcp_client/exceptions'
10
- require 'net/tcp_client/tcp_client'
7
+ require "net/tcp_client/version"
8
+ require "net/tcp_client/address"
9
+ require "net/tcp_client/exceptions"
10
+ require "net/tcp_client/tcp_client"
11
11
 
12
12
  # @formatter:off
13
13
  module Net
14
14
  class TCPClient
15
15
  module Policy
16
- autoload :Base, 'net/tcp_client/policy/base.rb'
17
- autoload :Custom, 'net/tcp_client/policy/custom.rb'
18
- autoload :Ordered, 'net/tcp_client/policy/ordered.rb'
19
- autoload :Random, 'net/tcp_client/policy/random.rb'
16
+ autoload :Base, "net/tcp_client/policy/base.rb"
17
+ autoload :Custom, "net/tcp_client/policy/custom.rb"
18
+ autoload :Ordered, "net/tcp_client/policy/ordered.rb"
19
+ autoload :Random, "net/tcp_client/policy/random.rb"
20
20
  end
21
21
  end
22
22
  end
@@ -1 +1 @@
1
- require 'net/tcp_client'
1
+ require "net/tcp_client"