Esempio n. 1
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)
Esempio n. 2
0
    def _create_new_identity(self):
        """
        Generate new Private key and new identity file.

        Reads some extra info from config files.
        """
        login = bpio.ReadTextFile(settings.UserNameFilename())
        externalIP = misc.readExternalIP(
        )  # bpio.ReadTextFile(settings.ExternalIPFilename())

        lg.out(
            4,
            'id_registrator._create_new_identity %s %s ' % (login, externalIP))

        key.InitMyKey()

        lg.out(4, '    my key is ready')

        ident = my_id.buildDefaultIdentity(name=login,
                                           ip=externalIP,
                                           idurls=self.free_idurls)
        # localIP = bpio.ReadTextFile(settings.LocalIPFilename())
        my_identity_xmlsrc = ident.serialize()
        newfilename = settings.LocalIdentityFilename() + '.new'
        bpio.WriteFile(newfilename, my_identity_xmlsrc)
        self.new_identity = ident
        lg.out(
            4, '    wrote %d bytes to %s' %
            (len(my_identity_xmlsrc), newfilename))
 def _check_update_original_identity(self):
     from logs import lg
     from lib import misc
     from main.config import conf
     from userid import identity
     orig_ident_xmlsrc = conf().getData(
         'services/proxy-transport/my-original-identity', '').strip()
     current_router_idurl = conf().getString(
         'services/proxy-transport/current-router', '').strip()
     if not orig_ident_xmlsrc:
         if current_router_idurl:
             lg.warn(
                 'current-router is %s, but my-original-identity is empty' %
                 current_router_idurl)
             self._reset_my_original_identity()
         return
     orig_ident = identity.identity(xmlsrc=orig_ident_xmlsrc)
     if not orig_ident.isCorrect() or not orig_ident.Valid():
         lg.warn('my original identity is not valid')
         self._reset_my_original_identity()
         return
     externalIP = misc.readExternalIP()
     if externalIP and orig_ident.getIP() != externalIP:
         lg.warn('external IP was changed : restore my original identity')
         self._reset_my_original_identity()
         return
     if not current_router_idurl:
         lg.warn('original identity is correct, but current router is empty')
         self._reset_my_original_identity()
 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)
Esempio n. 5
0
 def _create_new_identity(self):
     """
     Generate new Private key and new identity file.
     Reads some extra info from config files.
     """
     login = strng.to_bin(bpio.ReadTextFile(settings.UserNameFilename()))
     externalIP = strng.to_bin(misc.readExternalIP()) or b'127.0.0.1'
     if self.free_idurls[0].count(b'127.0.0.1'):
         externalIP = b'127.0.0.1'
     lg.out(
         4,
         'id_registrator._create_new_identity %s %s ' % (login, externalIP))
     key.InitMyKey()
     if not key.isMyKeyReady():
         key.GenerateNewKey()
     lg.out(4, '    my key is ready')
     ident = my_id.buildDefaultIdentity(name=login,
                                        ip=externalIP,
                                        idurls=self.free_idurls)
     # my_id.rebuildLocalIdentity(
     #     identity_object=ident, revision_up=True, save_identity=False)
     # localIP = bpio.ReadTextFile(settings.LocalIPFilename())
     my_identity_xmlsrc = ident.serialize(as_text=True)
     newfilename = settings.LocalIdentityFilename() + '.new'
     bpio.WriteTextFile(newfilename, my_identity_xmlsrc)
     self.new_identity = ident
     lg.out(
         4, '    wrote %d bytes to %s' %
         (len(my_identity_xmlsrc), newfilename))
Esempio n. 6
0
 def doSetUp(self, arg):
     """
     Action method.
     """
     self.hostname = settings.getIdServerHost()
     if self.hostname == '':
         self.hostname = strng.to_bin(misc.readExternalIP())  # bpio.ReadTextFile(settings.ExternalIPFilename())
     if self.hostname == '':
         self.hostname = net_misc.getLocalIp()
     lg.out(4, 'id_server.doSetUp hostname=%s' % strng.to_text(self.hostname))
     if not os.path.isdir(settings.IdentityServerDir()):
         os.makedirs(settings.IdentityServerDir())
         lg.out(4, '            created a folder %s' % settings.IdentityServerDir())
     root = WebRoot()
     root.putChild(b'', WebMainPage())
     try:
         self.tcp_listener = reactor.listenTCP(self.tcp_port, IdServerFactory())
         lg.out(4, "            identity server listen on TCP port %d started" % (self.tcp_port))
     except:
         lg.out(4, "id_server.set_up ERROR exception trying to listen on port " + str(self.tcp_port))
         lg.exc()
     try:
         self.web_listener = reactor.listenTCP(self.web_port, server.Site(root))
         lg.out(4, "            have started web server at http://%s:%d " % (strng.to_text(self.hostname), self.web_port))
     except:
         lg.out(4, "id_server.set_up ERROR exception trying to listen on port " + str(self.web_port))
         lg.exc()
