def doSetUp(self, *args, **kwargs):
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.doSetUp')
     if driver.is_on('service_udp_datagrams'):
         from lib import udp
         udp_port = settings.getUDPPort()
         if not udp.proto(udp_port):
             try:
                 udp.listen(udp_port)
             except:
                 lg.exc()
     if driver.is_on('service_service_entangled_dht'):
         from dht import dht_service
         dht_service.reconnect()
     if driver.is_on('service_ip_port_responder'):
         from stun import stun_server
         udp_port = int(settings.getUDPPort())
         stun_server.A('start', udp_port)
     if driver.is_on('service_my_ip_port'):
         from stun import stun_client
         if not stun_client.A() or stun_client.A().state in ['STOPPED', ]: 
             stun_client.A().dropMyExternalAddress()
             stun_client.A('start')
     if driver.is_on('service_private_messages'):
         from chat import nickname_holder
         nickname_holder.A('set')
     self.automat('network-up')
Beispiel #2
0
def main():
    from twisted.internet import reactor
    lg.set_debug_level(24)
    bpio.init()
    settings.init()
    dht_service.init(settings.getDHTPort())
    dht_service.connect()
    udp.listen(settings.getUDPPort())
    A('start', settings.getUDPPort())
    reactor.run()
Beispiel #3
0
def main():
    from twisted.internet import reactor
    lg.set_debug_level(24)
    bpio.init()
    settings.init()
    dht_service.init(settings.getDHTPort())
    dht_service.connect()
    udp.listen(settings.getUDPPort())
    A('start', settings.getUDPPort())
    reactor.run()
Beispiel #4
0
 def start(self):
     from stun import stun_server
     from main import settings
     from lib import udp
     from logs import lg
     if not udp.proto(settings.getUDPPort()):
         lg.warn('udp port %s is not opened yet' % settings.getUDPPort())
         return False
     udp_port = int(settings.getUDPPort())
     stun_server.A('start', udp_port)
     return True
Beispiel #5
0
    def doSetUp(self, arg):
        if _Debug:
            lg.out(_DebugLevel, 'network_connector.doSetUp')

#         Second attempt
#         l = []
#         for service_name in driver.affecting('service_network'):
#             d = driver.start_single(service_name)
#             l.append(d)
#
#         def _ok(x):
#             lg.info('network child services is UP')
#             self.automat('network-up')
#             return None
#
#         def _fail(err):
#             lg.err(err)
#             self.automat('network-up')
#             return None
#
#         dl = DeferredList(l, fireOnOneErrback=True, consumeErrors=True)
#         dl.addCallback(_ok)
#         d.addErrback(_fail)

# First Solution
        if driver.is_on('service_service_entangled_dht'):
            from dht import dht_service
            dht_service.reconnect()
        if driver.is_on('service_ip_port_responder'):
            from stun import stun_server
            udp_port = int(settings.getUDPPort())
            stun_server.A('start', udp_port)
        if driver.is_on('service_my_ip_port'):
            from stun import stun_client
            stun_client.A().dropMyExternalAddress()
            stun_client.A('start')
        if driver.is_on('service_private_messages'):
            from chat import nickname_holder
            nickname_holder.A('set')
        if driver.is_on('service_udp_datagrams'):
            from lib import udp
            udp_port = settings.getUDPPort()
            if not udp.proto(udp_port):
                try:
                    udp.listen(udp_port)
                except:
                    lg.exc()
        self.automat('network-up')
 def on_suspend(self, *args, **kwargs):
     from lib import udp
     from main import settings
     udp_port = settings.getUDPPort()
     if udp.proto(udp_port):
         udp.close(udp_port)
     return True
 def start(self):
     from twisted.internet import reactor
     from twisted.internet.defer import Deferred
     from stun import stun_client
     from main import settings
     stun_client.A('init', settings.getUDPPort())
     return True
