Ejemplo n.º 1
0
    def chEque():
        print
        if r:

            # compare float
            # https://ubuntuforums.org/showthread.php?t=840665
            def float_eq(a, b, epsilon=0.00000001):
                fpr.cyan('<float_eq> %s' % abs(a - b))
                if abs(a - b) < epsilon:
                    return True
                return False

            m1 = float(r) / rpm
            m2 = mpt * float(t)

            fpr.cyan('r/rpm = %s, mpt * t = %s' % (m1, m2))

            if float_eq(m1, m2):
                fpr.green('Equetion is met')
                waitin()
                return True
            else:
                fpr.err('Equetion is false')
                waitin()
                return False
Ejemplo n.º 2
0
def auth_spfplflow(dd, spfid):

    # info('info','SPF Validation  process tests SPF record if it is syntactically correct \n' \
    #             'according to RFC 7208 compliant library pyspf. To present the whole path \n' \
    #             'this test additionally follow all "include" mechanisms using DNS query to \n' \
    #             'retrieve all external SPF policies.' \
    #             , adj='l')
    # print

    fpr('SPF identity type  : %s' % spfid)
    fpr('SPF identity value : %s' % dd['id'].get(spfid))
    if spfid == 'mfrom':
        local_part, domain = spf.split_email(s=dd['id'].get('mfrom'),
                                             h=dd['id'].get('helo'))
    if spfid == 'helo':
        local_part, domain = spf.split_email(s='', h=dd['id'].get('helo'))
    fpr('Domain: %s' % domain)

    print
    try:
        q = spf.query(i=dd.get('ip'),
                      s=dd['id'].get('mfrom'),
                      h=dd['id'].get('helo'),
                      timeout=20,
                      verbose=False,
                      querytime=0)
    except Exception, e:
        fpr.err('Err: %s' % e)
        waitin()
        return
Ejemplo n.º 3
0
def main():
    try:
        signal.signal(signal.SIGINT, sig_handler)
        iworkspace()
        ishell()
    # except Ctrl+C, Ctrl+D
    # except (KeyboardInterrupt, EOFError):
    except EOFError:
        print
        print
        fpr.err('Interrupted by user! Session lost!')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)
    except Exception, error:
        print
        fpr.warn('> Unpredictable Exception has been catched')
        fpr.err('>>> %s' % str(error))
        fpr('> Need help regarding the error, please send me a copy. Thank you.'
            )
        fpr.warn(
            '> Restarting main() to keep the session.\n> Please save the session and restart me..'
        )
        waitin()
        main()
Ejemplo n.º 4
0
def att_load_eml(mbody, emlfn):

    #import os
    #from core.data import smtp,fpr,tc,tr
    #from core.func import waitin,dbginfo

    if os.path.isfile(emlfn):
        print
        fpr('Loading %s ..' % emlfn)

        fp = open(emlfn, 'rb')

        inputs = fp.read()
        fp.close()

        if not inputs:

            dbginfo(
                'error',
                'Err: File has no content. Please verify file size !\n[ %s ]' %
                emlfn)
            #break
            return False

        if inputs:
            info('info', '-- Loaded message: Top dump (view: 500 chars) --',
                 '%s' % inputs[:500] + ' . . .')
            print
            #dbglog(inputs)
            fpr.ok('Message content has been loaded')

            #smtp['content']['string'] = ''.join(inputs)
            mbody['string'] = ''.join(inputs)
            #smtp['content']['string'] = '\r\n'.join(inputs)

            #smtp['use_mime'] = False

        waitin()
    else:
        fpr('No such file or you don\'t have a permission to access it')
        print
        return False
Ejemplo n.º 5
0
def auth_spf(dd, spfid='all'):

    #TODO: validate value ip, helo (fqdn), mfrom (isemail)

    fpr('SPF Values')
    fpr('_' * (tc - 4) + '\n\n')
    fpr('  id MAIL FROM  : %s' % dd['id'].get('mfrom'))
    fpr('  id HELO/EHLO  : %s' % dd['id'].get('helo'))
    fpr.info('  id PRA        : %s' % dd['id'].get('pra'))
    fpr('  Client IP     : %s' % dd.get('ip'))
    fpr('_' * (tc - 4) + '\n\n')

    try:
        #if spfid == 'mfrom':
        qs = spf.query(
            i=dd.get('ip'),
            s=dd['id'].get('mfrom'),
            #s='',
            h=dd['id'].get('helo'),
            timeout=20,
            verbose=False,
            querytime=0)
        #if spfid == 'helo':
        qh = spf.query(
            i=dd.get('ip'),
            #   s=dd['id'].get('mfrom'),
            s='',
            h=dd['id'].get('helo'),
            timeout=20,
            verbose=False,
            querytime=0)

    except Exception, e:
        fpr.err('Err: %s' % e)
        waitin()
        return
Ejemplo n.º 6
0
def d_headers():

    fpr('Diagnostics: Header decoder')
    print
    if raw_input('  Would you like to decode some headers [y/N]> ') in [
            'y', 'Y'
    ]:
        print
        fpr('Please provide an encoded part of the header:')
        #ehead = raw_input('  ')
        fpr('Use Ctrl-D with new line to continue.')
        fpr.blue('_' * (tc - 4))
        print

        inputs = get_inputs(nl=True)

        fpr.info('_' * (tc - 4))
        # decode multiline email headers
        ehead = coders.decode_mheaders(inputs)
        waitin()
        if ehead.keys():
            fpr('Decoded Headers')
            fpr.info('_' * (tc - 4))
            #print
            for k in ehead.keys():
                print
                dhead, enc = decode_header(''.join(ehead[k]).replace(
                    '?==?', '?= =?'))[0]
                if re.match('-no-hn-', k):
                    fpr('Header-name: <None>')
                else:
                    fpr('Header-Name: %s' % k)
                fpr('Header: %s' % dhead)
                ##print dhead
                fpr('Encoding: %s' % enc)
            print
            fpr.blue('_' * (tc - 4))
            waitin()
        # _end_of_decode_multiline_headers
        else:
            fpr('Sorry! No header to decode')
            waitin()
        ehead.clear()
    else:
        waitin()
Ejemplo n.º 7
0
def att_zip_file(mbody, smtype, sn):

    #mbody  = smtp['content']['att']
    #sn     = '1'
    #smtype = 'img'

    #import os
    #from core.data import smpls,fpr,tc,tr
    #from core.func import waitin,get_zipfile,get_inputs,get_sample,dbginfo

    while True:
        print
        if smpls['zip-smpls'].get(
                smtype) and smpls['zip-smpls'][smtype]['astat'] != 0:
            fpr('It seems you have already attached this %s sample' % smtype)
            if not raw_input('  Do you want to append another one [y/N]:') in [
                    'y', 'Y'
            ]:
                break
        else:
            smpls['zip-smpls'].setdefault(smtype, {})['astat'] = 0
        if os.path.exists(smpls['img'][sn]['filename']):
            #mbody.append(smpls['img']['filename'])
            fp = open(smpls['img'][sn]['filename'], 'rb')
            inputs = fp.read()
            fp.close()

            if not inputs:

                dbginfo(
                    'error',
                    'Err: File has no content. Please verify file size !\n[%s] \
                  \nTry to remove file to download a new one.' %
                    smpls[smtype][sn]['filename'])

                break
            n = 1
            if mbody.keys():
                n = max(mbody.keys())
                n += 1
                #print max(mbody.keys())
            print
            fpr('Attaching zipped %s' % smpls[smtype][sn]['descr'])
            print
            zipinputs = get_zipfile({'val': inputs},
                                    fn=os.path.basename(
                                        smpls[smtype][sn]['filename']))
            #print type(inputs)
            mbody.setdefault(n, {})['raw'] = zipinputs

            mbody[n]['h_Content-Type'] = \
                 raw_input('  Content-Type: [%s]> ' %  'application/zip') \
                     or 'application/zip'

            mbody[n]['h_Content-Disposition'] = \
                   raw_input('  Content-Disposition: [%s]> ' %  \
                       'attachments; filename=%s' % (smtype+'_'+smpls['zip']['filename'])) \
                       or 'attachments; filename=%s' % (smtype+'_'+smpls['zip']['filename'])

            mbody[n]['h_Content-Transfer-Encoding'] = \
                 raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                     or 'base64'
            # if no cid - client like Mail.app does not
            # show the attachment
            mbody[n]['h_Content-ID'] = \
                 raw_input('  Content-ID: [%s]> ' %  '') \
                     or ''
            mbody[n]['h_Content-Description'] = \
                 raw_input('  Content-Description: [%s]> ' % '') \
                     or ''

            #smpls['img']['astat'] += 1
            smpls['zip-smpls']['astat'] += 1
            smpls['zip-smpls'].setdefault(smtype, {})['astat'] += 1
            print
            fpr('Zipped %s attached (x%d)' %
                (smpls[smtype][sn]['descr'],
                 smpls['zip-smpls'][smtype]['astat']))

            waitin()
            break
        else:
            fpr('Sample does not exists [%s]' % smpls[smtype][sn]['filename'])
            if raw_input(
                    '  Would you like to download this sample [y/N]> ') in [
                        'y', 'Y'
                    ]:
                get_sample(smpls[smtype][sn])
            else:
                break
Ejemplo n.º 8
0
def att_zip_plain_sample(mbody, smtype, sn):

    #mbody = smtp['content']['att']
    #sn = '1'

    #from core.data import smpls,fpr,tc,tr
    #from core.func import waitin,get_zipfile,dbginfo

    while True:
        #print  smpls['zip'].get(smtype,'dupa')
        if smpls['zip-smpls'].get(
                smtype) and smpls['zip-smpls'][smtype]['astat'] != 0:
            fpr('It seems you have already attached this zip  %s sample' %
                smtype)
            if not raw_input('  Do you want to append another one [y/N]:') in [
                    'y', 'Y'
            ]:
                break
        else:
            smpls['zip-smpls'].setdefault(smtype, {})['astat'] = 0

        #print get_zipfile(smpls['spam']['val'])
        # for VOF test a name of file in archive is important !!
        if smpls[smtype][sn].get('filename', ''):
            inputs = get_zipfile(smpls[smtype][sn],
                                 fn=smpls[smtype][sn]['filename'])
        else:
            inputs = get_zipfile(smpls[smtype][sn])
        #print type(inputs)
        if inputs:
            n = 1
            if mbody.keys():
                n = max(mbody.keys())
                n += 1
                #print max(mbody.keys())
            print
            fpr('Attaching zipped %s' % smpls[smtype][sn]['descr'])
            print
            mbody.setdefault(n, {})['raw'] = inputs
            #mbody['0']['b64'] = inputs

            mbody[n]['h_Content-Type'] = \
                  raw_input('  Content-Type: [%s]> ' %  'application/zip') \
                       or 'application/zip'
            mbody[n]['h_Content-Disposition'] = \
                   raw_input('  Content-Disposition: [%s]> ' %  \
                   'attachments; filename=%s' % (smtype+'_'+smpls['zip-smpls']['filename'])) \
                       or 'attachments; filename=%s' % (smtype+'_'+smpls['zip-smpls']['filename'])
            mbody[n]['h_Content-transfer-encoding'] = \
                   raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                       or 'base64'
            mbody[n]['h_Content-ID'] = \
                   raw_input('  Content-ID: [%s]> ' %  '') \
                       or ''
            mbody[n]['h_Content-Description'] = \
                   raw_input('  Content-Description: [%s]> ' %  '') \
                       or ''

            smpls['zip-smpls']['astat'] += 1
            smpls['zip-smpls'].setdefault(smtype, {})['astat'] += 1
            print
            fpr('Zipped %s attached (x%d)' %
                (smpls[smtype][sn]['descr'],
                 smpls['zip-smpls'][smtype]['astat']))
        else:
            fpr.err('Err: This should not happened ! ')
        waitin()
        break
Ejemplo n.º 9
0
def att_b64(mbody, smtype, sn):

    #import os
    #import email

    #from core.data import smpls,fpr,tc,tr,smtp
    #from core.func import waitin,get_sample,dbginfo
    #from core.ui.cmenu import Menu
    #from core.ui.banner import bancls

    while True:
        # you are ask about this in att_XXX_sample function
        #if smpls[smtype]['astat'] != 0:
        #    fpr('It seems you have already attached this sample')
        #    if not raw_input('  Do you want to append another one [y/N]:') in ['y','Y']:
        #        break
        #    #break

        if True:
            if smpls[smtype][sn]['val']:

                fpr('Attaching %s' % smpls[smtype][sn]['descr'])
                print
                n = 1

                mbody.setdefault(n, {})['b64'] = []

                mbody.setdefault(n,{})['b64'].append(\
                       email.base64MIME.encode(smpls[smtype][sn]['val']) )

                #print mbody[n]['b64']
                #print type(mbody[n]['b64'])
                #print "\n".join(mbody[n]['b64'])

                mbody[n]['h_Content-Type'] = \
                raw_input('  Content-Type: [%s]> ' %  smpls[smtype].get('mimetype','')) \
                    or  smpls[smtype].get('mimetype','')

                mbody[n]['h_Content-Disposition'] = \
                raw_input('  Content-Disposition: [%s]> ' %  'attachments; filename=%s' % \
                    os.path.basename(smpls[smtype][sn]['filename'])) \
                    or 'attachments; filename=%s' % \
                    os.path.basename(smpls[smtype][sn]['filename'])

                mbody[n]['h_Content-Transfer-Encoding'] = \
                raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                    or 'base64'

                # if no cid - client like Mail.app does not
                # show the attachment
                mbody[n]['h_Content-ID'] = \
                raw_input('  Content-ID: [%s]> ' %  '') \
                    or ''

                mbody[n]['h_Content-Description'] = \
                raw_input('  Content-Description: [%s]> ' % '') \
                    or ''

                #print mbody
                smpls[smtype]['astat'] += 1
                print
                fpr('Sample attached (x%d)' % smpls[smtype]['astat'])
                break

        waitin()