Esempio n. 7
0
 def doSetUp(self, arg):
     """
     Action method.
     """
     self.hostname = settings.getIdServerHost()
     if self.hostname == '':
         self.hostname = misc.readExternalIP()  # bpio.ReadTextFile(settings.ExternalIPFilename())
     if self.hostname == '':
         self.hostname = net_misc.getLocalIp()
     lg.out(4, 'id_server.doSetUp hostname=%s' % self.hostname)
     if not os.path.isdir(settings.IdentityServerDir()):
         os.makedirs(settings.IdentityServerDir())
         lg.out(4, '            created a folder %s' % settings.IdentityServerDir())
     root = WebRoot()
     root.putChild('', WebMainPage())
     try:
         self.web_listener = reactor.listenTCP(self.web_port, server.Site(root))
         lg.out(4, "            have started web listener on port %d " % (self.web_port))
     except:
         lg.out(4, "id_server.set_up ERROR exception trying to listen on port " + str(self.web_port))
         lg.exc()
     try:
         self.tcp_listener = reactor.listenTCP(self.tcp_port, IdServerFactory())
         lg.out(4, "            identity server listen on TCP port %d started" % (self.tcp_port))
     except:
         lg.out(4, "id_server.set_up ERROR exception trying to listen on port " + str(self.tcp_port))
         lg.exc()
Esempio n. 8
0
    def _create_new_identity(self):
        """
        Generate new Private key and new identity file.
        Reads some extra info from config files.
        """
        login = strng.to_bin(bpio.ReadTextFile(settings.UserNameFilename()))
        externalIP = strng.to_bin(misc.readExternalIP()) or b'127.0.0.1'
        if self.free_idurls[0].count(b'127.0.0.1'):
            externalIP = b'127.0.0.1'
        lg.out(
            4,
            'id_registrator._create_new_identity %s %s ' % (login, externalIP))

        my_id.forgetLocalIdentity()
        my_id.eraseLocalIdentity(do_backup=True)
        key.ForgetMyKey(erase_file=True, do_backup=True)
        key.InitMyKey()
        if not key.isMyKeyReady():
            key.GenerateNewKey()
        lg.out(4, '    my key is ready')
        ident = my_id.buildDefaultIdentity(name=login,
                                           ip=externalIP,
                                           idurls=self.free_idurls)
        my_identity_xmlsrc = ident.serialize(as_text=True)
        newfilename = settings.LocalIdentityFilename() + '.new'
        bpio.WriteTextFile(newfilename, my_identity_xmlsrc)
        try:
            id_url.identity_cached(ident)
        except:
            lg.exc()
        self.new_identity = ident
        lg.out(
            4, '    wrote %d bytes to %s' %
            (len(my_identity_xmlsrc), newfilename))
Esempio n. 9
0
 def verify_contacts(self, id_obj):
     """
     """
     nowip = strng.to_bin(misc.readExternalIP())
     tcp_contact = 'tcp://%s:%d' % (
         nowip,
         settings.getTCPPort(),
     )
     if id_obj.getContactIndex(contact=tcp_contact) < 0:
         if _Debug:
             lg.out(
                 4,
                 'tcp_interface.verify_contacts returning False: tcp contact not found or changed'
             )
         return False
     if tcp_node.get_internal_port() != settings.getTCPPort():
         if _Debug:
             lg.out(
                 4,
                 'tcp_interface.verify_contacts returning False: tcp port has been changed'
             )
         return False
     if _Debug:
         lg.out(4, 'tcp_interface.verify_contacts returning True')
     return True
