Beispiel #1
0
def _test():
    from crypt import signed
    from lib import packetid

    lg.set_debug_level(24)
    A("init")
    A().offline_mode = True
    A("start")
    coins = []
    for _ in xrange(5):
        coin = coins_io.storage_contract_open("http://some.id-host.org/alice_customer.xml", 3600, 4096)
        if coins_io.verify_coin_signature(coin):
            coins.append(coin)
        else:
            print coin
            sys.exit()
    outpacket = signed.Packet(
        commands.Coin(),
        my_id.getLocalID(),
        my_id.getLocalID(),
        packetid.UniqueID(),
        json.dumps(coins),
        "http://server.com/id.xml",
    )
    reactor.callLater(0.1, callback.run_inbox_callbacks, outpacket, None, "finished", "")
    # reactor.callLater(5.1, A, 'shutdown')
    reactor.run()
Beispiel #2
0
def main():
    from main import settings
    lg.set_debug_level(20)
    settings.init()
    init()
    # print '\n'.join(_BootUpOrder)
    shutdown()
Beispiel #3
0
def test():
    lg.set_debug_level(24)
    init()
    my_keys.generate_key('[email protected]')
    # copy [email protected]'s key to [email protected] in ~/.bitdust/keys/
    open_queue('event-test123&[email protected]&[email protected]')
    add_producer('*****@*****.**')
    connect_producer('*****@*****.**',
                     'event-test123&[email protected]&[email protected]')
    start_event_publisher('*****@*****.**', 'test123')
    add_consumer('*****@*****.**')
    add_callback_method('*****@*****.**', _test_callback_bob)
    subscribe_consumer(
        '*****@*****.**',
        'event-test123&[email protected]&[email protected]')
    add_consumer('*****@*****.**')
    add_callback_method('*****@*****.**', _test_callback_dave)
    subscribe_consumer(
        '*****@*****.**',
        'event-test123&[email protected]&[email protected]')
    events.send('test123', data=dict(abc='abc', counter=0))
    events.send('test123', data=dict(abc='abc', counter=2))
    events.send('test123', data=dict(abc='abc', counter=4))
    events.send('test123', data=dict(abc='abc', counter=1))
    events.send('test123', data=dict(abc='abc', counter=6))
    events.send('test123', data=dict(abc='abc', counter=23))
    events.send('test123', data=dict(abc='abc', counter=620))
    events.send('test123', data=dict(abc='abc', counter=20))
    events.send('test123', data=dict(abc='abc', counter=30))
    events.send('test123', data=dict(abc='abc', counter=40))
    reactor.run()  # @UndefinedVariable
Beispiel #4
0
def main():
    lg.set_debug_level(20)
    fout = open('out.tar', 'wb')

    def _read(p):
        from system import nonblocking
        # print 'read', p.state()
        if p.state() == nonblocking.PIPE_CLOSED:
            print 'closed'
            fout.close()
            reactor.stop()
            return
        if p.state() == nonblocking.PIPE_READY2READ:
            v = p.recv(100)
            fout.write(v)
            if v == '':
                print 'eof'
                fout.close()
                reactor.stop()
                return
        reactor.callLater(0, _read, p)

    def _go():
        p = backuptar(sys.argv[1])
        p.make_nonblocking()
        _read(p)
    from twisted.internet import reactor
    reactor.callLater(0, _go)
    reactor.run()
Beispiel #5
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]))
        settings.shutdown()
    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 #6
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 #7
0
def main():
    bpio.init()
    lg.set_debug_level(18)
    listnport = int(sys.argv[1])

    def received(dgrm, addr):
        send_command(listnport, CMD_ALIVE, 'ok', addr)

    def go(x, port):
        print('go', x)
        l = listen(port)
        l.protocol.add_callback(received)

    def restart(port):
        print('restart')
        if listener(port):
            close(port).addCallback(go, port)
        else:
            go(None, port)

    def ping(fromport, toaddr):
        print('ping')
        send_command(fromport, CMD_PING, b'ping', toaddr)

    if len(sys.argv) > 2:
        addr = sys.argv[2].split(':')
        addr = (addr[0], int(addr[1]))
        listen(listnport)
        task.LoopingCall(ping, listnport, addr).start(1, False)

    else:
        restart(listnport)
        # task.LoopingCall(restart, listnport).start(5)

    reactor.run()  # @UndefinedVariable
Beispiel #8
0
def main():
    lg.set_debug_level(20)
    fout = open('out.tar', 'wb')

    def _read(p):
        from system import nonblocking
        # print 'read', p.state()
        if p.state() == nonblocking.PIPE_CLOSED:
            print 'closed'
            fout.close()
            reactor.stop()
            return
        if p.state() == nonblocking.PIPE_READY2READ:
            v = p.recv(100)
            fout.write(v)
            if v == '':
                print 'eof'
                fout.close()
                reactor.stop()
                return
        reactor.callLater(0, _read, p)

    def _go():
        p = backuptardir(sys.argv[1], arcname='asd')
        p.make_nonblocking()
        _read(p)

    from twisted.internet import reactor
    reactor.callLater(0, _go)
    reactor.run()
