Class: LibTLS::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/libtls/client.rb

Overview

end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(configure:) {|self| ... } ⇒ Client

Construct a new [Client] instance

Once constructed, it runs the block. When the block finishes, it calls #finish.

Parameters:

  • configure (Hash)

    a mapping from setting name to value. The setting name is any of LibTLS::Config::VALID_SET_CONFIGS; the value is either a scalar value passed through to the C function, or an array of values. For example:

    { ca_file: 'ca.pem', key_mem: [key_ptr, 48] }
    

Yield Parameters:

  • self (Client)

    an initialized and configured instance of self

Raises:



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/libtls/client.rb', line 51

def initialize(configure:, &block)
  if LibTLS::Raw.tls_init < 0
    raise LibTLS::UnknownCError, "tls_init"
  end

  @config = Config.new(configure)

  if (@ctx = LibTLS::Raw.tls_client).null?
    raise LibTLS::UnknownCError, "tls_client"
  end

  if LibTLS::Raw::tls_configure(ctx, @config.as_raw) < 0
    raise LibTLS::CError, "tls_configure: #{LibTLS::Raw.tls_error(ctx)}"
  end

  if block
    begin
      block.call(self)
    ensure
      self.finish
    end
  end
end

Instance Attribute Details

#ctxObject (readonly)

The FFI wrapper around the struct tls object

This is only useful for calling any of the Raw methods.



35
36
37
# File 'lib/libtls/client.rb', line 35

def ctx
  @ctx
end

Instance Method Details

#connect(hostname, port) {|client| ... } ⇒ Object

Open a connection with the server

This method negotiates the TLS connection with the hostname, at the port. Once connected, it passes the connected client to the block. Once the block finishes, it calls OpenedClient#close on the connection.

Parameters:

  • hostname (String)

    the server to connect to, as an IPv4 address, an IPv6 address, or anything that can be resolved by getaddrinfo.

  • port (#to_s)

    the port on the server to connect to

Yield Parameters:

Returns:

  • the result of the block

Raises:



88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/libtls/client.rb', line 88

def connect(hostname, port, &block)
  opened_client = nil

  begin
    if LibTLS::Raw.tls_connect(ctx, hostname, port.to_s) < 0
      raise LibTLS::CError, "tls_connect: #{LibTLS::Raw.tls_error(ctx)}"
    end

    opened_client = OpenedClient.new(ctx)
    block.call(opened_client)
  ensure
    opened_client && opened_client.close
  end
end

#finishObject

Release any memory held on to by the C library

This method must be called either implicitly by passing a block to #initialize, or explicitly by you.



108
109
110
111
# File 'lib/libtls/client.rb', line 108

def finish
  @config.free
  LibTLS::Raw.tls_free(ctx)
end