Esempio n. 1
0
def loadKnownNodes():
    try:
        # We shouldn't have to use the knownnodes.knownNodesLock because this had
        # better be the only thread accessing knownNodes right now.
        pickleFile = open(state.appdata + 'knownnodes.dat', 'rb')
        loadedKnownNodes = pickle.load(pickleFile)
        pickleFile.close()
        # The old format of storing knownNodes was as a 'host: (port, time)'
        # mapping. The new format is as 'Peer: time' pairs. If we loaded
        # data in the old format, transform it to the new style.
        for stream, nodes in loadedKnownNodes.items():
            knownNodes[stream] = {}
            for node_tuple in nodes.items():
                try:
                    host, (port, lastseen) = node_tuple
                    peer = state.Peer(host, port)
                except:
                    peer, lastseen = node_tuple
                knownNodes[stream][peer] = lastseen
    except:
        createDefaultKnownNodes(state.appdata)
    # your own onion address, if setup
    if BMConfigParser().has_option(
            'bitmessagesettings',
            'onionhostname') and ".onion" in BMConfigParser().get(
                'bitmessagesettings', 'onionhostname'):
        knownNodes[1][state.Peer(
            BMConfigParser().get('bitmessagesettings', 'onionhostname'),
            BMConfigParser().getint('bitmessagesettings',
                                    'onionport'))] = int(time.time())
    if BMConfigParser().getint('bitmessagesettings', 'settingsversion') > 10:
        logger.error(
            'Bitmessage cannot read future versions of the keys file (keys.dat). Run the newer version of Bitmessage.'
        )
        raise SystemExit
Esempio n. 2
0
 def __init__(self, host=None, sock=None, announcing=False):
     super(BMProto, self).__init__(sock=sock)
     self.verackReceived = True
     self.verackSent = True
     # TODO sort out streams
     self.streams = [1]
     self.fullyEstablished = True
     self.connectedAt = 0
     self.skipUntil = 0
     if sock is None:
         if host is None:
             host = ''
         if ":" in host:
             self.create_socket(socket.AF_INET6, socket.SOCK_DGRAM)
         else:
             self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
         self.set_socket_reuse()
         logger.info("Binding UDP socket to %s:%i", host, UDPSocket.port)
         self.socket.bind((host, UDPSocket.port))
         #BINDTODEVICE is only available on linux and requires root
         #try:
             #print "binding to %s" % (host)
             #self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, host)
         #except AttributeError:
     else:
         self.socket = sock
         self.set_socket_reuse()
     self.listening = state.Peer(self.socket.getsockname()[0], self.socket.getsockname()[1])
     self.destination = state.Peer(self.socket.getsockname()[0], self.socket.getsockname()[1])
     ObjectTracker.__init__(self)
     self.connecting = False
     self.connected = True
     self.announcing = announcing
     self.set_state("bm_header", expectBytes=protocol.Header.size)
Esempio n. 3
0
 def __init__(self, host=None, sock=None, announcing=False):
     super(BMProto, self).__init__(sock=sock)
     self.verackReceived = True
     self.verackSent = True
     # TODO sort out streams
     self.streams = [1]
     self.fullyEstablished = True
     self.connectedAt = 0
     self.skipUntil = 0
     if sock is None:
         if host is None:
             host = ''
         self.create_socket(
             socket.AF_INET6 if ":" in host else socket.AF_INET,
             socket.SOCK_DGRAM)
         self.set_socket_reuse()
         logger.info("Binding UDP socket to %s:%i", host, self.port)
         self.socket.bind((host, self.port))
     else:
         self.socket = sock
         self.set_socket_reuse()
     self.listening = state.Peer(*self.socket.getsockname())
     self.destination = state.Peer(*self.socket.getsockname())
     ObjectTracker.__init__(self)
     self.connecting = False
     self.connected = True
     self.announcing = announcing
     self.set_state("bm_header", expectBytes=protocol.Header.size)