Esempio n. 10
0
 def isCurrentInterfaceActive(self, *args, **kwargs):
     # TODO: not sure about external IP
     # because if you have a white IP it should be the same as your local IP
     loc = strng.to_bin(misc.readLocalIP())
     ext = strng.to_bin(misc.readExternalIP())
     ips = args[0]
     if _Debug:
         lg.args(_DebugLevel, local=loc, external=ext)
     return (loc in ips) or (ext in ips)
Esempio n. 11
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
Esempio n. 12
0
 def build_contacts(self, id_obj):
     """
     """
     result = []
     nowip = strng.to_bin(misc.readExternalIP())
     result.append(b'http://%s:%d' % (nowip, settings.getHTTPPort()))
     if _Debug:
         lg.out(4, 'http_interface.build_contacts : %s' % result)
     return result
 def _check_reset_original_identity(self):
     from logs import lg
     from lib import misc
     from lib import strng
     from main.config import conf
     from userid import identity
     from userid import my_id
     from userid import id_url
     orig_ident_xmlsrc = conf().getData(
         'services/proxy-transport/my-original-identity', '').strip()
     current_router_idurl = conf().getString(
         'services/proxy-transport/current-router', '').strip()
     if current_router_idurl:
         current_router_idurl = id_url.field(
             current_router_idurl.split(' ')[0])
     if not orig_ident_xmlsrc:
         if current_router_idurl:
             lg.warn(
                 '"current-router" is %s, but "my-original-identity" is empty'
                 % current_router_idurl)
         else:
             lg.warn('"current-router" and "my-original-identity" is empty')
         self._reset_my_original_identity()
         return
     orig_ident = identity.identity(xmlsrc=orig_ident_xmlsrc)
     if not orig_ident.isCorrect() or not orig_ident.Valid():
         lg.warn('"my-original-identity" config has not valid value')
         self._reset_my_original_identity()
         return
     if orig_ident.getIDURL() != my_id.getIDURL():
         lg.warn(
             '"my-original-identity" source is not equal to local identity source'
         )
         self._reset_my_original_identity()
         return
     externalIP = strng.to_bin(misc.readExternalIP())
     if externalIP and strng.to_bin(orig_ident.getIP()) != externalIP:
         lg.warn(
             'external IP was changed : reset "my-original-identity" config'
         )
         self._reset_my_original_identity()
         return
     if not current_router_idurl:
         lg.warn(
             '"my-original-identity" config is correct, but current router is empty'
         )
         self._reset_my_original_identity()
     all_orig_contacts_present_in_local_identity = True
     for orig_contact in orig_ident.getContacts():
         if orig_contact not in my_id.getLocalIdentity().getContacts():
             all_orig_contacts_present_in_local_identity = False
     if all_orig_contacts_present_in_local_identity:
         lg.warn(
             'all of "my-original-identity" contacts is found in local identity: need to RESET!'
         )
         self._reset_my_original_identity()
Esempio n. 14
0
 def msg(self, msgid, arg=None):
     msg = self.MESSAGES.get(msgid, ['', 'black'])
     text = msg[0] % {
         'login': bpio.ReadTextFile(settings.UserNameFilename()),
         'externalip': misc.readExternalIP(),  # bpio.ReadTextFile(settings.ExternalIPFilename()),
         'localip': bpio.ReadTextFile(settings.LocalIPFilename()), }
     color = 'black'
     if len(msg) == 2:
         color = msg[1]
     return text, color
Esempio n. 15
0
 def msg(self, msgid, arg=None):
     msg = self.MESSAGES.get(msgid, ['', 'black'])
     text = msg[0] % {
         'login': bpio.ReadTextFile(settings.UserNameFilename()),
         'externalip': misc.readExternalIP(),  # bpio.ReadTextFile(settings.ExternalIPFilename()),
         'localip': bpio.ReadTextFile(settings.LocalIPFilename()), }
     color = 'black'
     if len(msg) == 2:
         color = msg[1]
     return text, color
Esempio n. 16
0
 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)
Esempio n. 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()))
Esempio n. 18
0
 def msg(self, msgid, *args, **kwargs):
     msg = self.MESSAGES.get(msgid, ['', 'black'])
     text = msg[0] % {
         'login': strng.to_bin(
             bpio.ReadTextFile(settings.UserNameFilename())),
         'externalip': strng.to_bin(misc.readExternalIP()),
         'localip': strng.to_bin(
             bpio.ReadTextFile(settings.LocalIPFilename())),
     }
     color = 'black'
     if len(msg) == 2:
         color = msg[1]
     return text, color