Beispiel #9
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 #10
0
def main():
    lg.set_debug_level(24)

    # TEST
    # call with parameters like that:
    # python raidworker.py ./somefile ecc/7x7 myID_ABC 1234 ./somefolder/
    tasks = {}

    def _cb(cmd, taskdata, result):
        print('DONE!', cmd, taskdata, result)
        tasks.pop(taskdata[3])
        if len(tasks) == 0:
            reactor.stop()
        else:
            print(len(tasks), 'more')

    def _add(blocknum):
        tasks[blocknum] = (sys.argv[1], sys.argv[2], sys.argv[3], blocknum, sys.argv[5])
        raid_worker.A('new-task',
                      ('make', (sys.argv[1], sys.argv[2], sys.argv[3], blocknum, sys.argv[5]),
                       _cb))
    from system import bpio
    bpio.init()
    lg.set_debug_level(20)
    from raid import raid_worker
    reactor.callWhenRunning(raid_worker.A, 'init')
    start_block_num = int(sys.argv[4])
    reactor.callLater(0.01, _add, start_block_num)
    reactor.callLater(0.02, _add, start_block_num + 1)
    reactor.callLater(0.03, _add, start_block_num + 2)
    reactor.callLater(0.04, _add, start_block_num + 3)
    reactor.callLater(0.05, _add, start_block_num + 4)
    reactor.run()
Beispiel #11
0
def main():
    bpio.init()
    lg.set_debug_level(18)
    listnport = int(sys.argv[1])

    def received(dgrm, addr):
        send_command(listnport, CMD_ALIVE, 'ok', addr)

    def go(x, port):
        print 'go', x
        l = listen(port)
        l.protocol.add_callback(received)

    def restart(port):
        print 'restart'
        if listener(port):
            close(port).addCallback(go, port)
        else:
            go(None, port)

    def ping(fromport, toaddr):
        print 'ping'
        send_command(fromport, CMD_PING, 'ping', toaddr)
    if len(sys.argv) > 2:
        addr = sys.argv[2].split(':')
        addr = (addr[0], int(addr[1]))
        listen(listnport)
        task.LoopingCall(ping, listnport, addr).start(1, False)
    else:
        restart(listnport)
        # task.LoopingCall(restart, listnport).start(5)
    reactor.run()
Beispiel #12
0
def main():
    lg.set_debug_level(24)

    # TEST
    # call with parameters like that:
    # python raidworker.py C:\temp\joomla2.sql ecc/7x7 myID_ABC 1234 c:\temp\somedir
    tasks = {}

    def _cb(cmd, taskdata, result):
        print 'DONE!', cmd, taskdata, result
        tasks.pop(taskdata[3])
        if len(tasks) == 0:
            reactor.stop()
        else:
            print len(tasks), 'more'

    def _add(blocknum):
        tasks[blocknum] = (sys.argv[1], sys.argv[2], sys.argv[3], blocknum, sys.argv[5])
        raid_worker.A('new-task',
                      ('make', (sys.argv[1], sys.argv[2], sys.argv[3], blocknum, sys.argv[5]),
                       _cb))
    from system import bpio
    bpio.init()
    lg.set_debug_level(20)
    from raid import raid_worker
    reactor.callWhenRunning(raid_worker.A, 'init')
    start_block_num = int(sys.argv[4])
    reactor.callLater(0.01, _add, start_block_num)
    reactor.callLater(0.02, _add, start_block_num + 1)
    reactor.callLater(0.03, _add, start_block_num + 2)
    reactor.callLater(0.04, _add, start_block_num + 3)
    reactor.callLater(0.05, _add, start_block_num + 4)
    reactor.run()
Beispiel #13
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()
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 #15
0
def main():
    from main import settings
    lg.set_debug_level(20)
    settings.init()
    init()
    # print '\n'.join(_BootUpOrder)
    shutdown()
    settings.shutdown()
Beispiel #16
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()
Beispiel #17
0
def main():
    def _cb(cmd, taskdata, result):
        print cmd, taskdata, result
    bpio.init()
    lg.set_debug_level(20)
    reactor.callWhenRunning(A, 'init')
    reactor.callLater(0.5, A, 'new-task', ('make', _cb, ('sdfsdf', '45', '324', '45')))
    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 #19
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
Beispiel #20
0
def main():
    from logs import lg
    lg.set_debug_level(18)
    do_in_memory(filename=sys.argv[1],
                 eccmapname=sys.argv[2],
                 version=sys.argv[3],
                 blockNumber=int(sys.argv[4]),
                 targetDir=sys.argv[5])
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 #22
0
def main():
    lg.set_debug_level(24)

    # TEST
    import transport.gate
    transport.gate.init(['tcp', ])
    import userid.propagate
    userid.propagate.SendServers()
    reactor.run()
