示例#1
0
文件: misc.py 项目: vesellov/devel
def ReadRepoLocation():
    """
    This method reutrn a tuple of two strings: "name of the current repo" and
    "repository location".
    """
    if bpio.Linux() or bpio.Mac():
        repo_file = os.path.join(bpio.getExecutableDir(), 'repo')
        if os.path.isfile(repo_file):
            src = bpio.ReadTextFile(repo_file)
            if src:
                try:
                    return src.split('\n')[0].strip(), src.split(
                        '\n')[1].strip()
                except:
                    lg.exc()
        return 'sources', 'https://bitdust.io/download/'
    src = strng.to_bin(bpio.ReadTextFile(settings.RepoFile())).strip()
    if not src:
        return settings.DefaultRepo(), settings.DefaultRepoURL(
            settings.DefaultRepo())
    l = src.split('\n')
    if len(l) < 2:
        return settings.DefaultRepo(), settings.DefaultRepoURL(
            settings.DefaultRepo())
    return l[0], l[1]
示例#2
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
示例#3
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
示例#4
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
示例#5
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))
示例#6
0
def get(url):
    """
    A smart way to get identity from cache.

    If not cached in memory but found on disk - will cache from disk.
    """
    if has_idurl(url):
        return idget(url)
    else:
        try:
            partfilename = nameurl.UrlFilename(url)
        except:
            lg.out(1, "identitydb.get ERROR %s is incorrect" % str(url))
            return None
        filename = os.path.join(settings.IdentityCacheDir(), partfilename)
        if not os.path.exists(filename):
            lg.out(
                6, "identitydb.get file %s not exist" %
                os.path.basename(filename))
            return None
        idxml = bpio.ReadTextFile(filename)
        if idxml:
            idobj = identity.identity(xmlsrc=idxml)
            url2 = idobj.getIDURL()
            if url == url2:
                idset(url, idobj)
                return idobj

            else:
                lg.out(1, "identitydb.get ERROR url=%s url2=%s" % (url, url2))
                return None
        lg.out(6, "identitydb.get %s not found" % nameurl.GetName(url))
        return None
示例#7
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))
示例#8
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
示例#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 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())
示例#11
0
 def __init__(self, supplier_idurl, customer_idurl, needed_bytes,
              key_id=None, queue_subscribe=True):
     """
     """
     self.supplier_idurl = supplier_idurl
     self.customer_idurl = customer_idurl
     self.needed_bytes = needed_bytes
     self.key_id = key_id
     self.queue_subscribe = queue_subscribe
     self.do_calculate_needed_bytes()
     name = 'supplier_%s_%s' % (
         nameurl.GetName(self.supplier_idurl),
         diskspace.MakeStringFromBytes(self.needed_bytes).replace(' ', ''),
     )
     self.request_packet_id = None
     self.callbacks = {}
     try:
         st = bpio.ReadTextFile(settings.SupplierServiceFilename(
             idurl=self.supplier_idurl,
             customer_idurl=self.customer_idurl,
         )).strip()
     except:
         st = 'DISCONNECTED'
     automat.Automat.__init__(
         self,
         name,
         state=st,
         debug_level=_DebugLevel,
         log_events=_Debug,
         log_transitions=_Debug,
     )
     for cb in self.callbacks.values():
         cb(self.supplier_idurl, self.state, self.state)
示例#12
0
def Load(filepath=None):
    """
    This load the data from local file and call ``ReadIndex()`` method.
    """
    global _LoadingFlag
    if _LoadingFlag:
        return False
    if filepath is None:
        filepath = settings.BackupIndexFilePath()
    if not os.path.isfile(filepath):
        lg.warn('file %s not exist' % filepath)
        WriteIndex(filepath)
        # return False
    src = bpio.ReadTextFile(filepath)
    if not src:
        lg.out(2, 'backup_control.Load ERROR reading file %s' % filepath)
        return False
    inpt = cStringIO.StringIO(src)
    try:
        known_revision = int(inpt.readline().rstrip('\n'))
    except:
        lg.exc()
        return False
    raw_data = inpt.read()
    inpt.close()
    ret = ReadIndex(raw_data)
    if ret:
        commit(known_revision)
        backup_fs.Scan()
        backup_fs.Calculate()
    else:
        lg.warn('catalog index reading failed')
    return ret
