Module: Lich::Common::SocketConfigurator

Defined in:
documented/common/socketconfigurator.rb

Overview

Provides methods to configure socket options. This module handles both Windows and Unix socket configurations.

Examples:

Configuring a socket

Lich::Common::SocketConfigurator.configure(socket, keepalive: { enable: true })

Defined Under Namespace

Modules: WinFFI

Class Method Summary collapse

Class Method Details

.configure(sock, keepalive: { enable: true, idle: 120, interval: 30 }, linger: { enable: true, timeout: 5 }, timeout: { recv: 30, send: 30 }, buffer_size: { recv: 32768, send: 32768 }, tcp_nodelay: true, tcp_maxrt: 10) ⇒ void

This method returns an undefined value.

Configures the given socket with specified options.

Examples:

Configuring a socket with custom options

Lich::Common::SocketConfigurator.configure(socket, keepalive: { enable: true, idle: 60 })

Parameters:

  • sock (Socket)

    The socket to configure.

  • keepalive (Hash) (defaults to: { enable: true, idle: 120, interval: 30 })

    Options for TCP keep-alive settings.

  • linger (Hash) (defaults to: { enable: true, timeout: 5 })

    Options for socket linger settings.

  • timeout (Hash) (defaults to: { recv: 30, send: 30 })

    Options for receive and send timeouts.

  • buffer_size (Hash) (defaults to: { recv: 32768, send: 32768 })

    Options for receive and send buffer sizes.

  • tcp_nodelay (Boolean) (defaults to: true)

    Whether to disable Nagle’s algorithm.

  • tcp_maxrt (Integer) (defaults to: 10)

    Maximum retransmission time.

Raises:

  • (StandardError)

    If socket configuration fails.



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'documented/common/socketconfigurator.rb', line 104

def self.configure(sock,
                   keepalive: { enable: true, idle: 120, interval: 30 },
                   linger: { enable: true, timeout: 5 },
                   timeout: { recv: 30, send: 30 },
                   buffer_size: { recv: 32768, send: 32768 },
                   tcp_nodelay: true,
                   tcp_maxrt: 10)
  Lich.log("Configuring socket: keepalive=#{keepalive}, linger=#{linger}, timeout=#{timeout}, buffer_size=#{buffer_size}, tcp_nodelay=#{tcp_nodelay}, tcp_maxrt=#{tcp_maxrt}") if ARGV.include?("--debug")

  begin
    if Gem.win_platform?
      configure_windows(sock, keepalive, linger, timeout, buffer_size, tcp_nodelay, tcp_maxrt)
    else
      configure_unix(sock, keepalive, linger, timeout, buffer_size, tcp_nodelay)
    end
    Lich.log("Socket configuration successful") if ARGV.include?("--debug")
  rescue => e
    Lich.log("Socket configuration failed: #{e.class} - #{e.message}\n\t#{e.backtrace.join("\n\t")}") if ARGV.include?("--debug")
    raise
  end
end

.configure_unix(sock, keepalive, linger, timeout, buffer_size, tcp_nodelay) ⇒ void

Note:

This method is specific to Unix systems.

This method returns an undefined value.

Configures socket options for Unix-based systems.

Parameters:

  • sock (Socket)

    The socket to configure.

  • keepalive (Hash)

    Options for TCP keep-alive settings.

  • linger (Hash)

    Options for socket linger settings.

  • timeout (Hash)

    Options for receive and send timeouts.

  • buffer_size (Hash)

    Options for receive and send buffer sizes.

  • tcp_nodelay (Boolean)

    Whether to disable Nagle’s algorithm.

Raises:

  • (StandardError)

    If socket configuration fails.



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'documented/common/socketconfigurator.rb', line 137

def self.configure_unix(sock, keepalive, linger, timeout, buffer_size, tcp_nodelay)
  # Helper: error-checked setsockopt
  check_setsockopt = lambda do |level, option, value|
    begin
      sock.setsockopt(level, option, value)
      Lich.log("Unix setsockopt succeeded: level=#{level}, option=#{option}") if ARGV.include?("--debug")
    rescue => e
      Lich.log("Unix setsockopt failed: level=#{level}, option=#{option}, error=#{e.message}") if ARGV.include?("--debug")
      raise
    end
  end

  # Keepalive
  if keepalive[:enable]
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, [1].pack('i'))
    if Socket.const_defined?(:TCP_KEEPIDLE)
      check_setsockopt.call(Socket::IPPROTO_TCP, Socket::TCP_KEEPIDLE, [keepalive[:idle]].pack('i'))
    elsif Socket.const_defined?(:TCP_KEEPALIVE)
      check_setsockopt.call(Socket::IPPROTO_TCP, Socket::TCP_KEEPALIVE, [keepalive[:idle]].pack('i'))
    end
    check_setsockopt.call(Socket::IPPROTO_TCP, Socket::TCP_KEEPINTVL, [keepalive[:interval]].pack('i')) if Socket.const_defined?(:TCP_KEEPINTVL)
    check_setsockopt.call(Socket::IPPROTO_TCP, Socket::TCP_KEEPCNT, [5].pack('i')) if Socket.const_defined?(:TCP_KEEPCNT)
  end

  # Linger
  if linger
    linger_struct = [linger[:enable] ? 1 : 0, linger[:timeout]].pack("ii")
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_LINGER, linger_struct)
  end

  # Timeouts
  if timeout
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, [timeout[:recv], 0].pack("l!l!"))
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, [timeout[:send], 0].pack("l!l!"))
  end

  # Buffer sizes
  if buffer_size
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_RCVBUF, [buffer_size[:recv]].pack('i')) if buffer_size[:recv]
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_SNDBUF, [buffer_size[:send]].pack('i')) if buffer_size[:send]
  end

  # TCP_NODELAY
  check_setsockopt.call(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, [1].pack('i')) if tcp_nodelay

  # TCP_USER_TIMEOUT (Linux only - how long to retry before giving up)
  if Socket.const_defined?(:TCP_USER_TIMEOUT)
    user_timeout_ms = 120000 # 120 seconds
    check_setsockopt.call(Socket::IPPROTO_TCP, Socket::TCP_USER_TIMEOUT, [user_timeout_ms].pack('i'))
  end