Beispiel #23
0
def main():
    lg.set_debug_level(24)

    # TEST
    import transport.gate
    transport.gate.init(['tcp', ])
    import userid.propagate
    userid.propagate.SendServers()
    reactor.run()
Beispiel #24
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 #25
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 #26
0
def main():
    def _cb(cmd, taskdata, result):
        print(cmd, taskdata, result)

    bpio.init()
    lg.set_debug_level(20)
    reactor.callWhenRunning(A, 'init')
    reactor.callLater(0.5, A, 'new-task',
                      ('make', _cb, ('sdfsdf', '45', '324', '45')))
    reactor.run()
Beispiel #27
0
def main():
    lg.set_debug_level(24)
    backupID = sys.argv[1]
    raid_worker.A('init')
    outfd, outfilename = tmpfile.make('restore', '.tar.gz',
                                      backupID.replace('/', '_') + '_')
    r = restore(backupID, outfd)
    r.MyDeferred.addBoth(lambda x: reactor.stop())
    reactor.callLater(1, r.automat, 'init')
    reactor.run()
Beispiel #28
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 #29
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])
    reactor.callWhenRunning(A, 'start', args)
    reactor.run()
Beispiel #31
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()
Beispiel #32
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 #33
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 #34
0
def main():
    global _PeerNode
    global _Wallet
    lg.set_debug_level(16)
    lg.life_begins()
    options = _parse_args(sys.argv)
    init(
        host=options.host,
        port=options.port,
        seed_nodes=[(
            i.split(':')[0],
            int(i.split(':')[1]),
        ) for i in options.seeds.split(',')],
        blockstore_filename=options.blockstore,
        keystore_filename=options.keystore,
        peerstore_filename=options.peerstore,
        loglevel='DEBUG' if _Debug else 'INFO',
    )
    if options.block_explorer:
        reactor.callLater(1, start_block_explorer, options.block_explorer,
                          _PeerNode)
    if options.wallet:
        reactor.callLater(1, start_wallet, options.wallet, _PeerNode, _Wallet)
    if options.generate:
        reactor.callFromThread(
            generate_block,
            json_data=dict(started=time.time(), data=json.loads(options.json)),
            with_inputs=False,
            repeat=False,
        )
    if options.mine:
        reactor.callFromThread(
            generate_block,
            json_data=dict(started=time.time(), data=json.loads(options.json)),
            with_inputs=True,
            repeat=True,
        )
    if options.transaction:
        reactor.callLater(
            5,
            new_transaction,
            options.destination,
            options.amount,
            json.loads(options.json),
        )
    if options.pdbshell:
        import pdb
        pdb.set_trace()
        return

    reactor.addSystemEventTrigger('before', 'shutdown', shutdown)
    reactor.callLater(5, shutdown)
    reactor.run()
Beispiel #35
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 #36
0
 def test_sign_verify(self):
     lg.set_debug_level(30)
     key_id = '[email protected]_8084'
     my_keys.erase_key(key_id, keys_folder='/tmp/')
     my_keys.register_key(key_id, _sample_private_key, keys_folder='/tmp/')
     is_valid = my_keys.validate_key(my_keys.key_obj(key_id))
     if not is_valid:
         print(key_id)
         print(my_keys.get_private_key_raw(key_id))
     else:
         my_keys.erase_key(key_id, keys_folder='/tmp/')
     self.assertTrue(is_valid)
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 #38
0
 def test_regression(self):
     lg.set_debug_level(30)
     for i in range(3):
         key_id = 'test_key_%[email protected]_8084' % i
         my_keys.erase_key(key_id, keys_folder='/tmp/')
         my_keys.generate_key(key_id, key_size=1024, keys_folder='/tmp/')
         is_valid = my_keys.validate_key(my_keys.key_obj(key_id))
         if not is_valid:
             print(key_id)
             print(my_keys.get_private_key_raw(key_id))
         else:
             my_keys.erase_key(key_id, keys_folder='/tmp/')
         self.assertTrue(is_valid)
Beispiel #39
0
def main():
    if len(sys.argv) <= 1:
        print('usage:')
        print('    natpunch.py server [min port] [max port]')
        print(
            '    natpunch.py listen [local port] [servers list filename] [incoming connections filename]'
        )
        print(
            '    natpunch.py connect [local port] [remote IP] [servers list file] [min port] [max port]'
        )
        return

    lg.set_debug_level(24)
    bpio.init()

    if sys.argv[1] == 'server':
        min_port = int(sys.argv[2])
        max_port = int(sys.argv[3])
        for port_num in range(min_port, max_port + 1):
            udp.listen(port_num)
            udp.proto(port_num).add_callback(
                lambda d, a: datagram_received(d, a, port_num))

    elif sys.argv[1] == 'listen':
        port_num = int(sys.argv[2])
        udp.listen(port_num)
        udp.proto(port_num).add_callback(
            lambda d, a: datagram_received(d, a, port_num))
        servers = []
        for line in open(sys.argv[3]).read().split('\n'):
            addr = line.strip().split(':')
            addr[1] = int(addr[1])
            servers.append(tuple(addr))
        listen(port_num, servers, sys.argv[4])

    elif sys.argv[1] == 'connect':
        port_num = int(sys.argv[2])
        remote_ip = sys.argv[3]
        udp.listen(port_num)
        udp.proto(port_num).add_callback(
            lambda d, a: datagram_received(d, a, port_num))
        servers = []
        for line in open(sys.argv[4]).read().split('\n'):
            addr = line.strip().split(':')
            addr[1] = int(addr[1])
            servers.append(tuple(addr))
        min_port = int(sys.argv[5])
        max_port = int(sys.argv[6])
        connect(port_num, remote_ip, servers, min_port, max_port)

    reactor.run()
