KODI addon structure

This commit is contained in:
Бородин Роман committed 2019-05-07 19:55:11 +03:00
1 parent 284a2cd01a
commit 34b5af6214
8 files changed
+27 -11

No files matched your search

View File
Whitespace-only changes.
+123
View File
@@ -0,0 +1,123 @@
"""
The MIT License
Copyright (c) 2015 Fred Stober
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
class BTFailure(Exception):
pass
# Encoding functions ##############################################
import sys
if sys.version_info[0] >= 3:
str_to_bytes = lambda x: x.encode('ascii')
else:
str_to_bytes = lambda x: x
def bencode_proc(result, x):
t = type(x)
if t == str:
result.extend((str_to_bytes(str(len(x))), b':', str_to_bytes(x)))
elif t == bytes:
result.extend((str_to_bytes(str(len(x))), b':', x))
elif t == int:
result.extend((b'i', str_to_bytes(str(x)), b'e'))
elif t == dict:
result.append(b'd')
for k, v in sorted(x.items()):
bencode_proc(result, k)
bencode_proc(result, v)
result.append(b'e')
elif t == list:
result.append(b'l')
for item in x:
bencode_proc(result, item)
result.append(b'e')
def bencode(x):
result = []
bencode_proc(result, x)
return b''.join(result)
# Decoding functions ##############################################
bdecode_marker_int = ord('i')
bdecode_marker_str_min = ord('0')
bdecode_marker_str_max = ord('9')
bdecode_marker_list = ord('l')
bdecode_marker_dict = ord('d')
bdecode_marker_end = ord('e')
def bdecode_proc(msg, pos):
t = msg[pos]
if t == bdecode_marker_int:
pos += 1
pos_end = msg.index(b'e', pos)
return (int(msg[pos:pos_end]), pos_end + 1)
elif t >= bdecode_marker_str_min and t <= bdecode_marker_str_max:
sep = msg.index(b':', pos)
n = int(msg[pos:sep])
sep += 1
return (bytes(msg[sep:sep + n]), sep + n)
elif t == bdecode_marker_dict:
result = {}
pos += 1
while msg[pos] != bdecode_marker_end:
k, pos = bdecode_proc(msg, pos)
result[k], pos = bdecode_proc(msg, pos)
return (result, pos + 1)
elif t == bdecode_marker_list:
result = []
pos += 1
while msg[pos] != bdecode_marker_end:
v, pos = bdecode_proc(msg, pos)
result.append(v)
return (result, pos + 1)
raise BTFailure("invalid bencoded data (invalid token)! %r" % msg)
def bdecode_extra(msg):
try:
result, pos = bdecode_proc(bytearray(msg), 0)
except (IndexError, KeyError, ValueError):
raise BTFailure("invalid bencoded data! %r" % msg)
return (result, pos)
def bdecode(msg):
try:
result, pos = bdecode_extra(msg)
except (IndexError, KeyError, ValueError):
raise BTFailure("invalid bencoded data: %r" % msg)
if pos != len(msg):
raise BTFailure("invalid bencoded value (data after valid prefix)")
return result
if __name__ == '__main__':
import logging
logging.basicConfig()
test = {b'k1': 145, b'k2': {b'sk1': list(range(10)), b'sk2': b'0'*60}}
for x in range(100):
assert(bdecode(bencode(test)) == test)
for test_bytes in [b'd5:keyi0ee', b'x3:keyi0ee', b'd3:keyi0ee...']:
try:
bdecode(test_bytes)
except BTFailure as ex:
logging.exception('expected bdecode exception')
+104
View File
@@ -0,0 +1,104 @@
"""
The MIT License
Copyright (c) 2014 Fred Stober
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# generated using pycrc (www.tty1.net/pycrc)
crc32c_table = (
0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4,
0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb,
0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b,
0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24,
0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b,
0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384,
0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54,
0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b,
0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a,
0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35,
0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5,
0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa,
0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45,
0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a,
0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a,
0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595,
0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48,
0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957,
0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687,
0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198,
0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927,
0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38,
0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8,
0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7,
0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096,
0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789,
0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859,
0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46,
0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9,
0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6,
0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36,
0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829,
0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c,
0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93,
0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043,
0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c,
0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3,
0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc,
0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c,
0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033,
0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652,
0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d,
0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d,
0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982,
0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d,
0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622,
0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2,
0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed,
0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530,
0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f,
0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff,
0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0,
0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f,
0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540,
0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90,
0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f,
0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee,
0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1,
0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321,
0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e,
0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81,
0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e,
0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e,
0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351,
)
def crc32c(data):
""" return CRC32C checksum """
crc = 0xffffffff
for byte in data:
crc = (crc32c_table[(crc ^ byte) & 0xff] ^ (crc >> 8)) & 0xffffffff
return (crc & 0xffffffff) ^ 0xffffffff
if __name__ == '__main__':
import logging
logging.basicConfig()
log = logging.getLogger()
log.critical(crc32c(bytearray(b'1')))
+487
View File
@@ -0,0 +1,487 @@
"""
The MIT License
Copyright (c) 2014-2015 Fred Stober
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import os, time, socket, hashlib, hmac, threading, logging, random, inspect
from bencode import bdecode
from lib.tinybt import bencode.bencode
from lib.tinybt.utils import encode_uint32, encode_ip, encode_connection, encode_nodes, AsyncTimeout
from lib.tinybt.utils import decode_uint32, decode_ip, decode_connection, decode_nodes, start_thread, ThreadManager
from lib.tinybt.krpc import KRPCPeer, KRPCError
# BEP #0042 - prefix is based on ip and last byte of the node id - 21 most significant bits must match
# * ip = ip address in string format eg. "127.0.0.1"
def bep42_prefix(ip, crc32_salt, first_node_bits): # first_node_bits determines the last 3 bits
from lib.tinybt import crc32c.crc32c
ip_asint = decode_uint32(encode_ip(ip))
value = crc32c(bytearray(encode_uint32((ip_asint & 0x030f3fff) | ((crc32_salt & 0x7) << 29))))
return (value & 0xfffff800) | ((first_node_bits << 8) & 0x00000700)
def valid_id(node_id, connection):
node_id = bytearray(node_id)
vprefix = bep42_prefix(connection[0], node_id[-1], 0)
return (((vprefix ^ decode_uint32(node_id[:4])) & 0xfffff800) == 0)
def decode_id(node_id):
try: # python 3
return int.from_bytes(node_id, byteorder='big')
except:
return int(node_id.encode('hex'), 16)
class DHT_Node(object):
def __init__(self, connection, id, version = None):
self.connection = (socket.gethostbyname(connection[0]), connection[1])
self.set_id(id)
self.version = version
self.tokens = {} # tokens to gain write access to self.values
self.values = {}
self.attempt = 0
self.pending = 0
self.last_ping = 0
def set_id(self, id):
self.id = id
self.id_cmp = decode_id(id)
def __repr__(self):
return 'id:%s con:%15s:%-5d v:%20s c:%5s last:%.2f' % (hex(self.id_cmp), self.connection[0], self.connection[1],
repr(self.version), valid_id(self.id, self.connection), time.time() - self.last_ping)
# Trivial node list implementation
class DHT_Router(object):
def __init__(self, name, user_setup = {}):
setup = {'report_t': 10, 'limit_t': 30, 'limit_N': 2000, 'redeem_t': 300, 'redeem_frac': 0.05}
setup.update(user_setup)
self._log = logging.getLogger(self.__class__.__name__ + '.%s' % name)
# This is our (trivial) routing table.
self._nodes = {}
self._nodes_lock = threading.RLock()
self._nodes_protected = set()
self._connections_bad = set()
# Start maintainance threads
self._threads = ThreadManager(self._log.getChild('maintainance'))
self.shutdown = self._threads.shutdown
# - Report status of routing table
def _show_status():
with self._nodes_lock:
self._log.info('Routing table contains %d ids with %d nodes (%d bad, %s protected)' %\
(len(self._nodes), sum(map(len, self._nodes.values())),
len(self._connections_bad), len(self._nodes_protected)))
if self._log.isEnabledFor(logging.DEBUG):
for node in self.get_nodes():
self._log.debug('\t%r' % node)
self._threads.start_continuous_thread(_show_status, thread_interval = setup['report_t'], thread_waitfirst = True)
# - Limit number of active nodes
def _limit(maxN):
self._log.debug('Starting limitation of nodes')
N = len(self.get_nodes())
if N > maxN:
for node in self.get_nodes(N - maxN,
expression = lambda n: n.connection not in self._connections_bad,
sorter = lambda x: random.random()):
self.remove_node(node, force = True)
self._threads.start_continuous_thread(_limit, thread_interval = setup['limit_t'], maxN = setup['limit_N'], thread_waitfirst = True)
# - Redeem random nodes from the blacklist
def _redeem_connections(fraction):
self._log.debug('Starting redemption of blacklisted nodes')
remove = int(fraction * len(self._connections_bad))
with self._nodes_lock:
while self._connections_bad and (remove > 0):
self._connections_bad.pop()
remove -= 1
self._threads.start_continuous_thread(_redeem_connections, thread_interval = setup['redeem_t'], fraction = setup['redeem_frac'], thread_waitfirst = True)
def protect_nodes(self, node_id_list):
self._log.info('protect %s' % repr(sorted(node_id_list)))
with self._nodes_lock:
self._nodes_protected.update(node_id_list)
def good_node(self, node):
with self._nodes_lock:
node.attempt = 0
def remove_node(self, node, force = False):
with self._nodes_lock:
node.attempt += 1
if node.id in self._nodes:
max_attempts = 2
if valid_id(node.id, node.connection):
max_attempts = 5
if force or ((node.id not in self._nodes_protected) and (node.attempt > max_attempts)):
if not force:
self._connections_bad.add(node.connection)
def is_not_removed_node(n):
return n.connection != node.connection
self._nodes[node.id] = list(filter(is_not_removed_node, self._nodes[node.id]))
if not self._nodes[node.id]:
self._nodes.pop(node.id)
def register_node(self, node_connection, node_id, node_version = None):
with self._nodes_lock:
if node_connection in self._connections_bad:
if self._log.isEnabledFor(logging.DEBUG):
self._log.debug('rejected bad connection %s' % repr(node_connection))
return
for node in self._nodes.get(node_id, []):
if node.connection == node_connection:
if not node.version:
node.version = node_version
return node
if self._log.isEnabledFor(logging.DEBUG):
self._log.debug('added connection %s' % repr(node_connection))
node = DHT_Node(node_connection, node_id, node_version)
self._nodes.setdefault(node_id, []).append(node)
return node
# Return nodes matching a filter expression
def get_nodes(self, N = None, expression = lambda n: True, sorter = lambda n: n.id_cmp):
if len(self._nodes) == 0:
raise RuntimeError('No nodes in routing table!')
result = []
with self._nodes_lock:
for id, node_list in self._nodes.items():
result.extend(filter(expression, node_list))
result.sort(key = sorter)
if N == None:
return result
return result[:N]
class DHT(object):
def __init__(self, listen_connection, bootstrap_connection = ('router.bittorrent.com', 6881),
user_setup = {}, user_router = None):
""" Start DHT peer on given (host, port) and bootstrap connection to the DHT """
setup = {'discover_t': 180, 'check_t': 30, 'check_N': 10}
setup.update(user_setup)
self._log = logging.getLogger(self.__class__.__name__ + '.%s.%d' % listen_connection)
self._log.info('Starting DHT node with bootstrap connection %s:%d' % bootstrap_connection)
listen_connection = (socket.gethostbyname(listen_connection[0]), listen_connection[1])
# Generate key for token generation
self._token_key = os.urandom(20)
# Start KRPC server process and Routing table
self._krpc = KRPCPeer(listen_connection, self._handle_query)
if not user_router:
user_router = DHT_Router('%s.%d' % listen_connection, setup)
self._nodes = user_router
self._node = DHT_Node(listen_connection, os.urandom(20))
self._node_lock = threading.RLock()
# Start bootstrap process
try:
tmp = self.ping(bootstrap_connection, sender_id = self._node.id).get_result(timeout = 1)
except Exception:
raise
tmp = {b'ip': encode_connection(listen_connection), b'r': {b'id': self._node.id}}
self._node.connection = decode_connection(tmp[b'ip'])
self._bootstrap_node = self._nodes.register_node(bootstrap_connection, tmp[b'r'][b'id'])
# BEP #0042 Enable security extension
local_id = bytearray(self._node.id)
bep42_value = encode_uint32(bep42_prefix(self._node.connection[0], local_id[-1], local_id[0]))
self._node.set_id(bep42_value[:3] + self._node.id[3:])
assert(valid_id(self._node.id, self._node.connection))
self._nodes.protect_nodes([self._node.id])
# Start maintainance threads
self._threads = ThreadManager(self._log.getChild('maintainance'))
# Periodically ping nodes in the routing table
def _check_nodes(N, last_ping = 15 * 60, timeout = 5):
def get_unpinged(n):
return time.time() - n.last_ping > last_ping
check_nodes = list(self._nodes.get_nodes(N, expression = get_unpinged))
if not check_nodes:
return
self._log.debug('Starting cleanup of known nodes')
node_result_list = []
for node in check_nodes:
node.last_ping = time.time()
node_result_list.append((node, node.id, self.ping(node.connection, self._node.id)))
t_end = time.time() + timeout
for (node, node_id, async_result) in node_result_list:
result = self._eval_dht_response(node, async_result, timeout = max(0, t_end - time.time()))
if result and (node.id != result.get(b'id')): # remove nodes with changing identities
self._nodes.remove_node(node, force = True)
self._threads.start_continuous_thread(_check_nodes, thread_interval = setup['check_t'], N = setup['check_N'])
# Try to discover a random node to populate routing table
def _discover_nodes():
self._log.debug('Starting discovery of random node')
for idx, entry in enumerate(self.dht_find_node(os.urandom(20), timeout = 1)):
if idx > 10:
break
self._threads.start_continuous_thread(_discover_nodes, thread_interval = setup['discover_t'])
def get_external_connection(self):
return self._node.connection
def shutdown(self):
""" This function allows to cleanly shutdown the DHT. """
self._log.info('shutting down DHT')
self._threads.shutdown() # Trigger shutdown of maintainance threads
self._krpc.shutdown() # Stop listening for incoming connections
self._nodes.shutdown()
self._threads.join() # Trigger shutdown of maintainance threads
# Handle remote queries
_reply_handler = {}
def _handle_query(self, send_krpc_reply, rec, source_connection):
if self._log.isEnabledFor(logging.DEBUG):
self._log.debug('handling query from %r: %r' % (source_connection, rec))
try:
remote_args_dict = rec[b'a']
if b'id' in remote_args_dict:
self._nodes.register_node(source_connection, remote_args_dict[b'id'], rec.get(b'v'))
query = rec[b'q']
callback = self._reply_handler[query]
callback_kwargs = {}
for arg in inspect.getargspec(callback).args[2:]:
arg_bytes = arg.encode('ascii')
if arg_bytes in remote_args_dict:
callback_kwargs[arg] = remote_args_dict[arg_bytes]
def send_dht_reply(**kwargs):
# BEP #0042 - require ip field in answer
return send_krpc_reply(kwargs, {b'ip': encode_connection(source_connection)})
send_dht_reply.connection = source_connection
callback(self, send_dht_reply, **callback_kwargs)
except Exception:
self._log.exception('Error while processing request %r' % rec)
# Evaluate async KRPC result and notify the routing table about failures
def _eval_dht_response(self, node, async_result, timeout):
try:
result = async_result.get_result(timeout)
node.version = result.get(b'v', node.version)
self._nodes.good_node(node)
return result[b'r']
except AsyncTimeout: # The node did not reply
if self._log.isEnabledFor(logging.DEBUG):
self._log.debug('KRPC timeout %r' % node)
except KRPCError: # Some other error occured
if self._log.isEnabledFor(logging.INFO):
self._log.exception('KRPC Error %r' % node)
self._nodes.remove_node(node)
async_result.discard_result()
return {}
# Iterate KRPC function on closest nodes - query_fun(connection, id, search_value)
def _iter_krpc_search(self, query_fun, process_fun, search_value, timeout, retries):
id_cmp = decode_id(search_value)
(returned, used_connections, discovered_nodes) = (set(), {}, set())
while not self._threads.shutdown_in_progress():
def above_retries(c):
return used_connections[c] > retries
blacklist_connections = set(filter(above_retries, used_connections))
def valid_node(n):
return n and (n.connection not in blacklist_connections)
discovered_nodes = set(filter(valid_node, discovered_nodes))
def not_blacklisted(n):
return n.connection not in blacklist_connections
def sort_by_id(n):
return n.id_cmp ^ id_cmp
close_nodes = set(self._nodes.get_nodes(N = 20, expression = not_blacklisted, sorter = sort_by_id))
if not close_nodes.union(discovered_nodes):
break
node_result_list = []
for node in close_nodes.union(discovered_nodes): # submit all queries at the same time
if node.pending > 3:
continue
if self._log.isEnabledFor(logging.DEBUG):
self._log.debug('asking %s' % repr(node))
async_result = query_fun(node.connection, self._node.id, search_value)
with self._node_lock:
node.pending += 1
node_result_list.append((node, async_result))
used_connections[node.connection] = used_connections.get(node.connection, 0) + 1
t_end = time.time() + timeout
for (node, async_result) in node_result_list: # sequentially retrieve results
if self._threads.shutdown_in_progress():
break
result = self._eval_dht_response(node, async_result, timeout = max(0, t_end - time.time()))
with self._node_lock:
node.pending -= 1
for node_id, node_connection in decode_nodes(result.get(b'nodes', b'')):
discovered_nodes.add(self._nodes.register_node(node_connection, node_id))
for tmp in process_fun(node, result):
if tmp not in returned:
returned.add(tmp)
yield tmp
# syncronous query / async reply implementation of BEP #0005 (DHT Protocol) #
#############################################################################
# Each KRPC method XYZ is implemented using 3 functions:
# dht_XYZ(...) - wrapper to process the result of the KRPC function
# XYZ(...) - direct call of the KRPC method - returns AsyncResult
# _XYZ(...) - handler to process incoming KRPC calls
# ping methods
# (sync method)
def dht_ping(self, connection, timeout = 5):
try:
result = self.ping(connection, self._node.id).get_result(timeout)
if result.get(b'r', {}).get(b'id'):
self._nodes.register_node(connection, result[b'r'][b'id'], result.get(b'v'))
return result.get(b'r', {})
except (AsyncTimeout, KRPCError):
pass
# (verbatim, async KRPC method)
def ping(self, target_connection, sender_id):
return self._krpc.send_krpc_query(target_connection, b'ping', id = sender_id)
# (reply method)
def _ping(self, send_krpc_reply, id):
send_krpc_reply(id = self._node.id)
_reply_handler[b'ping'] = _ping
# find_node methods
# (sync method, iterating on close nodes)
def dht_find_node(self, search_id, timeout = 5, retries = 2):
def process_find_node(node, result):
for node_id, node_connection in decode_nodes(result.get(b'nodes', b'')):
if node_id == search_id:
yield node_connection
return self._iter_krpc_search(self.find_node, process_find_node, search_id, timeout, retries)
# (verbatim, async KRPC method)
def find_node(self, target_connection, sender_id, search_id):
return self._krpc.send_krpc_query(target_connection, b'find_node', id = sender_id, target = search_id)
# (reply method)
def _find_node(self, send_krpc_reply, id, target):
id_cmp = decode_id(id)
def select_valid(n):
return valid_id(n.id, n.connection)
def sort_by_id(n):
return n.id_cmp ^ id_cmp
send_krpc_reply(id = self._node.id, nodes = encode_nodes(self._nodes.get_nodes(N = 20,
expression = select_valid, sorter = sort_by_id)))
_reply_handler[b'find_node'] = _find_node
# get_peers methods
# (sync method, iterating on close nodes)
def dht_get_peers(self, info_hash, timeout = 5, retries = 2):
def process_get_peers(node, result):
if result.get(b'token'):
node.tokens[info_hash] = result[b'token'] # store token for subsequent announce_peer
for node_connection in map(decode_connection, result.get(b'values', b'')):
yield node_connection
return self._iter_krpc_search(self.get_peers, process_get_peers, info_hash, timeout, retries)
# (verbatim, async KRPC method)
def get_peers(self, target_connection, sender_id, info_hash):
return self._krpc.send_krpc_query(target_connection, b'get_peers', id = sender_id, info_hash = info_hash)
# (reply method)
def _get_peers(self, send_krpc_reply, id, info_hash):
token = hmac.new(self._token_key, encode_ip(send_krpc_reply.connection[0]), hashlib.sha1).digest()
id_cmp = decode_id(id)
def select_valid(n):
return valid_id(n.id, n.connection)
def sort_by_id(n):
return n.id_cmp ^ id_cmp
reply_args = {'nodes': encode_nodes(self._nodes.get_nodes(N = 8, expression = select_valid, sorter = sort_by_id))}
if self._node.values.get(info_hash):
reply_args['values'] = list(map(encode_connection, self._node.values[info_hash]))
send_krpc_reply(id = self._node.id, token = token, **reply_args)
_reply_handler[b'get_peers'] = _get_peers
# announce_peer methods
# (sync method, announcing to all nodes giving tokens)
def dht_announce_peer(self, info_hash, implied_port = 1):
def has_info_hash_token(node):
return info_hash in node.tokens
for node in self._nodes.get_nodes(expression = has_info_hash_token):
yield self.announce_peer(node.connection, self._node.id, info_hash, self._node.connection[1],
node.tokens[info_hash], implied_port = implied_port)
# (verbatim, async KRPC method)
def announce_peer(self, target_connection, sender_id, info_hash, port, token, implied_port = None):
req = {'id': sender_id, 'info_hash': info_hash, 'port': port, 'token': token}
if implied_port != None: # (optional) "1": port not reliable - remote should use source port
req['implied_port'] = implied_port
return self._krpc.send_krpc_query(target_connection, b'announce_peer', **req)
# (reply method)
def _announce_peer(self, send_krpc_reply, id, info_hash, port, token, implied_port = None):
local_token = hmac.new(self._token_key, encode_ip(send_krpc_reply.connection[0]), hashlib.sha1).digest()
if (local_token == token) and valid_id(id, send_krpc_reply.connection): # Validate token and ID
if implied_port:
port = send_krpc_reply.connection[1]
self._node.values.setdefault(info_hash, []).append((send_krpc_reply.connection[0], port))
send_krpc_reply(id = self._node.id)
_reply_handler[b'announce_peer'] = _announce_peer
if __name__ == '__main__':
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)
logging.getLogger('DHT').setLevel(logging.INFO)
logging.getLogger('DHT_Router').setLevel(logging.ERROR)
logging.getLogger('KRPCPeer').setLevel(logging.ERROR)
logging.getLogger('KRPCPeer.local').setLevel(logging.ERROR)
logging.getLogger('KRPCPeer.remote').setLevel(logging.ERROR)
# Create a DHT swarm
setup = {}
bootstrap_connection = ('localhost', 10001)
# bootstrap_connection = ('router.bittorrent.com', 6881)
dht1 = DHT(('0.0.0.0', 10001), bootstrap_connection, setup)
dht2 = DHT(('0.0.0.0', 10002), bootstrap_connection, setup)
dht3 = DHT(('0.0.0.0', 10003), bootstrap_connection, setup)
dht4 = DHT(('0.0.0.0', 10004), ('localhost', 10003), setup)
dht5 = DHT(('0.0.0.0', 10005), ('localhost', 10003), setup)
dht6 = DHT(('0.0.0.0', 10006), ('localhost', 10005), setup)
log.critical('starting "ping" test')
log.critical('ping: dht1 -> bootstrap = %r' % dht1.dht_ping(bootstrap_connection))
log.critical('ping: dht6 -> bootstrap = %r' % dht6.dht_ping(bootstrap_connection))
log.critical('starting "find_node" test')
for idx, node in enumerate(dht3.dht_find_node(dht1._node.id)):
log.critical('find_node: dht3 -> id(dht1) result #%d: %s:%d' % (idx, node[0], node[1]))
if idx > 10:
break
import binascii
info_hash = binascii.unhexlify('ae3fa25614b753118931373f8feae64f3c75f5cd') # Ubuntu 15.10 info hash
log.critical('starting "get_peers" test')
for idx, peer in enumerate(dht5.dht_get_peers(info_hash)):
log.critical('get_peers: dht5 -> info_hash result #%d: %r' % (idx, peer))
log.critical('starting "announce_peer" test')
for idx, async_result in enumerate(dht5.dht_announce_peer(info_hash)):
log.critical('announce_peer: dht2 -> close_nodes(info_hash) #%d: %r' % (idx, async_result.get_result(1)))
log.critical('starting "get_peers" test')
for idx, peer in enumerate(dht1.dht_get_peers(info_hash)):
log.critical('get_peers: dht1 -> info_hash result #%d: %r' % (idx, peer))
for dht in [dht1, dht2, dht3, dht4, dht5, dht6]:
dht.shutdown()
+176
View File
@@ -0,0 +1,176 @@
"""
The MIT License
Copyright (c) 2014-2015 Fred Stober
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import socket, threading, logging
from bencode import bdecode, BTFailure
from lib.tinybt import bencode.bencode
from lib.tinybt.utils import client_version, AsyncResult, AsyncTimeout, encode_uint64, UDPSocket, ThreadManager
krpc_version = bytes(client_version[0] + bytearray([client_version[1], client_version[2]]))
class KRPCError(RuntimeError):
pass
class KRPCPeer(object):
def __init__(self, connection, handle_query, cleanup_timeout = 60, cleanup_interval = 10):
""" Start listening on the connection given by (addr, port)
Incoming messages are given to the handle_query function,
with arguments (send_krpc_response, rec).
send_krpc_response(**kwargs) is a function to send a reply,
rec contains the dictionary with the incoming message.
"""
self._log = logging.getLogger(self.__class__.__name__ + '.%s:%d' % connection)
self._log_msg = self._log.getChild('msg') # message handling
self._log_local = self._log.getChild('local') # local queries
self._log_remote = self._log.getChild('remote') # remote queries
self._sock = UDPSocket(connection)
self._transaction = {}
self._transaction_id = 0
self._transaction_lock = threading.Lock()
self._handle_query = handle_query
self._threads = ThreadManager(self._log)
self._threads.start_continuous_thread(self._listen)
self._threads.start_continuous_thread(self._cleanup_transactions,
thread_interval = cleanup_interval, timeout = cleanup_timeout)
def send_krpc_query(self, target_connection, method, **kwargs):
""" Invoke method on the node at target_connection.
The arguments for the method are given in kwargs.
Returns an AsyncResult (waitable) that will
eventually contain the peer response.
"""
target_connection = (socket.gethostbyname(target_connection[0]), target_connection[1])
with self._transaction_lock:
while True: # Generate transaction id
self._transaction_id += 1
local_transaction = bytes(bytearray(encode_uint64(self._transaction_id)).lstrip(b'\x00'))
if local_transaction not in self._transaction:
break
req = {b'y': b'q', b't': local_transaction, b'v': krpc_version, b'q': method, b'a': kwargs}
result = AsyncResult(source = (method, kwargs, target_connection))
if not self._threads.shutdown_in_progress():
if self._log_local.isEnabledFor(logging.INFO):
self._log_local.info('KRPC request to %r:\n\t%r' % (target_connection, req))
self._transaction[local_transaction] = result
self._sock.sendto(bencode(req), target_connection)
else:
result.set_result(AsyncTimeout('Shutdown in progress'))
return result
def shutdown(self):
""" This function allows to cleanly shutdown the KRPCPeer. """
self._threads.shutdown()
self._sock.close()
with self._transaction_lock:
for t in list(self._transaction):
self._transaction.pop(t).set_result(AsyncTimeout('Shutdown in progress'))
self._threads.join()
# Private members #################################################
def _cleanup_transactions(self, timeout):
# Remove transactions older than 1min
with self._transaction_lock:
timeout_transactions = [t for t, ar in self._transaction.items() if ar.get_age() > timeout]
if self._log.isEnabledFor(logging.DEBUG):
self._log.debug('Transactions: %d id=%d timeout=%d' % (len(self._transaction), self._transaction_id, len(timeout_transactions)))
for t in timeout_transactions:
self._transaction.pop(t).set_result(AsyncTimeout('Transaction %r: timeout' % t))
def _listen(self):
try:
recv_data = self._sock.recvfrom(timeout = 0.2)
if not recv_data:
return
(encoded_rec, source_connection) = recv_data
try:
rec = bdecode(encoded_rec)
except BTFailure:
if self._log_msg.isEnabledFor(logging.ERROR):
self._log_msg.error('Error while parsing KRPC requests from %r:\n\t%r' % (source_connection, encoded_rec))
return
except Exception:
return self._log_msg.exception('Exception while handling KRPC requests from %r:\n\t%r' % (source_connection, encoded_rec))
try:
if rec[b'y'] in [b'r', b'e']: # Response / Error message
t = rec[b't']
if rec[b'y'] == b'e':
if self._log_local.isEnabledFor(logging.ERROR):
self._log_local.error('KRPC error message from %r:\n\t%r' % (source_connection, rec))
with self._transaction_lock:
if self._transaction.get(t):
rec = KRPCError('Error while processing transaction %r:\n\t%r\n\t%r' % (t, rec, self._transaction.get(t).get_source()))
else:
rec = KRPCError('Error while processing transaction %r:\n\t%r' % (t, rec))
else:
if self._log_local.isEnabledFor(logging.INFO):
self._log_local.info('KRPC answer from %r:\n\t%r' % (source_connection, rec))
with self._transaction_lock:
if self._transaction.get(t):
self._transaction.pop(t).set_result(rec, source = source_connection)
elif self._log_local.isEnabledFor(logging.DEBUG):
self._log_local.debug('Received response from %r without associated transaction:\n%r' % (source_connection, rec))
elif rec[b'y'] == b'q':
if self._log_remote.isEnabledFor(logging.INFO):
self._log_remote.info('KRPC request from %r:\n\t%r' % (source_connection, rec))
def custom_send_krpc_response(message, top_level_message = {}):
return self._send_krpc_response(source_connection, rec.pop(b't'), message, top_level_message, self._log_remote)
self._handle_query(custom_send_krpc_response, rec, source_connection)
else:
if self._log_msg.isEnabledFor(logging.ERROR):
self._log_msg.error('Unknown type of KRPC message from %r:\n\t%r' % (source_connection, rec))
except Exception:
self._log_msg.exception('Exception while handling KRPC requests from %r:\n\t%r' % (source_connection, rec))
def _send_krpc_response(self, source_connection, remote_transaction, message, top_level_message = {}, log = None):
with self._transaction_lock:
resp = {b'y': b'r', b't': remote_transaction, b'v': krpc_version, b'r': message}
resp.update(top_level_message)
if log == None:
log = self._log_local
if log.isEnabledFor(logging.INFO):
log.info('KRPC response to %r:\n\t%r' % (source_connection, resp))
self._sock.sendto(bencode(resp), source_connection)
if __name__ == '__main__':
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
# Implement an echo message
peer = KRPCPeer(('0.0.0.0', 1111), handle_query = lambda send_krpc_response, rec, source_connection:
send_krpc_response(message = 'Hello %s!' % rec[b'a'][b'message']))
query = peer.send_krpc_query(('localhost', 1111), 'echo', message = 'World')
logging.getLogger().critical('result = %r' % query.get_result(2))
query1 = peer.send_krpc_query(('localhost', 1111), 'echo', message = 'World')
peer.shutdown()
query2 = peer.send_krpc_query(('localhost', 1111), 'echo', message = 'World')
try:
query1.get_result()
except Exception:
logging.exception('expected query exception')
try:
query2.get_result()
except Exception:
logging.exception('expected query exception')
+153
View File
@@ -0,0 +1,153 @@
"""
The MIT License
Copyright (c) 2015 Fred Stober
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import sys, socket, random
from lib.tinybt.bencode import bdecode
from lib.tinybt.utils import UDPSocket, encode_int32, decode_connection
from lib.tinybt.utils import encode_ip, encode_uint64, encode_uint32, encode_uint16
from lib.tinybt.utils import decode_ip, decode_uint64, decode_uint32
class TrackerException(Exception):
pass
if sys.version_info[0] >= 3:
import urllib.request, urllib.parse, urllib.error, urllib.parse
def parse_url(url):
return urllib.parse.urlparse(url)
def open_url(tracker_url, query):
url = tracker_url + '?' + urllib.parse.urlencode(list(query.items()))
return urllib.request.urlopen(url)
else:
import urllib, urlparse
def parse_url(url):
return urlparse.urlparse(url)
def open_url(tracker_url, query):
url = tracker_url + '?' + urllib.urlencode(query.items())
return urllib.urlopen(url)
def decode_connections(data):
while len(data) >= 6:
c = decode_connection(data[0:6])
if c[1] >= 1024:
yield c
data = data[6:]
# Implementation of BEP #0015 (UDP tracker protocol)
def udp_get_peers(tracker_url, info_hash, peer_id, ip = '0.0.0.0', port = 0,
uploaded = 0, downloaded = 0, left = 0, event = 'started', num_want = -1, key = 0):
event = {'empty': 0, 'completed': 1, 'started': 2, 'stopped': 3}[event]
url = parse_url(tracker_url)
conn = (socket.gethostbyname(url.hostname), url.port)
sock = UDPSocket(('0.0.0.0', 0))
def recv():
timeout = 5
while True:
try:
data, src = sock.recvfrom(timeout)
except:
data = None
if not data:
timeout *= 2
if timeout > 60:
break
continue
try:
assert(len(data) >= 16)
action = decode_uint32(data[0:4])
remote_tid = decode_uint32(data[4:8])
return (action, remote_tid, data[8:])
except:
raise
return (None, None, None)
def perform_announce():
cid = 0x41727101980
action_connect = 0
tid = random.randint(0, 2**32-1)
remote_tid = None
while remote_tid != tid:
req = encode_uint64(cid) + encode_uint32(action_connect) + encode_uint32(tid)
sock.sendto(req, conn)
(action, remote_tid, data) = recv()
if not data:
raise TrackerException('Tracker %s:%d did not answer to handshake' % conn)
remote_cid = decode_uint64(data[0:8])
if action != action_connect:
remote_tid = None
action_announce = 1
tid = random.randint(0, 2**32-1)
remote_tid = None
while remote_tid != tid:
assert(len(info_hash) == 20)
assert(len(peer_id) == 20)
req = encode_uint64(remote_cid) + encode_uint32(action_announce) + encode_uint32(tid) + \
info_hash + peer_id + \
encode_uint64(downloaded) + encode_uint64(left) + encode_uint64(uploaded) + \
encode_uint32(event) + encode_ip(ip) + encode_uint32(key) + encode_int32(num_want) + encode_uint16(port)
sock.sendto(req, conn)
(action, remote_tid, data) = recv()
if not data:
raise TrackerException('Tracker %s:%d did not answer to query' % conn)
if action != action_announce:
remote_tid = None
interval = decode_uint32(data[0:4])
num_leech = decode_uint32(data[4:8])
num_seed = decode_uint32(data[8:12])
return list(decode_connections(data[12:]))
try:
return perform_announce()
finally:
sock.close()
# Implementation of BEP #0003 (Bittorrent - section: HTTP Tracker protocol)
def http_get_peers(tracker_url, info_hash, peer_id, ip = '0.0.0.0', port = 0,
uploaded = 0, downloaded = 0, left = 0, event = 'started'):
query = {b'info_hash': info_hash, b'peer_id': peer_id, b'ip': ip, b'port': port,
b'uploaded': uploaded, b'downloaded': downloaded, b'left': left, b'compact': 1}
if event:
query['event'] = event
handle = open_url(tracker_url, query)
if handle.getcode() == 200:
decoded = bdecode(handle.read())
if not b'peers' in decoded:
raise TrackerException(decoded.get(b'failure reason', 'Unknown failure'))
return list(decode_connections(decoded.get(b'peers', '')))
if __name__ == '__main__':
import os, binascii, logging
peer_id = os.urandom(20)
info_hash = binascii.unhexlify('ae3fa25614b753118931373f8feae64f3c75f5cd') # Ubuntu 15.10 info hash
try:
print(http_get_peers('http://torrent.ubuntu.com:6969/announce', info_hash, peer_id))
except Exception:
logging.exception('Exception during http query')
try:
print(udp_get_peers('udp://tracker.coppersurfer.tk:6969', info_hash, peer_id))
except Exception:
logging.exception('Exception during udp query')
+261
View File
@@ -0,0 +1,261 @@
"""
The MIT License
Copyright (c) 2014 Fred Stober
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import sys, select, socket, struct, threading, time, collections, logging
client_version = (b'XK', 0, 0x01) # eXperimental Klient 0.0.1
encode_ip = lambda value: socket.inet_aton(value)
encode_uint16 = lambda value: struct.pack('!H', value)
encode_uint32 = lambda value: struct.pack('!I', value)
encode_uint64 = lambda value: struct.pack('!Q', value)
encode_int32 = lambda value: struct.pack('!i', value)
def encode_connection(con):
return encode_ip(con[0]) + encode_uint16(con[1])
def encode_nodes(nodes):
result = b''
for node in nodes:
result += bytes(bytearray(node.id).rjust(20, b'\0')) + encode_connection(node.connection)
return result
decode_ip = lambda value: socket.inet_ntoa(value)
decode_uint16 = lambda value: struct.unpack('!H', value)[0]
decode_uint32 = lambda value: struct.unpack('!I', value)[0]
decode_uint64 = lambda value: struct.unpack('!Q', value)[0]
def decode_connection(con):
return (decode_ip(con[0:4]), decode_uint16(con[4:6]))
def decode_nodes(nodes):
try:
while nodes:
node_id = struct.unpack('20s', nodes[:20])[0]
node_connection = decode_connection(nodes[20:26])
if node_connection[1] >= 1024: # discard invalid port numbers
yield (node_id, node_connection)
nodes = nodes[26:]
except Exception:
pass # catch malformed nodes
def start_thread(fun, *args, **kwargs):
thread = threading.Thread(name = repr(fun), target=fun, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread
class AsyncTimeout(RuntimeError):
pass
class AsyncResult(object):
def __init__(self, source = None):
self._event = threading.Event()
self._value = None
self._source = source
self._time = time.time()
def get_age(self):
return time.time() - self._time
def discard_result(self):
self._time = 0
def set_result(self, result, source = None):
self._value = result
if source != None:
self._source = source
self._event.set()
def has_result(self):
return self._event.is_set()
def get_source(self):
return self._source
def get_result(self, timeout = None):
if not self._event.wait(timeout):
raise AsyncTimeout
if isinstance(self._value, Exception):
raise self._value
return self._value
class ThreadManager(object):
def __init__(self, log):
self._log = log
self._threads = []
self._shutdown_event = threading.Event()
def shutdown_in_progress(self):
return self._shutdown_event.is_set()
def shutdown(self):
self._shutdown_event.set() # Trigger shutdown of threads
def join(self, timeout = 60):
self.shutdown()
for thread in self._threads:
thread.join(timeout)
def start_thread(self, name, daemon, fun, *args, **kwargs):
thread = threading.Thread(name = name, target=fun, args=args, kwargs=kwargs)
thread.daemon = daemon
thread.start()
self._threads.append(thread)
return thread
def start_continuous_thread(self, fun, thread_interval = 0, *args, **kwargs):
if thread_interval >= 0:
self.start_thread('continuous thread:' + repr(fun), False,
self._continuous_thread_wrapper, fun, thread_interval = thread_interval, *args, **kwargs)
def _continuous_thread_wrapper(self, fun, on_except = ['log', 'continue'], thread_waitfirst = False, thread_interval = 0, *args, **kwargs):
if thread_waitfirst:
self._shutdown_event.wait(thread_interval)
while not self._shutdown_event.is_set():
try:
fun(*args, **kwargs)
except Exception:
if 'log' in on_except:
self._log.exception('Exception in maintainance thread')
if 'continue' not in on_except:
return
self._shutdown_event.wait(thread_interval)
class NetworkSocket(object):
def __init__(self, name):
self._log = logging.getLogger(self.__class__.__name__).getChild(name)
self._threads = ThreadManager(self._log)
self._lock = threading.Lock()
self._send_event = threading.Event()
self._send_queue = collections.deque()
self._send_try = 0
self._recv_event = threading.Event()
self._recv_queue = collections.deque()
self._force_show_info = False
self._threads.start_continuous_thread(self._info_thread, thread_interval = 0.5)
self._threads.start_continuous_thread(self._send_thread)
self._threads.start_continuous_thread(self._recv_thread)
# Non-blocking send
def sendto(self, *args):
self._send_queue.append(args)
with self._lock: # set send flag
self._send_event.set()
# Blocking read - with timeout
def recvfrom(self, timeout = None):
result = None
if self._recv_event.wait(timeout):
if self._recv_queue:
result = self._recv_queue.pop()
with self._lock:
if not self._recv_queue and not self._threads.shutdown_in_progress():
self._recv_event.clear()
return result
def close(self):
with self._lock:
self._threads.shutdown()
self._send_queue.clear()
self._recv_queue.clear()
self._send_event.set()
self._recv_event.set()
self._close()
self._threads.join()
# Private members #################################################
def _info_thread(self):
if (len(self._recv_queue) > 20) or (len(self._send_queue) > 20) or self._force_show_info:
if self._log.isEnabledFor(logging.DEBUG):
self._log.debug('recv: %4d, send: %4d' % (len(self._recv_queue), len(self._send_queue)))
self._force_show_info = True
if not(len(self._recv_queue) or len(self._send_queue)):
self._force_show_info = False
def _send_thread(self, send_tries = 100):
if self._send_event.wait(0.1):
if self._send_queue:
if self._send(*self._send_queue[0]):
self._send_queue.popleft()
self._send_try = 0
elif self._send_try > send_tries:
self._send_queue.popleft()
else:
self._send_queue.rotate(-1)
self._send_try += 1
with self._lock: # clear send flag
if not self._send_queue and not self._threads.shutdown_in_progress():
self._send_event.clear()
def _send(self, *args):
raise NotImplemented
def _recv_thread(self):
tmp = self._recv()
if tmp:
self._recv_queue.append(tmp)
with self._lock:
self._recv_event.set()
def _recv(self):
raise NotImplemented
def _close(self):
raise NotImplemented
class UDPSocket(NetworkSocket):
def __init__(self, connection):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._sock.setblocking(0)
self._sock.bind(connection)
NetworkSocket.__init__(self, '%s:%d' % connection)
def _send(self, *args):
select.select([], [self._sock], [], 0.1)
try:
self._sock.sendto(*args)
return True
except socket.error:
pass
def _recv(self):
select.select([self._sock], [], [], 0.1)
try:
return self._sock.recvfrom(64*1024)
except socket.error:
pass
def _close(self):
self._sock.close()