Class: Minbox::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/minbox/server.rb

Constant Summary collapse

SUBJECT =
'/C=CA/ST=AB/L=Calgary/O=minbox/OU=development/CN=minbox'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host: 'localhost', port: 25, tls: false, logger: Minbox.logger, thread_pool: Concurrent::CachedThreadPool.new) ⇒ Server

Returns a new instance of Server.



8
9
10
11
12
13
14
15
16
# File 'lib/minbox/server.rb', line 8

def initialize(host: 'localhost', port: 25, tls: false, logger: Minbox.logger, thread_pool: Concurrent::CachedThreadPool.new)
  @host = host
  @logger = logger
  @tls = tls
  @key = OpenSSL::PKey::RSA.new(2048)
  logger.debug("Starting server on port #{port}...")
  @server = TCPServer.new(port.to_i)
  @thread_pool = thread_pool
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



6
7
8
# File 'lib/minbox/server.rb', line 6

def host
  @host
end

#keyObject (readonly)

Returns the value of attribute key.



6
7
8
# File 'lib/minbox/server.rb', line 6

def key
  @key
end

#loggerObject (readonly)

Returns the value of attribute logger.



6
7
8
# File 'lib/minbox/server.rb', line 6

def logger
  @logger
end

#serverObject (readonly)

Returns the value of attribute server.



6
7
8
# File 'lib/minbox/server.rb', line 6

def server
  @server
end

Instance Method Details

#handle(socket, &block) ⇒ Object



33
34
35
36
37
38
# File 'lib/minbox/server.rb', line 33

def handle(socket, &block)
  @thread_pool.post do
    logger.debug("client connected: #{socket.inspect}")
    Client.new(self, socket, logger).handle(&block)
  end
end

#listen!(&block) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/minbox/server.rb', line 22

def listen!(&block)
  @server = upgrade(@server) if tls?
  logger.debug('Server started!')

  loop do
    handle(server.accept, &block)
  rescue StandardError => error
    logger.error(error)
  end
end

#shutdown!Object



40
41
42
# File 'lib/minbox/server.rb', line 40

def shutdown!
  server&.close
end

#ssl_contextObject



44
45
46
47
48
49
50
51
52
53
# File 'lib/minbox/server.rb', line 44

def ssl_context
  @ssl_context ||=
    begin
      ssl_context = OpenSSL::SSL::SSLContext.new
      ssl_context.cert = certificate_for(key)
      ssl_context.key = key
      ssl_context.ssl_version = :TLSv1_2
      ssl_context
    end
end

#tls?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/minbox/server.rb', line 18

def tls?
  @tls
end