Пример #1
0
 def getBackupAddMap(self):
     """"""
     data = None
     if Io.file_exists(self.addmapPath + Kirmah.EXT):
         call = " ".join(
             [
                 Sys.executable,
                 "kirmah-cli.py",
                 "dec",
                 "-qf",
                 self.addmapPath + Kirmah.EXT,
                 "-z",
                 "-r",
                 "-m",
                 "-o",
                 self.addmapPath,
                 "-k",
                 self.idxu.index.keyPath,
             ]
         )
         print(call)
         Sys.sysCall(call)
         data = jloads(Io.get_data(self.addmapPath))
         Io.removeFile(self.addmapPath)
     return data
Пример #2
0
 def getCountParts(self, fromPath):
     """"""
     fsize = Sys.getsize(fromPath)
     count = Sys.ceil(fsize / 19710000)
     minp, maxp = 52, 62
     if fsize < 4800000:
         minp, maxp = 8, 16
     elif fsize < 22200000:
         minp, maxp = 16, 22
     elif fsize < 48000000:
         minp, maxp = 22, 32
     elif fsize < 222000000:
         minp, maxp = 32, 42
     if count < minp:
         count = choice(list(range(minp, maxp)))
     if not count > 62:
         return count
     else:
         raise Exception(
             fromPath
             + " size exceeds limits (max : "
             + formatBytes(self.ck.psize * 62)
             + " ["
             + str(self.ck.psize * 64)
             + " bytes])"
         )
Пример #3
0
    def update(self):
        """"""
        self.switchFileAccount(self.conf.profile)
        try:
            if self.idx != None :
                if not isinstance(self.idx,bytes):
                    self.idx = Io.bytes(self.idx)                
                self.delids.append(self.idx)
        except Exception as e :
            Sys.dprint('error : ')
            Sys.dprint(e)   

        self.index.fixDuplicateIds()
        #~ self.index.fixAccount('gmail5')
        self.index.encrypt()
        msgIndex    = self.mb.buildIndex(self.pathIdx)
        _, self.idx = self.ih.send(msgIndex.as_string(), self.rootBox)
        date        = self.ih.headerField(self.idx, 'date', True)
        self.conf.sets((['uid'  , self.idx              , 'index'],
                       ['date' , date                   , 'index'],
                       ['time' , str(Sys.datetime.now()), 'index']))
        
        Sys.pwlog([(' Index updated ('  , Const.CLZ_0),
                   (str(int(self.idx))  , Const.CLZ_2),
                   (') '                , Const.CLZ_0),
                   (str(date)           , Const.CLZ_7, True)])
        
        try :
            self.ih.delete(self.delids, True)       
        except :
            Sys.dprint('error : ')
            Sys.dprint(e)
        self.ih.clearTrash()
        return True
Пример #4
0
 def onCommandInfo(self):
     """"""
     key = self.getMatchKey()
     if key is not None:
         Sys.clear()
         self.pheader()
         self.impst.getInfo(int(self.a[1]))
Пример #5
0
 def save(self,path=None,notAssign=False):
     """"""
     path = path if path is not None else self.path
     Io.set_data(path, '# last updated : '+str(Sys.datetime.now())+Const.LF+self.toString())
     call = ' '.join(['python3', 'kirmah-cli.py', 'enc', '-qf', path, '-z', '-r', '-m', '-o', path+'.kmh', '-k', self.keyPath ])
     Sys.sysCall(call)
     Io.removeFile(path)
     if not notAssign : self.path = path
Пример #6
0
 def pheader(self):
     self.Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)
     self.Cli.printHeaderTitle(self.Cli.conf.PRG_CLI_NAME)
     self.Cli.printHeaderPart("account", self.account)
     self.Cli.printHeaderPart("index", self.uid)
     self.Cli.printHeaderPart("box", self.rootBox)
     Sys.echo(self.date, Sys.Clz.fgB7, True, True)
     self.Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)
Пример #7
0
 def createDefaultKeyIfNone(self):
     """"""
     kpath = self.getDefaultKeyPath()
     if not Io.file_exists(kpath):
         if Sys.isUnix():
             if not Sys.isdir(conf.DEFVAL_UKEY_PATH):
                 Sys.mkdir_p(conf.DEFVAL_UKEY_PATH)
                 Io.set_data(kpath, KeyGen(conf.DEFVAL_UKEY_LENGHT).key)
     self.selectKey(kpath)
Пример #8
0
 def on_new_file_source(self, fc, data=None):
     """"""
     try:
         self.app.setSourceFile(fc.get_filename())
         self.IS_SOURCE_DEF = True
     except FileNotFoundException as e:
         Sys.eprint('FileNotFoundException :' + str(fc.get_filename()), Const.ERROR)
         self.IS_SOURCE_DEF = False
     self.refreshProceed()
Пример #9
0
def main():
    try:
        c = 0
        Cli('.'+Sys.sep)
    except Exception as e :
        Sys.pwarn((('main : ',(str(e),Sys.CLZ_ERROR_PARAM), ' !'),), True)
        #~ raise e
        c = 1
    return c
Пример #10
0
def main():
    try:
        c = 0
        AppGui()
    except Exception as e:
        Sys.pwarn((('main : ',(str(e),Sys.CLZ_ERROR_PARAM), ' !'),), True)
        raise e
        c = 1
    return c
Пример #11
0
 def createDefaultKeyIfNone(self):
     """"""
     kpath = self.getDefaultKeyPath()
     if not Io.file_exists(kpath):
         if Sys.isUnix() :
             if not Sys.isdir(conf.DEFVAL_UKEY_PATH) :
                 Sys.mkdir_p(conf.DEFVAL_UKEY_PATH)
                 Io.set_data(kpath, KeyGen(conf.DEFVAL_UKEY_LENGHT).key)
     self.selectKey(kpath)
Пример #12
0
 def printHeaderPart(label,value):
     """"""
     a, b, c = ' [',':' ,'] '
     Sys.echo(a    , Sys.CLZ_HEAD_SEP, False)
     Sys.echo(label, Sys.CLZ_HEAD_KEY, False)
     Sys.echo(b    , Sys.CLZ_HEAD_SEP, False)
     Sys.echo(value, Sys.CLZ_HEAD_VAL, False)
     Sys.echo(c    , Sys.CLZ_HEAD_SEP, False)
     return [(a,Const.CLZ_HEAD_SEP),(label,Const.CLZ_HEAD_KEY),(b,Const.CLZ_HEAD_SEP),(value,Const.CLZ_HEAD_VAL),(c,Const.CLZ_HEAD_SEP)]
Пример #13
0
 def add(self, key, label, count, ext='', usr='', cat='', fhash='', size=0, account=''):
     """Add an entry to the index
     """
     if self.get(fhash) == None :
         self.dic[fhash] = (self.id, fhash, label, size, count, ext, usr, cat, account, key)
         self.id +=1
         return self.id-1 
     else :
        Sys.dprint(label+' already exist')