Beispiel #40
0
def test_safe_stun():
    from twisted.internet import reactor  # @UnresolvedImport

    def _cb(res):
        print(res)
        reactor.stop()  # @UndefinedVariable

    def _eb(err):
        print(err)
        reactor.stop()  # @UndefinedVariable

    lg.set_debug_level(30)
    safe_stun().addCallbacks(_cb, _eb)
    reactor.run()  # @UndefinedVariable
Beispiel #41
0
 def test_sign_verify(self):
     from logs import lg
     from crypt import my_keys
     lg.set_debug_level(30)
     key_id = 'some_key_abc'
     my_keys.erase_key(key_id, keys_folder='/tmp/')
     my_keys.register_key(key_id, _some_private_key, keys_folder='/tmp/')
     is_valid = my_keys.validate_key(my_keys.key_obj(key_id))
     if not is_valid:
         print(key_id)
         print(my_keys.get_private_key_raw(key_id))
     else:
         my_keys.erase_key(key_id, keys_folder='/tmp/')
     self.assertTrue(is_valid)
Beispiel #42
0
def test_safe_stun():
    from twisted.internet import reactor

    def _cb(res):
        print res
        reactor.stop()

    def _eb(err):
        print err
        reactor.stop()

    lg.set_debug_level(30)
    safe_stun().addCallbacks(_cb, _eb)
    reactor.run()
Beispiel #43
0
def main():
    import base64

    bpio.init()
    lg.set_debug_level(20)

    os.system('rm -rf /tmp/raidtest')
    os.system('mkdir -p /tmp/raidtest/F12345678')
    open('/tmp/source.txt', 'w').write(base64.b64encode(os.urandom(1000)).decode())

    reactor.callWhenRunning(A, 'init')  # @UndefinedVariable
    reactor.callLater(0.5, add_task, 'make', ('/tmp/source.txt', 'ecc/18x18', 'F12345678', '5', '/tmp/raidtest/F12345678'), _make_done)  # @UndefinedVariable

    reactor.run()  # @UndefinedVariable
Beispiel #44
0
def main():
    from interface import api
    from main import settings
    from main import bpmain
    from system import bpio
    from services import driver
    lg.open_log_file('test_api.log')
    lg.set_debug_level(20)
    lg.life_begins()
    lg._NoOutput = True
    bpio.init()
    bpmain.init()
    reactor.callWhenRunning(run_tests)
    reactor.callLater(60, api.stop)
    bpmain.run_twisted_reactor()
    bpmain.shutdown()
def main():
    sourcePath = sys.argv[1]
    backupID = sys.argv[2]
    lg.set_debug_level(24)
    compress_mode = 'none'  # 'gz'
    raid_worker.A('init')
    backupPath = backup_fs.MakeLocalDir(settings.getLocalBackupsDir(), backupID)
    if bpio.pathIsDir(sourcePath):
        backupPipe = backup_tar.backuptar(sourcePath, compress=compress_mode)
    else:
        backupPipe = backup_tar.backuptarfile(sourcePath, compress=compress_mode)
    backupPipe.make_nonblocking()

    job = backup.backup(backupID, backupPipe, backup_done)
    reactor.callLater(1, job.automat, 'start')
    reactor.run()
