예제 #1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("url", help="The URL to share.", nargs='?')
    parser.add_argument("-g",
                        "--get",
                        help="Get shared URL.",
                        action='store_true')
    pa = parser.parse_args()

    h = opendht.InfoHash.get(USER + PWD)
    print_debug("InfoHash: %s" % h.toString())

    dht = opendht.DhtRunner()
    dht.bootstrap(DEFAULT_DHT_BOOTSTRAP_HOST, DEFAULT_DHT_BOOTSTRAP_PORT)
    dht.run()
    print_debug("is running? %s" % dht.isRunning())

    if pa.get:
        lv = get_last_value(dht.get(h), PWD)
        if not lv:
            qute_print("No url found")
            return 1
        url = lv[b"data"].decode()
        qute_cmd(":open -t %s" % url)
        qute_print("URL found: %s" % url)
    else:
        if not pa.url:
            return
        lv = get_last_value(dht.get(h), PWD)
        last_id = lv[b"id"] if lv else -1
        pv = msgpack.packb({"id": last_id + 1, "data": pa.url})
        v = opendht.Value(encrypt(pv, PWD))
        print_debug(v)
        dht.put(h, v)
        qute_print("URL shared")
예제 #2
0
 def render_POST(self, req):
     uri = req.uri[1:]
     data = req.args[b'data'][0] if b'data' in req.args else None
     user_type = req.args[b'user_type'][0].decode(
     ) if b'user_type' in req.args else ""
     try:
         vid = int(req.args[b'id'][0].decode()) if b'id' in req.args else 0
     except ValueError:
         vid = 0
     if not data and b'base64' in req.args:
         data = base64.b64decode(req.args[b'base64'][0])
     h = dht.InfoHash(uri) if len(uri) == 40 else dht.InfoHash.get(
         uri.decode())
     print('POST', h, data)
     req.setHeader(b"content-type", b"application/json")
     if data:
         v = dht.Value(data)
         if vid != 0:
             v.id = vid
         v.user_type = user_type
         self.node.put(h, v)
         return json.dumps({'success': True}).encode()
     else:
         req.setResponseCode(400)
         return json.dumps({
             'success': False,
             'error': 'no data parameter'
         }).encode()
예제 #3
0
def ping(node, h):
	global i
	i += 1
	if i < MAX:
		node.put(h, dht.Value(b"hey"), lambda ok, nodes: done(node.getNodeId().decode(), ok))
	else:
		loop.stop()
예제 #4
0
def pong(node, h):
    global i
    print("got ping", h, i)
    time.sleep(0.0075)
    i += 1
    if i < MAX:
        node.put(h, dht.Value(b"hey"), lambda ok, nodes: print("over", ok))
    return True
예제 #5
0
 def sunucuya_kayit(self,deger,anahtar=None,gorev_bitince="sonlan"):
    """Verilen anahtar değeri ve değeri dht e kayıt eder."""
    if anahtar is None:
       anahtar=self.sunucu_isim
    sonuc=self.node.put(dht.InfoHash.get(anahtar),dht.Value(deger.encode()))
    '''dht dugumunu durdurmak için gorev_bitince="sonlan" atanır.'''
    if gorev_bitince == "sonlan":
        self.node=None
    return sonuc
예제 #6
0
 def render_POST(self, req):
     uri = req.uri[1:]
     data = req.args[b'data'][0] if b'data' in req.args else None
     if not data and b'base64' in req.args:
         data = base64.b64decode(req.args[b'base64'][0])
     h = dht.InfoHash(uri) if len(uri) == 40 else dht.InfoHash.get(uri.decode())
     print('POST', h, data)
     req.setHeader(b"content-type", b"application/json")
     if data:
         self.node.put(h, dht.Value(data))
         return json.dumps({'success':True}).encode()
     else:
         req.setResponseCode(400)
         return json.dumps({'success':False, 'error':'no data parameter'}).encode()
