Beispiel #1
0
def main():
    """
    This should print a current identity or create a new one.
    """
    settings.init(base_dir='/tmp/fake_id')
    from userid import my_id
    my_id.loadLocalIdentity()
    if my_id.isLocalIdentityReady():
        my_id.getLocalIdentity().sign()
        print(my_id.getLocalIdentity().serialize())
        print('Valid is: ', my_id.getLocalIdentity().Valid())
    else:
        if not key.InitMyKey():
            key.GenerateNewKey()
        ipaddr = '127.0.0.1'
        if len(sys.argv) > 2:
            ipaddr = sys.argv[2]
        rev = 0
        if len(sys.argv) > 3:
            rev = int(sys.argv[3])
        idurls = []
        if len(sys.argv) > 4:
            idurls = sys.argv[4:]
        my_id.setLocalIdentity(
            my_id.buildDefaultIdentity(name=sys.argv[1],
                                       ip=ipaddr,
                                       idurls=idurls,
                                       revision=rev))
        my_id.saveLocalIdentity()
        print(my_id.getLocalIdentity().serialize())
        print('Valid is: ', my_id.getLocalIdentity().Valid())
        my_id._LocalIdentity = None
        my_id.loadLocalIdentity()
    settings.shutdown()
Beispiel #2
0
def main():
    import pprint

    lg.set_debug_level(14)
    if sys.argv.count("list"):
        maps = lst()
        for itm in maps:
            pprint.pprint(itm)
    elif sys.argv.count("info"):
        locip, extip, maps = info()
        pprint.pprint(locip)
        pprint.pprint(extip)
        for itm in maps:
            pprint.pprint(itm)
    elif sys.argv.count("add"):
        print add(sys.argv[2], "TCP")
    elif sys.argv.count("del"):
        print dlt(sys.argv[2], "TCP")
    elif sys.argv.count("update"):
        bpio.init()
        settings.init()
        init()
        pprint.pprint(update(sys.argv[2]))
    elif sys.argv.count("clear"):
        print clear()
    else:
        print "usage:"
        print "run_upnpc.py info"
        print "run_upnpc.py list"
        print "run_upnpc.py add [port]"
        print "run_upnpc.py del [port]"
        print "run_upnpc.py update [port]"
        print "run_upnpc.py clear"
Beispiel #3
0
def main():
    bpio.init()
    settings.init()
    lg.set_debug_level(18)
    (options, args) = parseCommandLine()
    init(options.udpport, options.dhtdb)

    def _go(nodes):
        if len(args) == 0:
            pass
        elif len(args) > 0:

            def _r(x):
                print x
                reactor.stop()

            cmd = args[0]
            if cmd == 'get':
                get_value(args[1]).addBoth(_r)
            elif cmd == 'set':
                set_value(args[1], args[2]).addBoth(_r)
            elif cmd == 'find':
                find_node(key_to_hash(args[1])).addBoth(_r)
            elif cmd == 'discover':

                def _l(x):
                    print x
                    find_node(random_key()).addBoth(_l)

                _l('')

    connect().addBoth(_go)
    reactor.run()
Beispiel #4
0
def main():
    import logging
    logging.basicConfig(level=logging.DEBUG)
    from twisted.internet.defer import setDebugging
    setDebugging(True)
    # from twisted.python import log as twisted_log
    # twisted_log.startLogging(sys.stdout)
    lg.set_debug_level(20)
    settings.init()
    settings.update_proxy_settings()

    if sys.argv.count('receive'):
        start_receiving()
#         global _Contacts
#         _Contacts['http://p2p-id.ru/veselin.xml'] = ('127.0.0.1', 9122)

    elif sys.argv.count('send'):
        start_sending(port=int(sys.argv[2]))
        send_file(sys.argv[3], sys.argv[4])

    else:
        usage()
        return

    reactor.run()
Beispiel #5
0
 def setUp(self):
     try:
         bpio.rmdir_recursive('/tmp/.bitdust_tmp')
     except Exception:
         pass
     lg.set_debug_level(30)
     settings.init(base_dir='/tmp/.bitdust_tmp')
     try:
         os.makedirs('/tmp/.bitdust_tmp/metadata')
     except:
         pass
     automat.OpenLogFile('/tmp/.bitdust_tmp/logs/automats.log')
     self.my_current_key = None
     fout = open('/tmp/_some_priv_key', 'w')
     fout.write(_some_priv_key)
     fout.close()
     fout = open(settings.LocalIdentityFilename(), 'w')
     fout.write(_some_identity_xml)
     fout.close()
     self.assertTrue(key.LoadMyKey(keyfilename='/tmp/_some_priv_key'))
     self.assertTrue(my_id.loadLocalIdentity())
     my_id.init()
     try:
         os.makedirs('/tmp/.bitdust_tmp/logs')
     except:
         pass
     local_fs.WriteTextFile('/tmp/.bitdust_tmp/logs/parallelp.log', '')
     tmpfile.init(temp_dir_path='/tmp/.bitdust_tmp/temp/')
     os.makedirs(
         '/tmp/.bitdust_tmp/backups/[email protected]_8084/1/F1234')
     try:
         bpio.rmdir_recursive('/tmp/_some_folder', ignore_errors=True)
     except:
         pass
     os.makedirs('/tmp/_some_folder')
