Example #1
0
    def setup(self, sock, HOST, port, streamNumber,
              someObjectsOfWhichThisRemoteNodeIsAlreadyAware,
              selfInitiatedConnections, sendDataThreadQueue,
              objectHashHolderInstance):

        self.sock = sock
        self.peer = state.Peer(HOST, port)
        self.name = "receiveData-" + self.peer.host.replace(
            ":", ".")  # ":" log parser field separator
        self.streamNumber = state.streamsInWhichIAmParticipating
        self.remoteStreams = []
        self.selfInitiatedConnections = selfInitiatedConnections
        self.sendDataThreadQueue = sendDataThreadQueue  # used to send commands and data to the sendDataThread
        self.hostIdent = self.peer.port if ".onion" in BMConfigParser().get(
            'bitmessagesettings', 'onionhostname') and protocol.checkSocksIP(
                self.peer.host) else self.peer.host
        shared.connectedHostsList[
            self.
            hostIdent] = 0  # The very fact that this receiveData thread exists shows that we are connected to the remote host. Let's add it to this list so that an outgoingSynSender thread doesn't try to connect to it.
        self.connectionIsOrWasFullyEstablished = False  # set to true after the remote node and I accept each other's version messages. This is needed to allow the user interface to accurately reflect the current number of connections.
        self.services = 0
        if streamNumber == -1:  # This was an incoming connection. Send out a version message if we accept the other node's version message.
            self.initiatedConnection = False
        else:
            self.initiatedConnection = True
            for stream in self.streamNumber:
                self.selfInitiatedConnections[stream][self] = 0
        self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware
        self.objectHashHolderInstance = objectHashHolderInstance
        self.startTime = time.time()
Example #2
0
 def __init__(self, address=None, sock=None):
     BMProto.__init__(self, address=address, sock=sock)
     self.verackReceived = False
     self.verackSent = False
     self.streams = [0]
     self.fullyEstablished = False
     self.connectedAt = 0
     self.skipUntil = 0
     if address is None and sock is not None:
         self.destination = Peer(*sock.getpeername())
         self.isOutbound = False
         TLSDispatcher.__init__(self, sock, server_side=True)
         self.connectedAt = time.time()
         logger.debug(
             'Received connection from %s:%i',
             self.destination.host, self.destination.port)
         self.nodeid = randomBytes(8)
     elif address is not None and sock is not None:
         TLSDispatcher.__init__(self, sock, server_side=False)
         self.isOutbound = True
         logger.debug(
             'Outbound proxy connection to %s:%i',
             self.destination.host, self.destination.port)
     else:
         self.destination = address
         self.isOutbound = True
         self.create_socket(
             socket.AF_INET6 if ":" in address.host else socket.AF_INET,
             socket.SOCK_STREAM)
         self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         TLSDispatcher.__init__(self, sock, server_side=False)
         self.connect(self.destination)
         logger.debug(
             'Connecting to %s:%i',
             self.destination.host, self.destination.port)
     try:
         self.local = (
             protocol.checkIPAddress(
                 protocol.encodeHost(self.destination.host), True)
             and not protocol.checkSocksIP(self.destination.host)
         )
     except socket.error:
         # it's probably a hostname
         pass
     self.network_group = protocol.network_group(self.destination.host)
     ObjectTracker.__init__(self)  # pylint: disable=non-parent-init-called
     self.bm_proto_reset()
     self.set_state("bm_header", expectBytes=protocol.Header.size)
Example #3
0
    def peerValidityChecks(self):
        if self.remoteProtocolVersion < 3:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your is using an old protocol. Closing connection."))
            logger.debug ('Closing connection to old protocol version %s, node: %s',
                str(self.remoteProtocolVersion), str(self.destination))
            return False
        if self.timeOffset > BMProto.maxTimeOffset:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your time is too far in the future compared to mine. Closing connection."))
            logger.info("%s's time is too far in the future (%s seconds). Closing connection to it.",
                self.destination, self.timeOffset)
            shared.timeOffsetWrongCount += 1
            return False
        elif self.timeOffset < -BMProto.maxTimeOffset:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your time is too far in the past compared to mine. Closing connection."))
            logger.info("%s's time is too far in the past (timeOffset %s seconds). Closing connection to it.",
                self.destination, self.timeOffset)
            shared.timeOffsetWrongCount += 1
            return False
        else:
            shared.timeOffsetWrongCount = 0
        if not self.streams:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="We don't have shared stream interests. Closing connection."))
            logger.debug ('Closed connection to %s because there is no overlapping interest in streams.',
                str(self.destination))
            return False
        if self.destination in network.connectionpool.BMConnectionPool().inboundConnections:
            try:
                if not protocol.checkSocksIP(self.destination.host):
                    self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                        errorText="Too many connections from your IP. Closing connection."))
                    logger.debug ('Closed connection to %s because we are already connected to that IP.',
                        str(self.destination))
                    return False
            except:
                pass
        if network.connectionpool.BMConnectionPool().isAlreadyConnected(self.nonce):
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="I'm connected to myself. Closing connection."))
            logger.debug ("Closed connection to %s because I'm connected to myself.",
                str(self.destination))
            return False

        return True