Esempio n. 4
0
 def bm_command_addr(self):
     #        BMProto.bm_command_object(self)
     addresses = self._decode_addr()
     # only allow peer discovery from private IPs in order to avoid attacks from random IPs on the internet
     if not self.local:
         return True
     remoteport = False
     for i in addresses:
         seenTime, stream, services, ip, port = i
         decodedIP = protocol.checkIPAddress(ip)
         if stream not in state.streamsInWhichIAmParticipating:
             continue
         if seenTime < time.time(
         ) - BMProto.maxTimeOffset or seenTime > time.time(
         ) + BMProto.maxTimeOffset:
             continue
         if decodedIP is False:
             # if the address isn't local, interpret it as the hosts' own announcement
             remoteport = port
     if remoteport is False:
         return True
     logger.debug("received peer discovery from %s:%i (port %i):",
                  self.destination.host, self.destination.port, remoteport)
     if self.local:
         state.discoveredPeers[state.Peer(self.destination.host,
                                          remoteport)] = time.time()
     return True
 def __init__(self, sendDataThreadQueue, sock, HOST, PORT, streamNumber):
     threading.Thread.__init__(self, name="sendData")
     self.sendDataThreadQueue = sendDataThreadQueue
     state.sendDataQueues.append(self.sendDataThreadQueue)
     self.data = ''
     self.objectHashHolderInstance = objectHashHolder(
         self.sendDataThreadQueue)
     self.objectHashHolderInstance.daemon = True
     self.objectHashHolderInstance.start()
     self.connectionIsOrWasFullyEstablished = False
     self.sock = sock
     self.peer = state.Peer(HOST, PORT)
     self.name = "sendData-" + self.peer.host.replace(
         ":", ".")  # log parser field separator
     self.streamNumber = []
     self.services = 0
     self.buffer = ""
     self.initiatedConnection = False
     self.remoteProtocolVersion = - \
         1  # This must be set using setRemoteProtocolVersion command which is sent through the self.sendDataThreadQueue queue.
     self.lastTimeISentData = int(
         time.time()
     )  # If this value increases beyond five minutes ago, we'll send a pong message to keep the connection alive.
     if streamNumber == -1:  # This was an incoming connection.
         self.initiatedConnection = False
     else:
         self.initiatedConnection = True
Esempio n. 6
0
    def __init__(self, sock, HOST, port, streamNumber, sendDataThreadQueue, objectHashHolderInstance):
        threading.Thread.__init__(self, name="receiveData")
        self.data = ''
        self.verackSent = False
        self.verackReceived = False
        self.addrReceived = False

        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.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:
                shared.selfInitiatedConnections.setdefault(stream, {})[self] = 0
        self.objectHashHolderInstance = objectHashHolderInstance
        self.downloadQueue = PendingDownloadQueue()
        self.startTime = time.time()
Esempio n. 7
0
 def bm_command_addr(self):
     addresses = self._decode_addr()
     for i in addresses:
         seenTime, stream, services, ip, port = i
         decodedIP = protocol.checkIPAddress(str(ip))
         if stream not in state.streamsInWhichIAmParticipating:
             continue
         if decodedIP is not False and seenTime > time.time(
         ) - BMProto.addressAlive:
             peer = state.Peer(decodedIP, port)
             try:
                 if knownnodes.knownNodes[stream][peer][
                         "lastseen"] > seenTime:
                     continue
             except KeyError:
                 pass
             if len(knownnodes.knownNodes[stream]) < int(
                     BMConfigParser().get("knownnodes", "maxnodes")):
                 with knownnodes.knownNodesLock:
                     try:
                         knownnodes.knownNodes[stream][peer][
                             "lastseen"] = seenTime
                     except (TypeError, KeyError):
                         knownnodes.knownNodes[stream][peer] = {
                             "lastseen": seenTime,
                             "rating": 0,
                             "self": False,
                         }
             addrQueue.put((stream, peer, self.destination))
     return True
