Parcourir la source

Start on the CellRelay connection and cell command manager

Ian Goldberg il y a 4 ans
Parent
commit
605a64b05b
1 fichiers modifiés avec 40 ajouts et 1 suppressions
  1. 40 1
      relay.py

+ 40 - 1
relay.py

@@ -52,6 +52,34 @@ class MultiplexedCircuitConnection(network.Connection):
         print("received", msg, "on circuit", circid, "from", peer)
 
 
+class CellRelay:
+    """The class that manages the connections to other relays and
+    clients.  Relays and clients both use this class to both create
+    on-demand connections to relays, to gracefully handle the closing of
+    connections, and to handle commands received over the
+    connections."""
+
+    def __init__(self, myaddr):
+        # A dictionary of MultiplexedCircuitConnections to other hosts,
+        # indexed by NetAddr
+        self.connections = dict()
+        self.myaddr = myaddr
+
+    def get_connection_to(self, addr):
+        """Get the MultiplexedCircuitConnection connected to the given
+        NetAddr, creating one if none exists right now."""
+        if addr in self.connections:
+            return self.connections[addr]
+
+        # Create the new connection
+        newconn = network.thenetwork.connect(self.myaddr, addr)
+        self.connections[addr] = newconn
+        newconn.closer = lambda: self.connections.pop(addr)
+        newconn.cellrelay = self
+
+        return newconn
+
+
 class Relay(network.Server):
     """The class representing an onion relay."""
 
@@ -75,6 +103,9 @@ class Relay(network.Server):
         network.thenetwork.wantepochticks(self, True, end=True)
         network.thenetwork.wantepochticks(self, True)
 
+        # Create the CellRelay connection manager
+        self.cellrelay = CellRelay(self.netaddr)
+
         self.uploaddesc()
 
     def epoch_ending(self, epoch):
@@ -150,6 +181,14 @@ if __name__ == '__main__':
 
     print('ticked; epoch=', network.thenetwork.getepoch())
 
-    c = network.thenetwork.connect(relays[3].netaddr,relays[3].consensus.consdict['relays'][5].descdict['addr'])
+    c = relays[3].cellrelay.get_connection_to(relays[3].consensus.consdict['relays'][5].descdict['addr'])
 
     c.send_cell(1, network.StringNetMsg("test"))
+    c.close()
+    c2 = relays[3].cellrelay.get_connection_to(relays[3].consensus.consdict['relays'][6].descdict['addr'])
+    c = relays[3].cellrelay.get_connection_to(relays[3].consensus.consdict['relays'][5].descdict['addr'])
+    c.send_cell(2, network.StringNetMsg("cell"))
+    c3 = relays[3].cellrelay.get_connection_to(relays[3].consensus.consdict['relays'][1].descdict['addr'])
+    c = relays[3].cellrelay.get_connection_to(relays[3].consensus.consdict['relays'][5].descdict['addr'])
+    c.send_cell(3, network.StringNetMsg("again"))
+    c.close()