Пример #14
0
 def build(self):
     Sys.pwlog([(' Reading index, please wait...', Const.CLZ_7, True)])
     self.index = ImpraIndex(self.conf.get('key','keys'), self.pathIdx, self.getIndexDefaultCatg(), self.getAccountList())
     defUsers   = self.conf.get('users','catg')
     if not ImpraIndex.SEP_KEY_INTERN+'users' in self.index.dic:
         self.index.dic[ImpraIndex.SEP_KEY_INTERN+'users'] = {}
     for k in self.index.dic[ImpraIndex.SEP_KEY_INTERN+'users']:
         if self.index.dic[ImpraIndex.SEP_KEY_INTERN+'users'][k] not in [ i.strip() for i in defUsers.split(',')]:
             self.conf.set('users',defUsers+', '+self.index.dic[ImpraIndex.SEP_KEY_INTERN+'users'][k],'catg')
Пример #15
0
 def on_new_file_source(self, fc, data=None):
     """"""
     try:
         self.app.setSourceFile(fc.get_filename())
         self.IS_SOURCE_DEF = True
     except FileNotFoundException as e:
         Sys.eprint('FileNotFoundException :' + str(fc.get_filename()),
                    Const.ERROR)
         self.IS_SOURCE_DEF = False
     self.refreshProceed()
Пример #16
0
 def halt_thread(self, *args):
     Sys.wlog(Sys.dprint())
     Sys.pwarn(('thread interrupt',), False)
     self.get('button1').set_sensitive(False)
     if self.thkmh is not None and self.thkmh.isAlive():
         self.thkmh.cancel()
     else :
         self.textbuffer.insert_at_cursor('Kmh Thread is not Alive\n')
         self.on_proceed_end(True)
         self.pb.hide()
         self.show_log()
Пример #17
0
 def stop(self):
     """"""
     if self.isAlive():
         self.cancel()
         if current_thread().getName()==self.getName():
             try:
                 self.emit('interrupted')
                 Sys.thread_exit()
             except RuntimeError as e :
                 print(str(self.getName()) + ' COULD NOT BE TERMINATED')
                 raise e
Пример #18
0
 def stop(self):
     """"""
     if self.isAlive():
         self.cancel()
         if current_thread().getName() == self.getName():
             try:
                 self.emit("interrupted")
                 Sys.thread_exit()
             except RuntimeError as e:
                 print(str(self.getName()) + ' COULD NOT BE TERMINATED')
                 raise e
Пример #19
0
 def halt_thread(self, *args):
     Sys.wlog(Sys.dprint())
     Sys.pwarn(('thread interrupt', ), False)
     self.get('button1').set_sensitive(False)
     if self.thkmh is not None and self.thkmh.isAlive():
         self.thkmh.cancel()
     else:
         self.textbuffer.insert_at_cursor('Kmh Thread is not Alive\n')
         self.on_proceed_end(True)
         self.pb.hide()
         self.show_log()
Пример #20
0
 def load_profile(self):
     """"""
     if self.check_profile(self.o.active_profile):
         Sys.dprint(" ", end=" ")
         Sys.echo(" == profile `", Sys.Clz.bg2 + Sys.Clz.fgb7, False)
         Sys.echo(self.o.active_profile, Sys.Clz.bg2 + Sys.Clz.fgB3, False)
         Sys.echo("` loaded == ", Sys.Clz.bg2 + Sys.Clz.fgb7)
         Sys.dprint()
         self.ini.set("profile", self.o.active_profile)
         self.ini.save()
     else:
         self.check_profile(self.o.active_profile, True)
Пример #21
0
 def clearTrash(self):
     """"""
     self.cnx.select(self.BOXS[self.TRASH])
     ids = self.search('ALL',True)
     if len(ids) > 0 and ids[0]!='' and ids[0]!=None:
         delids = ImapHelper._getIdsList(ids)            
         status, resp = self.cnx.uid('store', delids, self.FLAGS, self.DELETED )
         
         Sys.pwlog([(' Deleting msg ', Const.CLZ_0),
                    (delids                    , Const.CLZ_1),
                    (' '+status              , Const.CLZ_7, True)])
         self.cnx.expunge()
     self.cnx.select(self.rootBox)
Пример #22
0
 def remove(self):
     """"""
     self._getId()
     try:
         if self.idx!= None : self.delids.append(Io.bytes(self.idx))
         self.ih.delete(self.delids, True)
         self.idx = None
     except Exception as e :
         Sys.dprint('error : ')
         Sys.dprint(e)
         
     self.ih.clearTrash()
     self.removeLocal()
Пример #23
0
 def on_refresh(self, btn, data=None):
     """"""
     self.BLOCK_REPOPULATE = True
     self.get('treestore1').clear()
     if btn is not None :
         Sys.cli_emit_progress(0)
         self.get('checkbutton1').set_sensitive(False)
         self.get('checkbutton1').set_active(False)
         self.unselect_actions()
         self.get('button9').set_sensitive(False)
         self.launch_action(ImpraThread.TASK_REFRESH, [])
     else :
         self.populate_index()
Пример #24
0
 def setDestFile(self, path):
     """"""
     if path is not None :
         self.dst = ''.join([path, Sys.sep, '' if self.src is None else Sys.basename(self.src)])
         if self.encmode:
             self.dst = ''.join([self.dst, Kirmah.EXT if not self.splitmode else Kirmah.EXT_TARK])
         else :
             self.dst, ext = Sys.getFileExt(self.dst)
             if not ext == (Kirmah.EXT if not self.splitmode else Kirmah.EXT_TARK):
                 self.dst += ext
         #~ if Io.file_exists(self.dst):
             #~ raise FileNeedOverwriteException(self.dst)
     else : self.dst = None
Пример #25
0
 def setDestFile(self, path):
     """"""
     if path is not None :
         self.dst = ''.join([path, Sys.sep, '' if self.src is None else Sys.basename(self.src)])
         if self.encmode:
             self.dst = ''.join([self.dst, Kirmah.EXT if not self.splitmode else Kirmah.EXT_TARK])
         else :
             self.dst, ext = Sys.getFileExt(self.dst)
             if not ext == (Kirmah.EXT if not self.splitmode else Kirmah.EXT_TARK):
                 self.dst += ext
         #~ if Io.file_exists(self.dst):
             #~ raise FileNeedOverwriteException(self.dst)
     else : self.dst = None