Beispiel #8
0
def safe_stun(udp_port=None, dht_port=None, ):
    from twisted.internet.defer import Deferred
    result = Deferred()
    try:
        settings.init()
        dht_port = dht_port or settings.getDHTPort()
        udp_port = udp_port or settings.getUDPPort()
        dht_service.init(dht_port)
        dht_service.connect()
        udp.listen(udp_port)

        def _cb(cod, typ, ip, details):
            # A('shutdown')
            result.callback({
                'result': cod,  # 'stun-success' or 'stun-failed'
                'type': typ,
                'ip': ip,
                'details': details,
            })

        A('init', (udp_port))
        A('start', _cb)
    except Exception as exc:
        lg.exc()
        result.callback(dict(ip='127.0.0.1', errors=[str(exc), ]))
        return result
    return result
Beispiel #9
0
def parseCommandLine():
    oparser = optparse.OptionParser()
    oparser.add_option("-d",
                       "--debug",
                       dest="debug",
                       type="int",
                       help="set debug level")
    oparser.set_default('debug', 10)
    oparser.add_option("-t",
                       "--tcpport",
                       dest="tcpport",
                       type="int",
                       help="specify port for TCP transport")
    oparser.set_default('tcpport', settings.getTCPPort())
    oparser.add_option("-u",
                       "--udpport",
                       dest="udpport",
                       type="int",
                       help="specify port for UDP transport")
    oparser.set_default('udpport', settings.getUDPPort())
    oparser.add_option("-p",
                       "--dhtport",
                       dest="dhtport",
                       type="int",
                       help="specify UDP port for DHT network")
    oparser.set_default('dhtport', settings.getDHTPort())
    oparser.add_option("-s",
                       "--packetsize",
                       dest="packetsize",
                       type="int",
                       help="set size of UDP datagrams")
    oparser.set_default('packetsize', 480)
    (options, args) = oparser.parse_args()
    return options, args
 def doStart(self, arg):
     """
     Action method.
     """
     options = {'idurl': my_id.getLocalID(), }
     id_contact = ''
     default_host = ''
     ident = my_id.getLocalIdentity()
     if ident:
         id_contact = ident.getContactsByProto().get(self.proto, '')
     if id_contact:
         assert id_contact.startswith(self.proto + '://')
         id_contact = id_contact.strip(self.proto + '://')
     if self.proto == 'tcp':
         if not id_contact:
             default_host = misc.readExternalIP() + ':' + str(settings.getTCPPort())
         options['host'] = id_contact or default_host
         options['tcp_port'] = settings.getTCPPort()
     elif self.proto == 'udp':
         if not id_contact:
             default_host = nameurl.GetName(my_id.getLocalID()) + '@' + platform.node()
         options['host'] = id_contact or default_host
         options['dht_port'] = settings.getDHTPort()
         options['udp_port'] = settings.getUDPPort()
     elif self.proto == 'proxy':
         pass
     if _Debug:
         lg.out(8, 'network_transport.doStart connecting %s transport : %s' % (self.proto.upper(), options))
     self.interface.connect(options)
 def start(self):
     from twisted.internet import reactor
     from twisted.internet.defer import Deferred
     from stun import stun_client
     from main import settings
     stun_client.A('init', settings.getUDPPort())
     return True
Beispiel #12
0
 def doSetUp(self, arg):
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.doSetUp')
     # if driver.is_on('service_identity_server'):
     #     if settings.enableIdServer():
     #         from userid import id_server
     #         id_server.A('start', (settings.getIdServerWebPort(),
     #                               settings.getIdServerTCPPort()))
     if driver.is_on('service_service_entangled_dht'):
         from dht import dht_service
         dht_service.reconnect()
     if driver.is_on('service_ip_port_responder'):
         from stun import stun_server
         udp_port = int(settings.getUDPPort())
         stun_server.A('start', udp_port)
     if driver.is_on('service_my_ip_port'):
         from stun import stun_client
         stun_client.A().dropMyExternalAddress()
         stun_client.A('start')
     if driver.is_on('service_private_messages'):
         from chat import nickname_holder
         nickname_holder.A('set', None)
     # if driver.is_on('service_gateway'):
     #     from transport import gateway
     #     gateway.start()
     self.automat('network-up')
