Пример #1
0
def eraseLocalIdentity(do_backup=True):
    if do_backup:
        if os.path.isfile(settings.LocalIdentityFilename()):
            current_identity_xmlsrc = local_fs.ReadBinaryFile(settings.LocalIdentityFilename())
            if current_identity_xmlsrc:
                fd, fname = tempfile.mkstemp(prefix='localidentity_', dir=settings.MetaDataDir())
                os.write(fd, current_identity_xmlsrc)
                os.close(fd)
                lg.info('created backup copy of my local identity in the file : %r' % fname)
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    if not os.path.exists(filename):
        if _Debug:
            lg.out(_DebugLevel, "my_id.eraseLocalIdentity SKIP file %s not exist" % filename)
        return True
    if not os.path.isfile(filename):
        if _Debug:
            lg.out(_DebugLevel, "my_id.eraseLocalIdentity ERROR path %s is not a file" % filename)
        return False
    try:
        os.remove(filename)
    except:
        lg.exc()
        return False
    events.send('local-identity-erased', data=dict())
    if _Debug:
        lg.out(_DebugLevel, "my_id.eraseLocalIdentity file %s was deleted" % filename)
    return True
Пример #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))
Пример #3
0
 def _do_send_my_identity(self):
     """
     Send my updated identity to the identity servers to register it.
     """
     from transport.tcp import tcp_node
     sendfilename = settings.LocalIdentityFilename()
     my_sources = my_id.getLocalIdentity().getSources(as_originals=True)
     dlist = []
     if _Debug:
         lg.out(
             _DebugLevel,
             'id_rotator._do_send_my_identity my_sources=%r' % my_sources)
     for idurl_bin in my_sources:
         _, host, _, _ = nameurl.UrlParse(idurl_bin)
         tcpport = None
         if host in self.preferred_servers:
             tcpport = int(self.preferred_servers[host][1])
         if not tcpport and host in self.known_servers:
             tcpport = int(self.known_servers[host][1])
         if not tcpport:
             tcpport = settings.IdentityServerPort()
         srvhost = net_misc.pack_address((
             host,
             tcpport,
         ))
         if _Debug:
             lg.out(_DebugLevel, '    sending to %r via TCP' % srvhost)
         dlist.append(
             tcp_node.send(
                 sendfilename,
                 srvhost,
                 'Identity',
                 keep_alive=False,
             ))
     return DeferredList(dlist, fireOnOneCallback=True)
Пример #4
0
 def _send_new_identity(self):
     """
     Send created identity to the identity servers to register it.
     """
     if _Debug:
         lg.out(_DebugLevel, 'id_registrator._send_new_identity')
     from transport.tcp import tcp_node
     sendfilename = settings.LocalIdentityFilename() + '.new'
     dlist = []
     for idurl in self.new_identity.getSources(as_originals=True):
         self.free_idurls.remove(strng.to_bin(idurl))
         _, host, _, _ = nameurl.UrlParse(idurl)
         _, tcpport = known_servers.by_host().get(
             host,
             (settings.IdentityWebPort(), settings.IdentityServerPort()))
         srvhost = net_misc.pack_address((
             host,
             tcpport,
         ))
         if _Debug:
             lg.out(_DebugLevel, '    sending to %r via TCP' % srvhost)
         dlist.append(
             tcp_node.send(
                 sendfilename,
                 srvhost,
                 'Identity',
                 keep_alive=False,
             ))
     return DeferredList(dlist, fireOnOneCallback=True)