示例#13
0
def rebuildLocalIdentity(skip_transports=[]):
    """
    If some transports was enabled or disabled we want to update identity
    contacts. Just empty all of the contacts and create it again in the same
    order.

    Also increase revision number by one - others may keep track of my modifications.
    """
    # getting current copy of local identity
    lid = getLocalIdentity()
    # remember the current identity - full XML source code
    current_identity_xmlsrc = lid.serialize()
    lg.out(4, 'my_id.rebuildLocalIdentity current identity is %d bytes long' % len(current_identity_xmlsrc))
    # create a full list of needed transport methods
    # to be able to accept incoming traffic from other nodes
    new_contacts, new_order = buildProtoContacts(lid, skip_transports=skip_transports)
    # erase current contacts from my identity
    lid.clearContacts()
    # add contacts data to the local identity
    lid.setContactsFromDict(new_contacts, new_order)
#    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
#        lid.setProtoContact(proto, contact)
    # update software version number
    vernum = bpio.ReadTextFile(settings.VersionNumberFile())
    repo, _ = misc.ReadRepoLocation()
    lid.version = (vernum.strip() + ' ' + repo.strip() + ' ' + bpio.osinfo().strip()).strip()
    # generate signature with changed content
    lid.sign()
    new_xmlsrc = lid.serialize()
    changed = False
    if new_xmlsrc == current_identity_xmlsrc:
        # no modifications in my identity - cool !!!
        lg.out(4, '    same revision: %s' % lid.revision)
    else:
        try:
            lid.revision = str(int(lid.revision) + 1)
        except:
            lg.exc()
            return False
        # generate signature again because revision were changed !!!
        lid.sign()
        lg.out(4, '    add revision: %s' % lid.revision)
        changed = True
        # remember the new identity
        setLocalIdentity(lid)
    lg.out(4, '    version: %s' % str(lid.version))
    lg.out(4, '    contacts: %s' % str(lid.contacts))
    lg.out(4, '    sources: %s' % str(lid.sources))
    if changed:
        lg.out(4, '    SAVING new identity #%s' % lid.revision)
        # finally saving modified local identity
        saveLocalIdentity()
    lg.out(4, '    my identity HAS %sBEEN changed !!!' % (('' if changed else 'NOT ')))
    lg.out(4, '\n' + new_xmlsrc + '\n')
    return changed
示例#14
0
 def doInit(self, arg):
     version_number = bpio.ReadTextFile(
         settings.VersionNumberFile()).strip()
     if _Debug:
         lg.out(
             4,
             'p2p_connector.doInit RevisionNumber=%s' % str(version_number))
     callback.insert_inbox_callback(0, inbox)
示例#15
0
 def doInit(self, *args, **kwargs):
     version_number = bpio.ReadTextFile(
         settings.VersionNumberFile()).strip()
     if _Debug:
         lg.out(
             _DebugLevel - 6,
             'p2p_connector.doInit RevisionNumber=%s' % str(version_number))
     callback.append_inbox_callback(inbox)
示例#16
0
def isMyKeyExists(keyfilename=None):
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    return os.path.exists(keyfilename)
示例#17
0
def connected_time(idurl):
    s = bpio.ReadTextFile(os.path.join(rating_dir(idurl), 'connected'))
    if not s:
        return 0
    try:
        return time.mktime(time.strptime(s, '%d%m%y %H:%M:%S'))
    except:
        lg.exc()
        return 0
示例#18
0
 def __init__(self,
              supplier_idurl,
              customer_idurl,
              needed_bytes,
              key_id=None,
              queue_subscribe=True):
     """
     """
     self.supplier_idurl = supplier_idurl
     self.customer_idurl = customer_idurl
     self.needed_bytes = needed_bytes
     self.key_id = key_id
     self.queue_subscribe = queue_subscribe
     if self.needed_bytes is None:
         total_bytes_needed = diskspace.GetBytesFromString(
             settings.getNeededString(), 0)
         num_suppliers = -1
         if self.customer_idurl == my_id.getLocalIDURL():
             num_suppliers = settings.getSuppliersNumberDesired()
         else:
             known_ecc_map = contactsdb.get_customer_meta_info(
                 customer_idurl).get('ecc_map')
             if known_ecc_map:
                 num_suppliers = eccmap.GetEccMapSuppliersNumber(
                     known_ecc_map)
         if num_suppliers > 0:
             self.needed_bytes = int(
                 math.ceil(2.0 * total_bytes_needed / float(num_suppliers)))
         else:
             raise Exception(
                 'not possible to determine needed_bytes value to be requested from that supplier'
             )
             # self.needed_bytes = int(math.ceil(2.0 * settings.MinimumNeededBytes() / float(settings.DefaultDesiredSuppliers())))
     name = 'supplier_%s_%s' % (
         nameurl.GetName(self.supplier_idurl),
         diskspace.MakeStringFromBytes(self.needed_bytes).replace(' ', ''),
     )
     self.request_packet_id = None
     self.callbacks = {}
     try:
         st = bpio.ReadTextFile(
             settings.SupplierServiceFilename(
                 idurl=self.supplier_idurl,
                 customer_idurl=self.customer_idurl,
             )).strip()
     except:
         st = 'DISCONNECTED'
     automat.Automat.__init__(
         self,
         name,
         state=st,
         debug_level=_DebugLevel,
         log_events=_Debug,
         log_transitions=_Debug,
     )
     for cb in self.callbacks.values():
         cb(self.supplier_idurl, self.state, self.state)