Beispiel #6
0
def main():
    """
    Entry point.
    """
    if len(sys.argv) < 2:
        return
    bpio.init()
    lg.disable_logs()
    lg.disable_output()
    settings.init()
    lg.set_debug_level(0)
    id_url.init()
    commands = {
        'update_customers': UpdateCustomers,
        'validate': Validate,
        'space_time': SpaceTime,
    }
    cmd = commands.get(sys.argv[1], None)
    if not cmd:
        if _Debug:
            printlog('ERROR wrong command: %r' % sys.argv)
        return
    cmd()
    settings.shutdown()
    id_url.shutdown()
def cmd_set(opts, args, overDict):
    from main import settings
    from interface import api
    name = args[1].lower()
    if name in ['list', 'ls', 'all', 'show', 'print', ]:
        settings.init()
        sort = True if (len(args) > 2 and args[2] in ['sort', 'sorted', ]) else False
        result = api.config_list(sort)
        for i in xrange(len(result['result'])):
            result['result'][i]['value'] = result['result'][i]['value'][:60]
        tpl = jsontemplate.Template(templ.TPL_OPTIONS_LIST_KEY_TYPE_VALUE)
        print_template(result, tpl)
        return 0
    path = '' if len(args) < 2 else args[1]
    path = option_name_to_path(name, path)
    if path != '':
        settings.init()
        if len(args) > 2:
            value = ' '.join(args[2:])
            result = api.config_set(path, unicode(value))
        else:
            result = api.config_get(path)
        tpl = jsontemplate.Template(templ.TPL_OPTION_MODIFIED)
        print_template(result, tpl)
        return 0
    return 2
 def setUp(self):
     try:
         bpio.rmdir_recursive('/tmp/.bitdust_tmp')
     except Exception:
         pass
     lg.set_debug_level(30)
     settings.init(base_dir='/tmp/.bitdust_tmp')
     self.my_current_key = None
     try:
         os.makedirs('/tmp/.bitdust_tmp/metadata/')
     except:
         pass
     try:
         os.makedirs('/tmp/.bitdust_tmp/identitycache/')
     except:
         pass
     fout = open('/tmp/_some_priv_key', 'w')
     fout.write(_some_priv_key)
     fout.close()
     fout = open(settings.LocalIdentityFilename(), 'w')
     fout.write(_some_identity_xml)
     fout.close()
     self.assertTrue(key.LoadMyKey(keyfilename='/tmp/_some_priv_key'))
     self.assertTrue(my_id.loadLocalIdentity())
     self.bob_ident = identity.identity(xmlsrc=_another_identity_xml)
     identitycache.UpdateAfterChecking(idurl=self.bob_ident.getIDURL(),
                                       xml_src=_another_identity_xml)
Beispiel #9
0
def safe_stun(udp_port=None, dht_port=None, ):
    from twisted.internet.defer import Deferred
    result = Deferred()
    try:
        settings.init()
        dht_port = dht_port or settings.getDHTPort()
        udp_port = udp_port or settings.getUDPPort()
        dht_service.init(dht_port)
        dht_service.connect()
        udp.listen(udp_port)

        def _cb(cod, typ, ip, details):
            # A('shutdown')
            result.callback({
                'result': cod,  # 'stun-success' or 'stun-failed'
                'type': typ,
                'ip': ip,
                'details': details,
            })

        A('init', (udp_port))
        A('start', _cb)
    except Exception as exc:
        lg.exc()
        result.callback(dict(ip='127.0.0.1', errors=[str(exc), ]))
        return result
    return result
def main():
    import pprint
    lg.set_debug_level(14)
    if sys.argv.count('list'):
        maps = lst()
        for itm in maps:
            pprint.pprint(itm)
    elif sys.argv.count('info'):
        locip, extip, maps = info()
        pprint.pprint(locip)
        pprint.pprint(extip)
        for itm in maps:
            pprint.pprint(itm)
    elif sys.argv.count('add'):
        print add(sys.argv[2], 'TCP')
    elif sys.argv.count('del'):
        print dlt(sys.argv[2], 'TCP')
    elif sys.argv.count('update'):
        bpio.init()
        settings.init()
        init()
        pprint.pprint(update(sys.argv[2]))
    elif sys.argv.count('clear'):
        print clear()
    else:
        print 'usage:'
        print 'run_upnpc.py info'
        print 'run_upnpc.py list'
        print 'run_upnpc.py add [port]'
        print 'run_upnpc.py del [port]'
        print 'run_upnpc.py update [port]'
        print 'run_upnpc.py clear'
Beispiel #11
0
def main():
    from main import settings
    lg.set_debug_level(20)
    settings.init()
    init()
    # print '\n'.join(_BootUpOrder)
    shutdown()
Beispiel #12
0
def main():
    from main import settings
    lg.set_debug_level(20)
    settings.init()
    init()
    # print '\n'.join(_BootUpOrder)
    shutdown()