Beispiel #13
0
 def doStart(self, *args, **kwargs):
     """
     Action method.
     """
     options = {'idurl': my_id.getLocalID(), }
     id_contact = ''
     default_host = ''
     if self.proto == 'tcp':
         if not id_contact:
             default_host = strng.to_bin(misc.readExternalIP()) + b':' + strng.to_bin(str(settings.getTCPPort()))
         options['host'] = id_contact or default_host
         options['tcp_port'] = settings.getTCPPort()
     elif self.proto == 'udp':
         if not id_contact:
             default_host = strng.to_bin(nameurl.GetName(my_id.getLocalID())) + b'@' + strng.to_bin(platform.node())
         options['host'] = id_contact or default_host
         options['dht_port'] = settings.getDHTPort()
         options['udp_port'] = settings.getUDPPort()
     elif self.proto == 'proxy':
         pass
     elif self.proto == 'http':
         if not id_contact:
             default_host = strng.to_bin(misc.readExternalIP()) + b':' + strng.to_bin(str(settings.getHTTPPort()))
         options['host'] = id_contact or default_host
         options['http_port'] = settings.getHTTPPort()
     if _Debug:
         lg.out(8, 'network_transport.doStart connecting %s transport : %s' % (self.proto.upper(), options))
     self.interface.connect(options)
Beispiel #14
0
 def stop(self):
     from lib import udp
     from main import settings
     from main.config import conf
     udp_port = settings.getUDPPort()
     if udp.proto(udp_port):
         udp.close(udp_port)
     conf().removeConfigNotifier('services/udp-datagrams/udp-port')
     return True
Beispiel #15
0
 def start(self):
     from stun import stun_client
     from main import settings
     from lib import misc
     stun_client.A('init', settings.getUDPPort())
     known_external_ip = misc.readExternalIP()
     if not known_external_ip or known_external_ip == '127.0.0.1':
         self._do_stun()
     return True
 def stop(self):
     from lib import udp
     from main import settings
     from main.config import conf
     udp_port = settings.getUDPPort()
     if udp.proto(udp_port):
         udp.close(udp_port)
     conf().removeCallback('services/udp-datagrams/udp-port')
     return True
Beispiel #17
0
 def doStartStunClient(self, *args, **kwargs):
     """
     Action method.
     """
     if driver.is_on('service_my_ip_port'):
         from stun import stun_client
         stun_client.A('start', self._stun_finished)
     else:
         self.automat('stun-success',
                      ('unknown', misc.readExternalIP()
                       or '127.0.0.1', settings.getUDPPort()))
Beispiel #18
0
 def on_resume(self, *args, **kwargs):
     from logs import lg
     from lib import udp
     from main import settings
     udp_port = settings.getUDPPort()
     if not udp.proto(udp_port):
         try:
             udp.listen(udp_port)
         except:
             lg.exc()
     return True
Beispiel #19
0
 def start(self):
     from lib import udp
     from main import settings
     from main.config import conf
     udp_port = settings.getUDPPort()
     conf().addCallback('services/udp-datagrams/udp-port',
                        self._on_udp_port_modified)
     if not udp.proto(udp_port):
         try:
             udp.listen(udp_port)
         except:
             return False
     return True
 def start(self):
     from lib import udp
     from main import settings
     from main.config import conf
     udp_port = settings.getUDPPort()
     conf().addCallback('services/udp-datagrams/udp-port',
                        self._on_udp_port_modified)
     if not udp.proto(udp_port):
         try:
             udp.listen(udp_port)
         except:
             return False
     return True
    def doStunExternalIP(self, arg):
        """
        Action method.
        """
        lg.out(4, 'id_registrator.doStunExternalIP')

        def save(ip):
            lg.out(4, '            external IP is %s' % ip)
            bpio.WriteFile(settings.ExternalIPFilename(), ip)
            self.automat('stun-success', ip)
        stun_rfc_3489.stunExternalIP(
            close_listener=True,  # False,
            internal_port=settings.getUDPPort(),).addCallbacks(
                save, lambda x: self.automat('stun-failed'))
Beispiel #22
0
def parseCommandLine():
    oparser = optparse.OptionParser()
    oparser.add_option("-d", "--debug", dest="debug", type="int", help="set debug level")
    oparser.set_default("debug", 10)
    oparser.add_option("-t", "--tcpport", dest="tcpport", type="int", help="specify port for TCP transport")
    oparser.set_default("tcpport", settings.getTCPPort())
    oparser.add_option("-u", "--udpport", dest="udpport", type="int", help="specify port for UDP transport")
    oparser.set_default("udpport", settings.getUDPPort())
    oparser.add_option("-p", "--dhtport", dest="dhtport", type="int", help="specify UDP port for DHT network")
    oparser.set_default("dhtport", settings.getDHTPort())
    oparser.add_option("-s", "--packetsize", dest="packetsize", type="int", help="set size of UDP datagrams")
    oparser.set_default("packetsize", 480)
    (options, args) = oparser.parse_args()
    return options, args
Beispiel #23
0
def main():
    from twisted.internet import reactor
    lg.set_debug_level(24)
    bpio.init()
    settings.init()
    dht_service.init(settings.getDHTPort())
    d = dht_service.connect()
    udp.listen(settings.getUDPPort())

    def _go(live_nodes):
        A('start', settings.getUDPPort())

    d.addCallback(_go)

    reactor.run()
Beispiel #24
0
def safe_stun(udp_port=None, dht_port=None, result_defer=None):
    from twisted.internet.defer import Deferred
    result = result_defer or Deferred()

    if driver.is_started('service_entangled_dht'):
        if dht_service.node()._joinDeferred and not dht_service.node()._joinDeferred.called:
            dht_service.node()._joinDeferred.addCallback(lambda ok: safe_stun(udp_port=udp_port, dht_port=dht_port, result_defer=result))
            dht_service.node()._joinDeferred.addErrback(result.errback)
            return result

    if not driver.is_on('service_entangled_dht'):
        result.errback(Exception('service_entangled_dht() is not started'))
        return result
    
    try:
        settings.init()
        dht_port = dht_port or settings.getDHTPort()
        udp_port = udp_port or settings.getUDPPort()
        if dht_port:
            dht_service.init(dht_port)
        d = dht_service.connect()
        if udp_port:
            udp.listen(udp_port)

        def _cb(cod, typ, ip, details):
            # A('shutdown')
            result.callback({
                'result': cod,  # 'stun-success' or 'stun-failed'
                'type': typ,
                'ip': ip,
                'details': details,
            })

        def _go(live_nodes):
            A('init', udp_port)
            A('start', _cb)

        d.addCallback(_go)
        d.addErrback(lambda err: result.callback(dict(ip='127.0.0.1', errors=[str(err), ])))

    except Exception as exc:
        lg.exc()
        result.callback(dict(ip='127.0.0.1', errors=[str(exc), ]))
        return result
    return result
 def doStart(self, arg):
     """
     Action method.
     """
     options = {
         'idurl': my_id.getLocalID(),
     }
     id_contact = ''
     default_host = ''
     #         ident = my_id.getLocalIdentity()
     #         if ident:
     #             id_contact = ident.getContactsByProto().get(self.proto, '')
     #         if id_contact:
     #             assert id_contact.startswith(self.proto + '://')
     #             id_contact = id_contact.lstrip(self.proto + '://')
     if self.proto == 'tcp':
         if not id_contact:
             default_host = strng.to_bin(
                 misc.readExternalIP()) + b':' + strng.to_bin(
                     str(settings.getTCPPort()))
         options['host'] = id_contact or default_host
         options['tcp_port'] = settings.getTCPPort()
     elif self.proto == 'udp':
         if not id_contact:
             default_host = strng.to_bin(nameurl.GetName(
                 my_id.getLocalID())) + b'@' + strng.to_bin(platform.node())
         options['host'] = id_contact or default_host
         options['dht_port'] = settings.getDHTPort()
         options['udp_port'] = settings.getUDPPort()
     elif self.proto == 'proxy':
         pass
     elif self.proto == 'http':
         if not id_contact:
             default_host = strng.to_bin(
                 misc.readExternalIP()) + b':' + strng.to_bin(
                     str(settings.getHTTPPort()))
         options['host'] = id_contact or default_host
         options['http_port'] = settings.getHTTPPort()
     if _Debug:
         lg.out(
             8, 'network_transport.doStart connecting %s transport : %s' %
             (self.proto.upper(), options))
     self.interface.connect(options)
Beispiel #26
0
    def doSetDown(self, arg):
        """
        """
        if _Debug:
            lg.out(_DebugLevel, 'network_connector.doSetDown')

#         Second Approach
#         l = []
#         for service_name in driver.affecting('service_network'):
#             d = driver.stop_single(service_name)
#             l.append(d)
#
#         def _ok(x):
#             lg.info('network child services is DOWN')
#             self.automat('network-down')
#             return None
#
#         def _fail(err):
#             lg.err(err)
#             self.automat('network-down')
#             return None
#
#         dl = DeferredList(l, fireOnOneErrback=True, consumeErrors=True)
#         dl.addCallback(_ok)
#         d.addErrback(_fail)

# First Solution
        if driver.is_on('service_gateway'):
            from transport import gateway
            gateway.stop()
        if driver.is_on('service_ip_port_responder'):
            from stun import stun_server
            stun_server.A('stop')
        if driver.is_on('service_service_entangled_dht'):
            from dht import dht_service
            dht_service.disconnect()
        if driver.is_on('service_udp_datagrams'):
            from lib import udp
            udp_port = settings.getUDPPort()
            if udp.proto(udp_port):
                udp.close(udp_port)
        self.automat('network-down')
 def doSetDown(self, *args, **kwargs):
     """
     """
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.doSetDown')
     if driver.is_on('service_gateway'):
         from transport import gateway
         gateway.stop()
     if driver.is_on('service_ip_port_responder'):
         from stun import stun_server
         stun_server.A('stop')
     if driver.is_on('service_service_entangled_dht'):
         from dht import dht_service
         dht_service.disconnect()
     if driver.is_on('service_udp_datagrams'):
         from lib import udp
         udp_port = settings.getUDPPort()
         if udp.proto(udp_port):
             udp.close(udp_port)
     self.automat('network-down')
Beispiel #28
0
def main():
    from twisted.internet import reactor  # @UnresolvedImport
    lg.set_debug_level(24)
    bpio.init()
    settings.init()
    dht_port = settings.getDHTPort()
    if len(sys.argv) > 1:
        dht_port = int(sys.argv[1])
    udp_port = settings.getUDPPort()
    if len(sys.argv) > 2:
        udp_port = int(sys.argv[2])
    dht_service.init(dht_port)
    d = dht_service.connect()
    udp.listen(udp_port)

    def _go(live_nodes):
        A('start', udp_port)

    d.addCallback(_go)
    reactor.run()  # @UndefinedVariable
    settings.shutdown()
Beispiel #29
0
def main():
    from twisted.internet import reactor
    settings.init()
    lg.set_debug_level(30)
    dht_port = settings.getDHTPort()
    udp_port = settings.getUDPPort()
    if len(sys.argv) > 1:
        dht_port = int(sys.argv[1])
    if len(sys.argv) > 2:
        udp_port = int(sys.argv[2])
    dht_service.init(dht_port)
    dht_service.connect()
    udp.listen(udp_port)

    def _cb(result, typ, ip, details):
        print result, typ, ip, details
        A('shutdown')
        reactor.stop()
    A('init', (udp_port))
    A('start', _cb)
    reactor.run()
Beispiel #30
0
def main():
    from twisted.internet import reactor  # @UnresolvedImport
    settings.init()
    lg.set_debug_level(30)
    dht_port = settings.getDHTPort()
    udp_port = settings.getUDPPort()
    if len(sys.argv) > 1:
        dht_port = int(sys.argv[1])
    if len(sys.argv) > 2:
        udp_port = int(sys.argv[2])
    dht_service.init(dht_port)
    dht_service.connect()
    udp.listen(udp_port)

    def _cb(result, typ, ip, details):
        print(result, typ, ip, details)
        A('shutdown')
        reactor.stop()  # @UndefinedVariable

    A('init', (udp_port))
    A('start', _cb)
    reactor.run()  # @UndefinedVariable
Beispiel #31
0
def udp_dht_stun(udp_port=None, dht_port=None, result_defer=None):
    if not driver.is_on('service_my_ip_port'):
        if _Debug:
            lg.out(
                _DebugLevel,
                'stun_client.udp_dht_stun   SKIP because service_my_ip_port() is not started'
            )
        if result_defer:
            result_defer.errback(
                Exception('service_my_ip_port() is not started'))
        return False

    from dht import dht_service

    if dht_service.node().connectingTask(
    ) and not dht_service.node().connectingTask().called:
        if _Debug:
            lg.out(
                _DebugLevel,
                'stun_client.udp_dht_stun   SKIP and run later because dht_service is still joining the network'
            )
        dht_service.node().connectingTask(
        ).addCallback(lambda ok: udp_dht_stun(
            udp_port=udp_port, dht_port=dht_port, result_defer=result_defer))
        if result_defer:
            dht_service.node().connectingTask().addErrback(
                result_defer.errback)
        return True

    dht_port = dht_port or settings.getDHTPort()
    udp_port = udp_port or settings.getUDPPort()
    if dht_port:
        dht_service.init(dht_port)
    d = dht_service.connect()
    if udp_port:
        udp.listen(udp_port)

    def _cb(cod, typ, ip, details):
        # A('shutdown')
        ret = {
            'result': cod,  # 'stun-success' or 'stun-failed'
            'type': typ,
            'ip': ip,
            'details': details,
        }
        if _Debug:
            lg.out(_DebugLevel, 'stun_client.udp_dht_stun   result : %r' % ret)
        result_defer.callback(ret)
        return None

    def _go(live_nodes):
        if _Debug:
            lg.out(_DebugLevel,
                   'stun_client.udp_dht_stun   GO with nodes: %r' % live_nodes)
        A('init', udp_port)
        A('start', _cb)
        return live_nodes

    d.addCallback(_go)
    if result_defer:
        d.addErrback(result_defer.errback)
        # d.addErrback(lambda err: result_defer.callback(dict(ip='127.0.0.1', errors=[str(err), ])))
    return True
 def on_resume(self, *args, **kwargs):
     from stun import stun_server
     from main import settings
     udp_port = int(settings.getUDPPort())
     stun_server.A('start', udp_port)
     return True
Beispiel #33
0
 def _go(live_nodes):
     A('start', settings.getUDPPort())
Beispiel #34
0
 def start(self):
     from stun import stun_server
     from main import settings
     udp_port = int(settings.getUDPPort())
     stun_server.A('start', udp_port)
     return True
 def start(self):
     from stun import stun_server
     from main import settings
     udp_port = int(settings.getUDPPort())
     stun_server.A('start', udp_port)
     return True
Beispiel #36
0
 def start(self):
     from stun import stun_client
     from main import settings
     stun_client.A('init', settings.getUDPPort())
     return True