Пример #5
0
def loadLocalIdentity():
    """
    The core method.

    The file [BitDust data dir]/metadata/localidentity keeps the user
    identity in XML format. Do read the local file and set into object
    in memory.
    """
    global _LocalIdentity
    xmlid = ''
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    if os.path.exists(filename):
        xmlid = bpio.ReadTextFile(filename)
        if _Debug:
            lg.out(_DebugLevel, 'my_id.loadLocalIdentity %d bytes read from %s' % (len(xmlid), filename))
    if not xmlid:
        if _Debug:
            lg.out(_DebugLevel, "my_id.loadLocalIdentity SKIPPED, local identity in %s is EMPTY !!!" % filename)
        return False
    lid = identity.identity(xmlsrc=xmlid)
    if not lid.isCorrect():
        if _Debug:
            lg.out(_DebugLevel, "my_id.loadLocalIdentity ERROR loaded identity is not Correct")
        return False
    if not lid.Valid():
        if _Debug:
            lg.out(_DebugLevel, "my_id.loadLocalIdentity ERROR loaded identity is not Valid")
        return False
    setLocalIdentity(lid)
    setTransportOrder(getOrderFromContacts(_LocalIdentity))
    if _Debug:
        lg.out(_DebugLevel, "my_id.loadLocalIdentity my global id is %s" % getGlobalID())
    return True
Пример #6
0
 def setUp(self):
     try:
         bpio.rmdir_recursive('/tmp/.bitdust_tmp')
     except Exception:
         pass
     lg.set_debug_level(30)
     settings.init(base_dir='/tmp/.bitdust_tmp')
     try:
         os.makedirs('/tmp/.bitdust_tmp/metadata')
     except:
         pass
     automat.OpenLogFile('/tmp/.bitdust_tmp/logs/automats.log')
     self.my_current_key = None
     fout = open('/tmp/_some_priv_key', 'w')
     fout.write(_some_priv_key)
     fout.close()
     fout = open(settings.LocalIdentityFilename(), 'w')
     fout.write(_some_identity_xml)
     fout.close()
     self.assertTrue(key.LoadMyKey(keyfilename='/tmp/_some_priv_key'))
     self.assertTrue(my_id.loadLocalIdentity())
     my_id.init()
     try:
         os.makedirs('/tmp/.bitdust_tmp/logs')
     except:
         pass
     local_fs.WriteTextFile('/tmp/.bitdust_tmp/logs/parallelp.log', '')
     tmpfile.init(temp_dir_path='/tmp/.bitdust_tmp/temp/')
     os.makedirs(
         '/tmp/.bitdust_tmp/backups/[email protected]_8084/1/F1234')
     try:
         bpio.rmdir_recursive('/tmp/_some_folder', ignore_errors=True)
     except:
         pass
     os.makedirs('/tmp/_some_folder')
Пример #7
0
 def _send_new_identity(self):
     """
     Send created identity to the identity server to register it.
     TODO: need to close transport and gateway after that
     """
     lg.out(4, 'id_registrator._send_new_identity ')
     from transport import gateway
     from transport import network_transport
     from transport.tcp import tcp_interface
     gateway.init()
     interface = tcp_interface.GateInterface()
     transport = network_transport.NetworkTransport('tcp', interface)
     transport.automat('init', gateway.listener())
     transport.automat('start')
     gateway.start()
     sendfilename = settings.LocalIdentityFilename() + '.new'
     dlist = []
     for idurl in self.new_identity.sources:
         self.free_idurls.remove(strng.to_bin(idurl))
         _, host, _, _ = nameurl.UrlParse(idurl)
         _, tcpport = known_servers.by_host().get(
             host,
             (settings.IdentityWebPort(), settings.IdentityServerPort()))
         srvhost = net_misc.pack_address((
             host,
             tcpport,
         ))
         dlist.append(
             gateway.send_file_single(idurl, 'tcp', srvhost, sendfilename,
                                      'Identity'))
     # assert len(self.free_idurls) == 0
     return DeferredList(dlist, fireOnOneCallback=True)
Пример #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))
Пример #9
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))
Пример #10
0
def saveLocalIdentity():
    """
    Save identity object from memory into local file.

    Do sign the identity than serialize to write to the file.
    """
    global _LocalIdentity
    if not isLocalIdentityReady():
        lg.warn("ERROR local identity not exist!")
        return False
    if not _LocalIdentity.isCorrect():
        lg.warn('local identity is not correct')
        return False
    _LocalIdentity.sign()
    if not _LocalIdentity.Valid():
        lg.err('local identity is not valid')
        return False
    xmlid = _LocalIdentity.serialize(as_text=True)
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    bpio.WriteTextFile(filename, xmlid)
    setTransportOrder(getOrderFromContacts(_LocalIdentity))
    events.send('local-identity-written', data=dict(idurl=_LocalIdentity.getIDURL(), filename=filename))
    if _Debug:
        lg.out(_DebugLevel, "my_id.saveLocalIdentity %d bytes wrote to %s" % (len(xmlid), filename))
    return True
Пример #11
0
def loadLocalIdentity():
    """
    The core method.

    The file [BitDust data dir]/metadata/localidentity keeps the user
    identity in XML format. Do read the local file and set into object
    in memory.
    """
    global _LocalIdentity
    global _LocalIDURL
    global _LocalName
    xmlid = ''
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    if os.path.exists(filename):
        xmlid = bpio.ReadTextFile(filename)
        lg.out(6, 'my_id.loadLocalIdentity %d bytes read from\n        %s' % (len(xmlid), filename))
    if xmlid == '':
        lg.out(2, "my_id.loadLocalIdentity SKIPPED, local identity in %s is EMPTY !!!" % filename)
        return
    lid = identity.identity(xmlsrc=xmlid)
    if not lid.isCorrect():
        lg.out(2, "my_id.loadLocalIdentity ERROR loaded identity is not Correct")
        return
    if not lid.Valid():
        lg.out(2, "my_id.loadLocalIdentity ERROR loaded identity is not Valid")
        return
    setLocalIdentity(lid)
#     _LocalIdentity = lid
#     _LocalIDURL = lid.getIDURL()
#     _LocalName = lid.getIDName()
    setTransportOrder(getOrderFromContacts(_LocalIdentity))
    lg.out(6, "my_id.loadLocalIdentity my name is [%s]" % lid.getIDName())
Пример #12
0
 def setUp(self):
     try:
         bpio.rmdir_recursive('/tmp/.bitdust_tmp')
     except Exception:
         pass
     lg.set_debug_level(30)
     settings.init(base_dir='/tmp/.bitdust_tmp')
     self.my_current_key = None
     try:
         os.makedirs('/tmp/.bitdust_tmp/metadata/')
     except:
         pass
     try:
         os.makedirs('/tmp/.bitdust_tmp/identitycache/')
     except:
         pass
     fout = open('/tmp/_some_priv_key', 'w')
     fout.write(_some_priv_key)
     fout.close()
     fout = open(settings.LocalIdentityFilename(), 'w')
     fout.write(_some_identity_xml)
     fout.close()
     self.assertTrue(key.LoadMyKey(keyfilename='/tmp/_some_priv_key'))
     self.assertTrue(my_id.loadLocalIdentity())
     self.bob_ident = identity.identity(xmlsrc=_another_identity_xml)
     identitycache.UpdateAfterChecking(idurl=self.bob_ident.getIDURL(),
                                       xml_src=_another_identity_xml)
Пример #13
0
 def _check_install(self):
     """
     Return True if Private Key and local identity files exists and both is
     valid.
     """
     if _Debug:
         lg.out(_DebugLevel, 'initializer._check_install')
     from userid import identity
     from crypt import key
     keyfilename = settings.KeyFileName()
     keyfilenamelocation = settings.KeyFileNameLocation()
     if os.path.exists(keyfilenamelocation):
         keyfilename = bpio.ReadTextFile(keyfilenamelocation)
         if not os.path.exists(keyfilename):
             keyfilename = settings.KeyFileName()
     idfilename = settings.LocalIdentityFilename()
     if not os.path.exists(keyfilename) or not os.path.exists(idfilename):
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install local key or local id not exists')
         return False
     current_key = bpio.ReadTextFile(keyfilename)
     current_id = bpio.ReadTextFile(idfilename)
     if not current_id:
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install local identity is empty ')
         return False
     if not current_key:
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install private key is empty ')
         return False
     try:
         key.InitMyKey()
     except:
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install fail loading private key ')
         return False
     try:
         ident = identity.identity(xmlsrc=current_id)
     except:
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install fail init local identity ')
         return False
     if not ident.isCorrect():
         lg.err('local identity is not correct !!!')
         return False
     try:
         res = ident.Valid()
     except:
         if _Debug:
             lg.out(_DebugLevel, 'failed to validate local identity')
         return False
     if not res:
         lg.err('local identity is not valid !!!')
         return False
     if _Debug:
         lg.out(_DebugLevel, 'initializer._check_install SUCCESS!!!')
     return True
Пример #14
0
 def setUp(self):
     from logs import lg
     from main import settings
     from crypt import key
     from userid import my_id
     lg.set_debug_level(30)
     settings.init()
     self.my_current_key = None
     if key.isMyKeyExists():
         os.rename(settings.KeyFileName(), '/tmp/_current_priv_key')
     fout = open('/tmp/_some_priv_key', 'w')
     fout.write(_some_priv_key)
     fout.close()
     if my_id.isLocalIdentityExists():
         os.rename(settings.LocalIdentityFilename(),
                   '/tmp/_current_localidentity')
     fout = open(settings.LocalIdentityFilename(), 'w')
     fout.write(_some_identity_xml)
     fout.close()
     self.assertTrue(key.LoadMyKey(keyfilename='/tmp/_some_priv_key'))
     self.assertTrue(my_id.loadLocalIdentity())
Пример #15
0
 def tearDown(self):
     from main import settings
     from crypt import key
     from userid import my_id
     key.ForgetMyKey()
     my_id.forgetLocalIdentity()
     if os.path.isfile('/tmp/_current_localidentity'):
         os.rename('/tmp/_current_localidentity',
                   settings.LocalIdentityFilename())
     if os.path.isfile('/tmp/_current_priv_key'):
         os.rename('/tmp/_current_priv_key', settings.KeyFileName())
     os.remove('/tmp/_some_priv_key')
Пример #16
0
def update():
    """
    A good way to check all things - load and sign again.
    """
    from userid import my_id
    bpio.init()
    settings.init()
    src = bpio.ReadTextFile(settings.LocalIdentityFilename())
    my_id.setLocalIdentity(identity(xmlsrc=src))
    my_id.getLocalIdentity().sign()
    my_id.saveLocalIdentity()
    print my_id.getLocalIdentity().serialize()
Пример #17
0
 def _check_install(self):
     """
     Return True if Private Key and local identity files exists and both is
     valid.
     """
     lg.out(2, 'initializer._check_install')
     from userid import identity
     from crypt import key
     keyfilename = settings.KeyFileName()
     keyfilenamelocation = settings.KeyFileNameLocation()
     if os.path.exists(keyfilenamelocation):
         keyfilename = bpio.ReadTextFile(keyfilenamelocation)
         if not os.path.exists(keyfilename):
             keyfilename = settings.KeyFileName()
     idfilename = settings.LocalIdentityFilename()
     if not os.path.exists(keyfilename) or not os.path.exists(idfilename):
         lg.out(
             2,
             'initializer._check_install local key or local id not exists')
         return False
     current_key = bpio.ReadBinaryFile(keyfilename)
     current_id = bpio.ReadBinaryFile(idfilename)
     if current_id == '':
         lg.out(2, 'initializer._check_install local identity is empty ')
         return False
     if current_key == '':
         lg.out(2, 'initializer._check_install private key is empty ')
         return False
     try:
         key.InitMyKey()
     except:
         lg.out(2, 'initializer._check_install fail loading private key ')
         return False
     try:
         ident = identity.identity(xmlsrc=current_id)
     except:
         lg.out(2, 'initializer._check_install fail init local identity ')
         return False
     try:
         res = ident.Valid() and ident.isCorrect()
     except:
         lg.out(
             2,
             'initializer._check_install wrong data in local identity   ')
         return False
     if not res:
         lg.out(2,
                'initializer._check_install local identity is not valid ')
         return False
     lg.out(2, 'initializer._check_install done')
     return True
Пример #18
0
def eraseLocalIdentity():
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    if not os.path.exists(filename):
        lg.out(6, "my_id.eraseLocalIdentity SKIP file %s not exist" % filename)
        return True
    if not os.path.isfile(filename):
        lg.out(6, "my_id.eraseLocalIdentity ERROR path %s is not a file" % filename)
        return False
    try:
        os.remove(filename)
    except:
        lg.exc()
        return False
    lg.out(6, "my_id.eraseLocalIdentity file %s was deleted" % filename)
    return True
Пример #19
0
def update():
    """
    A good way to check all things - load and sign again.
    Also will test rebuilding of the identity
    """
    from userid import my_id
    bpio.init()
    settings.init()
    src = bpio.ReadTextFile(settings.LocalIdentityFilename())
    print(src)
    my_id.setLocalIdentity(identity(xmlsrc=src))
    my_id.getLocalIdentity().sign()
    my_id.saveLocalIdentity()
    print(my_id.getLocalIdentity().serialize())
    print(my_id.rebuildLocalIdentity(revision_up=True))
Пример #20
0
def saveLocalIdentity():
    """
    Save identity object from memory into local file.

    Do sign the identity than serialize to write to the file.
    """
    global _LocalIdentity
    if not isLocalIdentityReady():
        lg.warn("ERROR local identity not exist!")
        return
    if not _LocalIdentity.isCorrect():
        lg.warn('local identity is not correct')
        return
    _LocalIdentity.sign()
    xmlid = _LocalIdentity.serialize()
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    bpio.WriteFile(filename, xmlid)
    lg.out(6, "my_id.saveLocalIdentity %d bytes wrote to %s" % (len(xmlid), filename))
Пример #21
0
 def setUp(self):
     try:
         bpio.rmdir_recursive('/tmp/.bitdust_tmp')
     except Exception:
         pass
     lg.set_debug_level(30)
     settings.init(base_dir='/tmp/.bitdust_tmp')
     self.my_current_key = None
     try:
         os.makedirs('/tmp/.bitdust_tmp/metadata/')
     except:
         pass
     fout = open('/tmp/_some_priv_key', 'w')
     fout.write(_some_priv_key)
     fout.close()
     fout = open(settings.LocalIdentityFilename(), 'w')
     fout.write(_some_identity_xml)
     fout.close()
     self.assertTrue(key.LoadMyKey(keyfilename='/tmp/_some_priv_key'))
     self.assertTrue(my_id.loadLocalIdentity())
Пример #22
0
    def test_signed_key(self):
        try:
            bpio.rmdir_recursive('/tmp/.bitdust_test_signed_key')
        except Exception:
            pass
        lg.set_debug_level(30)
        settings.init(base_dir='/tmp/.bitdust_test_signed_key')
        self.my_current_key = None
        try:
            os.makedirs('/tmp/.bitdust_test_signed_key/metadata/')
        except:
            pass
        fout = open('/tmp/_some_priv_key', 'w')
        fout.write(_some_priv_key)
        fout.close()
        fout = open(settings.LocalIdentityFilename(), 'w')
        fout.write(_some_identity_xml)
        fout.close()
        self.assertTrue(key.LoadMyKey(keyfilename='/tmp/_some_priv_key'))
        self.assertTrue(my_id.loadLocalIdentity())

        key_id = '[email protected]_8084'
        my_keys.erase_key(key_id, keys_folder='/tmp/')
        my_keys.register_key(key_id, _sample_private_key, keys_folder='/tmp/')
        is_valid = my_keys.validate_key(my_keys.key_obj(key_id))
        self.assertTrue(is_valid)
        my_keys.sign_key(key_id)
        signed_key_info = my_keys.get_key_info(key_id,
                                               include_private=True,
                                               include_signature=True)
        self.assertTrue(my_keys.verify_key_info_signature(signed_key_info))

        key.ForgetMyKey()
        my_id.forgetLocalIdentity()
        settings.shutdown()
        os.remove('/tmp/_some_priv_key')
        bpio.rmdir_recursive('/tmp/.bitdust_test_signed_key')
Пример #23
0
def isLocalIdentityExists():
    """
    Return True if local file `~/.bitdust/metadata/localidentity` exists.
    """
    return os.path.isfile(settings.LocalIdentityFilename())