Beispiel #46
0
def main():
    if len(sys.argv) <= 1:
        print 'usage:'
        print '    natpunch.py server [min port] [max port]'
        print '    natpunch.py listen [local port] [servers list filename] [incoming connections filename]'
        print '    natpunch.py connect [local port] [remote IP] [servers list file] [min port] [max port]'
        return

    lg.set_debug_level(24)
    bpio.init()

    if sys.argv[1] == 'server':
        min_port = int(sys.argv[2])
        max_port = int(sys.argv[3])
        for port_num in range(min_port, max_port + 1):
            udp.listen(port_num)
            udp.proto(port_num).add_callback(lambda d, a: datagram_received(d, a, port_num))

    elif sys.argv[1] == 'listen':
        port_num = int(sys.argv[2])
        udp.listen(port_num)
        udp.proto(port_num).add_callback(lambda d, a: datagram_received(d, a, port_num))
        servers = []
        for line in open(sys.argv[3]).read().split('\n'):
            addr = line.strip().split(':')
            addr[1] = int(addr[1])
            servers.append(tuple(addr))
        listen(port_num, servers, sys.argv[4])

    elif sys.argv[1] == 'connect':
        port_num = int(sys.argv[2])
        remote_ip = sys.argv[3]
        udp.listen(port_num)
        udp.proto(port_num).add_callback(lambda d, a: datagram_received(d, a, port_num))
        servers = []
        for line in open(sys.argv[4]).read().split('\n'):
            addr = line.strip().split(':')
            addr[1] = int(addr[1])
            servers.append(tuple(addr))
        min_port = int(sys.argv[5])
        max_port = int(sys.argv[6])
        connect(port_num, remote_ip, servers, min_port, max_port)

    reactor.run()
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 #48
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 #49
0
def main():
    from system import bpio
    import backup_tar
    import backup_fs
    lg.set_debug_level(24)
    sourcePath = sys.argv[1]
    compress_mode = 'none'  # 'gz'
    backupID = sys.argv[2]
    raid_worker.A('init')
    backupPath = backup_fs.MakeLocalDir(settings.getLocalBackupsDir(), backupID)
    if bpio.pathIsDir(sourcePath):
        backupPipe = backup_tar.backuptar(sourcePath, compress=compress_mode)
    else:
        backupPipe = backup_tar.backuptarfile(sourcePath, compress=compress_mode)
    backupPipe.make_nonblocking()

    def _bk_done(bid, result):
        from crypt import signed
        try:
            os.mkdir(os.path.join(settings.getLocalBackupsDir(), bid + '.out'))
        except:
            pass
        for filename in os.listdir(os.path.join(settings.getLocalBackupsDir(), bid)):
            filepath = os.path.join(settings.getLocalBackupsDir(), bid, filename)
            payld = str(bpio.ReadBinaryFile(filepath))
            newpacket = signed.Packet(
                'Data',
                my_id.getLocalID(),
                my_id.getLocalID(),
                filename,
                payld,
                'http://megafaq.ru/cvps1010.xml')
            newfilepath = os.path.join(settings.getLocalBackupsDir(), bid + '.out', filename)
            bpio.AtomicWriteFile(newfilepath, newpacket.Serialize())
        reactor.stop()
    job = backup(backupID, backupPipe, _bk_done)
    reactor.callLater(1, job.automat, 'start')
    reactor.run()
Beispiel #50
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 #51
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 #52
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 #53
0
def main(executable_path=None):
    """
    THIS IS THE ENTRY POINT OF THE PROGRAM!
    """
    global AppDataDir

    import warnings
    warnings.filterwarnings("ignore", message="You do not have a working installation of the service_identity module")

    try:
        from logs import lg
    except:
        dirpath = os.path.dirname(os.path.abspath(sys.argv[0]))
        sys.path.insert(0, os.path.abspath(os.path.join(dirpath, '..')))
        # sys.path.insert(0, os.path.abspath(os.path.join(dirpath, '..', '..')))
        from distutils.sysconfig import get_python_lib
        sys.path.append(os.path.join(get_python_lib(), 'bitdust'))
        try:
            from logs import lg
        except:
            print 'ERROR! can not import working code.  Python Path:'
            print '\n'.join(sys.path)
            return 1

    # init IO module, update locale
    from system import bpio
    bpio.init()

    # sys.excepthook = lg.exception_hook

    if not bpio.isFrozen():
        from twisted.internet.defer import setDebugging
        setDebugging(True)

    pars = parser()
    (opts, args) = pars.parse_args()

    if opts.appdir:
        appdata = opts.appdir
        AppDataDir = appdata

    else:
        curdir = os.getcwd()  # os.path.dirname(os.path.abspath(sys.executable))
        appdatafile = os.path.join(curdir, 'appdata')
        defaultappdata = os.path.join(os.path.expanduser('~'), '.bitdust')
        appdata = defaultappdata
        if os.path.isfile(appdatafile):
            try:
                appdata = os.path.abspath(open(appdatafile, 'rb').read().strip())
            except:
                appdata = defaultappdata
            if not os.path.isdir(appdata):
                appdata = defaultappdata
        AppDataDir = appdata

    cmd = ''
    if len(args) > 0:
        cmd = args[0].lower()

    # ask to count time for each log line from that moment, not absolute time
    lg.life_begins()
    # try to read debug level value at the early stage - no problem if fail here
    try:
        if cmd == '' or cmd == 'start' or cmd == 'go' or cmd == 'show' or cmd == 'open':
            lg.set_debug_level(int(
                bpio._read_data(
                    os.path.abspath(
                        os.path.join(appdata, 'config', 'logs', 'debug-level')))))
    except:
        pass

    if opts.no_logs:
        lg.disable_logs()

    #---logpath---
    logpath = os.path.join(appdata, 'logs', 'start.log')
    if opts.output:
        logpath = opts.output

    need_redirecting = False

    if bpio.Windows() and not bpio.isConsoled():
        need_redirecting = True

    if logpath != '':
        lg.open_log_file(logpath)
        lg.out(2, 'bpmain.main log file opened ' + logpath)
        if bpio.Windows() and bpio.isFrozen():
            need_redirecting = True

    if need_redirecting:
        lg.stdout_start_redirecting()
        lg.out(2, 'bpmain.main redirecting started')

    try:
        if os.path.isfile(os.path.join(appdata, 'logs', 'exception.log')):
            os.remove(os.path.join(appdata, 'logs', 'exception.log'))
    except:
        pass

    if opts.debug or str(opts.debug) == '0':
        lg.set_debug_level(opts.debug)

    # if opts.quite and not opts.verbose:
    #     lg.disable_output()

    if opts.verbose:
        copyright()

    lg.out(2, 'bpmain.main started ' + time.asctime())

    overDict = override_options(opts, args)

    lg.out(2, 'bpmain.main args=%s' % str(args))

    #---start---
    if cmd == '' or cmd == 'start' or cmd == 'go':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])

        # this is extra protection for Debian release
        # I am not sure how process name can looks on different systems
        # check the process ID from previous start
        # it file exists and we found this PID in the currently running apps - BitDust is working
        # if file not exists we don't want to start if found some other jobs with same name
