Class: Micetrap::Services::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/micetrap/services/base.rb

Direct Known Subclasses

Ftp, Http, Mysql, Samba, Torrent

Defined Under Namespace

Classes: ClientQuitError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBase

Returns a new instance of Base.



9
10
11
# File 'lib/micetrap/services/base.rb', line 9

def initialize
  @logger = Logger.new self.name.downcase.to_sym
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



7
8
9
# File 'lib/micetrap/services/base.rb', line 7

def logger
  @logger
end

Instance Method Details

#fire(port = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/micetrap/services/base.rb', line 13

def fire port = nil
  port = port ? port.to_i : default_ports.sample
  begin
    server = TCPServer.open(port || 0)
  rescue Errno::EACCES
    puts "Looks like you are trying to use a system port, for which you need root privileges.\nRun micetrap with another port if you don't want to sudo!\n"
    exit(1)
  end
  @port = server.addr[1]
  @addrs = server.addr[2..-1].uniq

  logger.log_message "#{name} trap listening on #{@addrs.collect{|a|"#{a}:#{port}"}.join(' ')}"
  listen(server)
end

#listen(server) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/micetrap/services/base.rb', line 28

def listen(server)
  # Handle Ctrl-C to exit!
  interrupted = false
  trap("INT") do
    puts "Gracefully exiting...";
    interrupted = true;
    Kernel.exit(0)
  end

  while not interrupted do
    socket = server.accept
    Thread.start do
      read_from(socket)
    end
  end
end

#read_from(socket) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/micetrap/services/base.rb', line 45

def read_from(socket)
  s = socket

  port = s.peeraddr[1]
  name = s.peeraddr[2]
  addr = s.peeraddr[3]

  begin
    while line = s.gets # read a line at a time
      raise ClientQuitError if line =~ /^die\r?$/

      logger.log_probe line, name, port

      if line.strip == ""
        s.write response
        logger.log_message "Responded misleadingly: let's drive those hackers nuts!"
        s.close
        Kernel.exit(0)
      end
    end
  rescue ClientQuitError
    logger.log_message "#{name}:#{port} disconnected"
  ensure
    s.close # close socket on error
  end
end