Example #4
0
    def peerValidityChecks(self):
        if self.remoteProtocolVersion < 3:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your is using an old protocol. Closing connection."))
            logger.debug ('Closing connection to old protocol version %s, node: %s',
                str(self.remoteProtocolVersion), str(self.destination))
            return False
        if self.timeOffset > BMProto.maxTimeOffset:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your time is too far in the future compared to mine. Closing connection."))
            logger.info("%s's time is too far in the future (%s seconds). Closing connection to it.",
                self.destination, self.timeOffset)
            shared.timeOffsetWrongCount += 1
            return False
        elif self.timeOffset < -BMProto.maxTimeOffset:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your time is too far in the past compared to mine. Closing connection."))
            logger.info("%s's time is too far in the past (timeOffset %s seconds). Closing connection to it.",
                self.destination, self.timeOffset)
            shared.timeOffsetWrongCount += 1
            return False
        else:
            shared.timeOffsetWrongCount = 0
        if not self.streams:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="We don't have shared stream interests. Closing connection."))
            logger.debug ('Closed connection to %s because there is no overlapping interest in streams.',
                str(self.destination))
            return False
        if self.destination in network.connectionpool.BMConnectionPool().inboundConnections:
            try:
                if not protocol.checkSocksIP(self.destination.host):
                    self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                        errorText="Too many connections from your IP. Closing connection."))
                    logger.debug ('Closed connection to %s because we are already connected to that IP.',
                        str(self.destination))
                    return False
            except:
                pass
        if network.connectionpool.BMConnectionPool().isAlreadyConnected(self.nonce):
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="I'm connected to myself. Closing connection."))
            logger.debug ("Closed connection to %s because I'm connected to myself.",
                str(self.destination))
            return False

        return True
Example #5
0
 def __init__(self, address=None, sock=None):
     BMProto.__init__(self, address=address, sock=sock)
     self.verackReceived = False
     self.verackSent = False
     self.streams = [0]
     self.fullyEstablished = False
     self.connectedAt = 0
     self.skipUntil = 0
     if address is None and sock is not None:
         self.destination = state.Peer(sock.getpeername()[0],
                                       sock.getpeername()[1])
         self.isOutbound = False
         TLSDispatcher.__init__(self, sock, server_side=True)
         self.connectedAt = time.time()
         logger.debug("Received connection from %s:%i",
                      self.destination.host, self.destination.port)
         self.nodeid = randomBytes(8)
     elif address is not None and sock is not None:
         TLSDispatcher.__init__(self, sock, server_side=False)
         self.isOutbound = True
         logger.debug("Outbound proxy connection to %s:%i",
                      self.destination.host, self.destination.port)
     else:
         self.destination = address
         self.isOutbound = True
         if ":" in address.host:
             self.create_socket(socket.AF_INET6, socket.SOCK_STREAM)
         else:
             self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
         self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         TLSDispatcher.__init__(self, sock, server_side=False)
         self.connect(self.destination)
         logger.debug("Connecting to %s:%i", self.destination.host,
                      self.destination.port)
     encodedAddr = protocol.encodeHost(self.destination.host)
     if protocol.checkIPAddress(
             encodedAddr,
             True) and not protocol.checkSocksIP(self.destination.host):
         self.local = True
     else:
         self.local = False
     #shared.connectedHostsList[self.destination] = 0
     ObjectTracker.__init__(self)
     UISignalQueue.put(('updateNetworkStatusTab', 'no data'))
     self.bm_proto_reset()
     self.set_state("bm_header", expectBytes=protocol.Header.size)
