Class: Ban::Server

Inherits:
Object
  • Object
show all
Includes:
EventEmitter
Defined in:
lib/ban/server.rb

Instance Method Summary collapse

Constructor Details

#initialize(user, group, chroot) ⇒ Server

Returns a new instance of Server.



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

def initialize(user, group, chroot)
  @clients = []
  @user, @group, @chroot = user, group, chroot
end

Instance Method Details

#broadcast(event) ⇒ Object



10
11
12
13
14
# File 'lib/ban/server.rb', line 10

def broadcast(event)
  @clients.each do |client|
    client.send({ event.name => event.to_hash }.to_json)
  end
end

#drop_priviledges!Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ban/server.rb', line 42

def drop_priviledges!
  Ban::Logger.info "Switching to #{@user}:#{@group} into #{@chroot}"
  uid = Etc.getpwnam(@user).uid
  gid = Etc.getgrnam(@group).gid
  Dir.chdir(@chroot)
  Dir.chroot(@chroot)
  Process::Sys.setgid(gid)
  Process::Sys.setuid(uid)
rescue => ex
  Ban::Logger.warn "Dropping the priviledges didn't work: #{ex}"
end

#start(interface, port) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ban/server.rb', line 16

def start(interface, port)
  @server = EM::WebSocket.run(host: interface, port: port) do |ws|
    ws.onopen do |handshake|
      Ban::Logger.debug "WebSocket connection open"
      @clients << ws
    end

    ws.onclose do
      Ban::Logger.debug "WebSocket connection closed"
      @clients.delete(ws)
    end

    ws.onmessage do |command_json|
      begin
        command = JSON.parse(command_json)
        emit :command, command
      rescue JSON::ParserError
        Ban::Logger.warn "Received invalid json: #{command_json}"
      end
    end
  end

  # server port has been started
  drop_priviledges!
end