Esempio n. 19
0
 def build_contacts(self, id_obj):
     """
     """
     result = []
     nowip = misc.readExternalIP()
     result.append('tcp://%s:%s' % (nowip, str(settings.getTCPPort())))
     # TODO:
     #    # if IP is not external and upnp configuration was failed for some reasons
     #    # we may want to use another contact methods, NOT tcp
     #    if IPisLocal() and run_upnpc.last_result('tcp') != 'upnp-done':
     #        lg.out(4, 'p2p_connector.update_identity want to push tcp contact: local IP, no upnp ...')
     #        lid.pushProtoContact('tcp')
     if _Debug:
         lg.out(4, 'tcp_interface.build_contacts : %s' % str(result))
     return result
Esempio n. 20
0
    def verify_contacts(self, id_obj):
        """
        """
        nowip = misc.readExternalIP()
        http_contact = 'http://%s:%s' % (nowip, str(settings.getHTTPPort()))
        if id_obj.getContactIndex(contact=http_contact) < 0:
            if _Debug:
                lg.out(4, 'http_interface.verify_contacts returning False: http contact not found or changed')
            return False
#         if http_node.get_internal_port() != settings.getHTTPPort():
#             if _Debug:
#                 lg.out(4, 'http_interface.verify_contacts returning False: http port has been changed')
#             return False
        if _Debug:
            lg.out(4, 'http_interface.verify_contacts returning True')
        return True
Esempio n. 21
0
 def doReportSuccess(self, *args, **kwargs):
     """
     Action method.
     """
     try:
         min_port = min(
             [addr[1] for addr in list(self.stun_results.values())])
         max_port = max(
             [addr[1] for addr in list(self.stun_results.values())])
         my_ip = strng.to_text(list(self.stun_results.values())[0][0])
         if min_port == max_port:
             result = ('stun-success', 'non-symmetric', my_ip, min_port)
         else:
             result = ('stun-success', 'symmetric', my_ip,
                       self.stun_results)
         self.my_address = (my_ip, min_port)
     except:
         lg.exc()
         result = ('stun-failed', None, None, [])
         self.my_address = None
     if _Debug:
         lg.out(
             _DebugLevel,
             'stun_client.doReportSuccess based on %d nodes: %r' % (
                 len(self.stun_results),
                 result,
             ))
     if self.my_address:
         current_external_ip = misc.readExternalIP()
         if current_external_ip != self.my_address[0]:
             events.send('my-external-ip-changed',
                         data=dict(
                             old=current_external_ip,
                             new=self.my_address[0],
                         ))
         bpio.WriteTextFile(settings.ExternalIPFilename(),
                            self.my_address[0])
         bpio.WriteTextFile(settings.ExternalUDPPortFilename(),
                            str(self.my_address[1]))
     for cb in self.callbacks:
         cb(result[0], result[1], result[2], result[3])
     self.callbacks = []
Esempio n. 22
0
def SendSettings(doAck=False, packetID=None):
    """
    Say what eccmap we are using for recovery info.
    How many suppliers we want (probably same as used by eccmap but just in case).
    Say how much disk we are donating now and home much we need from our suppliers.
    The response should be an Ack packet from Central server and
    also it can sent us a new lsit of suppliers with ListContacts packet.
    """
    if packetID is None:
        packetID = packetid.UniqueID()
    sdict = {}
    sdict['s'] = str(settings.getCentralNumSuppliers())
    # donated = DiskSpace(s=settings.getCentralMegabytesDonated())
    # needed = DiskSpace(s=settings.getCentralMegabytesNeeded())
    # sdict['d'] = str(donated.getValueMb())
    # sdict['n'] = str(needed.getValueMb())
    sdict['d'] = str(diskspace.GetMegaBytesFromString(settings.getCentralMegabytesDonated()))
    sdict['n'] = str(diskspace.GetMegaBytesFromString(settings.getCentralMegabytesNeeded()))
    sdict['e'] = settings.getECC()
    sdict['p'] = str(settings.BasePricePerGBDay())
    sdict['e1'] = str(settings.getEmergencyEmail())
    sdict['e2'] = str(settings.getEmergencyPhone())
    sdict['e3'] = str(settings.getEmergencyFax())
    sdict['e4'] = str(settings.getEmergencyOther()).replace('\n', '<br>')
    sdict['mf'] = settings.getEmergencyFirstMethod()
    sdict['ms'] = settings.getEmergencySecondMethod()
    sdict['ie'] = misc.readExternalIP()
    sdict['il'] = misc.readLocalIP()
    sdict['nm'] = str(settings.uconfig('personal.personal-name'))
    sdict['sn'] = str(settings.uconfig('personal.personal-surname'))
    sdict['nn'] = str(settings.uconfig('personal.personal-nickname'))
    sdict['bt'] = str(settings.uconfig('personal.personal-betatester'))
    i = 0
    for idurl in contacts.getCorrespondentIDs():
        sdict['f%03d' % i] = idurl
        i += 1

    data = dhnio._pack_dict(sdict)
    pid = send2central(commands.Settings(), data, doAck, packetID)
    dhnio.Dprint(4, "central_service.SendSettings PacketID=[%s]" % pid)
    return pid