Beispiel #13
0
def main():
    """
    Read settings from 'config' file and prints values from your queries to stdout.
    """
    from logs import lg
    lg.set_debug_level(24)
    from main import settings
    settings.init()
    init(settings.ConfigDir())
    print(conf().listEntries(''))
    try:
        inp = sys.argv[1].rstrip('/')
    except:
        print('wrong input')
        return
    if not conf().exist(inp):
        print('not exist')
        return
    if not conf().hasChilds(inp):
        print(inp, conf().getData(inp))
        return
    for child in conf().listEntries(inp):
        if conf().hasChilds(child):
            print(child, conf().listEntries(child))
        else:
            print(child, conf().getData(child))
    settings.shutdown()
    return
Beispiel #14
0
def main():
    lg.life_begins()
    bpio.init()
    settings.init()
    misc.init()
    my_id.init()
    identitycache.init()
    from crypt import key
    key.InitMyKey()
    (options, args) = parseCommandLine()
    settings.override('transport.transport-tcp.transport-tcp-port',
                      options.tcpport)
    settings.override('transport.transport-udp.transport-udp-port',
                      options.udpport)
    settings.override('network.network-dht-port', options.dhtport)
    lg.set_debug_level(options.debug)
    tmpfile.init()
    if True:
        import lib.udp
        lib.udp.listen(options.udpport)
        import dht.dht_service
        dht.dht_service.init(options.dhtport)
    reactor.addSystemEventTrigger('before', 'shutdown',
                                  shutdown)  # @UndefinedVariable
    init()
    start()
    globals()['num_in'] = 0

    def _in(a, b, c, d):
        lg.out(2, 'INBOX %d : %r' % (globals()['num_in'], a))
        globals()['num_in'] += 1
        return False

    callback.insert_inbox_callback(0, _in)
    if len(args) > 0:
        globals()['num_out'] = 0

        def _s():
            p = signed.Packet(commands.Data(), my_id.getLocalID(),
                              my_id.getLocalID(), my_id.getLocalID(),
                              bpio.ReadBinaryFile(args[1]), args[0])
            outbox(p, wide=True)
            lg.out(2, 'OUTBOX %d : %r' % (globals()['num_out'], p))
            globals()['num_out'] += 1

        old_state_changed = transport('udp').state_changed

        def new_state_changed(oldstate, newstate, event, *args, **kwargs):
            old_state_changed(oldstate, newstate, event, *args, **kwargs)
            if newstate == 'LISTENING':
                reactor.callLater(1, _s)  # @UndefinedVariable

        transport('udp').state_changed = new_state_changed
        # t = task.LoopingCall(_s)
        # reactor.callLater(5, t.start, 60, True)
        # reactor.callLater(2, t.stop)

    reactor.run()  # @UndefinedVariable
    settings.shutdown()
Beispiel #15
0
def main():
    from twisted.internet import reactor  # @UnresolvedImport
    lg.set_debug_level(24)
    settings.init()
    my_id.init()
    dht_service.init(settings.getDHTPort())
    reactor.callWhenRunning(A, 'init', sys.argv[1])  # @UndefinedVariable
    reactor.run()  # @UndefinedVariable
def main():
    from twisted.internet import reactor
    lg.set_debug_level(24)
    settings.init()
    my_id.init()
    dht_service.init(settings.getDHTPort())
    reactor.callWhenRunning(A, 'init', sys.argv[1])
    reactor.run()
Beispiel #17
0
def test1():
    lg.set_debug_level(20)
    bpio.init()
    settings.init()
    update_sheduler()
    #SetLocalDir('c:\\Program Files\\\xc4 \xd8 \xcd')
    # download_and_replace_starter()
    reactor.run()
def main():
    from twisted.internet import reactor
    lg.set_debug_level(24)
    settings.init()
    my_id.init()
    dht_service.init(settings.getDHTPort())
    reactor.callWhenRunning(A, 'init', sys.argv[1])
    reactor.run()
def test1():
    lg.set_debug_level(20)
    bpio.init()
    settings.init()
    update_sheduler()
    #SetLocalDir('c:\\Program Files\\\xc4 \xd8 \xcd')
    # download_and_replace_starter()
    reactor.run()
Beispiel #20
0
def main():
    from twisted.internet import reactor
    lg.set_debug_level(24)
    bpio.init()
    settings.init()
    dht_service.init(settings.getDHTPort())
    dht_service.connect()
    udp.listen(settings.getUDPPort())
    A('start', settings.getUDPPort())
    reactor.run()
Beispiel #21
0
def main():
    from twisted.internet import reactor
    lg.set_debug_level(24)
    bpio.init()
    settings.init()
    dht_service.init(settings.getDHTPort())
    dht_service.connect()
    udp.listen(settings.getUDPPort())
    A('start', settings.getUDPPort())
    reactor.run()
Beispiel #22
0
 def setUp(self):
     try:
         bpio.rmdir_recursive('/tmp/.bitdust_tmp')
     except Exception:
         pass
     settings.init(base_dir='/tmp/.bitdust_tmp')
     lg.set_debug_level(30)
     try:
         os.makedirs('/tmp/.bitdust_tmp/logs')
     except:
         pass
Beispiel #23
0
def main():
    bpio.init()
    settings.init()
    lg.set_debug_level(20)
    reactor.addSystemEventTrigger('before', 'shutdown',
                                  A().automat, 'shutdown')
    reactor.callWhenRunning(A, 'init',
                            (settings.getIdServerWebPort(), settings.getIdServerTCPPort()))
    reactor.callLater(0, A, 'start')
    reactor.run()
    lg.out(2, 'reactor stopped, EXIT')