Пример #24
0
    def doVerifyAndRestore(self, arg):
        global _WorkingKey
        lg.out(4, 'identity_restorer.doVerifyAndRestore')

        remote_identity_src = arg

        if os.path.isfile(settings.KeyFileName()):
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore will backup and remove '
                + settings.KeyFileName())
            bpio.backup_and_remove(settings.KeyFileName())

        if os.path.isfile(settings.LocalIdentityFilename()):
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore will backup and remove '
                + settings.LocalIdentityFilename())
            bpio.backup_and_remove(settings.LocalIdentityFilename())

        try:
            remote_ident = identity.identity(xmlsrc=remote_identity_src)
            local_ident = identity.identity(xmlsrc=remote_identity_src)
        except:
            # lg.exc()
            reactor.callLater(0.1, self.automat, 'restore-failed',
                              ('remote identity have incorrect format', 'red'))
            return

        lg.out(
            4, 'identity_restorer.doVerifyAndRestore checking remote identity')
        try:
            res = remote_ident.isCorrect()
        except:
            lg.exc()
            res = False
        if not res:
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore remote identity is not correct FAILED!!!!'
            )
            reactor.callLater(0.1, self.automat, 'restore-failed',
                              ('remote identity format is not correct', 'red'))
            return

        lg.out(
            4, 'identity_restorer.doVerifyAndRestore validate remote identity')
        try:
            res = remote_ident.Valid()
        except:
            lg.exc()
            res = False
        if not res:
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore validate remote identity FAILED!!!!'
            )
            reactor.callLater(0.1, self.automat, 'restore-failed',
                              ('remote identity is not valid', 'red'))
            return

        key.ForgetMyKey()
        bpio.WriteFile(settings.KeyFileName(), _WorkingKey)
        try:
            key.InitMyKey()
        except:
            key.ForgetMyKey()
            # lg.exc()
            try:
                os.remove(settings.KeyFileName())
            except:
                pass
            reactor.callLater(0.1, self.automat, 'restore-failed',
                              ('private key is not valid', 'red'))
            return

        try:
            local_ident.sign()
        except:
            # lg.exc()
            reactor.callLater(0.1, self.automat, 'restore-failed',
                              ('error while signing identity', 'red'))
            return

        if remote_ident.signature != local_ident.signature:
            reactor.callLater(
                0.1, self.automat, 'restore-failed',
                ('signature did not match, key verification failed!', 'red'))
            return

        my_id.setLocalIdentity(local_ident)
        my_id.saveLocalIdentity()

        bpio.WriteFile(settings.UserNameFilename(), my_id.getIDName())

        if os.path.isfile(settings.KeyFileName() + '.backup'):
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore will remove backup file for '
                + settings.KeyFileName())
            bpio.remove_backuped_file(settings.KeyFileName())

        if os.path.isfile(settings.LocalIdentityFilename() + '.backup'):
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore will remove backup file for '
                + settings.LocalIdentityFilename())
            bpio.remove_backuped_file(settings.LocalIdentityFilename())

        reactor.callLater(0.1, self.automat, 'restore-success')