Ejemplo n.º 10
0
def att_file_sample(mbody, smtype, sn):

    #import os
    #from core.data import smpls,fpr,tc,tr,smtp
    #from core.func import waitin,get_sample,dbginfo
    #from core.ui.cmenu import Menu
    #from core.ui.banner import bancls

    while True:
        # you are ask about this in att_XXX_sample function
        #if smpls[smtype]['astat'] != 0:
        #    fpr('It seems you have already attached this type of sample')
        #    if not raw_input('  Do you want to append another one [y/N]:') in ['y','Y']:
        #        break

        if os.path.exists(smpls[smtype][sn]['filename']):
            #mbody.append(smpls[smtype]['filename'])
            fp = open(smpls[smtype][sn]['filename'], 'rb')
            inputs = fp.read()
            fp.close()
            if not inputs:

                dbginfo(
                    'error',
                    'Err: File has no content. Please verify file size !\n[%s] \
                  \nTry to remove file to download a new one.' %
                    smpls[smtype][sn]['filename'])

                break
            n = 1

            if mbody.keys():
                n = max(mbody.keys())
                n += 1
                #print max(mbody.keys())
            print
            fpr('Attaching %s' % smpls[smtype][sn]['descr'])
            print
            mbody.setdefault(n, {})['raw'] = inputs
            # TODO wstaw do content
            mbody[n]['h_Content-Type'] = \
                 raw_input('  Content-Type: [%s]> ' %  smpls[smtype].get('mimetype','') ) \
                     or smpls[smtype].get('mimetype','')

            mbody[n]['h_Content-Disposition'] = \
                 raw_input('  Content-Disposition: [%s]> ' % \
                                'attachments; filename=%s' % \
                     os.path.basename(smpls[smtype][sn]['filename'])) \
                     or 'attachments; filename=%s' % \
                     os.path.basename(smpls[smtype][sn]['filename'])

            mbody[n]['h_Content-Transfer-Encoding'] = \
                 raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                     or 'base64'
            # !! if no cid - client like Mail.app does not
            #    show the attachment
            mbody[n]['h_Content-ID'] = \
                 raw_input('  Content-ID: [%s]> ' %  '') \
                     or ''

            mbody[n]['h_Content-Description'] = \
                 raw_input('  Content-Description: [%s]> ' % '') \
                     or ''

            smpls[smtype]['astat'] += 1
            print

            fpr('Sample attached (x%d)' % smpls[smtype]['astat'])

            break

        else:
            fpr('Sample does not exists [%s]' % smpls[smtype][sn]['filename'])
            if raw_input(
                    '  Would you like to download this sample [y/N]> ') in [
                        'y', 'Y'
                    ]:
                get_sample(smpls[smtype][sn])
            else:
                break

    waitin()
Ejemplo n.º 11
0
def att_zip_input(mbody, smtype, sn):

    #mbody  = mbody
    #sn     = '1'
    #smtype = 'img'

    #import os
    #from core.data import smpls,fpr,tc,tr,smtp
    #from core.func import waitin,get_zipfile,get_inputs,get_sample,dbginfo

    smtype = 'zip-input'
    while True:
        if smpls['zip'].get(smtype) and smpls['zip'][smtype]['astat'] != 0:
            fpr('It seems you have already attached one of USER input sample')
            if not raw_input('  Do you want to append another one [y/N]:') in [
                    'y', 'Y'
            ]:
                break
        else:
            smpls['zip'].setdefault(smtype, {})['astat'] = 0

        fpr.info('Zip your own text content')
        fpr.info('Use Ctrl-D with new line to continue.')
        print
        fpr.info('_' * (tc - 4))
        print

        inputs = get_inputs(nl=True)
        fpr.info('_' * (tc - 4))

        if inputs != '':
            print
            if raw_input('  Zip it [Y/n]:> ') in ['N', 'n']:
                break
            print
            # zipit
            zipinputs = get_zipfile({'val': '\n'.join(inputs)},
                                    fn='user-input.txt')

            n = 1
            if mbody.keys():
                n = max(mbody.keys())
                n += 1
                #print max(mbody.keys())

            mbody.setdefault(n, {})['raw'] = zipinputs

            mbody[n]['h_Content-Type'] = \
                 raw_input('  Content-Type: [%s]> ' %  'application/zip') \
                     or 'application/zip'

            mbody[n]['h_Content-Disposition'] = \
                 raw_input('  Content-Disposition: [%s]> ' %  'attachments; filename=%s' % 'uin-test.zip' ) \
                     or 'attachments; filename=%s' % 'test.zip'

            mbody[n]['h_Content-Transfer-Encoding'] = \
                 raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                     or 'base64'

            # if no cid - client like Mail.app does not
            # show the attachment
            mbody[n]['h_Content-ID'] = \
                 raw_input('  Content-ID: [%s]> ' %  '') \
                     or ''

            mbody[n]['h_Content-Description'] = \
                 raw_input('  Content-Description: [%s]> ' % '') \
                     or ''

            smpls['zip']['astat'] += 1
            smpls['zip'].setdefault(smtype, {})['astat'] += 1
            print
            fpr('Zipped %s attached (x%d)' %
                ('INPUT', smpls['zip'][smtype]['astat']))
        break
    waitin()
Ejemplo n.º 12
0
                        
                        ####
                        for k in thead.keys():
                            smtp['headers']["h_%s" % k ] = thead[k] 
                        ####
                        dbglog(smtp['headers']) 
                        waitin()
                        break
                else:
                    fpr('No header was specified')
                    waitin()
                    break
                """

    else:
        waitin()


# --------------------------------------------------------------------------- #
# decode base64 input
# --------------------------------------------------------------------------- #
def d_base64(op):

    # load from file
    if op == '1':

        fn = ''
        while True:
            bancls()
            fpr('Diagnostics: Base64 decoder')
            print
Ejemplo n.º 13
0
Archivo: m2s3.py Proyecto: bkzk/minja
def m2s3_rcptlist():             
    while True:
        bancls()
        m2s3_menu = Menu(menu.m2s3)
        #menu: return
        if m2s3_menu.op == '':
           break
        #menu: m2s3s1 - Set single recipient
        if m2s3_menu.op == '1':
           bancls()
           a = smtp['addrlist']['rcpt_to'] 
           smtp['addrlist']['rcpt_to'] = get_single_input(
                'Please set single RCPT TO (Envelope Recipient):', smtp['addrlist']['rcpt_to']
           )
           b = smtp['addrlist']['rcpt_to']
           if DEBUG: fpr('old: %s\nnew: %s' % (a,b)) 
           def upsingleRecipient(items, a, b):
               if not b:
                  if a and a in items:
                      #return [b if x == a else x for x in items]
                      # remove a - old 
                      items.remove(a)
                  return items
               if a and a in items: 
                   return [b if x == a else x for x in items]
               else:
                  #print a, 'not in ', items
                  items.insert(0,b)
                  #print items
                  return items
                  
 

           if DEBUG: print  smtp['addrlist']['rcpts'] 
           smtp['addrlist']['rcpts'] = upsingleRecipient( smtp['addrlist']['rcpts'],a,b)
           if DEBUG: print  smtp['addrlist']['rcpts'] 
           waitin()
        #menu: m2s3s2 - Build list from headers [To:, Cc:, Bcc:]
        if m2s3_menu.op == '2':
           while True:
             bancls()
             m2s3s2_menu = Menu(menu.m2s3s2)
             #menu: return
             if m2s3s2_menu.op == '':
                break
             if m2s3s2_menu.op in ['1','2','3','4']:
                bancls()
                # load func from msg.builder
                builder.rcpt_builder(m2s3s2_menu.op)
                waitin()                              

            #waitin()
           
        #menu: m2s3s3
        if m2s3_menu.op == '3':
           pass
        #menu: m2s3s4
        if m2s3_menu.op == '4':
           pass
        #menu: m2s3s5
        if m2s3_menu.op == '5':
           pass
        #menu: m2s3s6 - Get Recipients from STDIN 
        if m2s3_menu.op == '6':
           bancls()
           builder.rcpt_builder_f_inputs()
           waitin()
                         
        #menu: m2s3s7
        if m2s3_menu.op in ['7','v']:
           bancls()
           fpr('Envelope Recipients')
           print
           viewers.viewMsg('envelope')
           if smtp['addrlist']['rcpts']:
              viewers.viewEnvelope()
           waitin()
        #menu: m2s3s8
        if m2s3_menu.op in ['8','f']:
           bancls() 
           mutils.flushRecipients()
           waitin()
        #menu: m2s3sHELP
        if m2s3_menu.op == '?':
           pass
Ejemplo n.º 14
0
def splitHeaders(inputs, crlf=False):

    #TODO: split headers and parse one header per

    import email

    bancls()
    print
    fpr.warn('_' * (tc - 4))
    print
    print inputs
    print
    fpr.warn('_' * (tc - 4))
    print
    print '\r\n'.join(inputs)
    print
    fpr.warn('_' * (tc - 4))
    print
    waitin()
    bancls()

    if crlf:
        # remove empty elements from list
        # no newlines are allowed between headers
        inputs = [x for x in inputs if x != '']

    msg = email.message_from_string('\r\n'.join(inputs))

    AUTHRE = re.compile('Authentication-Results', re.IGNORECASE)
    RECSPF = re.compile('Received-SPF', re.IGNORECASE)

    hh = {
        'Received-SPF': list(),
        'Authentication-Results': list(),
    }

    parser = email.parser.HeaderParser()
    headers = parser.parsestr(msg.as_string())

    for hn, hv in headers.items():
        if DDDEBUG: fpr.green('Found: %s\n%s' % (hn, hv))
        m1 = re.match(AUTHRE, hn)
        m2 = re.match(RECSPF, hn)
        if m1:
            if DDDEBUG: print hn, hv
            hh['Authentication-Results'].append(hv)

        if m2:
            if DDDEBUG: print hn, hv

            hh['Received-SPF'].append(hv)

#    print "---------------------------------"
#    from pprint import pprint
#    pprint(hh)
#    print "---------------------------------"
#    print

#build a list
#    print len(hh['Received-SPF'])
#    print len(hh['Authentication-Results'])

    pp = {
        'Received-SPF': dict(),
        'Authentication-Results': dict(),
    }
    for hn in ['Received-SPF', 'Authentication-Results']:
        x = 0
        for h in hh[hn]:
            p = parse_spfHeaders2('%s: ' % hn + h)
            if DDDEBUG: pprint(p)
            pp.setdefault(hn, x)
            x += 1
            pp[hn].setdefault(x, p)

    print "---------------------------------"
    pprint(pp)
    print "---------------------------------"
    return pp
Ejemplo n.º 15
0
def att_load_and_zip_file(mbody, smtype, sn, attfn):

    #mbody  = smtp['content']['att']
    #sn     = '1'
    #smtype = 'img'

    #import os
    #from core.data import smpls,fpr,tc,tr,smtp
    #from core.func import waitin,get_zipfile,get_inputs,get_sample,dbginfo

    smtype = 'zipfile'
    while True:

        if smpls['zip'].get(smtype) and smpls['zip'][smtype]['astat'] != 0:
            print
            fpr('It seems you have already attached one file to zip')
            if not raw_input('  Do you want to append another one [y/N]:> '
                             ) in ['y', 'Y']:
                break
        else:
            smpls['zip'].setdefault(smtype, {})['astat'] = 0

        #print
        #fpr('Please provide a full PATH to an attachment (/path/to/your/doc.pdf)')
        #attfn = raw_input('  > ')

        if os.path.isfile(attfn):
            print
            fpr('Loading %s ..' % attfn)
            if False:  # skip checking file type for zip

                from mimetypes import guess_type
                from email.encoders import encode_base64
                mimetype, encoding = guess_type(attfn)

                # if no extension try to detect mime type with a libmagic library
                # from python-magic package if possible
                if mimetype == None:
                    try:
                        import magic
                        mimetype = magic.from_file(attfn, mime=True)
                    except ImportError:
                        dbginfo(
                            'warrning',
                            'Warrning: No "magic" library. Use: pip install python-magic'
                        )
                        print
                        mimetype = 'text/plain'

            fp = open(attfn, 'rb')

            inputs = fp.read()
            fp.close()
            if not inputs:
                print
                dbginfo(
                    'error',
                    'Err: File has no content. Please verify file size !\n[ %s ]'
                    % attfn)
                break

            n = 1
            if mbody.keys():
                n = max(mbody.keys())
                n += 1
                #print max(mbody.keys())
            print
            fpr('Attaching zipped %s -> %s' %
                (os.path.basename(attfn),
                 (os.path.splitext(os.path.basename(attfn))[0] + '.zip')))
            print
            zipinputs = get_zipfile({'val': inputs},
                                    fn=os.path.basename(attfn))
            #print type(inputs)
            mbody.setdefault(n, {})['raw'] = zipinputs

            mbody[n]['h_Content-Type'] = \
                 raw_input('  Content-Type: [%s]> ' %  'application/zip') \
                     or 'application/zip'

            mbody[n]['h_Content-Disposition'] = \
                 raw_input('  Content-Disposition: [%s]> ' % \
                     'attachments; filename=%s' % ( os.path.splitext(os.path.basename(attfn))[0] +'.zip' ) ) \
                     or 'attachments; filename=%s' %  ( os.path.splitext(os.path.basename(attfn))[0] +'.zip' )

            mbody[n]['h_Content-Transfer-Encoding'] = \
                 raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                     or 'base64'
            # if no cid - client like Mail.app does not
            # show the attachment
            mbody[n]['h_Content-ID'] = \
                 raw_input('  Content-ID: [%s]> ' %  '') \
                     or ''
            mbody[n]['h_Content-Description'] = \
                 raw_input('  Content-Description: [%s]> ' % '') \
                     or ''

            #smpls['img']['astat'] += 1
            #smpls['zip']['astat'] += 1
            smpls['zip'].setdefault(smtype, {})['astat'] += 1
            print
            fpr('Zipped %s attached (x%d)' %
                (os.path.basename(attfn), smpls['zip'][smtype]['astat']))
            waitin()
            break
        else:
            fpr('No such file or you don\'t have a permission to access it')
            print
            if raw_input('  Return to menu [y/N]> ') in ['y', 'Y']:
                break
Ejemplo n.º 16
0
def e_base64(op):
    # load from file
    if op == '1':
        fn = ''
        while True:
            bancls()
            fpr('Diagnostics: Base64 encoder')
            print
            fpr('Please provide a file name:')
            fn = raw_input('  []> ')
            print
            inputs = get_file_content(fn)
            print
            if inputs:
                #inputs = f.readlines()          # include \n
                #inputs = f.read().splitlines()   # exclude \n
                dbginfo('debug', inputs)
                print

                encb64 = coders.encode_attch(inputs)

                if isinstance(encb64, dict):
                    fpr.ok('File content was encoded successful')
                else:
                    fpr.fail('File content was not encoded')
                waitin()
                return encb64
            elif raw_input('  Return to menu [y/N]> ') in ['y', 'Y']:
                break

            waitin()
    # load from input - paste it
    if op == '2':
        bancls()
        fpr('Diagnostics: Base64 encoder')
        print
        if raw_input('  Would you like to encode some content [y/N]> ') in [
                'y', 'Y'
        ]:
            print
            fpr('Please provide some plain content')
            fpr('Use Ctrl-D with new line to continue.')
            print
            fpr.blue('_' * (tc - 4))
            print
            inputs = get_inputs()
            fpr.blue('_' * (tc - 4))

            if inputs:
                dbglog(inputs)
                print
                encb64 = coders.encode_attch('\n'.join(inputs))

                if isinstance(encb64, dict):
                    fpr.ok('Input content was encoded successful')
                else:
                    fpr.fail('Input content was not encoded')
                waitin()
                return encb64
            #print inputs
            waitin()
Ejemplo n.º 17
0
def att_load_file(mbody, attfn):

    #import os
    #from core.data import smtp,fpr,tc,tr
    #from core.func import waitin,dbginfo

    if os.path.isfile(attfn):
        print
        fpr('Loading %s ..' % attfn)

        #from mimetypes import guess_type
        #from email.encoders import encode_base64
        mimetype, encoding = guess_type(attfn)

        # if no extension try to detect mime type wit a libmagic library
        # from python-magic package if possible
        if mimetype == None:
            try:
                import magic
                mimetype = magic.from_file(attfn, mime=True)
            except ImportError:
                dbginfo(
                    'warrning',
                    'Warrning: Missing module: magic. Use: pip install python-magic'
                )
                print
                mimetype = 'text/plain'
        #mimetype = mimetype.split('/', 1)
        fp = open(attfn, 'rb')
        inputs = fp.read()
        fp.close()

        if not inputs:

            dbginfo(
                'error',
                'Err: File has no content. Please verify file size !\n[ %s ]' %
                attfn)
            #break
            return False

        if inputs:
            info('info','Default Content-* header values are generated based on file extension. If no' \
                        'extension and no \'magic\' module is found than text/plain is suggested by \ndefault.',adj='l')
            print
            fpr('Please define MIME headers for this attachment')
            print
            n = 1
            if mbody.keys():
                #global n
                n = max(mbody.keys())
                n += 1
                #print max(mbody.keys())

            fpr('Attachment no: %d' % n, 'c')
            print
            mbody.setdefault(n, {})['raw'] = inputs
            #mbody['0']['b64'] = inputs

            mbody[n]['h_Content-Type'] = \
                  raw_input('  Content-Type: [%s]> ' %  mimetype) \
                       or mimetype
            mbody[n]['h_Content-Disposition'] = \
                  raw_input('  Content-Disposition: [%s]> ' %  \
                          'attachments; filename=%s' % os.path.basename(attfn)) \
                       or 'attachments; filename=%s' % os.path.basename(attfn)
            mbody[n]['h_Content-transfer-encoding'] = \
                  raw_input('  Content-transfer-encoding: [%s]> ' %  '') \
                       or ''
            mbody[n]['h_Content-ID'] = \
                  raw_input('  Content-ID: [%s]> ' %  '') \
                       or ''
            mbody[n]['h_Content-Description'] = \
                  raw_input('  Content-Description: [%s]> ' % '') \
                       or ''

        waitin()
    else:
        fpr('No such file or you don\'t have a permission to access it')
        print
        return False
Ejemplo n.º 18
0
def e_headers():

    fpr('Diagnostics: Header encoder')
    print
    if raw_input('  Would you like to encode some headers [y/N]> ') in [
            'y', 'Y'
    ]:

        if True:
            print
            fpr('Please provide a header in format: >> Header-name: header-value <<'
                )
            fpr('Use Ctrl-D to continue.')
            fpr.blue('_' * (tc - 4))
            print
            # to preserve new line pass nl=True with get_inputs()
            inputs = get_inputs()
            if inputs != '':
                thead = {}
                ####### TODO: move this to def encode_mheaders()
                for (i, hline) in enumerate(inputs):
                    #print hline
                    m1 = re.match(r'(.*):(.*)', hline)  # it is a header
                    m2 = re.match(r'^(\s+)(.*)',
                                  hline)  # it is a continuation of prev header
                    if hline == '\n':
                        key = ''
                    elif m1:
                        if m1.group(1):
                            key = m1.group(1)
                            thead.setdefault(key, []).append(m1.group(2))
                    elif m2:
                        if key == '' and inputs[i - 1] != '\n':
                            key = '-no-hn-'
                            while key in thead.keys():
                                key += '-'
                        thead.setdefault(key,
                                         []).append(m2.group(1) + m2.group(2))
                #############
                fpr.blue('_' * (tc - 4))
                print
                fpr('Found headers')
                print
                for k in thead.keys():
                    fpr.info('_' * (tc - 4))
                    print
                    if re.match('-no-hn-', k):
                        fpr('Header-name: <None>')
                    else:
                        fpr('Header-Name: %s' % k)
                        fpr('Header: %s' % thead[k])
                        #fpr('Encoding: %s' % enc)

                    fpr.info('_' * (tc - 4))

                if thead.keys():
                    print
                    chset = raw_input(
                        '  Define headers encoding or leave empty to use a default one\n  [us-ascii]: '
                    ) or 'us-ascii'
                    fpr.blue('_' * (tc - 4))
                    print
                    #print
                    if chset:

                        #from email.message import Message
                        #from email.header import Header
                        for hn in thead.keys():
                            try:
                                h = Header(''.join(thead[hn]),
                                           charset=chset,
                                           maxlinelen=76,
                                           header_name=hn)
                                #print h.encode()
                                print
                                msg = Message()
                                msg[hn] = h
                                print msg.as_string()
                            except UnicodeDecodeError, e:
                                print
                                fpr.err('UnicodeDecodeError: %s' % e)
                                print
                                fpr('Try to set proper encoder! ')
                            print
                    fpr.blue('_' * (tc - 4))

                waitin()
                """ 
