Esempio n. 1
0
def connect_to(host, keep_alive=True):
    """
    """
    host = net_misc.normalize_address(host)
    if host in started_connections():
        lg.warn('already connecting to "%s"' % host)
        return False
    for peeraddr, connections in opened_connections().items():
        if peeraddr == host:
            lg.warn('already connected to "%s" with %d connections' %
                    (host, len(connections)))
            return True
        for connection in connections:
            if connection.getConnectionAddress():
                if connection.getConnectionAddress() == host:
                    lg.warn(
                        'already connected to "%s" with peer address: "%s"' %
                        (host, peeraddr))
                    return True
    if _Debug:
        lg.out(_DebugLevel,
               'tcp_node.connect_to "%s", keep_alive=%s' % (host, keep_alive))
    connection = TCPFactory(host, keep_alive=keep_alive)
    started_connections()[host] = connection
    connection.connector = reactor.connectTCP(
        host[0], host[1], connection,
        timeout=_ConnectionTimeout)  # @UndefinedVariable
    return False
Esempio n. 2
0
def send(filename, remoteaddress, description=None, keep_alive=True):
    """
    """
    remoteaddress = net_misc.normalize_address(remoteaddress)
    result_defer = Deferred()
    if remoteaddress in started_connections():
        started_connections()[remoteaddress].add_outbox_file(
            filename, description, result_defer, keep_alive)
        if not keep_alive:
            if _Debug:
                lg.out(
                    _DebugLevel,
                    'tcp_node.send single, use started connection to %s, %d already started and %d opened'
                    % (str(remoteaddress), len(
                        started_connections()), len(opened_connections())))
        return result_defer
    for peeraddr, connections in opened_connections().items():
        for connection in connections:
            if peeraddr == remoteaddress:
                connection.append_outbox_file(filename, description,
                                              result_defer, keep_alive)
                if not keep_alive:
                    if _Debug:
                        lg.out(
                            _DebugLevel,
                            'tcp_node.send single, use opened connection to %s, %d already started and %d opened'
                            % (str(remoteaddress), len(started_connections()),
                               len(opened_connections())))
                return result_defer
            if connection.getConnectionAddress():
                if connection.getConnectionAddress() == remoteaddress:
                    connection.append_outbox_file(filename, description,
                                                  result_defer, keep_alive)
                    if not keep_alive:
                        if _Debug:
                            lg.out(
                                _DebugLevel,
                                'tcp_node.send single, use opened connection to %s, %d already started and %d opened'
                                % (str(remoteaddress),
                                   len(started_connections()),
                                   len(opened_connections())))
                    return result_defer
    if _Debug:
        lg.out(_DebugLevel,
               'tcp_node.send start connecting to "%s"' % str(remoteaddress))
    connection = TCPFactory(remoteaddress, keep_alive=keep_alive)
    started_connections()[remoteaddress] = connection
    connection.add_outbox_file(filename, description, result_defer, keep_alive)
    connection.connector = reactor.connectTCP(remoteaddress[0],
                                              remoteaddress[1],
                                              connection,
                                              timeout=_ConnectionTimeout)
    if not keep_alive:
        if _Debug:
            lg.out(
                _DebugLevel,
                'tcp_node.send opened a single connection to %s, %d already started and %d opened'
                % (str(remoteaddress), len(
                    started_connections()), len(opened_connections())))
    return result_defer
Esempio n. 3
0
def my_host(normalize=False):
    global _MyHost
    if not _MyHost:
        return None
    if normalize:
        return net_misc.normalize_address(_MyHost)
    return _MyHost
Esempio n. 4
0
 def send_file_single(self, remote_idurl, filename, host, description=''):
     """
     """
     return tcp_node.send(filename,
                          net_misc.normalize_address(host),
                          description,
                          keep_alive=False)
Esempio n. 5
0
def SendServers():
    """
    My identity file can be stored in different locations, see the "sources"
    field.

    So I can use different identity servers to store more secure and reliable. This
    method will send my identity file to all my identity servers via
    transport_tcp.
    """
    from transport.tcp import tcp_node
    sendfile, sendfilename = tmpfile.make("propagate")
    os.close(sendfile)
    LocalIdentity = my_id.getLocalIdentity()
    bpio.WriteTextFile(sendfilename, LocalIdentity.serialize(as_text=True))
    dlist = []
    for idurl in LocalIdentity.getSources(as_originals=True):
        # sources for out identity are servers we need to send to
        protocol, host, port, filename = nameurl.UrlParse(idurl)
        # TODO: rebuild identity-server logic to be able to send my identity via HTTP POST instead of TCP and
        # get rid of second TCP port at all 
        webport, tcpport = known_servers.by_host().get(host, (
            # by default use "expected" port numbers
            settings.IdentityWebPort(), settings.IdentityServerPort()))
        normalized_address = net_misc.normalize_address((host, int(tcpport), ))
        dlist.append(tcp_node.send(
            sendfilename, normalized_address, 'Identity', keep_alive=False,
        ))
        if _Debug:
            lg.args(_DebugLevel, normalized_address=normalized_address, filename=filename)
    dl = DeferredList(dlist, consumeErrors=True)
    return dl
Esempio n. 6
0
def main():
    lg.set_debug_level(24)

    if len(sys.argv) >= 4 and sys.argv[1] == 'connect':
        tcp_node.connect_to(
            net_misc.normalize_address((sys.argv[2], int(sys.argv[3]))))
        reactor.run()
        return

    if len(sys.argv) >= 5 and sys.argv[1] == 'send':
        tcp_node.send(
            sys.argv[2],
            net_misc.normalize_address((sys.argv[3], int(sys.argv[4]))))
        reactor.run()
        return

    print('Usage:')
    print('tcp_node.py <command> <arguments>')
    print('')
    print('Commands:')
    print('    connect host port')
    print('    send filename host port')
    print('')