Esempio n. 8
0
def readKnownNodes():
    try:
        with open(state.appdata + 'knownnodes.dat', 'rb') as source:
            with knownNodesLock:
                try:
                    json_deserialize_knownnodes(source)
                except ValueError:
                    source.seek(0)
                    pickle_deserialize_old_knownnodes(source)
    except (IOError, OSError, KeyError, EOFError):
        logger.debug('Failed to read nodes from knownnodes.dat', exc_info=True)
        createDefaultKnownNodes()

    config = BMConfigParser()
    # if config.safeGetInt('lmessagesettings', 'settingsversion') > 10:
    #     sys.exit(
    #         'LMessage cannot read future versions of the keys file'
    #         ' (keys.dat). Run the newer version of LMessage.')

    # your own onion address, if setup
    onionhostname = config.safeGet('lmessagesettings', 'onionhostname')
    if onionhostname and ".onion" in onionhostname:
        onionport = config.safeGetInt('lmessagesettings', 'onionport')
        if onionport:
            addKnownNode(1, state.Peer(onionhostname, onionport), is_self=True)
Esempio n. 9
0
def knownNodes():
    try:
        with open(state.appdata + 'knownnodes.dat', 'rb') as pickleFile:
            with knownnodes.knownNodesLock:
                knownnodes.knownNodes = pickle.load(pickleFile)
            # the old format was {Peer:lastseen, ...}
            # the new format is {Peer:{"lastseen":i, "rating":f}}
            for stream in knownnodes.knownNodes.keys():
                for node, params in knownnodes.knownNodes[stream].items():
                    if isinstance(params, (float, int)):
                        addKnownNode(stream, node, params)
    except:
        knownnodes.knownNodes = defaultKnownNodes.createDefaultKnownNodes(
            state.appdata)
    # your own onion address, if setup
    if BMConfigParser().has_option(
            'bitmessagesettings',
            'onionhostname') and ".onion" in BMConfigParser().get(
                'bitmessagesettings', 'onionhostname'):
        addKnownNode(1,
                     state.Peer(
                         BMConfigParser().get('bitmessagesettings',
                                              'onionhostname'),
                         BMConfigParser().getint('bitmessagesettings',
                                                 'onionport')),
                     self=True)
    if BMConfigParser().getint('bitmessagesettings', 'settingsversion') > 10:
        logger.error(
            'Bitmessage cannot read future versions of the keys file (keys.dat). Run the newer version of Bitmessage.'
        )
        raise SystemExit
Esempio n. 10
0
 def try_add_known_node(stream, addr, port, method=''):
     try:
         socket.inet_aton(addr)
     except (TypeError, socket.error):
         return
     logger.info('Adding %s to knownNodes based on %s DNS bootstrap method',
                 addr, method)
     addKnownNode(stream, state.Peer(addr, port))
Esempio n. 11
0
 def __init__(self, host='127.0.0.1', port=8444):
     if not hasattr(self, '_map'):
         AdvancedDispatcher.__init__(self)
     self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.set_reuse_addr()
     self.bind((host, port))
     self.destination = state.Peer(host, port)
     self.listen(5)
Esempio n. 12
0
def json_deserialize_knownnodes(source):
    """
    Read JSON from source and make knownnodes dict
    """
    for node in json.load(source):
        peer = node['peer']
        peer['host'] = str(peer['host'])
        knownNodes[node['stream']][state.Peer(**peer)] = node['info']
Esempio n. 13
0
def _loadTrustedPeer():
    try:
        trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer')
    except ConfigParser.Error:
        # This probably means the trusted peer wasn't specified so we
        # can just leave it as None
        return

    host, port = trustedPeer.split(':')
    state.trustedPeer = state.Peer(host, int(port))
Esempio n. 14
0
 def announceSelf(self):
     for connection in BMConnectionPool().udpSockets.values():
         if not connection.announcing:
             continue
         for stream in state.streamsInWhichIAmParticipating:
             addr = (stream,
                     state.Peer(
                         '127.0.0.1',
                         BMConfigParser().safeGetInt(
                             "lmessagesettings", "port")), time.time())
             connection.append_write_buf(BMProto.assembleAddr([addr]))