Beispiel #24
0
def main():
    bpio.init()
    settings.init()
    lg.set_debug_level(28)
    (options, args) = parseCommandLine()
    init(options.udpport, options.dhtdb)

    def _go(nodes):
        try:
            if len(args) == 0:
                print('STARTED')
            elif len(args) > 0:
                def _r(x):
                    print(x)
                    reactor.stop()
                cmd = args[0]
                if cmd == 'get':
                    get_value(args[1]).addBoth(_r)
                elif cmd == 'set':
                    set_value(args[1], args[2], expire=int(args[3])).addBoth(_r)
                if cmd == 'get_json':
                    get_json_value(args[1]).addBoth(_r)
                elif cmd == 'set_json':
                    set_json_value(args[1], args[2], expire=int(args[3])).addBoth(_r)
                if cmd == 'get_valid_data':
                    get_valid_data(args[1], rules=json.loads(args[2])).addBoth(_r)
                elif cmd == 'set_valid_data':
                    set_valid_data(args[1], json.loads(args[2]),
                                   expire=int(args[3]), rules=json.loads(args[4])).addBoth(_r)
                elif cmd == 'find':
                    find_node(key_to_hash(args[1])).addBoth(_r)
                elif cmd == 'ping':
                    find_node(random_key()).addBoth(_r)
                elif cmd == 'discover':
                    def _l(x):
                        print(x)
                        find_node(random_key()).addBoth(_l)
                    _l('')
        except:
            lg.exc()

    seeds = []
    for dht_node_str in options.seeds.split(','):
        if dht_node_str.strip():
            try:
                dht_node = dht_node_str.strip().split(':')
                dht_node_host = dht_node[0].strip()
                dht_node_port = int(dht_node[1].strip())
            except:
                continue
            seeds.append((dht_node_host, dht_node_port, ))

    connect(seeds).addBoth(_go)
    reactor.run()
def main():
    bpio.init()
    settings.init()
    lg.set_debug_level(20)
    from twisted.internet import reactor
    if len(sys.argv) > 2:
        args = (sys.argv[1], sys.argv[2])
    else:
        args = (sys.argv[1])
    reactor.callWhenRunning(A, 'start', args)
    reactor.run()
Beispiel #26
0
def main():
    bpio.init()
    settings.init()
    lg.set_debug_level(20)
    from twisted.internet import reactor
    if len(sys.argv) > 2:
        args = (sys.argv[1], sys.argv[2])
    else:
        args = (sys.argv[1])
    reactor.callWhenRunning(A, 'start', args)
    reactor.run()
Beispiel #27
0
def update():
    """
    A good way to check all things - load and sign again.
    """
    from userid import my_id
    bpio.init()
    settings.init()
    src = bpio.ReadTextFile(settings.LocalIdentityFilename())
    my_id.setLocalIdentity(identity(xmlsrc=src))
    my_id.getLocalIdentity().sign()
    my_id.saveLocalIdentity()
    print my_id.getLocalIdentity().serialize()
Beispiel #28
0
def update():
    """
    A good way to check all things - load and sign again.
    """
    from userid import my_id
    bpio.init()
    settings.init()
    src = bpio.ReadTextFile(settings.LocalIdentityFilename())
    my_id.setLocalIdentity(identity(xmlsrc=src))
    my_id.getLocalIdentity().sign()
    my_id.saveLocalIdentity()
    print my_id.getLocalIdentity().serialize()
Beispiel #29
0
def main():
    from system import bpio
    bpio.init()
    settings.init()
    lg.set_debug_level(20)
    from twisted.internet import reactor  # @UnresolvedImport
    ir = IdRotator()
    ir.addStateChangedCallback(lambda *a: reactor.stop(), oldstate=None, newstate='DONE')  # @UndefinedVariable
    ir.addStateChangedCallback(lambda *a: reactor.stop(), oldstate=None, newstate='FAILED')  # @UndefinedVariable
    reactor.callWhenRunning(ir.automat, 'run')  # @UndefinedVariable
    reactor.run()  # @UndefinedVariable
    settings.shutdown()
Beispiel #30
0
def main():
    bpio.init()
    settings.init()
    lg.set_debug_level(20)
    reactor.addSystemEventTrigger('before', 'shutdown',
                                  A().automat, 'shutdown')
    reactor.callWhenRunning(
        A, 'init',
        (settings.getIdServerWebPort(), settings.getIdServerTCPPort()))
    reactor.callLater(0, A, 'start')
    reactor.run()
    lg.out(2, 'reactor stopped, EXIT')
def main():
    bpio.init()
    settings.init()
    lg.set_debug_level(20)
    from twisted.internet import reactor
    if len(sys.argv) > 2:
        args = (sys.argv[1], sys.argv[2])
    else:
        args = (sys.argv[1])
    A().addStateChangedCallback(lambda *a: reactor.stop(), oldstate=None, newstate='DONE')
    A().addStateChangedCallback(lambda *a: reactor.stop(), oldstate=None, newstate='FAILED')
    reactor.callWhenRunning(A, 'start', args)
    reactor.run()