예제 #7
0
 def put(self, log_name):
     log_name = log_name.replace("\x00", "").replace("\\u0000", "")
     print("dht_service - put: log_name = " + log_name)
     guid = request.form["guid"]
     data = bytes(
         json.dumps(request.form).replace("\x00",
                                          "").replace("\\u0000", ""),
         "utf-8")
     print("dht_service - put: creating new with data = " + str(data))
     node.put(dht.InfoHash.get(str(log_name)), dht.Value(data))
     result = [
         v.data.decode("utf-8")
         for v in node.get(dht.InfoHash.get(log_name))
     ]
     print("dht_service - put: result = " + str(result))
     return result
예제 #8
0
    def dhtPublish(self):
        # Publish this service to the DHT for WAN discovery.

        if not self.useDHT:
            return

        tryDHTConnect()

        timePeriod = struct.pack("<Q", int(time.time() / (3600 * 24)))
        rollingCode = blake2b(self.keyhash + timePeriod,
                              encoder=nacl.encoding.RawEncoder())[:20]

        # We never actually know if this will be available on the platform or not
        if dhtContainer[0]:
            try:
                import opendht as dht

                with dhtlock:
                    dhtContainer[0].put(
                        dht.InfoHash.get(rollingCode.hex()),
                        dht.Value(getWanHostsString().encode()))
            except Exception:
                logger.info("Could not use local DHT node")
                logger.info(traceback.format_exc())
            return

        # Using a DHT proxy we can host a site without actually using the DHT directly.
        # This is for future direct-from-android hosting.
        for i in getDHTProxies():
            import requests
            try:
                data = {
                    "data":
                    base64.b64encode(getWanHostsString().encode()).decode(),
                    "id": "id 1",
                    "seq": 0,
                    "type": 3
                }
                url = i + hashlib.sha1(
                    rollingCode.hex().encode()).digest()[:20].hex()
                r = requests.post(url, data=json.dumps(data))
                r.raise_for_status()
                break
            except Exception:
                logger.info(traceback.format_exc())
예제 #9
0

def listen(key):
    node1.listen(key,
                 lambda v, e: loop.call_soon_threadsafe(listen_cb, key, v, e))


for key in keys:
    listen(key)

next_test = time.time()
while True:
    start = time.time()
    #print(datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S'), 'Test started')
    for key in keys:
        val = dht.Value(str(dht.InfoHash.getRandom()).encode())
        pending_tests[str(key)] = {'v': val, 'c': 0}
        node2.put(key, val, lambda ok, nodes: ok)
    while len(pending_tests):
        loop.stop()
        loop.run_forever()
        time.sleep(1)
        if time.time() - start > args.timeout:
            print('Test timeout !')
            exit(1)

    end = time.time()
    print(
        datetime.fromtimestamp(end).strftime('%Y-%m-%d %H:%M:%S'),
        'Test completed successfully in', end - start)
    next_test += args.period
예제 #10
0
import opendht as dht

node = dht.DhtRunner()
node.run()

# Join the network through any running node,
# here using a know bootstrap node.
node.bootstrap("bootstrap.jami.net", "4222")

# blocking call (provide callback arguments to make the call non-blocking)
node.put(dht.InfoHash.get("unique_key"), dht.Value(b'some binary data'))

results = node.get(dht.InfoHash.get("unique_key"))
for r in results:
    print(r)
예제 #11
0
pong_node.run(port=5633)
#pong_node.enableLogging()
pong_node.bootstrap("192.168.49.55", "5632")
#pong_node.bootstrap("192.168.49.55", "5632");

loc_ping = dht.InfoHash.get("toto99")
loc_pong = dht.InfoHash.get(str(loc_ping))

i = 0
MAX = 8192


def pong(node, h):
    global i
    print("got ping", h, i)
    time.sleep(0.0075)
    i += 1
    if i < MAX:
        node.put(h, dht.Value(b"hey"), lambda ok, nodes: print("over", ok))
    return True


ping_node.listen(loc_ping, lambda v: pong(pong_node, loc_pong))
pong_node.listen(loc_pong, lambda v: pong(ping_node, loc_ping))

pong_node.put(loc_pong, dht.Value(b"hey"),
              lambda ok, nodes: print("i over", ok))

while (i < MAX):
    time.sleep(1)
예제 #12
0
 def dhtValue(self, value: str) -> dht.Value:
     '''
     Convert a string value to bytes (wiht optional encryption) then to a dht.Value
     '''
     return dht.Value(self.encryptData(value.encode('UTF-8')))