#        pid = -1
#        try:
#            if bpio.Windows():
#                _data_path = os.path.join(os.environ.get('APPDATA', os.path.join(os.path.expanduser('~'), 'Application Data')), 'BitDust')
#                pid_path = os.path.join(_data_path, 'metadata', 'processid')
#            else:
#                pid_path = os.path.join(appdata, 'metadata', 'processid')
#            if os.path.isfile(pid_path):
#                pid = int(bpio.ReadBinaryFile(pid_path).strip())
#        except:
#            lg.exc()

        if len(appList) > 0:
            lg.out(0, 'BitDust already started, found another process: %s\n' % str(appList))
            bpio.shutdown()
            return 0
        UI = ''
        # if cmd == 'show' or cmd == 'open':
        # UI = 'show'
        try:
            ret = run(UI, opts, args, overDict, executable_path)
        except:
            lg.exc()
            ret = 1
        bpio.shutdown()
        return ret

    #---detach---
    elif cmd == 'detach' or cmd == 'daemon' or cmd == 'background':
        # lg.set_debug_level(20)
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])
        if len(appList) > 0:
            lg.out(0, 'main BitDust process already started: %s\n' % str(appList))
            bpio.shutdown()
            return 0
        from lib import misc
        # from twisted.internet import reactor
        # def _detach():
        #     result = misc.DoRestart(detach=True)
        #     lg.out(0, 'run and detach main BitDust process: %s' % str(result))
        #     reactor.callLater(2, reactor.stop)
        # reactor.addSystemEventTrigger('after','shutdown', misc.DoRestart, detach=True)
        # reactor.callLater(0.01, _detach)
        # reactor.run()
        lg.out(0, 'main BitDust process started in daemon mode\n')
        bpio.shutdown()
        result = misc.DoRestart(detach=True)
        try:
            result = result.pid
        except:
            pass
        return 0

    #---restart---
    elif cmd == 'restart' or cmd == 'reboot':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])
        ui = False
        # if cmd == 'restart':
        # ui = True
        if len(appList) > 0:
            lg.out(0, 'found main BitDust process: %s, sending "restart" command ... ' % str(appList), '')

            def done(x):
                lg.out(0, 'DONE\n', '')
                from twisted.internet import reactor
                if reactor.running and not reactor._stopped:
                    reactor.stop()

            def failed(x):
                ok = str(x).count('Connection was closed cleanly') > 0
                from twisted.internet import reactor
                if ok and reactor.running and not reactor._stopped:
                    lg.out(0, 'DONE\n', '')
                    reactor.stop()
                    return
                lg.out(0, 'FAILED while killing previous process - do HARD restart\n', '')
                try:
                    kill()
                except:
                    lg.exc()
                from lib import misc
                reactor.addSystemEventTrigger('after', 'shutdown', misc.DoRestart, param='show' if ui else '', detach=True)
                reactor.stop()
            try:
                from twisted.internet import reactor
                # from interface.command_line import run_url_command
                # d = run_url_command('?action=restart', False)
                # from interface import cmd_line
                # d = cmd_line.call_xmlrpc_method('restart', ui)
                from interface import cmd_line_json
                d = cmd_line_json.call_jsonrpc_method('restart', ui)
                d.addCallback(done)
                d.addErrback(failed)
                reactor.run()
                bpio.shutdown()
                return 0
            except:
                lg.exc()
                bpio.shutdown()
                return 1
        else:
            ui = ''
            if cmd == 'restart':
                ui = 'show'
            try:
                ret = run(ui, opts, args, overDict, executable_path)
            except:
                lg.exc()
                ret = 1
            bpio.shutdown()
            return ret

    #---show---
    elif cmd == 'show' or cmd == 'open':
        from main import settings
        if not bpio.isGUIpossible() and not settings.NewWebGUI():
            lg.out(0, 'BitDust GUI is turned OFF\n')
            bpio.shutdown()
            return 0
        if bpio.Linux() and not bpio.X11_is_running():
            lg.out(0, 'this operating system not supported X11 interface\n')
            bpio.shutdown()
            return 0
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])
        if not settings.NewWebGUI():
            appList_bpgui = bpio.find_process([
                'bpgui.exe',
                'bpgui.py',
            ])
            if len(appList_bpgui) > 0:
                if len(appList) == 0:
                    for pid in appList_bpgui:
                        bpio.kill_process(pid)
                else:
                    lg.out(0, 'BitDust GUI already opened, found another process: %s\n' % str(appList))
                    bpio.shutdown()
                    return 0
        if len(appList) == 0:
            try:
                ret = run('show', opts, args, overDict, executable_path)
            except:
                lg.exc()
                ret = 1
            bpio.shutdown()
            return ret
        lg.out(0, 'found main BitDust process: %s, start the GUI\n' % str(appList))
        ret = show()
        bpio.shutdown()
        return ret

    #---stop---
    elif cmd == 'stop' or cmd == 'kill' or cmd == 'shutdown':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])
        if len(appList) > 0:
            lg.out(0, 'found main BitDust process: %s, sending command "exit" ... ' % str(appList), '')
            try:
                from twisted.internet import reactor
                # from interface.command_line import run_url_command
                # url = '?action=exit'
                # run_url_command(url, False).addBoth(wait_then_kill)
                # reactor.run()
                # bpio.shutdown()

                def _stopped(x):
                    lg.out(0, 'BitDust process finished correctly\n')
                    reactor.stop()
                    bpio.shutdown()
                # from interface import cmd_line
                # cmd_line.call_xmlrpc_method('stop').addBoth(_stopped)
                from interface import cmd_line_json
                cmd_line_json.call_jsonrpc_method('stop').addBoth(_stopped)
                reactor.run()
                return 0
            except:
                lg.exc()
                ret = kill()
                bpio.shutdown()
                return ret
        else:
            lg.out(0, 'BitDust is not running at the moment\n')
            bpio.shutdown()
            return 0

    #---uninstall---
    elif cmd == 'uninstall':
        def do_spawn(x=None):
            from main.settings import WindowsStarterFileName
            starter_filepath = os.path.join(bpio.getExecutableDir(), WindowsStarterFileName())
            lg.out(0, "bpmain.main bitstarter.exe path: %s " % starter_filepath)
            if not os.path.isfile(starter_filepath):
                lg.out(0, "ERROR: %s not found\n" % starter_filepath)
                bpio.shutdown()
                return 1
            cmdargs = [os.path.basename(starter_filepath), 'uninstall']
            lg.out(0, "bpmain.main os.spawnve cmdargs=" + str(cmdargs))
            ret = os.spawnve(os.P_DETACH, starter_filepath, cmdargs, os.environ)
            bpio.shutdown()
            return ret

        def do_reactor_stop_and_spawn(x=None):
            lg.out(0, 'BitDust process finished correctly\n')
            reactor.stop()
            ret = do_spawn()
            bpio.shutdown()
            return ret
        lg.out(0, 'bpmain.main UNINSTALL!')
        if not bpio.Windows():
            lg.out(0, 'This command can be used only under OS Windows.\n')
            bpio.shutdown()
            return 0
        if not bpio.isFrozen():
            lg.out(0, 'You are running BitDust from sources, uninstall command is available only for installable version.\n')
            bpio.shutdown()
            return 0
        appList = bpio.find_process(['bitdust.exe', ])
        if len(appList) > 0:
            lg.out(0, 'found main BitDust process...   ', '')
            try:
                # from twisted.internet import reactor
                # from interface.command_line import run_url_command
                # url = '?action=exit'
                # run_url_command(url).addBoth(do_reactor_stop_and_spawn)
                # reactor.run()
                # bpio.shutdown()
                # from interface import cmd_line
                # cmd_line.call_xmlrpc_method('stop').addBoth(do_reactor_stop_and_spawn)
                from interface import cmd_line_json
                cmd_line_json.call_jsonrpc_method('stop').addBoth(do_reactor_stop_and_spawn)
                reactor.run()
                return 0
            except:
                lg.exc()
        ret = do_spawn()
        bpio.shutdown()
        return ret

    #---command_line---
    # from interface import command_line as cmdln
    # from interface import cmd_line as cmdln
    from interface import cmd_line_json as cmdln
    ret = cmdln.run(opts, args, pars, overDict, executable_path)
    if ret == 2:
        print usage()
    bpio.shutdown()
    return ret