Ejemplo n.º 19
0
def att_custom_header():
    #import re
    print
    if raw_input('  Would you like to include your own headers [y/N]> ') in [
            'y', 'Y'
    ]:
        while True:
            print
            fpr('Please provide a header in format: >> Header-name: header-value <<'
                )
            fpr('Use Ctrl-D with new line to save it and continue.')
            fpr.blue('_' * (tc - 4))
            print
            #            inputs = []
            #            while True:
            #                try:
            #                    line = raw_input("")
            #                except EOFError:
            #                    break
            #                inputs.append(line)
            # to preserve new line pass nl=True with get_inputs()
            inputs = get_inputs()
            if inputs != '':
                thead = {}
                ####### TODO: move this to def encode_mheaders()
                for (i, hline) in enumerate(inputs):
                    #print hline
                    m1 = re.match(r'(.*):(.*)', hline)  # it is a header
                    m2 = re.match(r'^(\s+)(.*)',
                                  hline)  # it is a continuation of prev header
                    if hline == '\n':
                        key = ''
                    elif m1:
                        if m1.group(1):
                            key = m1.group(1)
                            thead.setdefault(key, []).append(m1.group(2))
                    elif m2:
                        if key == '' and inputs[i - 1] != '\n':
                            key = '-no-hn-'
                            while key in thead.keys():
                                key += '-'
                        thead.setdefault(key,
                                         []).append(m2.group(1) + m2.group(2))
                #############
                fpr.blue('_' * (tc - 4))
                for k in thead.keys():
                    fpr.info('_' * (tc - 4))
                    print
                    if re.match('-no-hn-', k):
                        fpr('Header-name: <None>')
                    else:
                        fpr('Header-Name: %s' % k)
                        fpr('Header: %s' % thead[k])
                        #fpr('Encoding: %s' % enc)

                    fpr.info('_' * (tc - 4))
                fpr.blue('_' * (tc - 4))
                print

                #print theadi
                if thead.keys():
                    if raw_input('  Are your headers parsed correctly [Y/n]:> '
                                 ) in ['n', 'N']:
                        if raw_input(
                                '  Would you like to add them one more time [Y/n]:> '
                        ) in ['n', 'N']:
                            break
                        else:
                            waitin()

                    else:

                        # if RFC: format header-name, format header length,
                        #                        rfcline = 1
                        #                        if raw_input('  Should lines follow the RFC or leave it as you put it [Y/n]> ') in ['n', 'N']:
                        #                            rfcline = 0

                        ####
                        for k in thead.keys():
                            smtp['headers']["h_%s" % k] = thead[k]
                        ####
                        dbglog(smtp['headers'])
                        waitin()
                        break
                else:
                    fpr('No header was specified')
                    waitin()
                    break
Ejemplo n.º 20
0
def att_load_base64(mbody):

    # attachment: paste base64 encoded part
    #from core.data import smtp,fpr,tc,tr,DEBUG
    #from core.func import waitin,get_inputs,dbglog,dbginfo
    #from core.msg.coders import isBase64

    while True:
        fpr.info('_' * (tc - 4))
        print

        inputs = get_inputs()

        fpr.info('_' * (tc - 4))

        if inputs != '':
            dbglog(inputs)
            b64result = 1
            for i in inputs:
                if not isBase64(i):

                    dbginfo('error', 'Err: Line is not a proper base64 line',
                            i)

                    b64result = 0
                    break
            if b64result and inputs:
                print
                fpr('Message seems to have proper base64 lines')
                print
                fpr('Please define MIME headers for this attachment')
                print
                n = 1
                if mbody.keys():
                    #global n
                    n = max(mbody.keys())
                    n += 1
                    #print max(mbody.keys())

                fpr('Attachment no: %d' % n, adj='c')
                print
                mbody.setdefault(n, {})['b64'] = inputs
                #mbody['0']['b64'] = inputs

                mbody[n]['h_Content-Type'] = \
                      raw_input('  Content-Type: [%s]> ' %  '') \
                           or ''
                mbody[n]['h_Content-Disposition'] = \
                      raw_input('  Content-Disposition: [%s]> ' % '') \
                           or ''
                mbody[n]['h_Content-transfer-encoding'] = \
                      raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                           or 'base64'
                mbody[n]['h_Content-ID'] = \
                      raw_input('  Content-ID: [%s]> ' %  '') \
                           or ''
                mbody[n]['h_Content-Description'] = \
                      raw_input('  Content-Description: [%s]> ' %  '') \
                           or ''
            waitin()
            break
Ejemplo n.º 21
0
Archivo: parser.py Proyecto: bkzk/minja
def mail_body_parser(body):

    if not hasattr(body, 'as_string'):
        fpr.err('Message can not be processed or not loaded !')
        return

    b = email.message_from_string(body.as_string())
    btype = b.get_content_type()

    dbginfo('debug', 'btype is %s' % btype)
    print

    # parse the body and save split parts in dictionary
    dparts = dict()
    body_parser(dparts, b)

    fpr.cyan('=' * (tc - 4))
    #    pprint(dparts)

    if DEBUG: dbginfo('debug', str(dparts.keys()))

    fpr.cyan('=' * (tc - 4))

    ## build a dictionary

    print
    if not dparts.keys():
        fpr('No MIME parts found')
        return

    mimemulti = ['multipart/mixed', 'multipart/alternative']
    print mimemulti

    while True:
        bancls()
        fpr('Message MIME structure')
        print
        fpr('_' * (tc - 4))
        print
        bstrio = StringIO()
        _structure(b, bstrio)
        fpr.warn('%s' % bstrio.getvalue())
        #fpr.warn(_structure(bpart))
        fpr('_' * (tc - 4))
        print
        fpr('MIME parts ready to review:')
        print
        for k in dparts.keys():
            #print k
            #print type(k)
            if dparts[k]['type'] in mimemulti:
                fpr.info('  [%s] %s ' % (k, dparts[k]['type'][:69]))
            else:
                fpr('  [%s] %s ' % (k, dparts[k]['type'][:69]))
        print
        op = raw_input('  []> ')

        # dparts keys are int not strings
        if op.isdigit():
            k = int(op)
        if op == '':
            break
        while k in dparts.keys():
            bancls()
            fpr('MIME Headers: %s' % k)
            fpr('_' * (tc - 4))
            print
            for (h, hv) in dparts[k]['mheaders']:
                fpr('%s: %s' % (h, hv))
            fpr('_' * (tc - 4))

            print
            #           pprint(dparts)
            #           waitin()
            if dparts[k].get('type') in mimemulti:
                fpr.warn('This part is not directly viewable')
                waitin()
                break
            elif dparts[k].get('payload'):
                fpr('Choose option:')
                print
                fpr('  1) view payload')
                fpr('  2) save payload')
                fpr.off('  3) attach payload to composer [?future feature?]')
                print
                op = raw_input('  []> ')
                if op == '':
                    waitin()
                    break
                # --- view payload ---
                if op in ['1']:
                    bancls()
                    fpr('MIME Payload ')
                    print
                    fpr.warn('%s' % dparts[k].get('type'))
                    print

                    xe = 0
                    for (h, hv) in dparts[k].get('mheaders'):
                        #fpr('%s: %s' % (h,hv))
                        if h.lower() == 'content-transfer-encoding':
                            #part['encext'] = '.'+hv.lower()
                            if hv in ['base64']:
                                info(
                                    'info',
                                    'This payload is base64 encoded. You can view it as it is or try to decode it first.'
                                )
                                print
                                if get_yesno_input(
                                        '  Would like to decode the payload first [y/N]:> '
                                ):

                                    dp = decode_attch(dparts[k]['payload'])
                                    #pprint(dp)
                                    #print len(dp.get('raw'))
                                    #print len(str(dp))
                                    if len(dp.get('raw')) > tr:
                                        #if True:
                                        if get_yesno_input(
                                                '  Would like to use system pager to view it [y/N]:> '
                                        ):

                                            fpr('_' * (tc - 4))
                                            print
                                            pager = Less(num_lines=tr)
                                            print dp.get('raw') | pager
                                            fpr('_' * (tc - 4))
                                        else:
                                            fpr('_' * (tc - 4))
                                            print
                                            fpr(dp.get('raw'))
                                            print
                                            fpr('_' * (tc - 4))

                                    waitin()
                                    xe = 1
                                    break
                    # if viewed decoded part do not display encoded one
                    if xe:
                        break
                    print
                    if len(dparts[k].get('payload')) > tr:
                        if get_yesno_input(
                                '  Would like to use system pager to view it [y/N]:> '
                        ):

                            fpr('_' * (tc - 4))
                            print
                            pager = Less(num_lines=tr)
                            print dparts[k]['payload'] | pager
                            fpr('_' * (tc - 4))
                        else:
                            fpr('_' * (tc - 4))
                            print
                            fpr(dparts[k]['payload'])
                            print
                            fpr('_' * (tc - 4))
                    else:

                        fpr('_' * (tc - 4))
                        print
                        if type(dparts[k].get('payload')) is not 'str':
                            fpr.err('An error occured')
                        else:
                            fpr(dparts[k].get('payload'))
                        print
                        fpr('_' * (tc - 4))

                    waitin()
                if op in ['2']:
                    bancls()
                    fpr('MIME Payload export')

                    fpr('Choose option:')
                    print
                    fpr('  1) save payload, as it is (no decoding)')
                    fpr('  2) save payload - base64 decoded')
                    print
                    op = raw_input('  []> ')
                    print
                    if op == '':
                        waitin()
                        break
                    if op in ['1']:
                        bancls()
                        mpart_saver(dparts[k], 1)
                        waitin()
                    if op in ['2']:
                        bancls()
                        mpart_saver(dparts[k], 2)
                        waitin()
                break
            else:
                fpr.warn(
                    'Wrr: Empty payloyd. Message malformed or parsing has failed.'
                )
                waitin()
                break