示例#19
0
文件: misc.py 项目: vesellov/devel
def readSupplierData(supplier_idurl, filename, customer_idurl):
    """
    Read a file from [BitDust data dir]/suppliers/[IDURL] folder.

    The file names right now is ['connected', 'disconnected',
    'listfiles'].
    """
    path = settings.SupplierPath(supplier_idurl, customer_idurl, filename)
    if not os.path.isfile(path):
        return ''
    return bpio.ReadTextFile(path).strip()
示例#20
0
 def identity_recover_v1(self, request):
     data = _request_data(request)
     private_key_source = data.get('private_key_source')
     if not private_key_source:
         private_key_local_file = data.get('private_key_local_file')
         if private_key_local_file:
             from system import bpio
             private_key_source = bpio.ReadTextFile(
                 bpio.portablePath(private_key_local_file))
     return api.identity_recover(private_key_source=private_key_source,
                                 known_idurl=data.get('known_idurl'))
示例#21
0
def update(idurl, xml_src):
    """
    This is a correct method to update an identity in the local cache.

    PREPRO need to check that date or version is after old one so not
    vulnerable to replay attacks.
    """
    idurl = id_url.to_original(idurl)
    try:
        newid = identity.identity(xmlsrc=xml_src)
    except:
        lg.exc()
        return False

    if not newid.isCorrect():
        lg.err("incorrect identity : %r" % idurl)
        return False

    try:
        if not newid.Valid():
            lg.err("identity not valid : %r" % idurl)
            return False
    except:
        lg.exc()
        return False

    filename = os.path.join(settings.IdentityCacheDir(),
                            nameurl.UrlFilename(idurl))
    if os.path.exists(filename):
        oldidentityxml = bpio.ReadTextFile(filename)
        oldidentity = identity.identity(xmlsrc=oldidentityxml)

        if oldidentity.publickey != newid.publickey:
            # TODO: SECURITY   add some kind of black list to be able to block certain IP's if the DDoS me
            lg.err(
                "new public key does not match with old, SECURITY VIOLATION : %r"
                % idurl)
            return False

        if oldidentity.signature != newid.signature:
            if _Debug:
                lg.out(
                    _DebugLevel, 'identitydb.update have new data for %r' %
                    nameurl.GetName(idurl))
        else:
            idset(idurl, newid)
            return True

    # publickeys match so we can update it
    bpio.WriteTextFile(filename, xml_src)
    idset(idurl, newid)

    return True
示例#22
0
def update(idurl, xml_src):
    """
    This is a correct method to update an identity in the local cache.

    PREPRO need to check that date or version is after old one so not
    vulnerable to replay attacks.
    """
    idurl = strng.to_bin(idurl)
    try:
        newid = identity.identity(xmlsrc=xml_src)
    except:
        lg.exc()
        return False

    if not newid.isCorrect():
        lg.out(1, "identitydb.update ERROR incorrect identity : %r" % idurl)
        return False

    try:
        if not newid.Valid():
            lg.out(1,
                   "identitydb.update ERROR identity not Valid : %r" % idurl)
            return False
    except:
        lg.exc()
        return False

    filename = os.path.join(settings.IdentityCacheDir(),
                            nameurl.UrlFilename(idurl))
    if os.path.exists(filename):
        oldidentityxml = bpio.ReadTextFile(filename)
        oldidentity = identity.identity(xmlsrc=oldidentityxml)

        if oldidentity.publickey != newid.publickey:
            lg.out(
                1,
                "identitydb.update ERROR new publickey does not match old, SECURITY VIOLATION : %r"
                % idurl)
            return False

        if oldidentity.signature != newid.signature:
            lg.out(
                6, 'identitydb.update have new data for %r' %
                nameurl.GetName(idurl))
        else:
            idset(idurl, newid)
            return True

    # publickeys match so we can update it
    bpio.WriteTextFile(filename, xml_src)
    idset(idurl, newid)

    return True