Beispiel #54
0
def main():
    from logs import lg
    lg.set_debug_level(18)
    do_in_memory(sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]), sys.argv[5], sys.argv[6] == '1')
Beispiel #55
0
        print my_id.getLocalIdentity().serialize()
        print 'Valid is: ', my_id.getLocalIdentity().Valid()
    else:
        my_id.setLocalIdentity(my_id.buildDefaultIdentity(sys.argv[1]))
        my_id.saveLocalIdentity()
        print my_id.getLocalIdentity().serialize()
        print 'Valid is: ', my_id.getLocalIdentity().Valid()
        my_id._LocalIdentity = None
        my_id.loadLocalIdentity()


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()

#------------------------------------------------------------------------------


if __name__ == '__main__':
    lg.set_debug_level(18)
    main()
#------------------------------------------------------------------------------ 

def _test():

#     print db().insert({'idurl': 'http://idurl1234', 'time': '12345678'})
#     print db().insert({'hash': '1234567812345678' + random.choice(['a,b,c']), 'data': {'a':'b', 'c': 'd', 'time': 123456,}})
    
#     print 'query all from "id"'
#     for x in query_from_json({'method': 'get_all', 'index': 'id'})[0]:
#         print x
#    
#     print 'query all from "idurl"'
#     for x in query_from_json({'method': 'get_all', 'index': 'idurl'})[0]:
#         print x

    print 'query one from "idurl"'
    ret = query_from_json({'method': 'get', 'index': 'idurl', 'key': 'http://idurl1234'})
    for x in ret[0]:
        print x

