Пример #1
0
def download_info():
    def _done(src, result):
        lg.out(6, 'os_windows_update.download_info.done ')
        lines = src.split('\n')
        files_dict = {}
        for line in lines:
            words = line.split(' ')
            if len(words) < 2:
                continue
            files_dict[words[1].strip()] = words[0].strip()
        result.callback(files_dict)
        return src

    def _fail(x, result):
        lg.out(1, 'os_windows_update.download_info FAILED')
        result.errback(Exception('error downloading info'))
        return x

    repo, locationURL = misc.ReadRepoLocation()
    url = locationURL + settings.FilesDigestsFilename()
    lg.out(6, 'os_windows_update.download_info ' + str(url))
    result = Deferred()
    d = net_misc.getPageTwisted(url)
    d.addCallback(_done, result)
    d.addErrback(_fail, result)
    return result
Пример #2
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
Пример #3
0
def download_and_replace_starter(output_func=None):
    repo, locationURL = misc.ReadRepoLocation()
    url = locationURL + settings.WindowsStarterFileName()
    lg.out(6, 'os_windows_update.download_and_replace_starter ' + str(url))
    result = Deferred()

    def _done(x, filename):
        try:
            fin = open(filename, 'rb')
            src = strng.to_text(fin.read())
            fin.close()
        except:
            if output_func:
                output_func('error opening downloaded starter file')
            result.errback(Exception('error opening downloaded starter file'))
            return
        local_filename = os.path.join(GetLocalDir(), settings.WindowsStarterFileName())
        bpio.backup_and_remove(local_filename)
        try:
            os.rename(filename, local_filename)
            lg.out(4, 'os_windows_update.download_and_replace_starter  file %s was updated' % local_filename)
        except:
            lg.out(1, 'os_windows_update.download_and_replace_starter ERROR can not rename %s to %s ' % (filename, local_filename))
            lg.exc()
            result.errback(Exception('can not rename the file ' + filename))
            return
        python27dll_path = os.path.join(GetLocalDir(), 'python27.dll')
        if not os.path.exists(python27dll_path):
            lg.out(4, 'os_windows_update.download_and_replace_starter file "python27.dll" not found download from "%s" repo' % repo)
            url = settings.DefaultRepoURL(repo) + 'python27.dll'
            d = net_misc.downloadHTTP(url, python27dll_path)
            d.addCallback(_done_python27_dll, filename)
            d.addErrback(_fail, filename)
            return
        result.callback(1)

    def _done_python27_dll(x, filename):
        lg.out(4, 'os_windows_update.download_and_replace_starter file %s was updated' % filename)
        result.callback(1)

    def _fail(x, filename):
        lg.out(1, 'os_windows_update.download_and_replace_starter FAILED')
        if output_func:
            try:
                output_func(x.getErrorMessage())
            except:
                output_func('error downloading starter')
        try:
            os.remove(filename)
        except:
            lg.out(1, 'os_windows_update.download_and_replace_starter ERROR can not remove ' + filename)
        result.errback(Exception('error downloading starter'))

    fileno, filename = tmpfile.make('all', extension='.starter')
    os.close(fileno)
    d = net_misc.downloadHTTP(url, filename)
    d.addCallback(_done, filename)
    d.addErrback(_fail, filename)
    return result
Пример #4
0
def step0():
    lg.out(4, 'os_windows_update.step0')
    global _UpdatingInProgress
    if _UpdatingInProgress:
        lg.out(6, 'os_windows_update.step0  _UpdatingInProgress is True, skip.')
        return

    repo, locationURL = misc.ReadRepoLocation()
    src = bpio.ReadTextFile(settings.RepoFile())
    if src == '':
        bpio.WriteTextFile(settings.RepoFile(), u'%s\n%s' % (repo, locationURL))

    _UpdatingInProgress = True
    d = download_version()
    d.addCallback(step1)
    d.addErrback(fail)
Пример #5
0
def download_version():
    repo, locationURL = misc.ReadRepoLocation()
    url = locationURL + settings.CurrentVersionDigestsFilename()
    lg.out(6, 'os_windows_update.download_version ' + str(url))
    return net_misc.getPageTwisted(url)
