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.



11
12
13
14
15
# File 'lib/ftpd/connection_tracker.rb', line 11

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

Instance Method Details

#connectionsObject

Return the total number of connections



19
20
21
22
23
# File 'lib/ftpd/connection_tracker.rb', line 19

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



27
28
29
30
31
32
# File 'lib/ftpd/connection_tracker.rb', line 27

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.



72
73
74
75
76
# File 'lib/ftpd/connection_tracker.rb', line 72

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

#start_track(socket) ⇒ Object

Start tracking a connection



48
49
50
51
52
53
54
55
# File 'lib/ftpd/connection_tracker.rb', line 48

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

#stop_track(socket) ⇒ Object

Stop tracking a connection



59
60
61
62
63
64
65
66
# File 'lib/ftpd/connection_tracker.rb', line 59

def stop_track(socket)
  @mutex.synchronize do
    ip = @socket_ips.delete(socket.object_id)
    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.



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

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