Esempio n. 7
0
def disconnect_from(host):
    """
    """
    host = net_misc.normalize_address(host)
    ok = False
    for peeraddr, connections in opened_connections().items():
        alll = False
        if peeraddr == host:
            alll = True
        for connection in connections:
            if alll:
                connection.automat('disconnect')
                ok = True
                continue
            if connection.getConnectionAddress():
                if connection.getConnectionAddress() == host:
                    connection.automat('disconnect')
                    return True
    return ok
Esempio n. 8
0
 def find_session(self, host=None, idurl=None):
     """
     """
     if idurl:
         for opened_connection in tcp_node.opened_connections().values():
             for channel in opened_connection:
                 if channel.get_idurl() and channel.get_idurl() == idurl:
                     if _Debug:
                         lg.dbg(_DebugLevel,
                                'found active connection for %r' % idurl)
                     return [
                         channel,
                     ]
         return []
     search_for_host = net_misc.normalize_address(host)
     if _Debug:
         lg.dbg(
             _DebugLevel, 'looking for %r, known connections: %r' % (
                 search_for_host,
                 list(tcp_node.opened_connections().keys()),
             ))
     return tcp_node.opened_connections().get(search_for_host, [])
Esempio n. 9
0
def cancel_outbox_file(host, filename):
    """
    """
    host = net_misc.normalize_address(host)
    if _Debug:
        lg.args(_DebugLevel, host=host, filename=filename)
    from transport.tcp import tcp_interface
    for connections in opened_connections().values():
        for connection in connections:
            if connection.peer_address and connection.peer_address == host or \
                    connection.peer_external_address and connection.peer_external_address == host:
                i = 0
                while i < len(connection.outboxQueue):
                    fn, description, result_defer, keep_alive = connection.outboxQueue[
                        i]
                    if fn == filename:
                        connection.outboxQueue.pop(i)
                        connection.failed_outbox_queue_item(
                            fn, description, 'cancelled')
                        continue
                    i += 1
    for connection in started_connections().values():
        if connection.connection_address and connection.connection_address == host:
            i = 0
            while i < len(connection.pendingoutboxfiles):
                fn, description, result_defer, keep_alive = connection.pendingoutboxfiles[
                    i]
                if fn == filename:
                    connection.pendingoutboxfiles.pop(i)
                    try:
                        tcp_interface.interface_cancelled_file_sending(
                            host, filename, 0, description, 'cancelled')
                    except Exception as exc:
                        lg.warn(str(exc))
                    if result_defer:
                        result_defer.callback(
                            (filename, description, 'failed', 'cancelled'))
                    continue
                i += 1
Esempio n. 10
0
def SendServers():
    """
    My identity file can be stored in different locations, see the "sources"
    field.

    So I can use different identity servers to store more secure. This
    method will send my identity file to all my identity servers via
    transport_tcp.
    """
    from transport.tcp import tcp_node
    sendfile, sendfilename = tmpfile.make("propagate")
    os.close(sendfile)
    LocalIdentity = my_id.getLocalIdentity()
    bpio.WriteTextFile(sendfilename, LocalIdentity.serialize())
    dlist = []
    for idurl in LocalIdentity.sources:
        # sources for out identity are servers we need to send to
        protocol, host, port, filename = nameurl.UrlParse(idurl)
        # if host == settings.IdentityServerName():
        #     host = '67.207.147.183'
        webport, tcpport = known_servers.by_host().get(
            host, (settings.IdentityWebPort(), settings.IdentityServerPort()))
        # srvhost = '%s:%d' % (host, int(tcpport))
        dlist.append(
            tcp_node.send(
                sendfilename,
                net_misc.normalize_address((
                    host,
                    int(tcpport),
                )),
                'Identity',
                keep_alive=False,
            ))
        # dlist.append(gateway.send_file_single('tcp', srvhost, sendfilename, 'Identity'))
    dl = DeferredList(dlist, consumeErrors=True)
    return dl
Esempio n. 11
0
 def find_session(self, host):
     """
     """
     return tcp_node.opened_connections().get(
         net_misc.normalize_address(host), [])
Esempio n. 12
0
 def cancel_outbox_file(self, host, filename):
     """
     """
     return tcp_node.cancel_outbox_file(net_misc.normalize_address(host),
                                        filename)
Esempio n. 13
0
 def disconnect_from(self, host):
     """
     """
     return tcp_node.disconnect_from(net_misc.normalize_address(host))
Esempio n. 14
0
 def connect_to(self, host):
     """
     """
     return tcp_node.connect_to(net_misc.normalize_address(host))
Esempio n. 15
0
 def send_keep_alive(self, host):
     """
     """
     return tcp_node.send_keep_alive(net_misc.normalize_address(host))
Esempio n. 16
0
 def getTransportAddress(self):
     peer = self.transport.getPeer()
     return net_misc.normalize_address((
         peer.host,
         int(peer.port),
     ))
Esempio n. 17
0
 def getConnectionAddress(self):
     return net_misc.normalize_address(self.factory.connection_address)
Esempio n. 18
0
 def getAddress(self):
     addr = self.getConnectionAddress()
     if not addr:
         addr = self.getTransportAddress()
     return net_misc.normalize_address(addr)