Beispiel #32
0
def main():
    from twisted.internet import reactor
    lg.set_debug_level(24)
    bpio.init()
    settings.init()
    dht_service.init(settings.getDHTPort())
    d = dht_service.connect()
    udp.listen(settings.getUDPPort())

    def _go(live_nodes):
        A('start', settings.getUDPPort())

    d.addCallback(_go)

    reactor.run()
Beispiel #33
0
def update():
    """
    A good way to check all things - load and sign again.
    Also will test rebuilding of the identity
    """
    from userid import my_id
    bpio.init()
    settings.init()
    src = bpio.ReadTextFile(settings.LocalIdentityFilename())
    print(src)
    my_id.setLocalIdentity(identity(xmlsrc=src))
    my_id.getLocalIdentity().sign()
    my_id.saveLocalIdentity()
    print(my_id.getLocalIdentity().serialize())
    print(my_id.rebuildLocalIdentity(revision_up=True))
Beispiel #34
0
 def do_restart(param):
     from lib import misc
     from system import bpio
     settings.init()
     # appdata = settings.BaseDir()
     detach = False
     if bpio.Windows():
         detach = True
     misc.DoRestart(
         param,
         detach=detach,
         # std_out=os.path.join(appdata, 'logs', 'stdout.log'),
         # std_err=os.path.join(appdata, 'logs', 'stderr.log'),
     )
     settings.shutdown()
Beispiel #35
0
def cmd_key(opts, args, overDict, running, executablePath):
    from main import settings
    from lib import misc
    from system import bpio
    from userid import my_id
    from crypt import key
    settings.init()
    my_id.init()

    if not key.LoadMyKey():
        print_text('private key not exist or is not valid\n')
        return 0
    if not my_id.isLocalIdentityReady():
        print_text('local identity not exist, your key worth nothing\n')
        return 0

    if len(args) == 2:
        if args[1] == 'copy':
            TextToSave = my_id.getLocalID() + "\n" + key.MyPrivateKey()
            misc.setClipboardText(TextToSave)
            del TextToSave
            print_text('now you can "paste" with Ctr+V your private key where you want')
            print_text('WARNING! keep your key in safe place, do not publish it!\n')
            return 0
        elif args[1] == 'print':
            TextToSave = my_id.getLocalID() + "\n" + key.MyPrivateKey()
            print_text('\n' + TextToSave + '\n')
            del TextToSave
            print_text('WARNING! keep your key in safe place, do not publish it!\n')
            return 0
    elif len(args) == 3:
        if args[1] == 'copy' or args[1] == 'save' or args[1] == 'backup':
            from system import bpio
            curpath = os.getcwd()
            os.chdir(executablePath)
            filenameto = bpio.portablePath(args[2])
            os.chdir(curpath)
            TextToSave = my_id.getLocalID() + "\n" + key.MyPrivateKey()
            if not bpio.AtomicWriteFile(filenameto, TextToSave):
                del TextToSave
                print_text('error writing to %s\n' % filenameto)
                return 1
            del TextToSave
            print_text('your private key were copied to file %s' % filenameto)
            print_text('WARNING! keep your key in safe place, do not publish it!\n')
            return 0

    return 2
Beispiel #36
0
def main():
    settings.init()
    lg.set_debug_level(12)
    connect_layers = []
    if options.layer != 0:
        connect_layers.append(options.layer)
    dht_service.init(udp_port=14441, open_layers=connect_layers)
    seeds = []

    for seed_env in os.environ.get('DHT_SEEDS').split(','):
        seed = seed_env.split(':')
        seeds.append((seed[0], int(seed[1])))

    dht_service.connect(seeds).addBoth(connected, seeds=seeds)
    reactor.run()  # @UndefinedVariable
    settings.shutdown()
Beispiel #37
0
def main():
    settings.init()

    lg.set_debug_level(12)

    dht_service.init(udp_port=14441, db_file_path=settings.DHTDBFile())

    seeds = []

    for seed_env in (os.environ.get('DHT_SEED_1'),
                     os.environ.get('DHT_SEED_2')):
        seed = seed_env.split(':')
        seeds.append((seed[0], int(seed[1])))

    dht_service.connect(seeds).addBoth(run)
    reactor.run()
Beispiel #38
0
def main():
    def _ok(x):
        print 'ok', x
        reactor.stop()

    def _fail(x):
        print 'fail', x
        reactor.stop()
    from lib import net_misc
    from main import settings
    settings.init()
    settings.update_proxy_settings()
    idurl = 'http://p2p-id.ru/atg314.xml'
    r = net_misc.getPageTwisted(idurl)
    r.addCallback(_ok)
    r.addErrback(_fail)
    reactor.run()
Beispiel #39
0
 def setUp(self):
     try:
         bpio.rmdir_recursive('/tmp/.bitdust_tmp')
     except Exception:
         pass
     lg.set_debug_level(30)
     settings.init(base_dir='/tmp/.bitdust_tmp')
     id_url._IdentityHistoryDir = tempfile.mkdtemp()
     id_url.init()
     try:
         os.makedirs('/tmp/.bitdust_tmp/identitycache/')
     except:
         pass
     try:
         os.makedirs('/tmp/.bitdust_tmp/identityhistory/')
     except:
         pass