Esempio n. 23
0
    def _create_new_identity(self):
        """
        Generate new Private key and new identity file.

        Reads some extra info from config files.
        """
        login = bpio.ReadTextFile(settings.UserNameFilename())
        externalIP = misc.readExternalIP()  # bpio.ReadTextFile(settings.ExternalIPFilename())

        lg.out(4, 'id_registrator._create_new_identity %s %s ' % (login, externalIP))

        key.InitMyKey()

        lg.out(4, '    my key is ready')

        ident = my_id.buildDefaultIdentity(
            name=login, ip=externalIP, idurls=self.free_idurls)
        # localIP = bpio.ReadTextFile(settings.LocalIPFilename())
        my_identity_xmlsrc = ident.serialize()
        newfilename = settings.LocalIdentityFilename() + '.new'
        bpio.WriteFile(newfilename, my_identity_xmlsrc)
        self.new_identity = ident
        lg.out(4, '    wrote %d bytes to %s' % (len(my_identity_xmlsrc), newfilename))
Esempio n. 24
0
def buildDefaultIdentity(name='', ip='', idurls=[]):
    """
    Use some local settings and config files to create some new identity.

    Nice to provide a user name or it will have a form like: [ip_address]_[date].
    """
    if not ip:
        ip = misc.readExternalIP()
    if not name:
        name = ip.replace('.', '-') + '_' + time.strftime('%M%S')
    lg.out(4, 'my_id.buildDefaultIdentity: %s %s' % (name, ip))
    # create a new identity object
    # it is stored in memory and another copy on disk drive
    ident = identity.identity(xmlsrc=identity.default_identity_src)
    # this is my IDURL address
    # you can have many IDURL locations for same identity
    # just need to keep all them synchronized
    # this is identity propagate procedure, see p2p/propagate.py
    if len(idurls) == 0:
        idurls.append(b'http://127.0.0.1/%s.xml' % strng.to_bin(name.lower()))
    for idurl in idurls:
        ident.sources.append(strng.to_bin(idurl.strip()))
    # create a full list of needed transport methods
    # to be able to accept incoming traffic from other nodes
    new_contacts, new_order = buildProtoContacts(ident)
    if len(new_contacts) == 0:
        if settings.enableTCP() and settings.enableTCPreceiving():
            new_contacts['tcp'] = b'tcp://' + strng.to_bin(
                ip) + b':' + strng.to_bin(str(settings.getTCPPort()))
            new_order.append('tcp')
        if settings.enableUDP() and settings.enableUDPreceiving():
            _, servername, _, _ = nameurl.UrlParse(ident.sources[0])
            new_contacts['udp'] = b'udp://' + strng.to_bin(
                name.lower()) + b'@' + strng.to_bin(servername)
            new_order.append('udp')
        if settings.enableHTTP() and settings.enableHTTPreceiving():
            new_contacts['http'] = b'http://' + strng.to_bin(
                ip) + b':' + strng.to_bin(str(settings.getHTTPPort()))
            new_order.append('http')
    # erase current contacts from my identity
    ident.clearContacts()
    # add contacts data to the local identity
    for proto in new_order:
        contact = new_contacts.get(proto, None)
        if contact is None:
            lg.warn('proto %s was not found in contacts' % proto)
            continue
        ident.setProtoContact(proto, contact)
    # set other info
    # ident.certificates = []
    ident.setDate(time.strftime('%b %d, %Y'))
    ident.setPostage(1)
    ident.setRevision(0)
    ident.setVersion('')  # TODO: put latest git commit hash here
    # update software version number
    # version_number = bpio.ReadTextFile(settings.VersionNumberFile()).strip()
    # repo, location = misc.ReadRepoLocation()
    # ident.version = (version_number.strip() + ' ' + repo.strip() + ' ' + bpio.osinfo().strip()).strip()
    # build a version info
    # vernum = bpio.ReadTextFile(settings.VersionNumberFile())
    # repo, location = misc.ReadRepoLocation()
    # ident.version = (vernum.strip() + ' ' + repo.strip() + ' ' + bpio.osinfo().strip()).strip()
    # put my public key in my identity
    ident.setPublicKey(key.MyPublicKey())
    # generate signature
    ident.sign()
    # validate new identity
    if not ident.Valid():
        lg.warn('generated identity is not valid !!!')
    return ident