Пример #26
0
    def populate_index(self):
        """"""
        self.BLOCK_REPOPULATE = False
        if self.index is None or self.index != self.thimpra.impst.idxu.index :
            self.index = self.thimpra.impst.idxu.index
        data     = sorted([(self.index.dic.get(k),k) for i, k in enumerate(self.index.dic) if not k.startswith(self.index.SEP_KEY_INTERN)], reverse=False, key=lambda lst:lst[0][self.index.UID])
        store    = self.get('treestore1')
        store.clear()
        drow     = None
        i        = 0
        tsize    = 0
        psize    = 0
        accounts = self.thimpra.impst.idxu.getAccountList()
        allCatg, allUsers, allAccounts, tmp = [], [], [ accounts[a] for a in accounts], ''
        for row, key in data :
            
            tsize += row[self.index.SIZE]
            if self.filterIds==None or row[self.index.UID] in self.filterIds:
            
                drow = list(row[:-1])
                psize += row[self.index.SIZE]

                if drow[self.index.CATG] not in allCatg :
                    allCatg.append(drow[self.index.CATG])
                tmp = self.index.getUser(drow[self.index.USER])                
                if tmp not in allUsers :
                    allUsers.append(tmp)
                drow[self.index.PARTS]     = ('%s' % drow[self.index.PARTS]).rjust(2,' ')
                drow[self.index.UID]       = ('%s' % drow[self.index.UID]).rjust(4,' ')
                drow[self.index.HASH]      = '%s' % drow[self.index.HASH][0:6]+'…'
                drow[self.index.SIZE]      = Sys.readableBytes(row[self.index.SIZE]).rjust(11,' ')+'  '
                drow[self.index.USER]      = self.index.getUser(drow[self.index.USER])
                drow[self.index.ACCOUNT]   = self.index.acclist[drow[self.index.ACCOUNT]]
                drow.append('#222222' if i%2!=0 else '#1C1C1C')
                drow.append('#640000' if i%2!=0 else '#900000')
                store.append(None, drow)
                i += 1
                self.progressbar.set_fraction(10+i*90/len(data)/100.0)
            
        # repopulate only if not search
        if self.filterIds==None :
            #~ Sys.pwlog([(' Populating search filters...', Const.CLZ_0, True)])
            self.populate_search_filters(allCatg, allUsers, allAccounts)
        
        self.get('checkbutton1').set_sensitive(True)
        
        self.get('label12').set_label(' '+(Sys.readableBytes(psize)+' / ' if psize != tsize else '')+Sys.readableBytes(tsize))
        
        self.get('button9').set_sensitive(True)
        self.get('button12').set_sensitive(True)
        return False
Пример #27
0
    def on_proceed_end(self, abort=False):
        """"""
        try :
            btn = self.get('button1')
            btn.set_label('Proceed')
            btn.set_sensitive(True)
            self.PROCEED = False
            if not abort : btn.set_label(conf.GUI_LABEL_OK)
            self.get('checkbutton3').hide()

        except Exception as e:
            Sys.pwarn((('on_proceed_end : ',(str(e),Sys.CLZ_WARN_PARAM), ' !'),), False)
            pass
        return False
Пример #28
0
 def createDefaultKeyIfNone(self):
     """"""
     kpath = self.getDefaultKeyPath()
     if not Io.file_exists(kpath):
         #if Sys.isUnix() :
             if not Sys.isdir(conf.DEFVAL_UKEY_PATH) :
                 Sys.mkdir_p(conf.DEFVAL_UKEY_PATH)
             k = KeyGen(conf.DEFVAL_UKEY_LENGHT)
             print(k)
             content = k.key
             print('content')
             Io.set_data(kpath, content)
             print('set content')
     self.selectKey(kpath)
Пример #29
0
    def onCommandKey(self):
        """"""
        if int(self.o.length) >= 128 and int(self.o.length) <= 4096:
            self.parser.print_header()
            if not self.o.outputfile:
                self.o.outputfile = self.home + '.kirmah' + Sys.sep + '.default.key'
            kg = KeyGen(int(self.o.length))
            done = True
            if Io.file_exists(self.o.outputfile) and not self.o.force:

                Sys.pwarn(((
                    'the key file ', (self.o.outputfile,
                                      Sys.Clz.fgb3), ' already exists !'
                ), 'if you rewrite this file, all previous files encrypted with the corresponding key will be unrecoverable !'
                           ))

                done = Sys.pask('Are you sure to rewrite this file')
                self.stime = Sys.datetime.now()
            if done:
                Io.set_data(self.o.outputfile, kg.key)
            Sys.pstep('Generate key file', self.stime, done)

            if done:
                Sys.print(' ' * 5 + Sys.realpath(self.o.outputfile),
                          Sys.Clz.fgB1, True)

        else:
            self.parser.error_cmd(
                (('invalid option ', ('-l, --length', Sys.Clz.fgb3),
                  ' value (', ('128', Sys.Clz.fgb3), ' to ',
                  ('4096', Sys.Clz.fgb3), ')'), ))
Пример #30
0
    def __init__(self, appname, debug, gui, color, loglvl, ppid, event, id, wp, delay, task, *args, **kwargs):
        def mptask(id, *args, **kwargs):
            Sys.sendMainProcMsg(Manager.MSG_INIT, None)
            otask = task(id=id, event=event, *args, **kwargs)
            Sys.sendMainProcMsg(Manager.MSG_END, None)
            return otask

        init(appname, debug, ppid, color, loglvl)
        Sys.g.WPIPE   = wp
        Sys.g.CPID    = id
        Sys.g.GUI     = gui
        # initialize child process event with parent process event
        Sys.g.MPEVENT = event
        if delay : Sys.sleep(delay)
        mptask(id, *args, **kwargs)
Пример #31
0
 def on_progress(self, thread=None, progress=None, ref=None):
     #~ print('thread_progress', thread.name, progress)
     while not Sys.g.LOG_QUEUE.empty():
         cth, data = Sys.g.LOG_QUEUE.get()
         #~ print('*'+str(cth))
         if data is not None :
             if data is Sys.g.SIGNAL_STOP :
                 Sys.dprint('STOP')
                 if thread is not None : thread.cancel()
             elif data is Sys.g.SIGNAL_CLEAR :
                 self.clearLog(thname=cth)
             else:
                 self.printTextView(data, thname=cth)
                 
     if progress is not None : self.update_progress(progress, thname=thread.name)
Пример #32
0
 def on_start(self):
     """"""
     Sys.g.GUI_PRINT_STDOUT = False
     Sys.g.GUI              = True
     init(conf.PRG_NAME, False, Sys.getpid(), True, Const.LOG_ALL)
     self.conf        = ImpraConf(KiniFile('impra2.ini'))
     self.populate_profiles()
     self.populate_config()
     self.taskLabel     = ImpraThread.TASK_LABEL
     self.taskStock     = ImpraThread.TASK_STOCK
     self.progressbar   = self.get('progressbar1')
     self.textview      = self.get('textview1')
     try :
         self.textview.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 1.0))
         self.textview.modify_font(Pango.font_description_from_string ('DejaVu Sans Mono Book 11' if Sys.isUnix() else 'Lucida Conosle 11'))
     except :
         pass
     self.textbuffer    = self.textview.get_buffer()
     self.tags          = self.buildTxtTags(self.textbuffer)
     self.initWidgetByThread('impra-1', self.textview, self.textbuffer, self.progressbar, self.tags)
     self.initWidgetByThread('MainThread', self.textview, self.textbuffer, self.progressbar, self.tags)
     self.tree          = self.get('treeview1')
     self.tree.connect('row-activated', self.on_row_select)
     self.tree.get_selection().connect('changed', self.on_tree_selection_changed)
     self.launch_thread(self.on_ended)
     
     self.searchCatg    = self.get('comboboxtext1')
     self.searchUser    = self.get('comboboxtext4')
     self.searchAccount = self.get('comboboxtext5')
     self.filterIds     = None
     self.index         = None
     self.taskList      = {}
     self.threads_work  = [False, False]
