Class: Ftpd::ConnectionTracker

Inherits:
Object
  • Object
show all
Includes:
GetsPeerAddress
Defined in:
lib/ftpd/connection_tracker.rb

Overview

This class keeps track of connections

Instance Method Summary collapse

Methods included from GetsPeerAddress

#peer_ip

Constructor Details

#initializeConnectionTracker

Returns a new instance of ConnectionTracker.



13
14
15
16
17
# File 'lib/ftpd/connection_tracker.rb', line 13

def initialize
  @mutex = Mutex.new
  @connections = {}
  @socket_ips ={}
end

Instance Method Details

#connectionsObject

Return the total number of connections



21
22
23
24
25
# File 'lib/ftpd/connection_tracker.rb', line 21

def connections
  @mutex.synchronize do
    @connections.values.inject(0, &:+)
  end
end

#connections_for(socket) ⇒ Object

Return the number of connections for a socket’s peer IP



29
30
31
32
33
34
# File 'lib/ftpd/connection_tracker.rb', line 29

def connections_for(socket)
  @mutex.synchronize do
    ip = peer_ip(socket)
    @connections[ip] || 0
  end
end

#known_ip_countObject

Return the number of known IPs. This exists for the benefit of the test, so that it can know the tracker has properly forgotten about an IP with no connections.



76
77
78
79
80
# File 'lib/ftpd/connection_tracker.rb', line 76

def known_ip_count
  @mutex.synchronize do
    @connections.size
  end
end

#start_track(socket) ⇒ Object

Start tracking a connection



50
51
52
53
54
55
56
57
58
# File 'lib/ftpd/connection_tracker.rb', line 50

def start_track(socket)
  @mutex.synchronize do
    ip = peer_ip(socket)
    @connections[ip] ||= 0
    @connections[ip] += 1
    @socket_ips[socket.object_id] = ip
  end
rescue Errno::ENOTCONN
end

#stop_track(socket) ⇒ Object

Stop tracking a connection



62
63
64
65
66
67
68
69
70
# File 'lib/ftpd/connection_tracker.rb', line 62

def stop_track(socket)
  @mutex.synchronize do
    ip = @socket_ips.delete(socket.object_id)
    break unless ip
    if (@connections[ip] -= 1) == 0
      @connections.delete(ip)
    end
  end
end

#track(socket) ⇒ Object

Track a connection. Yields to a block; the connection is tracked until the block returns.



39
40
41
42
43
44
45
46
# File 'lib/ftpd/connection_tracker.rb', line 39

def track(socket)
  start_track socket
  begin
    yield
  ensure
    stop_track socket
  end
end