-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_leecher.py
More file actions
executable file
·154 lines (107 loc) · 3.98 KB
/
simple_leecher.py
File metadata and controls
executable file
·154 lines (107 loc) · 3.98 KB
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
#!/usr/bin/env python3.6
# Stdlib
import sys, socket, math, hashlib, time
# Project
import torrent, pwp
def main():
# Port on which to connect
port = 6881
# Peer id used for this peer
my_peer_id = b'2' * 20
# Parse the options
for arg in sys.argv[1:-2]:
if arg.startswith('-p'):
port = int(arg[2:])
if arg.startswith('--port='):
port = int(arg[7:])
addr = sys.argv[-2]
torr_file = sys.argv[-1]
# Parse the given torrent file
torr_info = torrent.read_torrent_file(torr_file)
# Compute the infohash for the given torrent
bytehash = torrent.infohash(torr_info)
print('infohash:', bytehash.hex())
# TODO: Check for a partial download
# Create a socket object
conn = socket.socket()
# Connect to the remote addres
try:
conn.connect((addr, port))
except Exception as e:
print(e.args)
return
# Create our handshake bytestring
handshake = pwp.create_handshake(bytehash, my_peer_id)
# Send our handshake
conn.send(handshake)
# Receive handshake from peer
shake_resp = pwp.receive_full_handshake(conn)
if shake_resp['reserved'] != (b'\x00' * 8):
print('Handshake failed: unequal reserved bits')
return
if shake_resp['info_hash'] != bytehash:
print('Handshake failed: unequal infohashes')
return
print('Handshake success')
# Indicate that we are interested in receiving pieces
conn.send(pwp.interested())
# Request the entire file
req = pwp.request_all(torr_info['info']['length'])
conn.send(req)
piece_size = torr_info['info']['piece length']
blocks_expected = len(req) / 17
pieces_expected = int(math.ceil(blocks_expected / 16))
blocks_in_last_piece = blocks_expected % 16
bytes_received = 0
pieces = {i : set() for i in range(pieces_expected)}
print('Progress: {:.2f}%'.format(100 * bytes_received / torr_info['info']['length']), end='')
# Create the output file
with open('downloads/' + torr_info['info']['name'], 'w'):
pass
# Receive messages until file is complete
while len(pieces) > 0:
# Receive and parse the next message
msg = pwp.parse_next_message(conn)
msg_id = msg['id']
if msg_id == -2:
break
elif msg_id == 7:
if msg['payload']['index'] >= pieces_expected:
print('Received block with invalid piece index')
return
if msg['payload']['begin'] % (2**14) != 0:
print('Received block with invalid offset')
return
if len(msg['payload']['block']) > 2**14:
print('Received block longer than 2**14 bytes')
return
bytes_received += len(msg['payload']['block'])
# Display the download progress
print('\rProgress: {:.2f}%'.format(100 * bytes_received / torr_info['info']['length']), end='')
index = msg['payload']['index']
# Add the block to our collection
pieces[index].add((msg['payload']['begin'], msg['payload']['block']))
# Assemble the piece if all blocks have arrived
if (index == pieces_expected-1 and len(pieces[index]) == blocks_in_last_piece) or len(pieces[index]) == 16:
offset = index * piece_size
piece = pieces[index]
assembled = b''.join(block[1] for block in sorted(piece))
# If the piece is valid...
if hashlib.sha1(assembled).digest() == torr_info['info']['pieces'][20 * index: 20 * (index+1)]:
# Save the piece to disk
with open('downloads/' + torr_info['info']['name'], 'rb+') as f:
f.seek(offset)
f.write(assembled)
# This piece is no longer needed
del pieces[index]
# Send 'have' message to peer
conn.send(pwp.have(index))
else:
# Discard all blocks of the invalid piece
pieces[index] = set()
# Re-request the invalid piece
conn.send(pwp.request_piece(index, torr_info['info']['length']))
print('Received invalid piece: {}.'.format(msg['payload']['index']))
print()
if __name__ == '__main__':
main()