Esempio n. 25
0
def IPisLocal():
    externalip = misc.readExternalIP()
    localip = misc.readLocalIP()
    return localip != externalip
Esempio n. 26
0
def UpdateIdentity():
    global _RevisionNumber
    global _WorkingProtocols

    #getting local identity
    lid = misc.getLocalIdentity()
    nowip = misc.readExternalIP()
    order = lid.getProtoOrder()
    lid.clearContacts()

    #prepare contacts data
    cdict = {}
    cdict['tcp'] = 'tcp://'+nowip+':'+settings.getTCPPort()
    if transport_control._TransportSSHEnable:
        cdict['ssh'] = 'ssh://'+nowip+':'+settings.getSSHPort()
    if transport_control._TransportHTTPEnable:
        cdict['http'] = 'http://'+nowip+':'+settings.getHTTPPort()
    if transport_control._TransportQ2QEnable:
        cdict['q2q'] = 'q2q://'+settings.getQ2Quserathost()
    if transport_control._TransportEmailEnable:
        cdict['email'] = 'email://'+settings.getEmailAddress()
    if transport_control._TransportCSpaceEnable:
        cdict['cspace'] = 'cspace://'+settings.getCSpaceKeyID()
    if transport_control._TransportUDPEnable:
        if stun.getUDPClient() is None or stun.getUDPClient().externalAddress is None:
            cdict['udp'] = 'udp://'+nowip+':'+settings.getUDPPort()
        else:
            cdict['udp'] = 'udp://'+stun.getUDPClient().externalAddress[0]+':'+str(stun.getUDPClient().externalAddress[1])

    #making full order list
    for proto in cdict.keys():
        if proto not in order:
            order.append(proto)

    #add contacts data to the local identity
    #check if some transport is not installed
    for proto in order:
        if settings.transportIsEnabled(proto) and settings.transportReceivingIsEnabled(proto):
            contact = cdict.get(proto, None)
            if contact is not None:
                lid.setProtoContact(proto, contact)
        else:
            # if protocol is disabled - mark this
            # because we may want to turn it on in the future
            _WorkingProtocols.discard(proto)
            
    #misc.setLocalIdentity(lid)

    del order

#    #if IP is not external and upnp configuration was failed for some reasons
#    #we want to use another contact methods, NOT tcp or ssh
#    if IPisLocal() and run_upnpc.last_result('tcp') != 'upnp-done':
#        dhnio.Dprint(4, 'p2p_connector.update_identity want to push tcp contact: local IP, no upnp ...')
#        lid.pushProtoContact('tcp')
#        misc.setLocalIdentity(lid)

    #update software version number
    revnum = _RevisionNumber.strip()
    repo, location = misc.ReadRepoLocation()
    lid.version = (revnum.strip() + ' ' + repo.strip() + ' ' + dhnio.osinfo().strip()).strip()
    
    #generate signature with changed content
    lid.sign()
    
    #remember the identity
    misc.setLocalIdentity(lid)

    #finally saving local identity
    misc.saveLocalIdentity()
    dhnio.Dprint(4, 'p2p_connector.UpdateIdentity')
    dhnio.Dprint(4, '    version: %s' % str(lid.version))
    dhnio.Dprint(4, '    contacts: %s' % str(lid.contacts))
