Пример #1
0
def incoming_message(request, message_text):
    lg.out(16, 'dbwrite.incoming_message of %d bytes, type=%s' %
           (len(message_text), type(message_text)))
    from django.shortcuts import get_object_or_404
    from django.utils.html import escape
    from django.contrib.auth.models import User
    from web.jqchatapp.models import Room, Message, RoomMember
    from contacts import contactsdb
    from userid import my_id
    from lib import nameurl
    idurl = request.OwnerID
    try:
        ThisUser = User.objects.get(username=my_id.getIDName())
    except:
        lg.out(16, '        SKIP, seems user did not logged in')
        # lg.exc()
        return
    try:
        ThisRoom = get_object_or_404(Room, idurl=idurl)
    except:
        nik = contactsdb.get_correspondent_nickname(idurl)
        ThisRoom = Room(idurl=idurl,
                        name=(nik or nameurl.GetName(idurl)))
        ThisRoom.save()
    message_text = escape(unicode(message_text))
    Message.objects.create_message(idurl, ThisRoom, message_text)
    RoomMember.objects.create_member(idurl=idurl,
                                     # name=nameurl.GetName(idurl),
                                     room=ThisRoom)
Пример #2
0
def incoming_message(request, priv_message_object, message_text):
    lg.out(6, 'dbwrite.incoming_message of %d bytes, type=%s' %
           (len(message_text), type(message_text)))
    from django.shortcuts import get_object_or_404
    from django.utils.html import escape
    from django.contrib.auth.models import User
    from web.jqchatapp.models import Room, Message, RoomMember
    from contacts import contactsdb
    from userid import my_id
    from lib import nameurl
    idurl = request.OwnerID
    try:
        ThisUser = User.objects.get(username=my_id.getIDName())
    except:
        lg.out(16, '        SKIP, seems user did not logged in')
        # lg.exc()
        return
    try:
        ThisRoom = get_object_or_404(Room, idurl=idurl)
    except:
        nik = contactsdb.get_correspondent_nickname(idurl)
        ThisRoom = Room(idurl=idurl,
                        name=(nik or nameurl.GetName(idurl)))
        ThisRoom.save()
    message_text = escape(unicode(message_text))
    Message.objects.create_message(idurl, ThisRoom, message_text)
    if not RoomMember.objects.find_member(idurl=idurl):
        RoomMember.objects.create_member(idurl=idurl,
                                         # name=nameurl.GetName(idurl),
                                         room=ThisRoom)
Пример #3
0
 def _server_replied(htmlsrc, host, pos):
     if _Debug:
         lg.out(_DebugLevel, 'id_rotator.doSelectNewIDServer._server_replied %r' % host)
     webport, _ = target_servers[host]
     if webport == 80:
         webport = ''
     new_idurl = nameurl.UrlMake('http', strng.to_text(host), webport, my_id.getIDName() + '.xml')
     d = net_misc.getPageTwisted(new_idurl, timeout=10)
     d.addCallback(_new_idurl_exist, new_idurl, pos)
     d.addErrback(_new_idurl_not_exist, new_idurl)