#     print db().get('idurl', 'http://idurl1234')
    


if __name__ == "__main__":
    lg.set_debug_level(20)
    init()
    _test()
    shutdown()
    
def main():
    lg.set_debug_level(18)
    lg.life_begins()
    from crypt import key
    key.InitMyKey()
    from contacts import identitycache
    identitycache.init()
    from system import tmpfile
    tmpfile.init()
    from services import driver
    driver.disabled_services().add('service_tcp_connections')
    driver.disabled_services().add('service_p2p_hookups')
    driver.disabled_services().add('service_nodes_lookup')
    driver.disabled_services().add('service_identity_propagate')
    driver.disabled_services().add('service_ip_port_responder')
    driver.init()
    driver.enabled_services().clear()
    driver.enabled_services().add('service_udp_transport')
    driver.enabled_services().add('service_udp_datagrams')
    driver.enabled_services().add('service_my_ip_port')
    driver.enabled_services().add('service_gateway')
    driver.enabled_services().add('service_entangled_dht')
    driver.enabled_services().add('service_network')
    driver.start()
    # options = { 'idurl': my_id.getLocalID(),}
    # options['host'] = nameurl.GetName(my_id.getLocalID())+'@'+'somehost.org'
    # options['dht_port'] = int(settings.getDHTPort())
    # options['udp_port'] = int(settings.getUDPPort())
    # udp.listen(int(settings.getUDPPort()))
    # dht_service.init(settings.getDHTPort())
    # dht_service.connect()
    # udp_node.A('go-online', options)
    reactor.addSystemEventTrigger('before', 'shutdown', gateway.shutdown)
    gateway.init()
    gateway.start()

    def _ok_to_send(transport, oldstate, newstate):
        if newstate != 'LISTENING':
            return
        # [filename] [peer idurl]
        if len(sys.argv) >= 3:
            # bpio.WriteFile(sys.argv[1]+'.signed', p.Serialize())

            def _try_reconnect():
                sess = udp_session.get_by_peer_id(sys.argv[2])
                reconnect = False
                if not sess:
                    reconnect = True
                    print 'sessions', udp_session.sessions_by_peer_id().keys()
                    print map(lambda s: s.peer_id, udp_session.sessions().values())
                else:
                    if sess.state != 'CONNECTED':
                        print 'state: ', sess.state
                        reconnect = True
                if reconnect:
                    print 'reconnect', sess
                    udp_session.add_pending_outbox_file(
                        sys.argv[1] + '.signed', sys.argv[2], 'descr', Deferred(), False)
                    udp_node.A('connect', sys.argv[2])
                reactor.callLater(0.5, _try_reconnect)

            def _try_connect():
                if udp_node.A().state == 'LISTEN':
                    print 'connect'
                    gateway.stop_packets_timeout_loop()
                    udp_session.add_pending_outbox_file(
                        sys.argv[1] + '.signed', sys.argv[2], 'descr', Deferred(), False)
                    udp_node.A('connect', sys.argv[2])
                    reactor.callLater(5, _try_reconnect)
                else:
                    reactor.callLater(1, _try_connect)
            # _try_connect()

            def _send(c):
                from transport.udp import udp_stream
                for idurl in sys.argv[2:]:
                    print '_send', udp_stream.streams().keys()
                    p = signed.Packet(commands.Data(),
                                      my_id.getLocalID(),
                                      my_id.getLocalID(),
                                      'packet%d' % c,
                                      bpio.ReadBinaryFile(sys.argv[1]),
                                      idurl)
                    gateway.outbox(p)
                if c > 1:
                    reactor.callLater(0.01, _send, c - 1)
            reactor.callLater(0, _send, 15)

    gateway.add_transport_state_changed_callback(_ok_to_send)
    reactor.run()
Beispiel #58
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