Example #6
0
 def __init__(self, address=None, sock=None):
     BMProto.__init__(self, address=address, sock=sock)
     self.verackReceived = False
     self.verackSent = False
     self.streams = [0]
     self.fullyEstablished = False
     self.connectedAt = 0
     self.skipUntil = 0
     if address is None and sock is not None:
         self.destination = state.Peer(sock.getpeername()[0], sock.getpeername()[1])
         self.isOutbound = False
         TLSDispatcher.__init__(self, sock, server_side=True)
         self.connectedAt = time.time()
         logger.debug("Received connection from %s:%i", self.destination.host, self.destination.port)
         self.nodeid = randomBytes(8)
     elif address is not None and sock is not None:
         TLSDispatcher.__init__(self, sock, server_side=False)
         self.isOutbound = True
         logger.debug("Outbound proxy connection to %s:%i", self.destination.host, self.destination.port)
     else:
         self.destination = address
         self.isOutbound = True
         if ":" in address.host:
             self.create_socket(socket.AF_INET6, socket.SOCK_STREAM)
         else:
             self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
         self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         TLSDispatcher.__init__(self, sock, server_side=False)
         self.connect(self.destination)
         logger.debug("Connecting to %s:%i", self.destination.host, self.destination.port)
     encodedAddr = protocol.encodeHost(self.destination.host)
     if protocol.checkIPAddress(encodedAddr, True) and not protocol.checkSocksIP(self.destination.host):
         self.local = True
     else:
         self.local = False
     #shared.connectedHostsList[self.destination] = 0
     ObjectTracker.__init__(self)
     self.bm_proto_reset()
     self.set_state("bm_header", expectBytes=protocol.Header.size)
    def run(self):
        # If there is a trusted peer then we don't want to accept
        # incoming connections so we'll just abandon the thread
        if state.trustedPeer:
            return

        while BMConfigParser().safeGetBoolean(
                'bitmessagesettings', 'dontconnect') and state.shutdown == 0:
            self.stop.wait(1)
        helper_bootstrap.dns()
        # We typically don't want to accept incoming connections if the user is using a
        # SOCKS proxy, unless they have configured otherwise. If they eventually select
        # proxy 'none' or configure SOCKS listening then this will start listening for
        # connections. But if on SOCKS and have an onionhostname, listen
        # (socket is then only opened for localhost)
        while BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and \
            (not BMConfigParser().getboolean('bitmessagesettings', 'sockslisten') and \
            ".onion" not in BMConfigParser().get('bitmessagesettings', 'onionhostname')) and \
            state.shutdown == 0:
            self.stop.wait(5)

        logger.info('Listening for incoming connections.')

        # First try listening on an IPv6 socket. This should also be
        # able to accept connections on IPv4. If that's not available
        # we'll fall back to IPv4-only.
        try:
            sock = self._createListenSocket(socket.AF_INET6)
        except socket.error as e:
            if (isinstance(e.args, tuple) and e.args[0]
                    in (errno.EAFNOSUPPORT, errno.EPFNOSUPPORT,
                        errno.EADDRNOTAVAIL, errno.ENOPROTOOPT, errno.EINVAL)):
                sock = self._createListenSocket(socket.AF_INET)
            else:
                raise

        # regexp to match an IPv4-mapped IPv6 address
        mappedAddressRegexp = re.compile(
            r'^::ffff:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$')

        while state.shutdown == 0:
            # We typically don't want to accept incoming connections if the user is using a
            # SOCKS proxy, unless they have configured otherwise. If they eventually select
            # proxy 'none' or configure SOCKS listening then this will start listening for
            # connections.
            while BMConfigParser().get(
                    'bitmessagesettings', 'socksproxytype'
            )[0:5] == 'SOCKS' and not BMConfigParser().getboolean(
                    'bitmessagesettings',
                    'sockslisten') and ".onion" not in BMConfigParser().get(
                        'bitmessagesettings',
                        'onionhostname') and state.shutdown == 0:
                self.stop.wait(10)
            while len(shared.connectedHostsList) > \
                BMConfigParser().safeGetInt("bitmessagesettings", "maxtotalconnections", 200) + \
                BMConfigParser().safeGetInt("bitmessagesettings", "maxbootstrapconnections", 20) \
                and state.shutdown == 0:
                logger.info(
                    'We are connected to too many people. Not accepting further incoming connections for ten seconds.'
                )

                self.stop.wait(10)

            while state.shutdown == 0:
                try:
                    socketObject, sockaddr = sock.accept()
                except socket.error as e:
                    if isinstance(e.args, tuple) and \
                        e.args[0] in (errno.EINTR,):
                        continue
                    time.wait(1)
                    continue

                (HOST, PORT) = sockaddr[0:2]

                # If the address is an IPv4-mapped IPv6 address then
                # convert it to just the IPv4 representation
                md = mappedAddressRegexp.match(HOST)
                if md != None:
                    HOST = md.group(1)

                # The following code will, unfortunately, block an
                # incoming connection if someone else on the same LAN
                # is already connected because the two computers will
                # share the same external IP. This is here to prevent
                # connection flooding.
                # permit repeated connections from Tor
                if HOST in shared.connectedHostsList and \
                    (".onion" not in BMConfigParser().get('bitmessagesettings', 'onionhostname') or not protocol.checkSocksIP(HOST)):
                    socketObject.close()
                    logger.info('We are already connected to ' + str(HOST) +
                                '. Ignoring connection.')
                else:
                    break

            sendDataThreadQueue = Queue.Queue(
            )  # Used to submit information to the send data thread for this connection.
            socketObject.settimeout(20)

            sd = sendDataThread(sendDataThreadQueue)
            sd.setup(socketObject, HOST, PORT, -1)
            sd.start()

            rd = receiveDataThread()
            rd.daemon = True  # close the main program even if there are threads left
            rd.setup(socketObject, HOST, PORT, -1,
                     self.selfInitiatedConnections, sendDataThreadQueue,
                     sd.objectHashHolderInstance)
            rd.start()

            logger.info('connected to ' + HOST + ' during INCOMING request.')
Example #8
0
    def peerValidityChecks(self):
        if self.remoteProtocolVersion < 3:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your is using an old protocol. Closing connection."))
            logger.debug ('Closing connection to old protocol version %s, node: %s',
                str(self.remoteProtocolVersion), str(self.destination))
            return False
        if self.timeOffset > BMProto.maxTimeOffset:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your time is too far in the future compared to mine. Closing connection."))
            logger.info("%s's time is too far in the future (%s seconds). Closing connection to it.",
                self.destination, self.timeOffset)
            shared.timeOffsetWrongCount += 1
            return False
        elif self.timeOffset < -BMProto.maxTimeOffset:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="Your time is too far in the past compared to mine. Closing connection."))
            logger.info("%s's time is too far in the past (timeOffset %s seconds). Closing connection to it.",
                self.destination, self.timeOffset)
            shared.timeOffsetWrongCount += 1
            return False
        else:
            shared.timeOffsetWrongCount = 0
        if not self.streams:
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="We don't have shared stream interests. Closing connection."))
            logger.debug ('Closed connection to %s because there is no overlapping interest in streams.',
                str(self.destination))
            return False
        if self.destination in network.connectionpool.BMConnectionPool().inboundConnections:
            try:
                if not protocol.checkSocksIP(self.destination.host):
                    self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                        errorText="Too many connections from your IP. Closing connection."))
                    logger.debug ('Closed connection to %s because we are already connected to that IP.',
                        str(self.destination))
                    return False
            except:
                pass
        if not self.isOutbound:
            # incoming from a peer we're connected to as outbound, or server full
            # report the same error to counter deanonymisation
            if state.Peer(self.destination.host, self.peerNode.port) in \
                network.connectionpool.BMConnectionPool().inboundConnections or \
                len(network.connectionpool.BMConnectionPool().inboundConnections) + \
                len(network.connectionpool.BMConnectionPool().outboundConnections) > \
                BMConfigParser().safeGetInt("bitmessagesettings", "maxtotalconnections") + \
                BMConfigParser().safeGetInt("bitmessagesettings", "maxbootstrapconnections"):
                self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                    errorText="Server full, please try again later."))
                logger.debug ("Closed connection to %s due to server full or duplicate inbound/outbound.",
                    str(self.destination))
                return False
        if network.connectionpool.BMConnectionPool().isAlreadyConnected(self.nonce):
            self.append_write_buf(protocol.assembleErrorMessage(fatal=2,
                errorText="I'm connected to myself. Closing connection."))
            logger.debug ("Closed connection to %s because I'm connected to myself.",
                str(self.destination))
            return False

        return True
    def run(self):
        # If there is a trusted peer then we don't want to accept
        # incoming connections so we'll just abandon the thread
        if state.trustedPeer:
            return

        while BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect') and state.shutdown == 0:
            self.stop.wait(1)
        helper_bootstrap.dns()
        # We typically don't want to accept incoming connections if the user is using a
        # SOCKS proxy, unless they have configured otherwise. If they eventually select
        # proxy 'none' or configure SOCKS listening then this will start listening for
        # connections. But if on SOCKS and have an onionhostname, listen
        # (socket is then only opened for localhost)
        while BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and \
            (not BMConfigParser().getboolean('bitmessagesettings', 'sockslisten') and \
            ".onion" not in BMConfigParser().get('bitmessagesettings', 'onionhostname')) and \
            state.shutdown == 0:
            self.stop.wait(5)

        logger.info('Listening for incoming connections.')

        # First try listening on an IPv6 socket. This should also be
        # able to accept connections on IPv4. If that's not available
        # we'll fall back to IPv4-only.
        try:
            sock = self._createListenSocket(socket.AF_INET6)
        except socket.error as e:
            if (isinstance(e.args, tuple) and
                e.args[0] in (errno.EAFNOSUPPORT,
                              errno.EPFNOSUPPORT,
                              errno.EADDRNOTAVAIL,
                              errno.ENOPROTOOPT,
                              errno.EINVAL)):
                sock = self._createListenSocket(socket.AF_INET)
            else:
                raise

        # regexp to match an IPv4-mapped IPv6 address
        mappedAddressRegexp = re.compile(r'^::ffff:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$')

        while state.shutdown == 0:
            # We typically don't want to accept incoming connections if the user is using a
            # SOCKS proxy, unless they have configured otherwise. If they eventually select
            # proxy 'none' or configure SOCKS listening then this will start listening for
            # connections.
            while BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and not BMConfigParser().getboolean('bitmessagesettings', 'sockslisten') and ".onion" not in BMConfigParser().get('bitmessagesettings', 'onionhostname') and state.shutdown == 0:
                self.stop.wait(10)
            while len(shared.connectedHostsList) > \
                BMConfigParser().safeGetInt("bitmessagesettings", "maxtotalconnections", 200) + \
                BMConfigParser().safeGetInt("bitmessagesettings", "maxbootstrapconnections", 20) \
                and state.shutdown == 0:
                logger.info('We are connected to too many people. Not accepting further incoming connections for ten seconds.')

                self.stop.wait(10)

            while state.shutdown == 0:
                try:
                    socketObject, sockaddr = sock.accept()
                except socket.error as e:
                    if isinstance(e.args, tuple) and \
                        e.args[0] in (errno.EINTR,):
                        continue
                    time.wait(1)
                    continue

                (HOST, PORT) = sockaddr[0:2]

                # If the address is an IPv4-mapped IPv6 address then
                # convert it to just the IPv4 representation
                md = mappedAddressRegexp.match(HOST)
                if md != None:
                    HOST = md.group(1)

                # The following code will, unfortunately, block an
                # incoming connection if someone else on the same LAN
                # is already connected because the two computers will
                # share the same external IP. This is here to prevent
                # connection flooding.
                # permit repeated connections from Tor
                if HOST in shared.connectedHostsList and \
                    (".onion" not in BMConfigParser().get('bitmessagesettings', 'onionhostname') or not protocol.checkSocksIP(HOST)):
                    socketObject.close()
                    logger.info('We are already connected to ' + str(HOST) + '. Ignoring connection.')
                else:
                    break

            sendDataThreadQueue = Queue.Queue() # Used to submit information to the send data thread for this connection.
            socketObject.settimeout(20)

            sd = sendDataThread(sendDataThreadQueue)
            sd.setup(
                socketObject, HOST, PORT, -1)
            sd.start()

            rd = receiveDataThread()
            rd.daemon = True  # close the main program even if there are threads left
            rd.setup(
                socketObject, HOST, PORT, -1, self.selfInitiatedConnections, sendDataThreadQueue, sd.objectHashHolderInstance)
            rd.start()

            logger.info('connected to ' + HOST + ' during INCOMING request.')
 def setup(
     self,
     sock,
     HOST,
     port,
     streamNumber,
     selfInitiatedConnections,
     sendDataThreadQueue,
     objectHashHolderInstance):
     
     self.sock = sock
     self.peer = state.Peer(HOST, port)
     self.name = "receiveData-" + self.peer.host.replace(":", ".") # ":" log parser field separator
     self.streamNumber = state.streamsInWhichIAmParticipating
     self.remoteStreams = []
     self.selfInitiatedConnections = selfInitiatedConnections
     self.sendDataThreadQueue = sendDataThreadQueue # used to send commands and data to the sendDataThread
     self.hostIdent = self.peer.port if ".onion" in BMConfigParser().get('bitmessagesettings', 'onionhostname') and protocol.checkSocksIP(self.peer.host) else self.peer.host
     shared.connectedHostsList[
         self.hostIdent] = 0  # The very fact that this receiveData thread exists shows that we are connected to the remote host. Let's add it to this list so that an outgoingSynSender thread doesn't try to connect to it.
     self.connectionIsOrWasFullyEstablished = False  # set to true after the remote node and I accept each other's version messages. This is needed to allow the user interface to accurately reflect the current number of connections.
     self.services = 0
     if streamNumber == -1:  # This was an incoming connection. Send out a version message if we accept the other node's version message.
         self.initiatedConnection = False
     else:
         self.initiatedConnection = True
         for stream in self.streamNumber:
             self.selfInitiatedConnections[stream][self] = 0
     self.objectHashHolderInstance = objectHashHolderInstance
     self.downloadQueue = PendingDownloadQueue()
     self.startTime = time.time()