Esempio n. 15
0
def _loadTrustedPeer():
    try:
        trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer')
    except ConfigParser.Error:
        # This probably means the trusted peer wasn't specified so we
        # can just leave it as None
        return
    try:
        host, port = trustedPeer.split(':')
    except ValueError:
        sys.exit('Bad trustedpeer config setting! It should be set as'
                 ' trustedpeer=<hostname>:<portnumber>')
    state.trustedPeer = state.Peer(host, int(port))
def json_deserialize_knownnodes(source):
    """
    Read JSON from source and make knownnodes dict
    """
    global knownNodesActual  # pylint: disable=global-statement
    for node in json.load(source):
        peer = node['peer']
        info = node['info']
        peer = state.Peer(str(peer['host']), peer.get('port', 8444))
        knownNodes[node['stream']][peer] = info

        if (not (knownNodesActual or info.get('is_self'))
                and peer not in DEFAULT_NODES
                and peer not in DEFAULT_NODES_ONION):
            knownNodesActual = True
Esempio n. 17
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)
Esempio n. 18
0
 def handle_accept(self):
     pair = self.accept()
     if pair is not None:
         sock, addr = pair
         state.ownAddresses[state.Peer(sock.getsockname()[0],
                                       sock.getsockname()[1])] = True
         if len(network.connectionpool.BMConnectionPool().inboundConnections) + \
             len(network.connectionpool.BMConnectionPool().outboundConnections) > \
             BMConfigParser().safeGetInt("bitmessagesettings", "maxtotalconnections") + \
             BMConfigParser().safeGetInt("bitmessagesettings", "maxbootstrapconnections"):
             sock.close()
             return
         try:
             network.connectionpool.BMConnectionPool().addConnection(
                 TCPConnection(sock=sock))
         except socket.error:
             pass
 def _getPeer(self):
     # If the user has specified a trusted peer then we'll only
     # ever connect to that. Otherwise we'll pick a random one from
     # the known nodes
     if state.trustedPeer:
         with knownnodes.knownNodesLock:
             peer = state.trustedPeer
             knownnodes.knownNodes[self.streamNumber][peer] = time.time()
     else:
         while not self._stopped:
             try:
                 with knownnodes.knownNodesLock:
                     peer, = random.sample(
                         knownnodes.knownNodes[self.streamNumber], 1)
                     priority = (
                         183600 -
                         (time.time() -
                          knownnodes.knownNodes[self.streamNumber][peer])
                     ) / 183600  # 2 days and 3 hours
             except ValueError:  # no known nodes
                 self.stop.wait(1)
                 continue
             if BMConfigParser().get('bitmessagesettings',
                                     'socksproxytype') != 'none':
                 if peer.host.find(".onion") == -1:
                     priority /= 10  # hidden services have 10x priority over plain net
                 else:
                     # don't connect to self
                     if peer.host == BMConfigParser().get(
                             'bitmessagesettings', 'onionhostname'
                     ) and peer.port == BMConfigParser().getint(
                             "bitmessagesettings", "onionport"):
                         continue
             elif peer.host.find(
                     ".onion") != -1:  # onion address and so proxy
                 continue
             if priority <= 0.001:  # everyone has at least this much priority
                 priority = 0.001
             if (random.random() <= priority):
                 break
             self.stop.wait(
                 0.01)  # prevent CPU hogging if something is broken
     try:
         return peer
     except NameError:
         return state.Peer('127.0.0.1', 8444)
Esempio n. 20
0
    def handle_read(self):
        try:
            (recdata, addr) = self.socket.recvfrom(AdvancedDispatcher._buf_len)
        except socket.error as e:
            logger.error("socket error: %s", str(e))
            return

        self.destination = state.Peer(addr[0], addr[1])
        encodedAddr = protocol.encodeHost(addr[0])
        # if protocol.checkIPAddress(encodedAddr, True):
        #     self.local = True
        # else:
        #     self.local = False
        # overwrite the old buffer to avoid mixing data and so that self.local works correctly
        self.read_buf[0:] = recdata
        self.bm_proto_reset()
        receiveDataQueue.put(self.listening)