示例#23
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()
示例#24
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
示例#25
0
    def doRequestServers(self, *args, **kwargs):
        """
        Action method.
        """
        login = bpio.ReadTextFile(settings.UserNameFilename())

        def _cb(xmlsrc, idurl, host):
            if not xmlsrc:
                if self.preferred_servers and host in self.preferred_servers:
                    if self.preferred_servers[0] == host:
                        self.free_idurls.insert(0, idurl)
                    else:
                        self.free_idurls.insert(1, idurl)
                else:
                    self.free_idurls.append(idurl)
                self.registrations.remove(idurl)
                self.automat('id-not-exist', idurl)
            else:
                lg.out(4, '                EXIST: %s' % idurl)
                self.registrations.remove(idurl)
                self.automat('id-exist', idurl)

        def _eb(err, idurl, host):
            lg.out(4, '            NOT EXIST: %s' % idurl)
            if self.preferred_servers and host in self.preferred_servers:
                if self.preferred_servers[0] == host:
                    self.free_idurls.insert(0, idurl)
                else:
                    self.free_idurls.insert(1, idurl)
            else:
                self.free_idurls.append(idurl)
            self.registrations.remove(idurl)
            self.automat('id-not-exist', idurl)

        for host in self.good_servers:
            webport, tcpport = known_servers.by_host().get(
                host,
                (settings.IdentityWebPort(), settings.IdentityServerPort()))
            if webport == 80:
                webport = ''
            idurl = nameurl.UrlMake('http', strng.to_text(host), webport,
                                    login + '.xml')
            lg.out(4, '    %s' % idurl)
            d = net_misc.getPageTwisted(idurl, timeout=7)
            d.addCallback(_cb, idurl, host)
            d.addErrback(_eb, idurl, host)
            self.registrations.append(idurl)
        lg.out(
            4, 'id_registrator.doRequestServers login=%s registrations=%d' %
            (login, len(self.registrations)))
示例#26
0
def getTransportOrder():
    """
    Read and validate tranports from [BitDust data dir]\metadata\torder file.
    """
    global _ValidTransports
    lg.out(8, 'my_id.getTransportOrder')
    order = bpio.ReadTextFile(settings.DefaultTransportOrderFilename()).strip()
    if order == '':
        orderL = _ValidTransports
    else:
        orderL = order.split(' ')
        orderL = validateTransports(orderL)
    setTransportOrder(orderL)
    return orderL
示例#27
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))
示例#28
0
 def doInit(self, arg):
     """
     Action method.
     """
     self.listen_port = arg
     if udp.proto(self.listen_port):
         udp.proto(self.listen_port).add_callback(self._datagramReceived)
     else:
         lg.err('udp port %s is not opened' % self.listen_port)
     try:
         externalPort = int(
             bpio.ReadTextFile(settings.ExternalUDPPortFilename()))
     except:
         externalPort = self.listen_port
     dht_service.set_node_data('stun_port', externalPort)
示例#29
0
文件: key.py 项目: hack-bitdust/devel
def LoadMyKey(keyfilename=None):
    global _MyRsaKey
    global _MyKeyObject
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    if os.path.exists(keyfilename):
        _MyKeyObject = keys.Key.fromFile(keyfilename)
        _MyRsaKey = _MyKeyObject.keyObject
        lg.out(4, 'key.InitMyKey loaded private key from %s' % (keyfilename))
        return ValidateKey()
    return False
示例#30
0
文件: key.py 项目: hack-bitdust/devel
def GenerateNewKey(keyfilename=None):
    global _MyKeyObject
    global _MyRsaKey
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    lg.out(4, 'key.InitMyKey generate new private key')
    _MyRsaKey = RSA.generate(settings.getPrivateKeySize(), os.urandom)
    _MyKeyObject = keys.Key(_MyRsaKey)
    keystring = _MyKeyObject.toString('openssh')
    bpio.WriteFile(keyfilename, keystring)
    lg.out(4, '    wrote %d bytes to %s' % (len(keystring), keyfilename))