Class: Tojour::Sock

Inherits:
Object
  • Object
show all
Defined in:
lib/tojour/sock.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Sock

Returns a new instance of Sock.



11
12
13
14
15
16
# File 'lib/tojour/sock.rb', line 11

def initialize(options)
  @options = options
  @key_path = @options[:key_path]
  @crt_path = @options[:crt_path]
  @port = @options[:port]
end

Instance Attribute Details

#crt_pathObject

Returns the value of attribute crt_path.



9
10
11
# File 'lib/tojour/sock.rb', line 9

def crt_path
  @crt_path
end

#key_pathObject

Returns the value of attribute key_path.



9
10
11
# File 'lib/tojour/sock.rb', line 9

def key_path
  @key_path
end

#optionsObject

Returns the value of attribute options.



9
10
11
# File 'lib/tojour/sock.rb', line 9

def options
  @options
end

#portObject

Returns the value of attribute port.



9
10
11
# File 'lib/tojour/sock.rb', line 9

def port
  @port
end

Instance Method Details

#client(host, port, &block) ⇒ Object



23
24
25
# File 'lib/tojour/sock.rb', line 23

def client(host, port, &block)
  block.call(ssl_client)
end

#server(&block) ⇒ Object



18
19
20
21
# File 'lib/tojour/sock.rb', line 18

def server(&block)
  Utils.log("Listening on port #{@port}.")
  block.call(ssl_server)
end

#ssl_clientObject



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/tojour/sock.rb', line 35

def ssl_client
  socket = TCPSocket.new(host, port)
  expected_cert = OpenSSL::X509::Certificate.new(File.open(@crt_path))
  ssl_client = OpenSSL::SSL::SSLSocket.new(socket)
  ssl_client.sync_close = true
  ssl_client.connect
  if ssl_client.peer_cert.to_s != expected_cert.to_s
    $stderr.puts 'Unexpected certificate.'
    exit(1)
  end
end

#ssl_serverObject



27
28
29
30
31
32
33
# File 'lib/tojour/sock.rb', line 27

def ssl_server
  server = TCPServer.new(@port)
  ssl_context = OpenSSL::SSL::SSLContext.new
  ssl_context.cert = OpenSSL::X509::Certificate.new(File.open(@crt_path))
  ssl_context.key = OpenSSL::PKey::RSA.new(File.open(@key_path))
  OpenSSL::SSL::SSLServer.new(server, ssl_context)
end