Example #1
0
    def run(self):
        try:
            self.lock.acquire()
            while not self.shouldStop:
                self.lock.release()
                recvable, sendable, errored = self.samSockManager.select(
                    self.connsWithRecvInterest, self.connsWithSendInterest, self.allConns, timeout=1
                )
                self.lock.acquire()

                for connId in errored:
                    # conn failed, close it
                    self._failedConn(connId, "connection failed")

                for connId in sendable:
                    if connId in self.conns:
                        # connected
                        connSet = self.conns[connId]
                        torrentInfo = self.torrents[connSet["torrentIdent"]]
                        connSet["sock"].send(Messages.generateHandshake(torrentInfo["infohash"], self.peerId))
                        self.connsWithSendInterest.remove(connId)
                        self.connsWithRecvInterest.add(connId)

                for connId in recvable:
                    if connId in self.conns:
                        # received data
                        self._recvFromConn(connId)

            self.thread = None
            self.log.info("Stopping")
            self.lock.release()
        except:
            self.log.error("Error in main loop:\n%s", logTraceback())
Example #2
0
 def _gotShortHandshake(self, connId, connSet):
     success = False
     data = ''.join(connSet['inBuffer'])
     connSet['inBuffer'] = [data]
     
     #decode handshake
     length, proto, reserved, infohash = Messages.decodeShortHandshake(data)
     
     if not proto.lower()=='bittorrent protocol':
         #invalid handshake, close conn
         self._closeConn(connId, 'received invalid handshake')
         
     elif not infohash in self.torrents:
         #invalid handshake, close conn
         self._closeConn(connId, 'received handshake with unknown infohash')
         
     else:
         #valid handshake
         connSet['torrentIdent'] = self.torrents[infohash]
         if self.peerPool.establishedConnection(connSet['torrentIdent'], connSet['sock'].getpeername()):
             #no connection to this address exists up to now
             success = True
             connSet['added'] = True
             self.log.info("Conn %d: Got valid handshake, sending response", connId)
             connSet['sock'].send(Messages.generateHandshake(infohash, self.peerId))
             
         else:
             #we already have a connection to this address
             self._closeConn(connId, 'we already have a connection to this address')
     
     return success