Created
March 25, 2012 22:22
-
-
Save infinityb/2200386 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ctypes import c_int, POINTER, cdll, Structure | |
import time | |
import socket | |
try: | |
import gevent | |
except ImportError: | |
gevent = False | |
dht_so = cdll.LoadLibrary("./libdht.so.1.0.1") | |
class dht_client(Structure): | |
_fields_ = [ | |
('s4', c_int), | |
('s6', c_int), | |
('tosleep', c_int) | |
] | |
def __repr__(self): | |
return "dht_client(%r, %r, %r)" % (self.s4, self.s6, self.tosleep) | |
class DhtClient(object): | |
def __init__(self, node_id): | |
self._refs = [] | |
s4 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) | |
s4.bind(('0.0.0.0', 7681)) | |
self._refs.append(s4) | |
s6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, 0) | |
s6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) | |
s6.bind(('::', 7681)) | |
self._refs.append(s6) | |
self._cstruct = dht_client(s4.fileno(), s6.fileno(), 0) | |
print "%r" % self._cstruct | |
rc = dht_so.dht_init(self._cstruct.s4, self._cstruct.s6, | |
node_id.decode('hex'), "JC\0\0"); | |
assert not (rc < 0) | |
def _start_gevent(self): | |
ptr = POINTER(dht_client)(self._cstruct) | |
while True: | |
dht_so.dht_do_round(ptr) | |
gevent.sleep() | |
def start(self): | |
if gevent: | |
return self._start_gevent() | |
ptr = POINTER(dht_client)(self._cstruct) | |
while True: | |
dht_so.dht_do_round(ptr) | |
def dump_tables(self, file): | |
return dht_so.dht_dump_tables2(file.fileno()) | |
dht_c = DhtClient("62e921d26349925860c4eafd3ded8a7eed88dc8c") | |
import tempfile | |
import gevent.wsgi | |
def application(env, sr): | |
if env['PATH_INFO'] == '/dht-dump': | |
sr('200 OK', [('Content-Type', 'text/plain')]) | |
tmp = tempfile.TemporaryFile() | |
dht_c.dump_tables(tmp) | |
tmp.seek(0) | |
while True: | |
buf = tmp.read(4096) | |
if not buf: break | |
yield buf | |
else: | |
sr('404 Not Found', [('Content-Type', 'text/plain')]) | |
yield "NotFound" | |
gevent.wsgi.WSGIServer(('', 8080), application).start() | |
dht_c.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment