Module: ICMP4EM::Proxy::UdpHandler

Defined in:
lib/icmp4em/proxy/udp_handler.rb

Instance Method Summary collapse

Instance Method Details

#initialize(args) ⇒ Object



4
5
6
7
8
9
# File 'lib/icmp4em/proxy/udp_handler.rb', line 4

def initialize args
  @icmp_socket      = args[:icmp_socket]
  @pending_requests = args[:pending_requests]

  log "Listening for incoming requests"
end

#log(msg) ⇒ Object



11
12
13
# File 'lib/icmp4em/proxy/udp_handler.rb', line 11

def log msg
  puts "[#{Time.now}] #{msg}" if $debug
end

#receive_data(data) ⇒ Object



15
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/icmp4em/proxy/udp_handler.rb', line 15

def receive_data data
  source_port, source_ip = Socket.unpack_sockaddr_in(get_peername)

  log "Received incoming request from #{source_ip}:#{source_port}"

  begin
    request = Request.from_bytes :source_ip => source_ip, :source_port => source_port, :data => data
  rescue ArgumentError
    log "  Received error - #{$!}"
    return
  end

  unless request.packet.is_request?
    log "  Incoming packet is not an ICMP request"
    return
  end

  log "  Key = #{request.key_string}"
  log "  Sending to #{request.dest_ip}"

  begin
    request.send :socket => @icmp_socket
  rescue
    log "  Got exception while sending packet #{request.dest_ip} #{$!}"
    return
  end

  request.timeout(30)

  request.callback do |packet|
    log "  Got reply for request #{request.key_string}"
    log "  Sending reply back to #{source_ip}:#{source_port}"
    send_datagram packet.to_bytes, source_ip, source_port
    @pending_requests.delete request.key
  end

  request.errback do
    log "Request #{request.key_string} has timed out"
    @pending_requests.delete request.key
  end

  @pending_requests[request.key] = request
end