Created
May 28, 2014 20:04
-
-
Save loadletter/ef22f4aa07f9f321e523 to your computer and use it in GitHub Desktop.
Bittorrent HTTP announce
This file contains hidden or 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
import binascii, urllib, socket, random, struct | |
from bcode import bdecode | |
from urlparse import urlparse, urlunsplit | |
def announce(tracker, hashes): | |
tracker = tracker.lower() | |
parsed = urlparse(tracker) | |
if parsed.scheme == "udp": | |
#return scrape_udp(parsed, hashes) | |
pass | |
if parsed.scheme in ["http", "https"]: | |
parsed = urlparse(tracker) | |
return announce_http(parsed, hashes) | |
raise RuntimeError("Unknown tracker scheme: %s" % parsed.scheme) | |
def announce_http(parsed_tracker, ihash): | |
print "Announcing HTTP: %s for %s" % (parsed_tracker.geturl(), ihash) | |
qs = [] | |
qs.append(("info_hash", binascii.a2b_hex(ihash))) | |
qs.append(("compact", 1)) | |
qs = urllib.urlencode(qs) | |
pt = parsed_tracker | |
url = urlunsplit((pt.scheme, pt.netloc, pt.path, qs, pt.fragment)) | |
handle = urllib.urlopen(url) | |
if handle.getcode() is not 200: | |
raise RuntimeError("%s status code returned" % handle.getcode()) | |
decoded = bdecode(handle.read()) | |
decoded['peers'] = http_parse_seeds(decoded['peers']) | |
return decoded | |
def http_parse_seeds(p): | |
peers = [] | |
if type(p) == type(''): | |
for x in xrange(0, len(p), 6): | |
ip = '.'.join([str(ord(i)) for i in p[x:x+4]]) | |
port = (ord(p[x+4]) << 8) | ord(p[x+5]) | |
peers.append(((ip, port), 0)) | |
else: | |
for x in p: | |
peers.append(((x['ip'].strip(), x['port']), x.get('peer id',0))) | |
return peers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment