Class: Micetrap::Services::Base
- Inherits:
-
Object
- Object
- Micetrap::Services::Base
- Defined in:
- lib/micetrap/services/base.rb
Defined Under Namespace
Classes: ClientQuitError
Instance Attribute Summary collapse
-
#logger ⇒ Object
readonly
Returns the value of attribute logger.
Instance Method Summary collapse
- #fire(port = nil) ⇒ Object
-
#initialize ⇒ Base
constructor
A new instance of Base.
- #listen(server) ⇒ Object
- #read_from(socket) ⇒ Object
Constructor Details
Instance Attribute Details
#logger ⇒ Object (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. "#{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. "Responded misleadingly: let's drive those hackers nuts!" s.close Kernel.exit(0) end end rescue ClientQuitError logger. "#{name}:#{port} disconnected" ensure s.close # close socket on error end end |