Пример #33
0
    def on_proceed_end(self, abort=False):
        """"""
        try:
            btn = self.get('button1')
            btn.set_label('Proceed')
            btn.set_sensitive(True)
            self.PROCEED = False
            if not abort: btn.set_label(conf.GUI_LABEL_OK)
            self.get('checkbutton3').hide()

        except Exception as e:
            Sys.pwarn(
                (('on_proceed_end : ', (str(e), Sys.CLZ_WARN_PARAM), ' !'), ),
                False)
            pass
        return False
Пример #34
0
 def run(self):
     """"""
     self.cancelled = False
     Sys.g.MPEVENT.clear()
     print(Sys.g.LOG_LEVEL)
     Cli('./', Sys.getpid(), self.cliargs, self, Sys.g.LOG_LEVEL)
     self.emit("completed")
Пример #35
0
 def run(self):
     """"""
     self.cancelled = False
     Sys.g.MPEVENT.clear()
     print(Sys.g.LOG_LEVEL)
     Cli("./", Sys.getpid(), self.cliargs, self, Sys.g.LOG_LEVEL)
     self.emit("completed")
Пример #36
0
    def onCommandList(self):
        """"""
        matchIdsCatg = None
        matchIdsUser = None
        matchIdsAcc = None
        matchIds = None

        if self.o.account is not None:
            matchIdsAcc = []
            # print(self.impst.idxu.index.acclist)
            # print(self.impst.idxu.index.acclist.keys())
            if self.impst.idxu.conf.ini.has("user", self.o.account + ".imap"):
                usr = self.impst.idxu.conf.ini.get("user", self.o.account + ".imap")
                if usr in self.impst.idxu.index.acclist.keys():
                    print(usr)
                for k in self.impst.idxu.index.acclist.keys():
                    if self.impst.idxu.index.acclist[k] == usr:
                        print("matched")
                        matchIdsAcc = self.impst.idxu.index.getByAccount(k)
                        print(matchIdsAcc)
                        break
            else:
                matchIdsAcc = []

        if self.o.category is not None:
            matchIdsCatg = self.impst.idxu.index.getByCategory(self.o.category)
        if self.o.user is not None:
            matchIdsUser = self.impst.idxu.index.getByUser(self.o.user)

        if self.o.category is not None:
            if self.o.user is not None:
                matchIds = self.impst.idxu.index.getIntersection(matchIdsCatg, matchIdsUser)
            else:
                matchIds = matchIdsCatg

        elif self.o.user is not None:
            matchIds = matchIdsUser

        if matchIdsAcc is not None:
            matchIds = matchIdsAcc if matchIds is None else self.impst.idxu.index.getIntersection(matchIdsAcc, matchIds)

        order = self.o.order
        if self.o.order_inv is not None:
            order = "-" + self.o.order_inv
        Sys.clear()
        self.pheader()
        self.impst.idxu.index.print(order, matchIds)
Пример #37
0
 def send(self, msg, box='INBOX'):
     """"""
     mid  = None
     date = Time2Internaldate(Sys.time())
     status, resp  = self.cnx.append(box, '\Draft', date, bytes(msg,'utf-8'))
     if status==self.OK:
         mid = str(resp[0],'utf-8')[11:-11].split(' ')
     return mid
Пример #38
0
    def on_start(self):
        """"""
        self.app.createDefaultKeyIfNone()
        key, size, mark = self.app.getKeyInfos()

        self.curKey = self.DEFAULT_KEY
        self.get('filechooserbutton1').set_filename(
            self.app.getDefaultKeyPath())
        self.get('filechooserbutton3').set_current_folder(
            conf.DEFVAL_USER_PATH)
        devPath = '/home/dev/git_repos/kirmah2.15/'
        #~ self.get('filechooserbutton3').set_current_folder(devPath)
        self.get('checkbutton1').set_active(conf.DEFVAL_NPROC >= 2)
        self.get('checkbutton3').set_active(True)
        self.get('checkbutton4').set_active(True)
        self.get('spinbutton2').set_value(conf.DEFVAL_NPROC)
        if conf.DEFVAL_NPROC >= 2:
            self.disable('spinbutton2', False)
        self.get('checkbutton2').set_active(conf.DEFVAL_MIXMODE)
        self.get('checkbutton4').set_active(conf.DEFVAL_RANDOMMODE)
        self.get('entry1').set_text(mark)

        Sys.g.UI_AUTO_SCROLL = True
        self.textview = self.get('textview1')
        self.textview.override_background_color(Gtk.StateFlags.NORMAL,
                                                Gdk.RGBA(0, 0, 0, 1.0))
        self.textview.modify_font(
            Pango.font_description_from_string('DejaVu Sans Mono Book 11'))
        self.textbuffer = self.textview.get_buffer()
        self.tags = self.buildTxtTags(self.textbuffer)
        self.progressbar = self.get('progressbar1')
        cbt = self.get('comboboxtext1')
        cbt.connect("changed", self.on_compression_changed)
        tree_iter = cbt.get_model().get_iter_first()
        print(cbt.get_model().get_string_from_iter(tree_iter))
        tree_iter = cbt.get_model().get_iter_from_string('3')
        cbt.set_active_iter(tree_iter)
        cbt = self.get('comboboxtext2')
        cbt.connect("changed", self.on_logging_changed)
        tree_iter = cbt.get_model().get_iter_first()
        tree_iter = cbt.get_model().get_iter_from_string('4')
        cbt.set_active_iter(tree_iter)
        Sys.clear()
        Sys.dprint('INIT UI')
        self.start = True
        self.thkmh = None
Пример #39
0
 def update_progress(self, progress, lvl=20, thname=None):
     #~ print('update_progress : '+str(thname))
     if True :
         pbar = self.widgetByThread[thname]['pbar']
         if progress > 0 :                
             pbar.set_text(str(progress))
             lp   = pbar.get_fraction()
             diff = (progress/100.0 - lp)
             if diff > 0 :
                 for i in range(lvl):
                     nf = lp+(i*diff/lvl)
                     if nf < progress/100.0 :
                         pbar.set_fraction(nf)
                         Sys.sleep(0.015)
             pbar.set_fraction(progress/100.0)
         else :
             pbar.set_fraction(pbar.get_fraction()+0.01)