Beispiel #40
0
def safe_stun(udp_port=None, dht_port=None, result_defer=None):
    from twisted.internet.defer import Deferred
    result = result_defer or Deferred()

    if driver.is_started('service_entangled_dht'):
        if dht_service.node()._joinDeferred and not dht_service.node()._joinDeferred.called:
            dht_service.node()._joinDeferred.addCallback(lambda ok: safe_stun(udp_port=udp_port, dht_port=dht_port, result_defer=result))
            dht_service.node()._joinDeferred.addErrback(result.errback)
            return result

    if not driver.is_on('service_entangled_dht'):
        result.errback(Exception('service_entangled_dht() is not started'))
        return result
    
    try:
        settings.init()
        dht_port = dht_port or settings.getDHTPort()
        udp_port = udp_port or settings.getUDPPort()
        if dht_port:
            dht_service.init(dht_port)
        d = dht_service.connect()
        if udp_port:
            udp.listen(udp_port)

        def _cb(cod, typ, ip, details):
            # A('shutdown')
            result.callback({
                'result': cod,  # 'stun-success' or 'stun-failed'
                'type': typ,
                'ip': ip,
                'details': details,
            })

        def _go(live_nodes):
            A('init', udp_port)
            A('start', _cb)

        d.addCallback(_go)
        d.addErrback(lambda err: result.callback(dict(ip='127.0.0.1', errors=[str(err), ])))

    except Exception as exc:
        lg.exc()
        result.callback(dict(ip='127.0.0.1', errors=[str(exc), ]))
        return result
    return result
def main():
    if len(sys.argv) < 3:
        print 'usage: nickname_observer.py <"many"|"one"> <nickname> <attempts>'
        return
    from twisted.internet import reactor
    lg.set_debug_level(24)
    settings.init()
    my_id.init()
    dht_service.init(settings.getDHTPort())

    def _result(result, nickname):
        print result, nickname
        if result == 'finished':
            reactor.stop()
    if sys.argv[1] == 'many':
        observe_many(sys.argv[2], int(sys.argv[3]), results_callback=_result)
    else:
        find_one(sys.argv[2], int(sys.argv[3]), _result)
    reactor.run()
Beispiel #42
0
def main():
    def _ok(x):
        print "ok", x
        reactor.stop()

    def _fail(x):
        print "fail", x
        reactor.stop()

    from lib import net_misc
    from main import settings

    settings.init()
    settings.update_proxy_settings()
    idurl = "http://p2p-id.ru/atg314.xml"
    r = net_misc.getPageTwisted(idurl)
    r.addCallback(_ok)
    r.addErrback(_fail)
    reactor.run()
Beispiel #43
0
def main():
    from twisted.internet import reactor
    settings.init()
    lg.set_debug_level(30)
    dht_port = settings.getDHTPort()
    udp_port = settings.getUDPPort()
    if len(sys.argv) > 1:
        dht_port = int(sys.argv[1])
    if len(sys.argv) > 2:
        udp_port = int(sys.argv[2])
    dht_service.init(dht_port)
    dht_service.connect()
    udp.listen(udp_port)

    def _cb(result, typ, ip, details):
        print result, typ, ip, details
        A('shutdown')
        reactor.stop()
    A('init', (udp_port))
    A('start', _cb)
    reactor.run()
Beispiel #44
0
def main():
    """
    Read settings from 'userconfig' file and print in HTML form.
    """
    from main import settings
    settings.init()
    init(settings.ConfigDir())
#    last = ''
#    for entry in sorted(conf()._types.keys()):
#        parent, key = entry.rsplit('/', 1)
#        while parent.count('/'):
#            p, parent = parent.rsplit('/', 1)
#            if p != 'services':
#                print p
#            parent = '  ' + parent
#        if parent != last:
#            print parent
#            last = parent
#        print ' ' * (last.count(' ') + 1) * 2, key, '\t\t\t\t', conf().get_type_label(entry).upper()
    # print '\n'.join(map(lambda x: "    '%s':\t\t\tNode," % x, sorted(conf().listAllEntries())))
    s = conf().getData('details')
    conf().loadDetails(s)
Beispiel #45
0
def main():
    bpio.init()
    settings.init()
    lg.set_debug_level(18)
    (options, args) = parseCommandLine()
    init(options.udpport, options.dhtdb)
    connect()
    if len(args) == 0:
        pass
    elif len(args) > 0:

        def _r(x):
            print x
            reactor.stop()

        cmd = args[0]
        if cmd == "get":
            get_value(args[1]).addBoth(_r)
        elif cmd == "set":
            set_value(args[1], args[2]).addBoth(_r)
        elif cmd == "find":
            find_node(key_to_hash(args[1])).addBoth(_r)
    reactor.run()