Esempio n. 21
0
def createDefaultKnownNodes(appdata):
    stream1 = {}

    stream1[state.Peer('5.45.99.75', 8444)] = int(time.time())
    stream1[state.Peer('75.167.159.54', 8444)] = int(time.time())
    stream1[state.Peer('95.165.168.168', 8444)] = int(time.time())
    stream1[state.Peer('85.180.139.241', 8444)] = int(time.time())
    stream1[state.Peer('158.222.217.190', 8080)] = int(time.time())
    stream1[state.Peer('178.62.12.187', 8448)] = int(time.time())
    stream1[state.Peer('24.188.198.204', 8111)] = int(time.time())
    stream1[state.Peer('109.147.204.113', 1195)] = int(time.time())
    stream1[state.Peer('178.11.46.221', 8444)] = int(time.time())

    stream2 = {}

    stream3 = {}

    knownNodes[1] = stream1
    knownNodes[2] = stream2
    knownNodes[3] = stream3

    with open(appdata + 'knownnodes.dat', 'wb') as output:
        pickle.dump(knownNodes, output)
Esempio n. 22
0
 def setup(self, sock, HOST, PORT, streamNumber):
     self.sock = sock
     self.peer = state.Peer(HOST, PORT)
     self.name = "sendData-" + self.peer.host.replace(
         ":", ".")  # log parser field separator
     self.streamNumber = []
     self.services = 0
     self.buffer = ""
     self.initiatedConnection = False
     self.remoteProtocolVersion = - \
         1  # This must be set using setRemoteProtocolVersion command which is sent through the self.sendDataThreadQueue queue.
     self.lastTimeISentData = int(
         time.time()
     )  # If this value increases beyond five minutes ago, we'll send a pong message to keep the connection alive.
     if streamNumber == -1:  # This was an incoming connection.
         self.initiatedConnection = False
     else:
         self.initiatedConnection = True
Esempio n. 23
0
    def processonion(data):
        """Process onionpeer object"""
        readPosition = 20  # bypass the nonce, time, and object type
        length = decodeVarint(data[readPosition:readPosition + 10])[1]
        readPosition += length
        stream, length = decodeVarint(data[readPosition:readPosition + 10])
        readPosition += length
        # it seems that stream is checked in network.bmproto
        port, length = decodeVarint(data[readPosition:readPosition + 10])
        host = protocol.checkIPAddress(data[readPosition + length:])

        if not host:
            return
        peer = state.Peer(host, port)
        with knownnodes.knownNodesLock:
            knownnodes.addKnownNode(stream,
                                    peer,
                                    is_self=state.ownAddresses.get(peer))
Esempio n. 24
0
 def handle_accept(self):
     pair = self.accept()
     if pair is not None:
         sock, addr = pair
         state.ownAddresses[state.Peer(sock.getsockname()[0], sock.getsockname()[1])] = True
         if len(network.connectionpool.BMConnectionPool().inboundConnections) + \
             len(network.connectionpool.BMConnectionPool().outboundConnections) > \
             BMConfigParser().safeGetInt("bitmessagesettings", "maxtotalconnections") + \
             BMConfigParser().safeGetInt("bitmessagesettings", "maxbootstrapconnections") + 10:
             # 10 is a sort of buffer, in between it will go through the version handshake
             # and return an error to the peer
             logger.warning("Server full, dropping connection")
             sock.close()
             return
         try:
             network.connectionpool.BMConnectionPool().addConnection(TCPConnection(sock=sock))
         except socket.error:
             pass
Esempio n. 25
0
def pickle_knownnodes():
    now = time.time()
    with open(knownnodes_file, 'wb') as dst:
        pickle.dump(
            {
                stream: {
                    state.Peer(
                        '%i.%i.%i.%i' %
                        tuple([random.randint(1, 255)
                               for i in range(4)]), 8444): {
                                   'lastseen': now,
                                   'rating': 0.1
                               }
                    for i in range(1, 4)  # 3 test nodes
                }
                for stream in range(1, 4)  # 3 test streams
            },
            dst)