Esempio n. 27
0
 def _start_transports():
     startlist = []
     for contact in misc.getLocalIdentity().getContacts():
         proto, host, port, filename = nameurl.UrlParse(contact)
         opts = transport_control.ProtocolOptions(proto)
         if not transport_control.ProtocolIsSupported(proto):
             if settings.transportIsEnabled(proto) and settings.transportIsInstalled(proto) and settings.transportReceivingIsEnabled(proto):
                 #---tcp---
                 if proto == 'tcp':
                     def _tcp_started(l, opts):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._tcp_started')
                         if l is not None:
                             transport_control.StartProtocol('tcp', l, opts[0], opts[1], opts[2])
                         return l
                     def _tcp_failed(x):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._tcp_failed WARNING: '+str(x))
                         return x
                     def _start_tcp(options):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._start_tcp on port %d' % int(options[1]))
                         d = transport_tcp.receive(int(options[1]))
                         d.addCallback(_tcp_started, options)
                         d.addErrback(_tcp_failed)
                         startlist.append(d)
                     def _upnp_result(result, options):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._upnp_result %s' % str(result))
                         if result is not None:
                             options[1] = str(result[1])
                         _start_tcp(options)
                     def _run_upnpc(port):
                         shutdowner.A('block')
                         run_upnpc.update(port)
                         shutdowner.A('unblock')
                     externalIP = misc.readExternalIP() 
                     if opts is None:
                         opts = (externalIP, '', '')
                     opts = list(opts)
                     opts[0] = externalIP
                     opts[1] = settings.getTCPPort()
                     if settings.enableUPNP():
                         d = maybeDeferred(_run_upnpc, int(opts[1]))
                         d.addCallback(_upnp_result, opts)
                     else:
                         _start_tcp(opts)
                 #---cspace---
                 elif proto == 'cspace' and transport_control._TransportCSpaceEnable:
                     def _cspace_started(x, opts):
                         if not transport_cspace.registered():
                             dhnio.Dprint(4, 'p2p_connector.UpdateTransports._cspace_started WARNING not registered: ' + str(x))
                             return x
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._cspace_started')
                         keyID = transport_cspace.keyID()
                         settings.setCSpaceKeyID(keyID)
                         opts[0] = keyID
                         l = transport_cspace.getListener()
                         transport_control.StartProtocol('cspace', l, opts[0], opts[1], opts[2])
                         return x
                     if opts is None:
                         opts = (settings.getCSpaceKeyID(), '', '')
                     opts = list(opts)
                     d = transport_cspace.init().addBoth(_cspace_started, opts)
                     startlist.append(d)
                 #---udp---
                 elif proto == 'udp' and transport_control._TransportUDPEnable:
                     def _udp_start(x, opts):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._udp_start')
                         if opts is None:
                             opts = (stun.getUDPClient().externalAddress[0], str(stun.getUDPClient().externalAddress[1]), '')
                         opts = list(opts)
                         opts[0] = stun.getUDPClient().externalAddress[0]
                         opts[1] = str(stun.getUDPClient().externalAddress[1])
                         transport_udp.init(stun.getUDPClient())
                         l = transport_udp.getListener()
                         if l is not None:
                             transport_control.StartProtocol('udp', l, opts[0], opts[1], opts[2])
                         return x
                     def _udp_failed(x):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._udp_failed')
                         return x
                     if stun.getUDPClient() is None or stun.getUDPClient().externalAddress is None:
                         d = stun.stunExternalIP(
                             close_listener=False, 
                             internal_port=settings.getUDPPort(), 
                             block_marker=shutdowner.A)
                     else:
                         d = succeed('')
                     d.addCallback(_udp_start, opts)
                     d.addErrback(_udp_failed)
                     startlist.append(d)
                     
     #need to wait before all listeners will be started
     return DeferredList(startlist)
Esempio n. 28
0
 def isCurrentInterfaceActive(self, *args, **kwargs):
     # I am not sure about external IP,
     # because if you have a white IP it should be the same with your local IP
     return (strng.to_bin(misc.readLocalIP()) in args[0]) or (strng.to_bin(misc.readExternalIP()) in args[0])
Esempio n. 29
0
 def isCurrentInterfaceActive(self, arg):
     # I am not sure about external IP,
     # because if you have a white IP it should be the same with your local IP
     return (misc.readLocalIP() in arg) or (misc.readExternalIP() in arg)
Esempio n. 30
0
 def isCurrentInterfaceActive(self, arg):
     # Not sure about external IP, because if we have white IP it is the same to local IP
     return ( misc.readLocalIP() in arg ) or ( misc.readExternalIP() in arg )