Beispiel #46
0
def init(UI='', options=None, args=None, overDict=None, executablePath=None):
    """
    In the method ``main()`` program firstly checks the command line arguments
    and then calls this method to start the whole process.

    This initialize some low level modules and finally create an
    instance of ``initializer()`` state machine and send it an event
    "run".
    """
    global AppDataDir

    from logs import lg
    lg.out(4, 'bpmain.run UI="%s"' % UI)

    from system import bpio

    #---settings---
    from main import settings
    if overDict:
        settings.override_dict(overDict)
    settings.init(AppDataDir)
    if not options or options.debug is None:
        lg.set_debug_level(settings.getDebugLevel())
    from main import config
    config.conf().addCallback('logs/debug-level',
                              lambda p, value, o, r: lg.set_debug_level(value))

    #---USE_TRAY_ICON---
    if os.path.isfile(settings.LocalIdentityFilename()) and os.path.isfile(settings.KeyFileName()):
        try:
            from system.tray_icon import USE_TRAY_ICON
            if bpio.Mac() or not bpio.isGUIpossible():
                lg.out(4, '    GUI is not possible')
                USE_TRAY_ICON = False
            if USE_TRAY_ICON:
                from twisted.internet import wxreactor
                wxreactor.install()
                lg.out(4, '    wxreactor installed')
        except:
            USE_TRAY_ICON = False
            lg.exc()
    else:
        lg.out(4, '    local identity or key file is not ready')
        USE_TRAY_ICON = False
    lg.out(4, '    USE_TRAY_ICON=' + str(USE_TRAY_ICON))
    if USE_TRAY_ICON:
        from system import tray_icon
        icons_path = bpio.portablePath(os.path.join(bpio.getExecutableDir(), 'icons'))
        lg.out(4, 'bpmain.run call tray_icon.init(%s)' % icons_path)
        tray_icon.init(icons_path)

        def _tray_control_func(cmd):
            if cmd == 'exit':
                import shutdowner
                shutdowner.A('stop', 'exit')
        tray_icon.SetControlFunc(_tray_control_func)

    #---OS Windows init---
    if bpio.Windows():
        try:
            from win32event import CreateMutex
            mutex = CreateMutex(None, False, "BitDust")
            lg.out(4, 'bpmain.run created a Mutex: %s' % str(mutex))
        except:
            lg.exc()

    #---twisted reactor---
    lg.out(4, 'bpmain.run want to import twisted.internet.reactor')
    try:
        from twisted.internet import reactor
    except:
        lg.exc()
        sys.exit('Error initializing reactor in bpmain.py\n')

    #---logfile----
    if lg.logs_enabled() and lg.log_file():
        lg.out(2, 'bpmain.run want to switch log files')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_stop_redirecting()
        lg.close_log_file()
        lg.open_log_file(settings.MainLogFilename() + '-' + time.strftime('%y%m%d%H%M%S') + '.log')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_start_redirecting()

    #---memdebug---
#    if settings.uconfig('logs.memdebug-enable') == 'True':
#        try:
#            from logs import memdebug
#            memdebug_port = int(settings.uconfig('logs.memdebug-port'))
#            memdebug.start(memdebug_port)
#            reactor.addSystemEventTrigger('before', 'shutdown', memdebug.stop)
#            lg.out(2, 'bpmain.run memdebug web server started on port %d' % memdebug_port)
#        except:
#            lg.exc()

    #---process ID---
    try:
        pid = os.getpid()
        pid_file_path = os.path.join(settings.MetaDataDir(), 'processid')
        bpio.WriteFile(pid_file_path, str(pid))
        lg.out(2, 'bpmain.run wrote process id [%s] in the file %s' % (str(pid), pid_file_path))
    except:
        lg.exc()

#    #---reactor.callLater patch---
#    if lg.is_debug(12):
#        patchReactorCallLater(reactor)
#        monitorDelayedCalls(reactor)

#    #---plugins---
#    from plugins import plug
#    plug.init()
#    reactor.addSystemEventTrigger('before', 'shutdown', plug.shutdown)

    lg.out(2, "bpmain.run UI=[%s]" % UI)

    if lg.is_debug(20):
        lg.out(0, '\n' + bpio.osinfofull())

    lg.out(4, 'bpmain.run import automats')

    #---START!---
    from automats import automat
    automat.LifeBegins(lg.when_life_begins())
    automat.OpenLogFile(settings.AutomatsLog())

    import initializer
    I = initializer.A()
    lg.out(4, 'bpmain.run send event "run" to initializer()')
    reactor.callWhenRunning(I.automat, 'run', UI)
    return I
Beispiel #47
0
def main():
    lg.life_begins()
    bpio.init()
    settings.init()
    misc.init()
    my_id.init()
    identitycache.init()
    from crypt import key

    key.InitMyKey()
    (options, args) = parseCommandLine()
    settings.override("transport.transport-tcp.transport-tcp-port", options.tcpport)
    settings.override("transport.transport-udp.transport-udp-port", options.udpport)
    settings.override("network.network-dht-port", options.dhtport)
    lg.set_debug_level(options.debug)
    tmpfile.init()
    if True:
        import lib.udp

        lib.udp.listen(options.udpport)
        import dht.dht_service

        dht.dht_service.init(options.dhtport)
    reactor.addSystemEventTrigger("before", "shutdown", shutdown)
    init()
    start()
    globals()["num_in"] = 0

    def _in(a, b, c, d):
        lg.out(2, "INBOX %d : %r" % (globals()["num_in"], a))
        globals()["num_in"] += 1
        return True

    callback.insert_inbox_callback(-1, _in)
    if len(args) > 0:
        globals()["num_out"] = 0

        def _s():
            p = signed.Packet(
                commands.Data(),
                my_id.getLocalID(),
                my_id.getLocalID(),
                my_id.getLocalID(),
                bpio.ReadBinaryFile(args[1]),
                args[0],
            )
            outbox(p, wide=True)
            lg.out(2, "OUTBOX %d : %r" % (globals()["num_out"], p))
            globals()["num_out"] += 1

        old_state_changed = transport("udp").state_changed

        def new_state_changed(oldstate, newstate, event, arg):
            old_state_changed(oldstate, newstate, event, arg)
            if newstate == "LISTENING":
                reactor.callLater(1, _s)

        transport("udp").state_changed = new_state_changed
        # t = task.LoopingCall(_s)
        # reactor.callLater(5, t.start, 60, True)
        # reactor.callLater(2, t.stop)

    reactor.run()