Пример #25
0
def init(UI='', options=None, args=None, overDict=None, executablePath=None):
    """
    In the method ``main()`` program firstly checks the command line arguments
    and then calls this method to start the whole process.

    This initialize some low level modules and finally create an
    instance of ``initializer()`` state machine and send it an event
    "run".
    """
    global AppDataDir

    from logs import lg
    lg.out(4, 'bpmain.run UI="%s"' % UI)

    from system import bpio

    #---settings---
    from main import settings
    if overDict:
        settings.override_dict(overDict)
    settings.init(AppDataDir)
    if not options or options.debug is None:
        lg.set_debug_level(settings.getDebugLevel())
    from main import config
    config.conf().addCallback('logs/debug-level',
                              lambda p, value, o, r: lg.set_debug_level(value))

    #---USE_TRAY_ICON---
    if os.path.isfile(settings.LocalIdentityFilename()) and os.path.isfile(settings.KeyFileName()):
        try:
            from system.tray_icon import USE_TRAY_ICON
            if bpio.Mac() or not bpio.isGUIpossible():
                lg.out(4, '    GUI is not possible')
                USE_TRAY_ICON = False
            if USE_TRAY_ICON:
                from twisted.internet import wxreactor
                wxreactor.install()
                lg.out(4, '    wxreactor installed')
        except:
            USE_TRAY_ICON = False
            lg.exc()
    else:
        lg.out(4, '    local identity or key file is not ready')
        USE_TRAY_ICON = False
    lg.out(4, '    USE_TRAY_ICON=' + str(USE_TRAY_ICON))
    if USE_TRAY_ICON:
        from system import tray_icon
        icons_path = bpio.portablePath(os.path.join(bpio.getExecutableDir(), 'icons'))
        lg.out(4, 'bpmain.run call tray_icon.init(%s)' % icons_path)
        tray_icon.init(icons_path)

        def _tray_control_func(cmd):
            if cmd == 'exit':
                from . import shutdowner
                shutdowner.A('stop', 'exit')
        tray_icon.SetControlFunc(_tray_control_func)

    #---OS Windows init---
    if bpio.Windows():
        try:
            from win32event import CreateMutex  # @UnresolvedImport
            mutex = CreateMutex(None, False, "BitDust")
            lg.out(4, 'bpmain.run created a Mutex: %s' % str(mutex))
        except:
            lg.exc()

    #---twisted reactor---
    lg.out(4, 'bpmain.run want to import twisted.internet.reactor')
    try:
        from twisted.internet import reactor  # @UnresolvedImport
    except:
        lg.exc()
        sys.exit('Error initializing reactor in bpmain.py\n')

    #---logfile----
    if lg.logs_enabled() and lg.log_file():
        lg.out(2, 'bpmain.run want to switch log files')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_stop_redirecting()
        lg.close_log_file()
        lg.open_log_file(settings.MainLogFilename())
        # lg.open_log_file(settings.MainLogFilename() + '-' + time.strftime('%y%m%d%H%M%S') + '.log')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_start_redirecting()

    #---memdebug---
#    if settings.uconfig('logs.memdebug-enable') == 'True':
#        try:
#            from logs import memdebug
#            memdebug_port = int(settings.uconfig('logs.memdebug-port'))
#            memdebug.start(memdebug_port)
#            reactor.addSystemEventTrigger('before', 'shutdown', memdebug.stop)
#            lg.out(2, 'bpmain.run memdebug web server started on port %d' % memdebug_port)
#        except:
#            lg.exc()

    #---process ID---
    try:
        pid = os.getpid()
        pid_file_path = os.path.join(settings.MetaDataDir(), 'processid')
        bpio.WriteTextFile(pid_file_path, str(pid))
        lg.out(2, 'bpmain.run wrote process id [%s] in the file %s' % (str(pid), pid_file_path))
    except:
        lg.exc()

#    #---reactor.callLater patch---
#    if lg.is_debug(12):
#        patchReactorCallLater(reactor)
#        monitorDelayedCalls(reactor)

#    #---plugins---
#    from plugins import plug
#    plug.init()
#    reactor.addSystemEventTrigger('before', 'shutdown', plug.shutdown)

    lg.out(2, "    python executable is: %s" % sys.executable)
    lg.out(2, "    python version is:\n%s" % sys.version)
    lg.out(2, "    python sys.path is:\n                %s" % ('\n                '.join(sys.path)))

    lg.out(2, "bpmain.run UI=[%s]" % UI)

    if lg.is_debug(20):
        lg.out(0, '\n' + bpio.osinfofull())

    lg.out(4, 'import automats')

    #---START!---
    from automats import automat
    automat.LifeBegins(lg.when_life_begins())
    automat.OpenLogFile(settings.AutomatsLog())

    from main import events
    events.init()

    from main import initializer
    IA = initializer.A()
    lg.out(4, 'sending event "run" to initializer()')
    reactor.callWhenRunning(IA.automat, 'run', UI)  # @UndefinedVariable
    return IA