Пример #40
0
 def thread_progress(self, thread, progress, ref):
     while not Sys.g.LOG_QUEUE.empty():
         data = Sys.g.LOG_QUEUE.get()
         if data is not None:
             if data is not Sys.g.SIGNAL_STOP:
                 for item in data:
                     ei = self.textbuffer.get_end_iter()
                     offs = ei.get_offset()
                     self.textbuffer.insert_at_cursor(item[0])
                     ei = self.textbuffer.get_end_iter()
                     oi = self.textbuffer.get_iter_at_offset(offs)
                     tagName = item[1]
                     self.textbuffer.apply_tag(self.tags[tagName], oi, ei)
                 self.textbuffer.insert_at_cursor('\n')
                 self.scroll_end()
             else:
                 Sys.dprint('STOP')
                 thread.cancel()
     self.update_progress(progress)
Пример #41
0
 def __init__(self, debug=True, color=True, loglvl=Const.LOG_DEFAULT):
     """"""
     self.encmode         = conf.DEFVAL_ENCMODE
     self.splitmode       = False
     self.compression     = conf.DEFVAL_COMP
     self.mix             = conf.DEFVAL_MIXMODE
     self.random          = conf.DEFVAL_RANDOMMODE
     self.nproc           = conf.DEFVAL_NPROC
     self.src             = None
     self.dst             = None
     self.kpath           = None
     Sys.g.GUI            = True
     init(conf.PRG_NAME, debug, Sys.getpid(), color, loglvl)
Пример #42
0
    def onCommandDec(self):
        """"""
        done = True
        if self.o.outputfile is None:
            self.o.outputfile = self.a[1][:-4] if self.a[1][
                -4:] == Kirmah.EXT else self.a[1]

        if not Sys.g.QUIET: self.parser.print_header()

        if Io.file_exists(self.o.outputfile) and not self.o.force:
            Sys.pwarn((('the file ', (self.o.outputfile, Sys.Clz.fgb3),
                        ' already exists !'), ))
            done = Sys.pask('Are you sure to rewrite this file')
            self.stime = Sys.datetime.now()

        if done:

            try:

                if (self.o.multiprocess is not None
                        and not represents_int(self.o.multiprocess)) or (
                            not self.o.multiprocess is None
                            and not (int(self.o.multiprocess) >= 2
                                     and int(self.o.multiprocess) <= 8)):
                    self.parser.error_cmd(
                        (('invalid option ', ('-j, --multiprocess',
                                              Sys.Clz.fgb3), ' value (',
                          ('2', Sys.Clz.fgb3), ' to ', ('8',
                                                        Sys.Clz.fgb3), ')'), ))

                nproc = int(self.o.multiprocess
                            ) if not self.o.multiprocess is None and int(
                                self.o.multiprocess) >= 2 and int(
                                    self.o.multiprocess) <= 8 else 1

                Sys.ptask()

                key = Io.get_data(self.o.keyfile)
                km = Kirmah(key)

                km.decrypt(self.a[1], self.o.outputfile, nproc)

            except BadKeyException:
                done = False
                Sys.pwarn((('BadKeyException : ',
                            ('wrong key ', Sys.CLZ_WARN_PARAM), ' !'), ),
                          False)

        if not Sys.g.QUIET:
            self.onend_cmd('Kirmah Decrypt', self.stime, done,
                           self.o.outputfile)