Example #11
0
    def peerValidityChecks(self):
        """Check the validity of the peer"""
        if self.remoteProtocolVersion < 3:
            self.append_write_buf(
                protocol.assembleErrorMessage(
                    errorText=
                    "Your is using an old protocol. Closing connection.",
                    fatal=2))
            logger.debug(
                'Closing connection to old protocol version %s, node: %s',
                self.remoteProtocolVersion, self.destination)
            return False
        if self.timeOffset > MAX_TIME_OFFSET:
            self.append_write_buf(
                protocol.assembleErrorMessage(
                    errorText="Your time is too far in the future"
                    " compared to mine. Closing connection.",
                    fatal=2))
            logger.info(
                "%s's time is too far in the future (%s seconds)."
                " Closing connection to it.", self.destination,
                self.timeOffset)
            BMProto.timeOffsetWrongCount += 1
            return False
        elif self.timeOffset < -MAX_TIME_OFFSET:
            self.append_write_buf(
                protocol.assembleErrorMessage(
                    errorText=
                    "Your time is too far in the past compared to mine."
                    " Closing connection.",
                    fatal=2))
            logger.info(
                "%s's time is too far in the past (timeOffset %s seconds)."
                " Closing connection to it.", self.destination,
                self.timeOffset)
            BMProto.timeOffsetWrongCount += 1
            return False
        else:
            BMProto.timeOffsetWrongCount = 0
        if not self.streams:
            self.append_write_buf(
                protocol.assembleErrorMessage(
                    errorText="We don't have shared stream interests."
                    " Closing connection.",
                    fatal=2))
            logger.debug(
                'Closed connection to %s because there is no overlapping'
                ' interest in streams.', self.destination)
            return False
        if self.destination in connectionpool.BMConnectionPool(
        ).inboundConnections:
            try:
                if not protocol.checkSocksIP(self.destination.host):
                    self.append_write_buf(
                        protocol.assembleErrorMessage(
                            errorText="Too many connections from your IP."
                            " Closing connection.",
                            fatal=2))
                    logger.debug(
                        'Closed connection to %s because we are already'
                        ' connected to that IP.', self.destination)
                    return False
            except Exception:
                pass
        if not self.isOutbound:
            # incoming from a peer we're connected to as outbound,
            # or server full report the same error to counter deanonymisation
            if (Peer(self.destination.host, self.peerNode.port)
                    in connectionpool.BMConnectionPool().inboundConnections
                    or len(connectionpool.BMConnectionPool()) >
                    BMConfigParser().safeGetInt('bitmessagesettings',
                                                'maxtotalconnections') +
                    BMConfigParser().safeGetInt('bitmessagesettings',
                                                'maxbootstrapconnections')):
                self.append_write_buf(
                    protocol.assembleErrorMessage(
                        errorText="Server full, please try again later.",
                        fatal=2))
                logger.debug(
                    'Closed connection to %s due to server full'
                    ' or duplicate inbound/outbound.', self.destination)
                return False
        if connectionpool.BMConnectionPool().isAlreadyConnected(self.nonce):
            self.append_write_buf(
                protocol.assembleErrorMessage(
                    errorText="I'm connected to myself. Closing connection.",
                    fatal=2))
            logger.debug(
                "Closed connection to %s because I'm connected to myself.",
                self.destination)
            return False

        return True