Ejemplo n.º 22
0
def chThrDep(t=None, rpm=None, mpt=None):

    #VERIFY:  In Python 2.x : int/int --> int and int/float --> float In Python 3.x : int/int can result in a float

    from core.data import smtp, fpr, tc, tr
    from core.func import waitin

    r = get_rcpts('NoR')

    #Warunki Konieczne - Essential Conditions
    # to met WK1, WK2, WK3
    if not t:
        t = smtp['replay']['threads'].get('not', None)
    elif t and not (1 <= int(t) <= r):
        if r > 1:
            t = r
        if r == 1:  #special case
            pass
    if t:
        smtp['replay']['threads']['not'] = int(t)

    if not rpm:
        rpm = smtp['replay']['threads'].get('rpm', None)
    elif rpm and not (1 <= int(rpm) <= r):
        rpm = int(r)
    if rpm:
        fpr.ok('Saving RpM as %s' % rpm)
        smtp['replay']['threads']['rpm'] = int(rpm)

    if not mpt:
        mpt = smtp['replay']['threads'].get('mpt', None)
    elif mpt and not (1 <= int(mpt) <= r):
        mpt = int(r)
    if mpt:
        fpr.ok('Saving MpT as %s' % mpt)
        smtp['replay']['threads']['mpt'] = int(mpt)

    if r:

        # specific feature: the result depends from number of recipients
        # -------------------------------------------------------------------- #
        if t and not rpm and not mpt:
            fpr.warn('%s : %s : %s - %s' % (t, rpm, mpt, r))
            # allow to set t if no rpm or mpt values and number of rcpt > 1
            # but t must be <= r, so if t greater then r => it will be equal to r
            if r > 1:
                smtp['replay']['threads']['not'] = int(t)
                fpr.ok('Saving NoT as %s' % t)
                return t

            # special case when r == 1 , not related to our Equation
            # for r = 1 allow to set T > 1 but do not allow than set rpm or mpt
            # in this special case the sam message is flooding a sepcific rcpt
            # with this smae message in multiple threads/connection !
            if r == 1:
                #pass
                smtp['replay']['threads']['not'] = int(t)
                fpr.ok('Saving NoT as %s' % t)
                return t

        # set initial
        elif rpm and not t and not mpt:
            fpr.warn('%s : %s : %s - %s' % (t, rpm, mpt, r))
            if r > 1:
                smtp['replay']['threads']['rpm'] = int(rpm)
                #return rpm
                #return True
            if r == 1:
                fpr.warn('It doesn\'t make sense to define RpM when NoR = 1')
                return False
        #
        elif mpt and not t and not rpm:
            fpr.warn('%s : %s : %s - %s' % (t, rpm, mpt, r))
            if r > 1:
                smtp['replay']['threads']['mpt'] = int(mpt)
                #return mpt
                #return True
            if r == 1:
                fpr.warn('It doesn\'t make sense to define MpT when NoR = 1')
                return False

    else:
        fpr.err('Recipients not defined. Build a list of recipients first.')
        fpr.err('Flush the values if the recipient list has been modified.')
        return

    # Some maths :)
    #
    # rpm - recipient per message
    # r - number of recipients (all)
    # m - number of messages (all)
    #
    # rpm = r / m ==> m = r / rpm

    # mpt - messages per thread
    # t - number of threads
    # m - number of messages (all)
    #
    # mpt = m / t ==> m = mpt * t

    # r / rpm = mpt * t
    #
    # ==>   t = r / (rpm * mpt)
    #
    # ==> rpm = r / (mpt * t)
    #
    # ==> mpt = r / (rpm * t)

    fpr.info('_' * (tc - 4))
    print
    fpr.warn('Your limits:')
    fpr.warn('t = %s : rpm = %s : mpt = %s - r = %s' %
             (smtp['replay']['threads'].get(
                 'not', None), smtp['replay']['threads'].get('rpm', None),
              smtp['replay']['threads'].get('mpt', None), r))
    print
    fpr.err('Maximum possible limits to met Essential Conditions:')
    fpr.err('t = %s : rpm = %s : mpt = %s - r = %s' % (t, rpm, mpt, r))
    fpr.info('_' * (tc - 4))

    print

    def chEque():
        print
        if r:

            # compare float
            # https://ubuntuforums.org/showthread.php?t=840665
            def float_eq(a, b, epsilon=0.00000001):
                fpr.cyan('<float_eq> %s' % abs(a - b))
                if abs(a - b) < epsilon:
                    return True
                return False

            m1 = float(r) / rpm
            m2 = mpt * float(t)

            fpr.cyan('r/rpm = %s, mpt * t = %s' % (m1, m2))

            if float_eq(m1, m2):
                fpr.green('Equetion is met')
                waitin()
                return True
            else:
                fpr.err('Equetion is false')
                waitin()
                return False

    def setReals(t, rpm, mpt):

        if t and rpm and mpt:
            smtp['replay']['threads']['reals'].setdefault('not', t)
            smtp['replay']['threads']['reals'].setdefault('rpm', rpm)
            smtp['replay']['threads']['reals'].setdefault('mpt', mpt)

            smtp['replay']['threads']['reals']['not'] = t
            smtp['replay']['threads']['reals']['rpm'] = rpm
            smtp['replay']['threads']['reals']['mpt'] = mpt
            fpr.ok('Reals were set!')

    if r:

        # count the mpt - based on rpm and t
        # -------------------------------------------------------------------- #
        if t and rpm and not mpt:
            fpr.green('%s : %s : %s - %s' % (t, rpm, mpt, r))

            # m = r / rpm
            # mpt = m / t

            # I - validate MPT - MPT <= R
            mpt = float(r) / (rpm * t)
            fpr.green('counting mpt = %s' % mpt)

            chEque()

            # round up - if there is a remainder
            if (r % (rpm * t) > 0):
                mpt = r / (rpm * t) + (r % (rpm * t) > 0)
                fpr.green('rounding up mpt = %s' % mpt)

                # find the lowest T for rounded MpT to met RpM
                t_new = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)
                fpr.green('counting new t = %s' % t_new)

                if (r % (rpm * mpt) > 0):  # if remainder
                    t_new = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                    fpr.green('rounding up new t = %s' % t_new)

                fpr.err(
                    'realistic returns would be: *t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t_new), rpm, int(mpt), r))
                setReals(int(t_new), rpm, int(mpt))
            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, rpm, int(mpt), r))
                setReals(t, rpm, int(mpt))

        # count the rpm - for mpt and t
        # -------------------------------------------------------------------- #
        elif t and mpt and not rpm:
            fpr.blue('%s : %s : %s - %s' % (t, rpm, mpt, r))

            # m = mpt * t
            # m = r / rpm

            # TODO
            # WK: validate RPM , RPM <= R

            rpm = float(r) / (mpt * t)
            fpr.blue('counting: rpm = %s' % rpm)

            chEque()

            # if there is a remainder
            if (r % (mpt * t) > 0):
                rpm = r / (mpt * t) + (r % (mpt * t) > 0)
                fpr.blue('rounding up rpm = %s' % rpm)

                # find the lowest T for rounded MpT to met RpM
                t_new = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)
                fpr.green('counting new t = %s' % t_new)

                if (r % (rpm * mpt) > 0):  # if remainder
                    t_new = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                    fpr.green('rounding up new t = %s' % t_new)

                fpr.err(
                    'realistic returns would be: *t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t_new), int(rpm), mpt, r))
                setReals(int(t_new), int(rpm), mpt)

            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, int(rpm), mpt, r))
                setReals(t, int(rpm), mpt)

        # count the mpt ( use t = 1 )
        # -------------------------------------------------------------------- #
        elif rpm and not t and not mpt:
            t = 1
            fpr.purple('assuming t eq 1 for equation')
            fpr.purple('%s : %s : %s - %s' % (t, rpm, mpt, r))

            mpt = float(r) / rpm
            fpr.purple('counting: mpt = %s' % mpt)

            chEque()

            #if there is a remainder
            if (r % rpm > 0):

                mpt = r / rpm + (r % rpm > 0)
                fpr.purple('rounding up mpt = %s' % mpt)

                # find the lowest T for rounded MpT to met RpM
                t_new = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)
                fpr.green('counting new t = %s' % t_new)

                if (r % (rpm * mpt) > 0):  # if remainder
                    t_new = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                    fpr.green('rounding up new t = %s' % t_new)

                fpr.err(
                    'realistic returns would be: *t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t_new), rpm, mpt, r))
                setReals(int(t_new), rpm, mpt)

            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, rpm, int(mpt), r))
                setReals(t, rpm, int(mpt))

        # count the rpm ( use t = 1 )
        # -------------------------------------------------------------------- #
        elif mpt and not t and not rpm:
            t = 1
            fpr.purple('assuming t eq 1 for equation')
            fpr.purple('%s : %s : %s - %s' % (t, rpm, mpt, r))

            rpm = float(r) / mpt
            fpr.purple('counting: rpm = %s' % rpm)
            t = 1
            chEque()

            #if there is a remainder
            if (r % mpt > 0):

                rpm = r / mpt + (r % mpt > 0)
                fpr.purple('rounding up rpm = %s' % rpm)

                # find the lowest T for rounded MpT to met RpM
                t_new = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)
                fpr.green('counting new t = %s' % t_new)

                if (r % (rpm * mpt) > 0):  # if remainder
                    t_new = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                    fpr.green('rounding up new t = %s' % t_new)

                fpr.err(
                    'realistic returns would be: *t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t_new), int(rpm), mpt, r))
                setReals(int(t_new), int(rpm), mpt)

            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, int(rpm), mpt, r))
                setReals(t, int(rpm), mpt)

        # count t - for rpm and mpt
        # -------------------------------------------------------------------- #
        elif mpt and rpm and not t:
            fpr.white('%s : %s : %s - %s' % (t, rpm, mpt, r))
            print type(mpt)

            # add 1 to round up a result
            # (r % (rpm * mpt) > 0) it will return True which is 1
            # if there is a remainder and 0 if not
            t = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)

            fpr.white('counted: t = %s' % t)

            chEque()

            # round up
            if (r % (rpm * mpt) > 0):
                t = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                fpr.white('rounding up t = %s' % t)

            # validate WK
            # t = <1,r>
            # if t < 1
            if (float(r) / (rpm * mpt)) < 1:
                fpr.info('Now to met equetion for t=1 it is not possible for %s (R) recipients '\
                         'to send %s (MpT) messeges in one thread with %s (RpM) recipient in message' %
                         (r,mpt,rpm))

                print
                fpr.info('New RpM value can be counted based on existing MpT or new MpT ' \
                         'value can be counted based on existing RpM' )
                print
                fpr.info('For simplicity it is assumed that RpM limits is more important so MpT ' \
                         'is going to be recounted to met an equation')
                print

                mpt_new = float(r) / rpm
                fpr.white('New MpT to met equetion is %s' % mpt_new)
                mpt = mpt_new

                chEque()

                # now just round up
                mpt_new = r / rpm + (r % rpm > 0)
                fpr.white('rounding up new mpt = %s' % mpt_new)

                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, *mpt = %s  for r = %s'
                    % (int(t), rpm, int(mpt_new), r))
                setReals(int(t), rpm, int(mpt_new))
            else:
                # so if t > 1 and it was counted
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t), rpm, int(mpt), r))
                setReals(int(t), rpm, int(mpt))

        # only true if r / rpm = mpt * t
        # -------------------------------------------------------------------- #
        elif t and rpm and mpt:
            fpr.cyan('%s : %s : %s - %s' % (t, rpm, mpt, r))
            if not chEque():
                fpr.info('_' * (tc - 4))
                print
                fpr.warn('It is not recommended trying to set NoT with RpM and MpT.  ' \
                         'Suggested action would be to flush these values.' )
                fpr.info('_' * (tc - 4))
                print
                waitin()
                return False
            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, rpm, mpt, r))
                setReals(t_new, rpm, mpt)

    # for test
    waitin()