-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathpeer.py
195 lines (153 loc) · 6.18 KB
/
peer.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
import time
__author__ = 'alexisgallepe'
import socket
import struct
import bitstring
from pubsub import pub
import logging
import message
class Peer(object):
def __init__(self, number_of_pieces, ip, port=6881):
self.last_call = 0.0
self.has_handshaked = False
self.healthy = False
self.read_buffer = b''
self.socket = None
self.ip = ip
self.port = port
self.number_of_pieces = number_of_pieces
self.bit_field = bitstring.BitArray(number_of_pieces)
self.state = {
'am_choking': True,
'am_interested': False,
'peer_choking': True,
'peer_interested': False,
}
def __hash__(self):
return "%s:%d" % (self.ip, self.port)
def connect(self):
try:
self.socket = socket.create_connection((self.ip, self.port), timeout=2)
self.socket.setblocking(False)
logging.debug("Connected to peer ip: {} - port: {}".format(self.ip, self.port))
self.healthy = True
except Exception as e:
print("Failed to connect to peer (ip: %s - port: %s - %s)" % (self.ip, self.port, e.__str__()))
return False
return True
def send_to_peer(self, msg):
try:
self.socket.send(msg)
self.last_call = time.time()
except Exception as e:
self.healthy = False
logging.error("Failed to send to peer : %s" % e.__str__())
def is_eligible(self):
now = time.time()
return (now - self.last_call) > 0.2
def has_piece(self, index):
return self.bit_field[index]
def am_choking(self):
return self.state['am_choking']
def am_unchoking(self):
return not self.am_choking()
def is_choking(self):
return self.state['peer_choking']
def is_unchoked(self):
return not self.is_choking()
def is_interested(self):
return self.state['peer_interested']
def am_interested(self):
return self.state['am_interested']
def handle_choke(self):
logging.debug('handle_choke - %s' % self.ip)
self.state['peer_choking'] = True
def handle_unchoke(self):
logging.debug('handle_unchoke - %s' % self.ip)
self.state['peer_choking'] = False
def handle_interested(self):
logging.debug('handle_interested - %s' % self.ip)
self.state['peer_interested'] = True
if self.am_choking():
unchoke = message.UnChoke().to_bytes()
self.send_to_peer(unchoke)
def handle_not_interested(self):
logging.debug('handle_not_interested - %s' % self.ip)
self.state['peer_interested'] = False
def handle_have(self, have):
"""
:type have: message.Have
"""
logging.debug('handle_have - ip: %s - piece: %s' % (self.ip, have.piece_index))
self.bit_field[have.piece_index] = True
if self.is_choking() and not self.state['am_interested']:
interested = message.Interested().to_bytes()
self.send_to_peer(interested)
self.state['am_interested'] = True
# pub.sendMessage('RarestPiece.updatePeersBitfield', bitfield=self.bit_field)
def handle_bitfield(self, bitfield):
"""
:type bitfield: message.BitField
"""
logging.debug('handle_bitfield - %s - %s' % (self.ip, bitfield.bitfield))
self.bit_field = bitfield.bitfield
if self.is_choking() and not self.state['am_interested']:
interested = message.Interested().to_bytes()
self.send_to_peer(interested)
self.state['am_interested'] = True
# pub.sendMessage('RarestPiece.updatePeersBitfield', bitfield=self.bit_field)
def handle_request(self, request):
"""
:type request: message.Request
"""
logging.debug('handle_request - %s' % self.ip)
if self.is_interested() and self.is_unchoked():
pub.sendMessage('PiecesManager.PeerRequestsPiece', request=request, peer=self)
def handle_piece(self, message):
"""
:type message: message.Piece
"""
pub.sendMessage('PiecesManager.Piece', piece=(message.piece_index, message.block_offset, message.block))
def handle_cancel(self):
logging.debug('handle_cancel - %s' % self.ip)
def handle_port_request(self):
logging.debug('handle_port_request - %s' % self.ip)
def _handle_handshake(self):
try:
handshake_message = message.Handshake.from_bytes(self.read_buffer)
self.has_handshaked = True
self.read_buffer = self.read_buffer[handshake_message.total_length:]
logging.debug('handle_handshake - %s' % self.ip)
return True
except Exception:
logging.exception("First message should always be a handshake message")
self.healthy = False
return False
def _handle_keep_alive(self):
try:
keep_alive = message.KeepAlive.from_bytes(self.read_buffer)
logging.debug('handle_keep_alive - %s' % self.ip)
except message.WrongMessageException:
return False
except Exception:
logging.exception("Error KeepALive, (need at least 4 bytes : {})".format(len(self.read_buffer)))
return False
self.read_buffer = self.read_buffer[keep_alive.total_length:]
return True
def get_messages(self):
while len(self.read_buffer) > 4 and self.healthy:
if (not self.has_handshaked and self._handle_handshake()) or self._handle_keep_alive():
continue
payload_length, = struct.unpack(">I", self.read_buffer[:4])
total_length = payload_length + 4
if len(self.read_buffer) < total_length:
break
else:
payload = self.read_buffer[:total_length]
self.read_buffer = self.read_buffer[total_length:]
try:
received_message = message.MessageDispatcher(payload).dispatch()
if received_message:
yield received_message
except message.WrongMessageException as e:
logging.exception(e.__str__())