-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.py
198 lines (145 loc) · 5.92 KB
/
tracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
from bencode import Bencode
import pprint
import socket
import secrets
import re
import hashlib
import queue
import requests
def IntToBytes(i, len = 4, endian = 'big', signed = False):
return (i).to_bytes(len, endian, signed = signed)
def BytesToInt(byts, endian = 'big', signed = False):
return int.from_bytes(byts, endian, signed = signed)
class Tracker:
def __init__(self, torr_info):
self.torr_info = torr_info
self.torr_urls = [ torr_info['announce'] ]
if torr_info['announce-list']:
for url in torr_info['announce-list']:
self.torr_urls += url
# Keep only udp trackers
self.torr_urls = list(filter(lambda f: f.startswith('udp'),self.torr_urls))
self.url_idx = 0
self.tot_urls = len(self.torr_urls)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.NumPieces = len(self.torr_info['info']['pieces']) // 20
self.PieceLen = self.torr_info['info']['piece length']
self.TorrLen = self.GetTorrLen()
self.reconnect_time = 10*60
self.filename = self.torr_info['info']['name']
self.info_hash = self.GetInfoHash()
if len(self.torr_urls) == 0:
raise ValueError('No UDP Trackers available')
self.multifileinfo = self.GetFilesInfo()
def MakeConnectRequest(self):
msg = b'\x00\x00\x04\x17\x27\x10\x19\x80' #connection id
msg += b'\x00\x00\x00\x00' # connect identifier
self.transcation_id = secrets.token_bytes(4) # transaction id
msg += self.transcation_id
return msg
def ParseConnectResponse(self, rsp):
t_id = BytesToInt(rsp[4:8])
self.conn_id = BytesToInt(rsp[8:16])
# ignore the connect identifier?
def MakeAnnounceRequest(self, pt, dwnld = 0, lft = 0, upld = 0):
rqst = b""
rqst += IntToBytes(self.conn_id, 8) # conn_id
rqst += b"\x00\x00\x00\x01" #announce identifier
self.new_t_id = secrets.token_bytes(4)
rqst += self.new_t_id
rqst += self.info_hash
self.peer_id = secrets.token_bytes(20)
rqst += self.peer_id
rqst += IntToBytes(dwnld, 8)
rqst += IntToBytes(lft, 8)
rqst += IntToBytes(upld,8)
rqst += IntToBytes(0,12) # event + ip + key
rqst += IntToBytes(-1, signed = True) # num_want
rqst += IntToBytes(pt, 2) # harcoded port?
return rqst
def ParseAnnounceResponse(self,rsp):
announce_identifier = BytesToInt(rsp[0:4])
t_id = BytesToInt(rsp[4:8])
self.reconnect_time = BytesToInt(rsp[8:12])
self.leechers = BytesToInt(rsp[12:16])
self.seeders = BytesToInt(rsp[16:20])
self.PopulatePeerList(rsp[20:])
def PopulatePeerList(self, addrs):
while len(addrs) >= 6:
new_peer_addr = addrs[:6]
self.peerlist.append(self.GetIpPort(new_peer_addr))
addrs = addrs[6:]
def GetIpPort(self, peeraddr):
ip = ''
for i in range(4):
ip += str(peeraddr[i])
if not i==3:
ip += '.'
prt = int.from_bytes(peeraddr[4:], 'big', signed=False)
return (ip,prt)
def GetPeers(self, dwnld = 0, left = 0, upld = 0):
self.peerlist = []
for i in range(3):
self.sock.settimeout(5*2**i)
for i in range(self.tot_urls):
'''
Keep trying trackers unless we get a list of peers
'''
url = self.torr_urls[self.url_idx]
try:
self.GetTrackerResponse(url, dwnld, left, upld)
self.url_idx = (self.url_idx + 1) % self.tot_urls # For dynamism this is outside except
return self.peerlist
except (socket.error, requests.exceptions.RequestException) as err:
print('Tracker Sent {}'.format(err))
except Exception as e:
print('Tracker raised unexpected exception', e)
self.url_idx = (self.url_idx + 1) % self.tot_urls # For dynamism this is outside except
return None
def GetTrackerResponse(self, url, dwnld, left, upld):
match_obj = re.search("(?P<protocol>[a-zA-Z]+)://(?P<domain>[^:]+):(?P<port>\d+)", url)
domain = match_obj.group('domain')
port = int(match_obj.group('port'))
addr = (domain, port)
# Connect
self.sock.sendto(self.MakeConnectRequest(), addr)
data, adr = self.sock.recvfrom(2048)
self.ParseConnectResponse(data)
# Announce
for i in range(9):
try:
pt = 6881+i
self.sock.sendto(self.MakeAnnounceRequest(pt, dwnld, left, upld), addr)
data, adr = self.sock.recvfrom(2048)
break
except OSError as os:
print('Port Unavailable? ', os)
self.ParseAnnounceResponse(data)
def GetHashes(self):
MixedHashes = self.torr_info['info']['pieces']
h = [MixedHashes[i:i+20] for i in range(0, 20*self.NumPieces, 20)]
return h
def GetInfoHash(self):
to_hash = Bencode(self.torr_info['info']).encode()
o = hashlib.sha1(to_hash).digest()
return o
def GetTorrLen(self):
dic = self.torr_info['info']
if 'length' in dic:
#Single-file-torrent
return dic['length']
else:
l = 0
dic = dic['files']
for i in dic:
l += i['length']
return l
def GetFilesInfo(self):
if 'length' in self.torr_info['info']:
return None
files = []
lens = []
for j in self.torr_info['info']['files']:
files.append(j['path'][-1])
lens.append(j['length'])
return list(zip(files,lens))