Пример #6
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 ip == '':
        ip = misc.readExternalIP(
        )  # bpio.ReadTextFile(settings.ExternalIPFilename())
    if 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('http://localhost/' + name.lower() + '.xml')
    for idurl in idurls:
        ident.sources.append(idurl.encode("ascii").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'] = 'tcp://' + ip + ':' + str(
                settings.getTCPPort())
            new_order.append('tcp')
        if settings.enableUDP() and settings.enableUDPreceiving():
            x, servername, x, x = nameurl.UrlParse(ident.sources[0])
            new_contacts['udp'] = 'udp://%s@%s' % (name.lower(), servername)
            new_order.append('udp')
        if settings.enableHTTP() and settings.enableHTTPreceiving():
            new_contacts['http'] = 'http://' + ip + ':' + 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.date = time.strftime('%b %d, %Y')
    ident.postage = "1"
    ident.revision = "0"
    # 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.publickey = key.MyPublicKey()
    # generate signature
    ident.sign()
    # validate new identity
    if not ident.Valid():
        lg.warn('generated identity is not valid !!!')
    return ident
Пример #7
0
def rebuildLocalIdentity(identity_object=None,
                         skip_transports=[],
                         new_sources=None,
                         revision_up=False,
                         new_revision=None,
                         save_identity=True):
    """
    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.
    """
    # remember the current identity - full XML source code
    current_identity_xmlsrc = getLocalIdentity().serialize()
    if _Debug:
        lg.out(
            _DebugLevel,
            'my_id.rebuildLocalIdentity current identity is %d bytes long new_revision=%r'
            % (
                len(current_identity_xmlsrc),
                new_revision,
            ))
    # getting a copy of local identity to be modified or another object to be used
    lid = identity_object or identity.identity(xmlsrc=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)
    # if I need to rotate my sources do it now
    if new_sources:
        lid.setSources(new_sources)
    # update software version number
    # TODO: need to read GIT commit hash here instead of version
    vernum = strng.to_bin(bpio.ReadTextFile(
        settings.VersionNumberFile())).strip()
    repo, _ = misc.ReadRepoLocation()
    lid.setVersion((vernum + b' ' + strng.to_bin(repo.strip()) + b' ' +
                    strng.to_bin(bpio.osinfo().strip()).strip()))
    # generate signature with changed content
    lid.sign()
    new_xmlsrc = lid.serialize()
    changed = False
    if new_xmlsrc != current_identity_xmlsrc or revision_up:
        if not new_revision:
            new_revision = lid.getRevisionValue() + 1
        try:
            lid.setRevision(new_revision)
        except:
            lg.exc()
            return False
        # generate signature again because revision were changed !!!
        lid.sign()
        if _Debug:
            lg.out(_DebugLevel, '    incremented revision: %s' % lid.revision)
        changed = True
    else:
        # no modifications in my identity - cool !!!
        if _Debug:
            lg.out(_DebugLevel, '    same revision: %r' % lid.revision)
    if _Debug:
        lg.out(_DebugLevel, '    version: %r' % lid.version)
        lg.out(_DebugLevel, '    contacts: %r' % lid.contacts)
        lg.out(_DebugLevel,
               '    sources: %r' % lid.getSources(as_originals=True))
    if changed:
        if save_identity:
            # finally saving modified local identity
            if _Debug:
                lg.out(_DebugLevel,
                       '    SAVING new identity #%s' % lid.revision)
            # remember the new identity
            setLocalIdentity(lid)
            saveLocalIdentity()
            # NOW TEST IT!
            # forgetLocalIdentity()
            # loadLocalIdentity()
            if _Debug:
                lg.out(
                    _DebugLevel, '    LOCAL IDENTITY CORRECT: %r' %
                    getLocalIdentity().isCorrect())
                lg.out(
                    _DebugLevel, '    LOCAL IDENTITY VALID: %r' %
                    getLocalIdentity().Valid())
    lg.info('my identity HAS %sBEEN changed' % (('' if changed else 'NOT ')))
    if _Debug:
        lg.out(_DebugLevel, '\n' + strng.to_text(lid.serialize()) + '\n')
    return changed