Beispiel #48
0
def cmd_identity(opts, args, overDict, running):
    from userid import my_id
    from main import settings
    settings.init()
    my_id.init()

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

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

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

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

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

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

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

    return 2
Beispiel #49
0
def run(opts, args, overDict, pars):
    """
    The entry point, this is called from ``p2p.bpmain`` to process command line arguments.
    """
    print 'Copyright 2014, BitDust. All rights reserved.'
    
    if overDict:
        settings.override_dict(overDict)
    bpio.init()
    settings.init()
    if not opts or opts.debug is None:
        lg.set_debug_level(0)

    appList = bpio.find_process([
        'bitdust.exe',
        'bpmain.py',
        'bitdust.py',
        'regexp:^/usr/bin/python.*bitdust.*$',
        ])
    running = len(appList) > 0
   
    cmd = ''
    if len(args) > 0:
        cmd = args[0].lower()
    
    #---help---
    if cmd in ['help', 'h']:
        from main import help
        if len(args) >= 2 and args[1].lower() == 'schedule':
            print help.schedule_format()
        elif len(args) >= 2 and args[1].lower() == 'settings':
            print config.conf().print_all()
        else:
            print help.help()
            print pars.format_option_help()
        return 0
    
    #---backup---
    elif cmd in ['backup', 'backups', 'bk']:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_backups(opts, args, overDict)

    #---restore---
    elif cmd in ['restore', 're']:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_restore(opts, args, overDict)

    #---schedule---
    elif cmd in ['schedule', 'shed', 'sched', 'sh']:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_schedule(opts, args, overDict)

    #---suppliers---
    elif cmd in [ 'suppliers', 'supplier', 'sup', 'supp', 'sp', ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_suppliers(opts, args, overDict)
    
    #---customers---
    elif cmd in [ 'customers', 'customer', 'cus', 'cust', 'cs', ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_customers(opts, args, overDict)

    #---register---
    elif cmd == 'register':
        if running:
            print 'BitDust already started.\n'
            return 0
        return cmd_register(opts, args, overDict)

    #---recover---
    elif cmd == 'recover':
        if running:
            print 'BitDust already started.\n'
            return 0
        return cmd_recover(opts, args, overDict)

    #---key---
    elif cmd == 'key':
        return cmd_key(opts, args, overDict)

    #---stats---
    elif cmd in [ 'stats', 'st' ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_stats(opts, args, overDict)

    #---version---
    elif cmd in [ 'version', 'v', 'ver' ]:
        ver = bpio.ReadTextFile(settings.VersionNumberFile()).strip()
        chksum = bpio.ReadTextFile(settings.CheckSumFile()).strip()
        repo, location = misc.ReadRepoLocation()
        print 'checksum:   ', chksum 
        print 'version:    ', ver
        print 'repository: ', repo
        print 'location:   ', location
        return 0

    #---states---
    elif cmd in [ 'states', 'sta', 'automats', 'auto' ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_states(opts, args, overDict)
    
    #---cache---
    elif cmd in [ 'cache' ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_cache(opts, args, overDict)

    #---reconnect---
    elif cmd in [ 'reconnect', ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_reconnect(opts, args, overDict)
        
    #---set---
    elif cmd in [ 'set', 'setting', 'settings', 'conf', 'config', 'configs', 'option', 'options', ]:
        if len(args) == 1 or args[1].lower() in [ 'help', '?' ]:
            from main import help
            print help.settings_help()
            return 0
        if not running:
            cmd_set_directly(opts, args, overDict)
            return 0
        return cmd_set_request(opts, args, overDict)
    
    #---memory---
    elif cmd == 'memory':
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_memory(opts, args, overDict)
    
    #---money---
    elif cmd == 'money':
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_money(opts, args, overDict)

    #---storage---
    elif cmd == 'storage':
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_storage(opts, args, overDict)
    
    #---message---
    elif cmd == 'msg' or cmd == 'message' or cmd == 'messages':
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_message(opts, args, overDict)

    #---integrate---
    elif cmd == 'integrate':
        return cmd_integrate(opts, args, overDict)
    
#    elif cmd == 'uninstall':
#        return cmd_uninstall(opts, args, overDict)
    
    return 2
Beispiel #50
0
# ------------------------------------------------------------------------------


def message2gui(proto, text):
    pass


#    statusline.setp(proto, text)


def getErrorString(error):
    try:
        return error.getErrorMessage()
    except:
        if error is None:
            return ""
        return str(error)


def getHostString(host):
    try:
        return str(host.host) + ":" + str(host.port)
    except:
        if host is None:
            return ""
        return str(host)


if __name__ == "__main__":
    settings.init()