Пример #4
0
def cmd_identity(opts, args, overDict, running):
    from userid import my_id
    from main import settings
    settings.init()
    my_id.init()

    if args[0] == 'idurl':
        if my_id.isLocalIdentityReady():
            print_text(my_id.getLocalID())
        else:
            print_text('local identity is not exist')
        return 0

    if len(args) == 1 or args[1].lower() in ['info', '?', 'show', 'print']:
        if my_id.isLocalIdentityReady():
            print_text(my_id.getLocalIdentity().serialize())
        else:
            print_text('local identity is not exist')
        return 0

    def _register():
        if len(args) <= 2:
            return 2
        pksize = settings.getPrivateKeySize()
        if len(args) > 3:
            try:
                pksize = int(args[3])
            except:
                print_text('incorrect private key size\n')
                return 0
        from automats import automat
        from main import initializer
        from lib import misc
        if not misc.ValidUserName(args[2]):
            return 0
        initializer.A('run-cmd-line-register', {'username': args[2], 'pksize': pksize})
        reactor.run()
        automat.objects().clear()
        if my_id.isLocalIdentityReady():
            print_text('new identity created:')
            print_text(my_id.getLocalIdentity().serialize())
        else:
            print_text('identity creation FAILED')
        return 0

    def _recover():
        from system import bpio
        from lib import nameurl
        if len(args) < 3:
            return 2
        src = bpio.ReadBinaryFile(args[2])
        if len(src) > 1024 * 10:
            print_text('file is too big for private key')
            return 0
        try:
            lines = src.split('\n')
            idurl = lines[0]
            txt = '\n'.join(lines[1:])
            if idurl != nameurl.FilenameUrl(nameurl.UrlFilename(idurl)):
                idurl = ''
                txt = src
        except:
            idurl = ''
            txt = src
        if idurl == '' and len(args) > 3:
            idurl = args[3]
        if idurl == '':
            print_text('BitDust need to know your IDURL to recover your account\n')
            return 2
        from automats import automat
        from main import initializer
        initializer.A('run-cmd-line-recover', {'idurl': idurl, 'keysrc': txt})
        reactor.run()
        automat.objects().clear()
        if my_id.isLocalIdentityReady():
            print_text('your identity were restored:')
            print_text(my_id.getLocalIdentity().serialize())
        else:
            print_text('identity recovery FAILED')
        return 0

    if args[1].lower() in ['create', 'new', 'register', 'generate', ]:
        if my_id.isLocalIdentityReady():
            print_text('local identity [%s] already exist\n' % my_id.getIDName())
            return 1
        if running:
            print_text('BitDust is running at the moment, need to stop the software at first\n')
            return 0
        return _register()

    if args[1].lower() in ['restore', 'recover', 'read', 'load', ]:
        if running:
            print_text('BitDust is running at the moment, need to stop the software at first\n')
            return 0
        return _recover()

    if args[1].lower() in ['delete', 'remove', 'erase', 'del', 'rm', 'kill']:
        if running:
            print_text('BitDust is running at the moment, need to stop the software at first\n')
            return 0
        oldname = my_id.getIDName()
        my_id.forgetLocalIdentity()
        my_id.eraseLocalIdentity()
        print_text('local identity [%s] is no longer exist\n' % oldname)
        return 0

    return 2
Пример #5
0
def build_json_conversation(**record):
    conv = {
        'key_id': '',
        'label': '',
        'state': 'OFFLINE',
        'index': None,
        'id': None,
        'name': None,
        'repr': None,
        'events': None,
    }
    conv.update(record)
    if conv['type'] == 'private_message':
        local_key_id1, _, local_key_id2 = conv['conversation_id'].partition(
            '&')
        try:
            local_key_id1 = int(local_key_id1)
            local_key_id2 = int(local_key_id2)
        except:
            lg.exc()
            return None
        usr1 = my_keys.get_local_key(local_key_id1)
        usr2 = my_keys.get_local_key(local_key_id2)
        if not usr1 or not usr2:
            # lg.warn('%r %r : not found sender or recipient key_id for %r' % (usr1, usr2, conv, ))
            return None
        usr1 = usr1.replace('master$', '')
        usr2 = usr2.replace('master$', '')
        idurl1 = global_id.glob2idurl(usr1, as_field=True)
        idurl2 = global_id.glob2idurl(usr2, as_field=True)
        conv_key_id = None
        conv_label = None
        user_idurl = None
        if (id_url.is_cached(idurl1) and idurl1 == my_id.getIDURL()
            ) or usr1.split('@')[0] == my_id.getIDName():
            user_idurl = idurl2
            conv_key_id = global_id.UrlToGlobalID(idurl2, include_key=True)
            conv_label = conv_key_id.replace('master$', '').split('@')[0]
        if (id_url.is_cached(idurl2) and idurl2 == my_id.getIDURL()
            ) or usr2.split('@')[0] == my_id.getIDName():
            user_idurl = idurl1
            conv_key_id = global_id.UrlToGlobalID(idurl1, include_key=True)
            conv_label = conv_key_id.replace('master$', '').split('@')[0]
        if conv_key_id:
            conv['key_id'] = conv_key_id
        if conv_label:
            conv['label'] = conv_label
        else:
            conv['label'] = conv_key_id
        if user_idurl:
            on_st = online_status.getInstance(user_idurl, autocreate=False)
            if on_st:
                conv.update(on_st.to_json())
    elif conv['type'] == 'group_message' or conv['type'] == 'personal_message':
        local_key_id, _, _ = conv['conversation_id'].partition('&')
        try:
            local_key_id = int(local_key_id)
        except:
            lg.exc()
            return None
        key_id = my_keys.get_local_key(local_key_id)
        if not key_id:
            # lg.warn('key_id was not found for %r' % conv)
            return None
        conv['key_id'] = key_id
        conv['label'] = my_keys.get_label(key_id) or key_id
        gm = group_member.get_active_group_member(key_id)
        if gm:
            conv.update(gm.to_json())
    return conv
Пример #6
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')
Пример #7
0
def username():
    return my_id.getIDName()
Пример #8
0
def username():
    return my_id.getIDName()
Пример #9
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')