rescue => e
  Lich.log("Unix socket configuration error: #{e.class} - #{e.message}") if ARGV.include?("--debug")
  raise
end

.configure_windows(sock, keepalive, linger, timeout, buffer_size, tcp_nodelay, tcp_maxrt) ⇒ void

Note:

This method is specific to Windows systems.

This method returns an undefined value.

Configures socket options for Windows systems.

Parameters:

  • sock (Socket)

    The socket to configure.

  • keepalive (Hash)

    Options for TCP keep-alive settings.

  • linger (Hash)

    Options for socket linger settings.

  • timeout (Hash)

    Options for receive and send timeouts.

  • buffer_size (Hash)

    Options for receive and send buffer sizes.

  • tcp_nodelay (Boolean)

    Whether to disable Nagle’s algorithm.

  • tcp_maxrt (Integer)

    Maximum retransmission time.

Raises:

  • (StandardError)

    If socket configuration fails.



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'documented/common/socketconfigurator.rb', line 205

def self.configure_windows(sock, keepalive, linger, timeout, buffer_size, tcp_nodelay, tcp_maxrt)
  # Helper: error-checked setsockopt using Ruby's Socket API
  check_setsockopt = lambda do |level, option, value|
    begin
      sock.setsockopt(level, option, value)
      Lich.log("Windows setsockopt succeeded: level=#{level}, option=#{option}") if ARGV.include?("--debug")
    rescue => e
      Lich.log("Windows setsockopt failed: level=#{level}, option=#{option}, error=#{e.class}: #{e.message}") if ARGV.include?("--debug")
      raise SystemCallError.new("setsockopt(level=#{level}, option=#{option})", 0)
    end
  end

  # Keepalive - Step 1: Enable SO_KEEPALIVE using Ruby's API
  if keepalive[:enable]
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, [1].pack('i'))

    # Step 2: Try to configure keep-alive parameters via WSAIoctl
    # This may fail on Ruby 3.x, so we'll catch and log but continue
    begin
      crt_fd = sock.fileno
      fd = WinFFI._get_osfhandle(crt_fd)

      if fd != -1
        ka = WinFFI::TcpKeepalive.new
        ka[:onoff] = 1
        ka[:keepalivetime] = keepalive[:idle] * 1000
        ka[:keepaliveinterval] = keepalive[:interval] * 1000
        bytes_returned = FFI::MemoryPointer.new(:ulong)

        ret = WinFFI.WSAIoctl(fd, WinFFI::SIO_KEEPALIVE_VALS, ka.to_ptr, ka.size,
                              nil, 0, bytes_returned, nil, nil)
        if ret == 0
          Lich.log("WSAIoctl keepalive configuration succeeded") if ARGV.include?("--debug")
        else
          errno = FFI.errno
          Lich.log("WSAIoctl keepalive failed (errno=#{errno}), using default Windows keepalive settings") if ARGV.include?("--debug")
        end
      else
        Lich.log("Could not get OS handle for WSAIoctl, using default Windows keepalive settings") if ARGV.include?("--debug")
      end
    rescue => e
      Lich.log("WSAIoctl keepalive configuration failed: #{e.class} - #{e.message}") if ARGV.include?("--debug")
      Lich.log("Continuing with basic keepalive enabled (default Windows settings)") if ARGV.include?("--debug")
    end
  end

  # Linger - using Ruby's Socket API
  if linger
    linger_bytes = [linger[:enable] ? 1 : 0, linger[:timeout]].pack('SS')
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_LINGER, linger_bytes)
  end

  # Timeouts - using Ruby's Socket API
  if timeout
    # Windows expects timeout in milliseconds as a DWORD (4 bytes)
    recv_timeout_ms = timeout[:recv] * 1000
    send_timeout_ms = timeout[:send] * 1000
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, [recv_timeout_ms].pack('L'))
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, [send_timeout_ms].pack('L'))
  end

  # Buffer sizes - using Ruby's Socket API
  if buffer_size
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_RCVBUF, [buffer_size[:recv]].pack('i')) if buffer_size[:recv]
    check_setsockopt.call(Socket::SOL_SOCKET, Socket::SO_SNDBUF, [buffer_size[:send]].pack('i')) if buffer_size[:send]
  end

  # TCP_NODELAY - using Ruby's Socket API
  if tcp_nodelay
    check_setsockopt.call(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, [1].pack('i'))
  end

  # TCP_MAXRT - Windows-specific, may not be supported
  if tcp_maxrt
    begin
      # Try using Ruby's API first
      if defined?(Socket::TCP_MAXRT)
        check_setsockopt.call(Socket::IPPROTO_TCP, Socket::TCP_MAXRT, [tcp_maxrt].pack('i'))
      else
        Lich.log("TCP_MAXRT constant not available in Ruby's Socket API") if ARGV.include?("--debug")
      end
    rescue => e
      Lich.log("TCP_MAXRT not supported on this Windows version: #{e.message}") if ARGV.include?("--debug")
    end
  end

  Lich.log("Windows socket configuration completed successfully") if ARGV.include?("--debug")
rescue => e
  Lich.log("Windows socket configuration error: #{e.class} - #{e.message}") if ARGV.include?("--debug")
  raise
end