Пример #43
0
    def print_options():
        """"""
        Sys.dprint('\n')
        Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)

        Sys.print('  MAIN OPTIONS :\n', Sys.CLZ_HELP_CMD)
        Sys.print(' ' * 4 + '-v'.ljust(13, ' ') + ', --version',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'display programm version', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-d'.ljust(13, ' ') + ', --debug',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'enable debug mode', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-f'.ljust(13, ' ') + ', --force',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'force rewriting existing files without alert',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-q'.ljust(13, ' ') + ', --quiet',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'don\'t print status messages to stdout',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-h'.ljust(13, ' ') + ', --help', Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'display help', Sys.CLZ_HELP_ARG_INFO)

        Sys.dprint('\n')
        Sys.print('  KEY OPTIONS :\n', Sys.CLZ_HELP_CMD)
        Sys.print(' ' * 4 + '-l ', Sys.CLZ_HELP_ARG, False)
        Sys.print('LENGTH'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --length'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('LENGTH'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(
            ' ' * 50 + 'specified key length (128 to 4096 - default:1024)',
            Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --outputfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'specified key output filename',
                  Sys.CLZ_HELP_ARG_INFO)

        Sys.dprint('\n')
        Sys.print('  ENCRYPT OPTIONS :\n', Sys.CLZ_HELP_CMD)
        Sys.print(' ' * 4 + '-a'.ljust(13, ' ') + ', --fullcompress',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'enable full compression mode',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-z'.ljust(13, ' ') + ', --compress',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'enable compression mode', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-Z'.ljust(13, ' ') + ', --nocompress',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'disable compression mode', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-r'.ljust(13, ' ') + ', --random',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'enable random mode', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-R'.ljust(13, ' ') + ', --norandom',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'disable random mode', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-m'.ljust(13, ' ') + ', --mix', Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'enable mix mode', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-M'.ljust(13, ' ') + ', --nomix',
                  Sys.CLZ_HELP_ARG)
        Sys.print(' ' * 50 + 'disable mix mode', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-j ', Sys.CLZ_HELP_ARG, False)
        Sys.print('COUNT'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --multiprocess'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('COUNT'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'number of process for encryption (2 to 8)',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-k ', Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --keyfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'key filename used to encrypt',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --outputfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'specified encrypted output filename',
                  Sys.CLZ_HELP_ARG_INFO)

        Sys.dprint('\n')
        Sys.print('  DECRYPT OPTIONS :\n', Sys.CLZ_HELP_CMD)
        Sys.print(' ' * 4 + '-j ', Sys.CLZ_HELP_ARG, False)
        Sys.print('COUNT'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --multiprocess'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('COUNT'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'number of process for decryption (2 to 8)',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-k ', Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --keyfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'key filename used to decrypt',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --outputfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'specified decrypted output filename',
                  Sys.CLZ_HELP_ARG_INFO)

        Sys.dprint('\n')
        Sys.print('  SPLIT OPTIONS :\n', Sys.CLZ_HELP_CMD)
        Sys.print(' ' * 4 + '-p ', Sys.CLZ_HELP_ARG, False)
        Sys.print('COUNT'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --part'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('COUNT'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'count part to split', Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-k ', Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --keyfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'key filename used to split',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('TARFILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --outputfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('TARFILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'specified tar output filename',
                  Sys.CLZ_HELP_ARG_INFO)

        Sys.dprint('\n')
        Sys.print('  MERGE OPTIONS :\n', Sys.CLZ_HELP_CMD)
        Sys.print(' ' * 4 + '-k ', Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --keyfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'key filename used to merge',
                  Sys.CLZ_HELP_ARG_INFO)
        Sys.print(' ' * 4 + '-o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM, False)
        Sys.print(', --outputfile'.ljust(18, ' '), Sys.CLZ_HELP_ARG, False)
        Sys.print('FILE'.ljust(10, ' '), Sys.CLZ_HELP_PARAM)
        Sys.print(' ' * 50 + 'specified decrypted output filename',
                  Sys.CLZ_HELP_ARG_INFO)

        Sys.dprint('\n')
Пример #44
0
 def createNewKey(self, filename, size):
     """"""
     if not Sys.isdir(Sys.dirname(filename)):
         Sys.mkdir_p(Sys.dirname(filename))
     Io.set_data(filename,KeyGen(size).key[:size])
Пример #45
0
    def print_help():
        """"""
        Cli.print_header()
        Sys.print(Cli.conf.PRG_DESC, Sys.CLZ_HELP_DESC)
        Cli.print_usage('', True)
        Cli.print_options()
        Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)
        Sys.dprint()
        Sys.print('  EXEMPLES :\n', Sys.CLZ_HELP_CMD)
        CHQ = "'"

        Sys.print(' ' * 4 + 'command key :', Sys.CLZ_HELP_CMD)

        Sys.print(' ' * 8 + '# generate a new crypted key of 2048 length',
                  Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('key -l ', Sys.CLZ_HELP_CMD, False)
        Sys.print('2048 ', Sys.CLZ_HELP_PARAM)

        Sys.print(
            ' ' * 8 +
            '# generate a new crypted key (default length is 1024) in a specified location',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('key -o ', Sys.CLZ_HELP_CMD, False)
        Sys.print(Cli.DIRKEY + '.myNewKey', Sys.CLZ_HELP_PARAM)

        Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)
        Sys.print('\n' + ' ' * 4 + 'command encrypt :', Sys.CLZ_HELP_CMD)

        Sys.print(
            ' ' * 8 +
            '# encrypt specified file with default crypted key and default options',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('enc ', Sys.CLZ_HELP_CMD, False)
        Sys.print(Cli.HOME + 'mySecretTextFile.txt', Sys.CLZ_HELP_PARAM)

        Sys.print(
            ' ' * 8 +
            '# encrypt specified file with specified crypted key (full compression, no random but mix mode)',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + '# on specified output location',
                  Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('enc ', Sys.CLZ_HELP_CMD, False)
        Sys.print('mySecretTextFile.txt', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -aRm -k ', Sys.CLZ_HELP_ARG, False)
        Sys.print(Cli.DIRKEY + '.myNewKey', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('test.kmh', Sys.CLZ_HELP_PARAM)

        Sys.print(
            ' ' * 8 +
            '# encrypt specified file with default crypted key (no compression but random & mix mode and multiprocessing)',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('enc ', Sys.CLZ_HELP_CMD, False)
        Sys.print('myBigTextFile.txt', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -Zrm -j ', Sys.CLZ_HELP_ARG, False)
        Sys.print('4', Sys.CLZ_HELP_PARAM)

        Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)
        Sys.print('\n' + ' ' * 4 + 'command decrypt :', Sys.CLZ_HELP_CMD)

        Sys.print(
            ' ' * 8 + '# decrypt specified file with default crypted key',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('dec ', Sys.CLZ_HELP_CMD, False)
        Sys.print(Cli.HOME + 'mySecretFile.kmh', Sys.CLZ_HELP_PARAM)

        Sys.print(
            ' ' * 8 +
            '# decrypt specified file with specified crypted key on specified output location',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + Cli.conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG,
                  False)
        Sys.print('dec ', Sys.CLZ_HELP_CMD, False)
        Sys.print('myEncryptedSecretFile.kmh', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -k ', Sys.CLZ_HELP_ARG, False)
        Sys.print(Cli.HOME + '.kirmah' + Sys.sep + '.myNewKey',
                  Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('myDecryptedSecretFile.txt', Sys.CLZ_HELP_PARAM)

        Sys.print(
            ' ' * 8 +
            '# decrypt specified file with default crypted key and multiprocessing',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('dec ', Sys.CLZ_HELP_CMD, False)
        Sys.print('myEncryptedSecretFile.kmh', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -j ', Sys.CLZ_HELP_ARG, False)
        Sys.print('4', Sys.CLZ_HELP_PARAM)

        Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)
        Sys.print('\n' + ' ' * 4 + 'command split :', Sys.CLZ_HELP_CMD)

        Sys.print(' ' * 8 + '# split specified file with default crypted key',
                  Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('split ', Sys.CLZ_HELP_CMD, False)
        Sys.print(Cli.HOME + 'myBigBinaryFile.avi', Sys.CLZ_HELP_PARAM)

        Sys.print(
            ' ' * 8 +
            '# split specified file on 55 parts with specified crypted key on specified output location',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('split ', Sys.CLZ_HELP_CMD, False)
        Sys.print('myBigBinaryFile.avi', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -p ', Sys.CLZ_HELP_ARG, False)
        Sys.print('55', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -k ', Sys.CLZ_HELP_ARG, False)
        Sys.print(Cli.DIRKEY + '.myNewKey', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('myBigBinaryFile.encrypted', Sys.CLZ_HELP_PARAM)

        Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)
        Sys.print('\n' + ' ' * 4 + 'command merge :', Sys.CLZ_HELP_CMD)

        Sys.print(
            ' ' * 8 +
            '# merge specified splitted file with default crypted key',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('merge ', Sys.CLZ_HELP_CMD, False)
        Sys.print(
            Cli.HOME +
            '6136bd1b53d84ecbad5380594eea7256176c19e0266c723ea2e982f8ca49922b.kcf',
            Sys.CLZ_HELP_PARAM)

        Sys.print(
            ' ' * 8 +
            '# merge specified tark splitted file with specified crypted key on specified output location',
            Sys.CLZ_HELP_COMMENT)
        Sys.print(' ' * 8 + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('merge ', Sys.CLZ_HELP_CMD, False)
        Sys.print('myBigBinaryFile.encrypted.tark', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -k ', Sys.CLZ_HELP_ARG, False)
        Sys.print(Cli.DIRKEY + '.myNewKey', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('myBigBinaryFile.decrypted.avi', Sys.CLZ_HELP_PARAM)

        Cli.printLineSep(Const.LINE_SEP_CHAR, Const.LINE_SEP_LEN)
        Sys.dprint()
Пример #46
0
    def print_usage(data, withoutHeader=False):
        """"""
        if not withoutHeader: Cli.print_header()

        Sys.print('  USAGE :\n', Sys.CLZ_HELP_CMD)
        Sys.print('    ' + Cli.conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG,
                  False)
        Sys.print('help ', Sys.CLZ_HELP_CMD)

        Sys.print('    ' + Cli.conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG,
                  False)
        Sys.print('key   ', Sys.CLZ_HELP_CMD, False)
        Sys.print('[ -l ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('length', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('outputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(']', Sys.CLZ_HELP_ARG)

        Sys.print('    ' + Cli.conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG,
                  False)
        Sys.print('enc   ', Sys.CLZ_HELP_CMD, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('inputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('} ', Sys.CLZ_HELP_PARAM, False)
        Sys.print('[', Sys.CLZ_HELP_ARG, False)
        Sys.print(' -z|Z|a -r|R -m|M -j ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('numProcess', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -k ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('keyFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('outputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(']', Sys.CLZ_HELP_ARG)

        Sys.print('    ' + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('dec   ', Sys.CLZ_HELP_CMD, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('inputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('} ', Sys.CLZ_HELP_PARAM, False)
        Sys.print('[', Sys.CLZ_HELP_ARG, False)
        Sys.print(' -j ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('numProcess', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -k ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('keyFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('outputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(']', Sys.CLZ_HELP_ARG)

        Sys.print('    ' + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('split ', Sys.CLZ_HELP_CMD, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('inputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('} ', Sys.CLZ_HELP_PARAM, False)
        Sys.print('[', Sys.CLZ_HELP_ARG, False)
        Sys.print(' -p ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('numParts', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -k ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('keyFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('tarOutputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(']', Sys.CLZ_HELP_ARG)

        Sys.print('    ' + conf.PRG_CLI_NAME + ' ', Sys.CLZ_HELP_PRG, False)
        Sys.print('merge ', Sys.CLZ_HELP_CMD, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('inputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('} ', Sys.CLZ_HELP_PARAM, False)
        Sys.print('[', Sys.CLZ_HELP_ARG, False)
        Sys.print(' -k ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('keyFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(' -o ', Sys.CLZ_HELP_ARG, False)
        Sys.print('{', Sys.CLZ_HELP_PARAM, False)
        Sys.print('outputFile', Sys.CLZ_HELP_PARAM, False)
        Sys.print('}', Sys.CLZ_HELP_PARAM, False)
        Sys.print(']', Sys.CLZ_HELP_ARG)
Пример #47
0
 def onend_cmd(self, title, stime, done, outputfile):
     """"""
     s = Const.LINE_SEP_CHAR * Const.LINE_SEP_LEN
     Sys.print(s, Sys.CLZ_HEAD_LINE)
     Sys.wlog([(s, Const.CLZ_HEAD_SEP)])
     Sys.pstep(title, stime, done, True)
     Sys.print(s, Sys.CLZ_HEAD_LINE)
     Sys.wlog([(s, Const.CLZ_HEAD_SEP)])
     if done and outputfile is not None:
         Sys.cli_emit_progress(100)
         Sys.print(' ' * 5 + Sys.realpath(outputfile), Sys.Clz.fgB1, False)
         Sys.print(' (' + Sys.getFileSize(outputfile) + ')', Sys.Clz.fgB3)
         bdata = [(' ' * 5 + Sys.realpath(outputfile), 'io'),
                  (' (' + Sys.getFileSize(outputfile) + ')', 'func')]
         Sys.wlog(bdata)
         Sys.wlog(Sys.dprint())
Пример #48
0
    def onCommandMerge(self):
        """"""
        done = True

        if not Sys.g.QUIET: self.parser.print_header()

        if done:
            toPath = None
            try:
                Sys.ptask()

                key = Io.get_data(self.o.keyfile)
                km = Kirmah(key)
                kcf = None
                istar = True
                try:
                    import tarfile
                    dpath = Sys.dirname(
                        Sys.realpath(self.o.outputfile)
                    ) + Sys.sep if self.o.outputfile is not None else Sys.dirname(
                        Sys.realpath(self.a[1])) + Sys.sep
                    if self.o.outputfile is None:
                        self.o.outputfile = dpath
                    with tarfile.open(self.a[1], mode='r') as tar:
                        #~ print(dpath)
                        tar.extractall(path=dpath)
                        kcf = None
                        for tarinfo in tar:
                            #~ print(tarinfo.name)
                            if tarinfo.isreg() and tarinfo.name[-4:] == '.kcf':
                                #~ print(dpath+tarinfo.name)
                                kcf = dpath + tarinfo.name
                    if kcf is not None:
                        km.DIR_OUTBOX = dpath
                        toPath = km.mergeFile(kcf, self.o.outputfile)
                except BadKeyException:
                    Sys.pwarn((('BadKeyException : ',
                                ('wrong key ', Sys.CLZ_WARN_PARAM), ' !'), ),
                              False)
                    done = False

                except Exception:
                    istar = False
                    toPath = km.mergeFile(self.a[1], self.o.outputfile)

                #~ if self.o.outputfile is not None :
                #~ Io.rename(toPath, self.o.outputfile)
                #~ toPath = self.o.outputfile

            except BadKeyException:
                Sys.pwarn((('BadKeyException : ',
                            ('wrong key ', Sys.CLZ_WARN_PARAM), ' !'), ),
                          False)
                done = False

            except Exception as e:
                done = False
                if Sys.g.DEBUG:
                    print(e)
                elif not Sys.g.QUIET:
                    Sys.pwarn((str(e), ))
        if not done:
            if istar:
                with tarfile.open(self.a[1], mode='r') as tar:
                    for tarinfo in tar:
                        Sys.removeFile(dpath + tarinfo.name)

        if not Sys.g.QUIET:
            self.onend_cmd('Kirmah Merge', self.stime, done, toPath)
Пример #49
0
    def onCommandSplit(self):
        """"""
        done = True
        Sys.cli_emit_progress(1)
        if not self.o.parts is None and not (int(self.o.parts) >= 12
                                             and int(self.o.parts) <= 62):
            self.parser.error_cmd(
                (('invalid option ', ('-p, --parts', Sys.Clz.fgb3), ' value (',
                  ('12', Sys.Clz.fgb3), ' to ', ('62', Sys.Clz.fgb3), ')'), ))
        else:
            self.o.parts = int(self.o.parts)

        if not Sys.g.QUIET: self.parser.print_header()
        if self.o.outputfile is not None:
            if self.o.outputfile[-5:] != '.tark': self.o.outputfile += '.tark'
            if Io.file_exists(self.o.outputfile) and not self.o.force:
                Sys.pwarn((('the file ', (self.o.outputfile, Sys.Clz.fgb3),
                            ' already exists !'), ))
                done = Sys.pask('Are you sure to rewrite this file')
                self.stime = Sys.datetime.now()

        if done:

            try:
                Sys.ptask()
                Sys.cli_emit_progress(2)
                key = Io.get_data(self.o.keyfile)
                km = Kirmah(key)
                hlst = km.ck.getHashList(Sys.basename(self.a[1]), self.o.parts,
                                         True)
                Sys.cli_emit_progress(3)
                kcf = km.splitFile(self.a[1], hlst)
                t = int(Sys.time())
                times = (t, t)
                p = 85
                Sys.cli_emit_progress(p)
                Io.touch(kcf, times)
                frav = 0.24
                for row in hlst['data']:
                    p += frav
                    Io.touch(row[1] + km.EXT, times)
                    Sys.cli_emit_progress(p)
                if self.o.outputfile is not None:
                    d = Sys.datetime.now()
                    if Sys.g.DEBUG: Sys.wlog(Sys.dprint())
                    Sys.ptask('Preparing tark file')
                    hlst['data'] = sorted(hlst['data'], key=lambda lst: lst[4])
                    with tarfile.open(self.o.outputfile, mode='w') as tar:
                        tar.add(kcf, arcname=Sys.basename(kcf))
                        p = 90
                        for row in hlst['data']:
                            tar.add(row[1] + km.EXT,
                                    arcname=Sys.basename(row[1] + km.EXT))
                            p += frav
                            Sys.cli_emit_progress(p)
                    Sys.pstep('Packing destination file', d, True)
                    d = Sys.datetime.now()
                    Sys.ptask('Finalize')
                    for row in hlst['data']:
                        Io.removeFile(row[1] + km.EXT)
                        p += frav
                        Sys.cli_emit_progress(p)
                    Io.removeFile(kcf)
                    Sys.pstep('Cleaning', d, True)

            except Exception as e:
                done = False
                if Sys.g.DEBUG:
                    print('split exception')
                    print(e)

                    #~ raise e
                elif not Sys.g.QUIET:
                    Sys.pwarn((str(e), ))

        if not Sys.g.QUIET:
            Sys.cli_emit_progress(100)
            self.onend_cmd('Kirmah Split', self.stime, done, self.o.outputfile)
Пример #50
0
    def onCommandEnc(self):
        """"""
        done = True
        if self.o.outputfile is None:
            self.o.outputfile = Sys.basename(self.a[1])
        if self.o.outputfile[-len(Kirmah.EXT):] != Kirmah.EXT:
            print(self.o.outputfile[-len(Kirmah.EXT):])
            self.o.outputfile += Kirmah.EXT
        print(self.o.outputfile)

        d = self.getDefaultOption(
            (self.o.compress, self.o.fullcompress, self.o.nocompress))
        compress = (KirmahHeader.COMP_END if d == 0 or
                    (d is None and Io.is_binary(self.a[1])) else
                    (KirmahHeader.COMP_ALL
                     if d == 1 or d is None else KirmahHeader.COMP_NONE))
        random = True if (self.o.random is None and
                          self.o.norandom is None) or self.o.random else False
        mix = True if (self.o.mix is None
                       and self.o.nomix is None) or self.o.mix else False

        if (self.o.multiprocess is not None
                and not represents_int(self.o.multiprocess)) or (
                    not self.o.multiprocess is None
                    and not (int(self.o.multiprocess) >= 2
                             and int(self.o.multiprocess) <= 8)):
            self.parser.error_cmd(
                (('invalid option ', ('-j, --multiprocess',
                                      Sys.Clz.fgb3), ' value (',
                  ('2', Sys.Clz.fgb3), ' to ', ('8', Sys.Clz.fgb3), ')'), ))

        nproc = int(
            self.o.multiprocess) if not self.o.multiprocess is None and int(
                self.o.multiprocess) >= 2 and int(
                    self.o.multiprocess) <= 8 else 1

        if not Sys.g.QUIET: self.parser.print_header()

        if Io.file_exists(self.o.outputfile) and not self.o.force:
            Sys.pwarn((('the file ', (self.o.outputfile, Sys.Clz.fgb3),
                        ' already exists !'), ))
            done = Sys.pask('Are you sure to rewrite this file')
            self.stime = Sys.datetime.now()

        if done:

            try:
                Sys.ptask()

                key = Io.get_data(self.o.keyfile)
                km = Kirmah(key, None, compress, random, mix)

                km.encrypt(self.a[1], self.o.outputfile, nproc)

            except Exception as e:
                done = False
                print(e)
                raise e
                pass

        if not Sys.g.QUIET:
            self.onend_cmd('Kirmah Encrypt', self.stime, done,
                           self.o.outputfile)
Пример #51
0
    def __init__(self,
                 path,
                 remote=False,
                 rwargs=None,
                 thread=None,
                 loglvl=Const.LOG_DEFAULT):
        """"""
        AbstractCli.__init__(self, conf, self)

        Cli.HOME = conf.DEFVAL_USER_PATH
        Cli.DIRKEY = Cli.HOME + '.' + conf.PRG_NAME.lower() + Sys.sep
        if not Sys.isUnix():
            CHQ = '"'
            self.HOME = 'C:' + Sys.sep + conf.PRG_NAME.lower() + Sys.sep
            self.DIRKEY = self.HOME + 'keys' + Sys.sep
        Sys.mkdir_p(Cli.DIRKEY)

        gpData = OptionGroup(self.parser, '')
        gpData.add_option('-a', '--fullcompress', action='store_true')
        gpData.add_option('-z', '--compress', action='store_true')
        gpData.add_option('-Z', '--nocompress', action='store_true')
        gpData.add_option('-r', '--random', action='store_true')
        gpData.add_option('-R', '--norandom', action='store_true')
        gpData.add_option('-m', '--mix', action='store_true')
        gpData.add_option('-M', '--nomix', action='store_true')
        gpData.add_option('-j', '--multiprocess', action='store')
        gpData.add_option('-k', '--keyfile', action='store')
        gpData.add_option('-l', '--length', action='store', default=1024)
        gpData.add_option('-p', '--parts', action='store', default=22)
        gpData.add_option('-o', '--outputfile', action='store')
        self.parser.add_option_group(gpData)

        # rewrite argv sended by remote
        if rwargs is not None:
            import sys
            sys.argv = rwargs

        (o, a) = self.parser.parse_args()

        Sys.g.QUIET = o.quiet
        Sys.g.THREAD_CLI = thread
        Sys.g.GUI = thread is not None

        init(conf.PRG_NAME, o.debug, remote, not o.no_color, loglvl)

        if not a:
            try:
                if not o.help or not o.version:
                    self.parser.error_cmd(('no command specified', ), True)
                else:
                    Sys.clear()
                    Cli.print_help()
            except:
                if not o.version:
                    self.parser.error_cmd(('no command specified', ), True)
                else:
                    Cli.print_header()

        else:
            if a[0] == 'help':
                Sys.clear()
                Cli.print_help()

            elif a[0] in ['key', 'enc', 'dec', 'split', 'merge']:

                app = CliApp(self.HOME, path, self, a, o)

                if a[0] == 'key':
                    app.onCommandKey()
                else:
                    if not len(a) > 1:
                        self.parser.error_cmd(
                            (('an ', ('inputFile', Sys.Clz.fgb3),
                              ' is required !'), ), True)
                    elif not Io.file_exists(a[1]):
                        self.parser.error_cmd(
                            (('the file ',
                              (a[1], Sys.Clz.fgb3), ' doesn\'t exists !'), ),
                            True)

                    elif a[0] == 'enc':
                        app.onCommandEnc()
                    elif a[0] == 'dec':
                        app.onCommandDec()
                    elif a[0] == 'split':
                        app.onCommandSplit()
                    elif a[0] == 'merge':
                        app.onCommandMerge()

                    Sys.dprint('PUT END SIGNAL')
                    if Sys.g.LOG_QUEUE is not None:
                        Sys.g.LOG_QUEUE.put(Sys.g.SIGNAL_STOP)

            else:
                self.parser.error_cmd(
                    (('unknow command ', (a[0], Sys.Clz.fgb3)), ))

        if not o.quiet: Sys.dprint()