Esempio n. 26
0
def createDefaultKnownNodes(appdata):
    ############## Stream 1 ################
    stream1 = {}

    #stream1[state.Peer('2604:2000:1380:9f:82e:148b:2746:d0c7', 8080)] = int(time.time())
    stream1[state.Peer('5.45.99.75', 8444)] = int(time.time())
    stream1[state.Peer('75.167.159.54', 8444)] = int(time.time())
    stream1[state.Peer('95.165.168.168', 8444)] = int(time.time())
    stream1[state.Peer('85.180.139.241', 8444)] = int(time.time())
    stream1[state.Peer('158.222.211.81', 8080)] = int(time.time())
    stream1[state.Peer('178.62.12.187', 8448)] = int(time.time())
    stream1[state.Peer('24.188.198.204', 8111)] = int(time.time())
    stream1[state.Peer('109.147.204.113', 1195)] = int(time.time())
    stream1[state.Peer('178.11.46.221', 8444)] = int(time.time())

    ############# Stream 2 #################
    stream2 = {}
    # None yet

    ############# Stream 3 #################
    stream3 = {}
    # None yet

    allKnownNodes = {}
    allKnownNodes[1] = stream1
    allKnownNodes[2] = stream2
    allKnownNodes[3] = stream3

    #print stream1
    #print allKnownNodes

    with open(appdata + 'knownnodes.dat', 'wb') as output:
        # Pickle dictionary using protocol 0.
        pickle.dump(allKnownNodes, output)

    return allKnownNodes
Esempio n. 27
0
 def removeConnection(self, connection):
     if isinstance(connection, UDPSocket):
         del self.udpSockets[connection.listening.host]
     elif isinstance(connection, TCPServer):
         del self.listeningSockets[state.Peer(connection.destination.host, connection.destination.port)]
     elif connection.isOutbound:
         try:
             del self.outboundConnections[connection.destination]
         except KeyError:
             pass
     else:
         try:
             del self.inboundConnections[connection.destination]
         except KeyError:
             try:
                 del self.inboundConnections[connection.destination.host]
             except KeyError:
                 pass
     connection.close()
Esempio n. 28
0
 def __init__(self, host='127.0.0.1', port=8444):
     if not hasattr(self, '_map'):
         AdvancedDispatcher.__init__(self)
     self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.set_reuse_addr()
     for attempt in range(50):
         try:
             if attempt > 0:
                 port = random.randint(32767, 65535)
             self.bind((host, port))
         except socket.error as e:
             if e.errno in (asyncore.EADDRINUSE, asyncore.WSAEADDRINUSE):
                 continue
         else:
             if attempt > 0:
                 BMConfigParser().set("bitmessagesettings", "port", str(port))
                 BMConfigParser().save()
             break
     self.destination = state.Peer(host, port)
     self.bound = True
     self.listen(5)
def readKnownNodes():
    try:
        with open(state.appdata + 'knownnodes.dat', 'rb') as source:
            with knownNodesLock:
                try:
                    json_deserialize_knownnodes(source)
                except ValueError:
                    source.seek(0)
                    pickle_deserialize_old_knownnodes(source)
    except (IOError, OSError, KeyError, EOFError):
        logger.debug('Failed to read nodes from knownnodes.dat', exc_info=True)
        createDefaultKnownNodes()

    config = BMConfigParser()

    # your own onion address, if setup
    onionhostname = config.safeGet('bitmessagesettings', 'onionhostname')
    if onionhostname and ".onion" in onionhostname:
        onionport = config.safeGetInt('bitmessagesettings', 'onionport')
        if onionport:
            self_peer = state.Peer(onionhostname, onionport)
            addKnownNode(1, self_peer, is_self=True)
            state.ownAddresses[self_peer] = True
Esempio n. 30
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