## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
# see LICENSE.txt for license information
-import os, re
+"""Some utitlity functions for use in apt-dht's khashmir DHT."""
-from twisted.python import log
+from twisted.trial import unittest
def bucket_stats(l):
- """given a list of khashmir instances, finds min, max, and average number of nodes in tables"""
+ """Given a list of khashmir instances, finds min, max, and average number of nodes in tables."""
max = avg = 0
min = None
def count(buckets):
avg = avg / len(l)
return {'min':min, 'max':max, 'avg':avg}
-isLocal = re.compile('^(192\.168\.[0-9]{1,3}\.[0-9]{1,3})|'+
- '(10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})|'+
- '(172\.0?([1][6-9])|([2][0-9])|([3][0-1])\.[0-9]{1,3}\.[0-9]{1,3})|'+
- '(127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})$')
-
-def findMyIPAddr(addrs, intended_port):
- log.msg("got addrs: %r" % (addrs,))
- my_addr = None
+def uncompact(s):
+ """Extract the contact info from a compact node representation.
- try:
- ifconfig = os.popen("/sbin/ifconfig |/bin/grep inet|"+
- "/usr/bin/awk '{print $2}' | "+
- "sed -e s/.*://", "r").read().strip().split('\n')
- except:
- ifconfig = []
+ @type s: C{string}
+ @param s: the compact representation
+ @rtype: C{dictionary}
+ @return: the node ID, IP address and port to contact the node on
+ @raise ValueError: if the compact representation doesn't exist
+ """
+ if (len(s) != 26):
+ raise ValueError
+ id = s[:20]
+ host = '.'.join([str(ord(i)) for i in s[20:24]])
+ port = (ord(s[24]) << 8) | ord(s[25])
+ return {'id': id, 'host': host, 'port': port}
- # Get counts for all the non-local addresses returned
- addr_count = {}
- for addr in ifconfig:
- if not isLocal.match(addr):
- addr_count.setdefault(addr, 0)
- addr_count[addr] += 1
-
- local_addrs = addr_count.keys()
- if len(local_addrs) == 1:
- my_addr = local_addrs[0]
- log.msg('Found remote address from ifconfig: %r' % (my_addr,))
+def compact(id, host, port):
+ """Create a compact representation of node contact info.
- # Get counts for all the non-local addresses returned
- addr_count = {}
- port_count = {}
- for addr in addrs:
- if not isLocal.match(addr[0]):
- addr_count.setdefault(addr[0], 0)
- addr_count[addr[0]] += 1
- port_count.setdefault(addr[1], 0)
- port_count[addr[1]] += 1
+ @type id: C{string}
+ @param id: the node ID
+ @type host: C{string}
+ @param host: the IP address of the node
+ @type port: C{int}
+ @param port: the port number to contact the node on
+ @rtype: C{string}
+ @return: the compact representation
+ @raise ValueError: if the compact representation doesn't exist
+ """
- # Find the most popular address
- popular_addr = []
- popular_count = 0
- for addr in addr_count:
- if addr_count[addr] > popular_count:
- popular_addr = [addr]
- popular_count = addr_count[addr]
- elif addr_count[addr] == popular_count:
- popular_addr.append(addr)
-
- # Find the most popular port
- popular_port = []
- popular_count = 0
- for port in port_count:
- if port_count[port] > popular_count:
- popular_port = [port]
- popular_count = port_count[port]
- elif port_count[port] == popular_count:
- popular_port.append(port)
-
- port = intended_port
- if len(port_count.keys()) > 1:
- log.msg('Problem, multiple ports have been found: %r' % (port_count,))
- if port not in port_count.keys():
- log.msg('And none of the ports found match the intended one')
- elif len(port_count.keys()) == 1:
- port = port_count.keys()[0]
- else:
- log.msg('Port was not found')
+ s = id + ''.join([chr(int(i)) for i in host.split('.')]) + \
+ chr((port & 0xFF00) >> 8) + chr(port & 0xFF)
+ if len(s) != 26:
+ raise ValueError
+ return s
- if len(popular_addr) == 1:
- log.msg('Found popular address: %r' % (popular_addr[0],))
- if my_addr and my_addr != popular_addr[0]:
- log.msg('But the popular address does not match: %s != %s' % (popular_addr[0], my_addr))
- my_addr = popular_addr[0]
- elif len(popular_addr) > 1:
- log.msg('Found multiple popular addresses: %r' % (popular_addr,))
- if my_addr and my_addr not in popular_addr:
- log.msg('And none of the addresses found match the ifconfig one')
- else:
- log.msg('No non-local addresses found: %r' % (popular_addr,))
-
- if not my_addr:
- log.msg("Remote IP Address could not be found for this machine")
-
- return my_addr
+class TestUtil(unittest.TestCase):
+ """Tests for the utilities."""
+
+ timeout = 5
+ myid = '\xca\xec\xb8\x0c\x00\xe7\x07\xf8~])\x8f\x9d\xe5_B\xff\x1a\xc4!'
+ host = '165.234.1.34'
+ port = 61234
-def ipAddrFromChicken():
- import urllib
- ip_search = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
- try:
- f = urllib.urlopen("http://www.ipchicken.com")
- data = f.read()
- f.close()
- current_ip = ip_search.findall(data)
- return current_ip
- except Exception:
- return []
+ def test_compact(self):
+ d = uncompact(compact(self.myid, self.host, self.port))
+ self.failUnlessEqual(d['id'], self.myid)
+ self.failUnlessEqual(d['host'], self.host)
+ self.failUnlessEqual(d['port'], self.port)
+
\ No newline at end of file