1 | /* |
---|
2 | * This file Copyright (C) 2007-2008 Charles Kerr <charles@rebelbase.com> |
---|
3 | * |
---|
4 | * This file is licensed by the GPL version 2. Works owned by the |
---|
5 | * Transmission project are granted a special exemption to clause 2(b) |
---|
6 | * so that the bulk of its code can remain under the MIT license. |
---|
7 | * This exemption does not extend to derived works not owned by |
---|
8 | * the Transmission project. |
---|
9 | * |
---|
10 | * $Id: peer-mgr.c 5647 2008-04-19 15:07:59Z charles $ |
---|
11 | */ |
---|
12 | |
---|
13 | #include <assert.h> |
---|
14 | #include <string.h> /* memcpy, memcmp, strstr */ |
---|
15 | #include <stdlib.h> /* qsort */ |
---|
16 | #include <stdio.h> /* printf */ |
---|
17 | #include <limits.h> /* INT_MAX */ |
---|
18 | |
---|
19 | #include <libgen.h> /* basename */ |
---|
20 | |
---|
21 | #include <event.h> |
---|
22 | |
---|
23 | #include "transmission.h" |
---|
24 | #include "blocklist.h" |
---|
25 | #include "clients.h" |
---|
26 | #include "completion.h" |
---|
27 | #include "crypto.h" |
---|
28 | #include "handshake.h" |
---|
29 | #include "net.h" |
---|
30 | #include "peer-io.h" |
---|
31 | #include "peer-mgr.h" |
---|
32 | #include "peer-mgr-private.h" |
---|
33 | #include "peer-msgs.h" |
---|
34 | #include "ptrarray.h" |
---|
35 | #include "ratecontrol.h" |
---|
36 | #include "torrent.h" |
---|
37 | #include "trcompat.h" /* strlcpy */ |
---|
38 | #include "trevent.h" |
---|
39 | #include "utils.h" |
---|
40 | |
---|
41 | /** |
---|
42 | *** The "SWIFT" system is described by Karthik Tamilmani, |
---|
43 | *** Vinay Pai, and Alexander Mohr of Stony Brook University |
---|
44 | *** in their paper "SWIFT: A System With Incentives For Trading" |
---|
45 | *** http://citeseer.ist.psu.edu/tamilmani04swift.html |
---|
46 | *** |
---|
47 | *** More SWIFT constants are defined in peer-mgr-private.h |
---|
48 | **/ |
---|
49 | |
---|
50 | /** |
---|
51 | * Allow new peers to download this many bytes from |
---|
52 | * us when getting started. This can prevent gridlock |
---|
53 | * with other peers using tit-for-tat algorithms |
---|
54 | */ |
---|
55 | static const int SWIFT_INITIAL_CREDIT = 64 * 1024; /* 64 KiB */ |
---|
56 | |
---|
57 | /** |
---|
58 | * We expend a fraction of our torrent's total upload speed |
---|
59 | * on largesse by uniformly distributing free credit to |
---|
60 | * all of our peers. This too helps prevent gridlock. |
---|
61 | */ |
---|
62 | static const double SWIFT_LARGESSE = 0.15; /* 15% of our UL */ |
---|
63 | |
---|
64 | /** |
---|
65 | * How frequently to extend largesse-based credit |
---|
66 | */ |
---|
67 | static const int SWIFT_PERIOD_MSEC = 5000; |
---|
68 | |
---|
69 | |
---|
70 | enum |
---|
71 | { |
---|
72 | /* how frequently to change which peers are choked */ |
---|
73 | RECHOKE_PERIOD_MSEC = (10 * 1000), |
---|
74 | |
---|
75 | /* how frequently to refill peers' request lists */ |
---|
76 | REFILL_PERIOD_MSEC = 666, |
---|
77 | |
---|
78 | /* following the BT spec, we consider ourselves `snubbed' if |
---|
79 | * we're we don't get piece data from a peer in this long */ |
---|
80 | SNUBBED_SEC = 60, |
---|
81 | |
---|
82 | /* when many peers are available, keep idle ones this long */ |
---|
83 | MIN_UPLOAD_IDLE_SECS = (60 * 3), |
---|
84 | |
---|
85 | /* when few peers are available, keep idle ones this long */ |
---|
86 | MAX_UPLOAD_IDLE_SECS = (60 * 10), |
---|
87 | |
---|
88 | /* how frequently to decide which peers live and die */ |
---|
89 | RECONNECT_PERIOD_MSEC = (2 * 1000), |
---|
90 | |
---|
91 | /* max # of peers to ask fer per torrent per reconnect pulse */ |
---|
92 | MAX_RECONNECTIONS_PER_PULSE = 1, |
---|
93 | |
---|
94 | /* max number of peers to ask for per second overall. |
---|
95 | * this throttle is to avoid overloading the router */ |
---|
96 | MAX_CONNECTIONS_PER_SECOND = 8, |
---|
97 | |
---|
98 | /* number of unchoked peers per torrent */ |
---|
99 | MAX_UNCHOKED_PEERS = 12, |
---|
100 | |
---|
101 | /* number of bad pieces a peer is allowed to send before we ban them */ |
---|
102 | MAX_BAD_PIECES_PER_PEER = 3, |
---|
103 | |
---|
104 | /* use for bitwise operations w/peer_atom.myflags */ |
---|
105 | MYFLAG_BANNED = 1, |
---|
106 | |
---|
107 | /* unreachable for now... but not banned. if they try to connect to us it's okay */ |
---|
108 | MYFLAG_UNREACHABLE = 2 |
---|
109 | }; |
---|
110 | |
---|
111 | |
---|
112 | /** |
---|
113 | *** |
---|
114 | **/ |
---|
115 | |
---|
116 | /* We keep one of these for every peer we know about, whether |
---|
117 | * it's connected or not, so the struct must be small. |
---|
118 | * When our current connections underperform, we dip back |
---|
119 | * into this list for new ones. */ |
---|
120 | struct peer_atom |
---|
121 | { |
---|
122 | uint8_t from; |
---|
123 | uint8_t flags; /* these match the added_f flags */ |
---|
124 | uint8_t myflags; /* flags that aren't defined in added_f */ |
---|
125 | uint16_t port; |
---|
126 | uint16_t numFails; |
---|
127 | struct in_addr addr; |
---|
128 | time_t time; |
---|
129 | time_t piece_data_time; |
---|
130 | }; |
---|
131 | |
---|
132 | typedef struct |
---|
133 | { |
---|
134 | uint8_t hash[SHA_DIGEST_LENGTH]; |
---|
135 | tr_ptrArray * outgoingHandshakes; /* tr_handshake */ |
---|
136 | tr_ptrArray * pool; /* struct peer_atom */ |
---|
137 | tr_ptrArray * peers; /* tr_peer */ |
---|
138 | tr_timer * reconnectTimer; |
---|
139 | tr_timer * rechokeTimer; |
---|
140 | tr_timer * refillTimer; |
---|
141 | tr_timer * swiftTimer; |
---|
142 | tr_torrent * tor; |
---|
143 | tr_peer * optimistic; /* the optimistic peer, or NULL if none */ |
---|
144 | tr_bitfield * requested; |
---|
145 | |
---|
146 | unsigned int isRunning : 1; |
---|
147 | |
---|
148 | struct tr_peerMgr * manager; |
---|
149 | } |
---|
150 | Torrent; |
---|
151 | |
---|
152 | struct tr_peerMgr |
---|
153 | { |
---|
154 | tr_handle * handle; |
---|
155 | tr_ptrArray * torrents; /* Torrent */ |
---|
156 | tr_ptrArray * incomingHandshakes; /* tr_handshake */ |
---|
157 | }; |
---|
158 | |
---|
159 | /** |
---|
160 | *** |
---|
161 | **/ |
---|
162 | |
---|
163 | static void |
---|
164 | myDebug( const char * file, int line, const Torrent * t, const char * fmt, ... ) |
---|
165 | { |
---|
166 | FILE * fp = tr_getLog( ); |
---|
167 | if( fp != NULL ) |
---|
168 | { |
---|
169 | va_list args; |
---|
170 | char timestr[64]; |
---|
171 | struct evbuffer * buf = evbuffer_new( ); |
---|
172 | char * myfile = tr_strdup( file ); |
---|
173 | |
---|
174 | evbuffer_add_printf( buf, "[%s] ", tr_getLogTimeStr( timestr, sizeof(timestr) ) ); |
---|
175 | if( t != NULL ) |
---|
176 | evbuffer_add_printf( buf, "%s ", t->tor->info.name ); |
---|
177 | va_start( args, fmt ); |
---|
178 | evbuffer_add_vprintf( buf, fmt, args ); |
---|
179 | va_end( args ); |
---|
180 | evbuffer_add_printf( buf, " (%s:%d)\n", basename(myfile), line ); |
---|
181 | fwrite( EVBUFFER_DATA(buf), 1, EVBUFFER_LENGTH(buf), fp ); |
---|
182 | |
---|
183 | tr_free( myfile ); |
---|
184 | evbuffer_free( buf ); |
---|
185 | } |
---|
186 | } |
---|
187 | |
---|
188 | #define tordbg(t, fmt...) myDebug(__FILE__, __LINE__, t, ##fmt ) |
---|
189 | |
---|
190 | /** |
---|
191 | *** |
---|
192 | **/ |
---|
193 | |
---|
194 | static void |
---|
195 | managerLock( const struct tr_peerMgr * manager ) |
---|
196 | { |
---|
197 | tr_globalLock( manager->handle ); |
---|
198 | } |
---|
199 | static void |
---|
200 | managerUnlock( const struct tr_peerMgr * manager ) |
---|
201 | { |
---|
202 | tr_globalUnlock( manager->handle ); |
---|
203 | } |
---|
204 | static void |
---|
205 | torrentLock( Torrent * torrent ) |
---|
206 | { |
---|
207 | managerLock( torrent->manager ); |
---|
208 | } |
---|
209 | static void |
---|
210 | torrentUnlock( Torrent * torrent ) |
---|
211 | { |
---|
212 | managerUnlock( torrent->manager ); |
---|
213 | } |
---|
214 | static int |
---|
215 | torrentIsLocked( const Torrent * t ) |
---|
216 | { |
---|
217 | return tr_globalIsLocked( t->manager->handle ); |
---|
218 | } |
---|
219 | |
---|
220 | /** |
---|
221 | *** |
---|
222 | **/ |
---|
223 | |
---|
224 | static int |
---|
225 | compareAddresses( const struct in_addr * a, const struct in_addr * b ) |
---|
226 | { |
---|
227 | return tr_compareUint32( a->s_addr, b->s_addr ); |
---|
228 | } |
---|
229 | |
---|
230 | static int |
---|
231 | handshakeCompareToAddr( const void * va, const void * vb ) |
---|
232 | { |
---|
233 | const tr_handshake * a = va; |
---|
234 | return compareAddresses( tr_handshakeGetAddr( a, NULL ), vb ); |
---|
235 | } |
---|
236 | |
---|
237 | static int |
---|
238 | handshakeCompare( const void * a, const void * b ) |
---|
239 | { |
---|
240 | return handshakeCompareToAddr( a, tr_handshakeGetAddr( b, NULL ) ); |
---|
241 | } |
---|
242 | |
---|
243 | static tr_handshake* |
---|
244 | getExistingHandshake( tr_ptrArray * handshakes, const struct in_addr * in_addr ) |
---|
245 | { |
---|
246 | return tr_ptrArrayFindSorted( handshakes, |
---|
247 | in_addr, |
---|
248 | handshakeCompareToAddr ); |
---|
249 | } |
---|
250 | |
---|
251 | static int |
---|
252 | comparePeerAtomToAddress( const void * va, const void * vb ) |
---|
253 | { |
---|
254 | const struct peer_atom * a = va; |
---|
255 | return compareAddresses( &a->addr, vb ); |
---|
256 | } |
---|
257 | |
---|
258 | static int |
---|
259 | comparePeerAtoms( const void * va, const void * vb ) |
---|
260 | { |
---|
261 | const struct peer_atom * b = vb; |
---|
262 | return comparePeerAtomToAddress( va, &b->addr ); |
---|
263 | } |
---|
264 | |
---|
265 | /** |
---|
266 | *** |
---|
267 | **/ |
---|
268 | |
---|
269 | static int |
---|
270 | torrentCompare( const void * va, const void * vb ) |
---|
271 | { |
---|
272 | const Torrent * a = va; |
---|
273 | const Torrent * b = vb; |
---|
274 | return memcmp( a->hash, b->hash, SHA_DIGEST_LENGTH ); |
---|
275 | } |
---|
276 | |
---|
277 | static int |
---|
278 | torrentCompareToHash( const void * va, const void * vb ) |
---|
279 | { |
---|
280 | const Torrent * a = va; |
---|
281 | const uint8_t * b_hash = vb; |
---|
282 | return memcmp( a->hash, b_hash, SHA_DIGEST_LENGTH ); |
---|
283 | } |
---|
284 | |
---|
285 | static Torrent* |
---|
286 | getExistingTorrent( tr_peerMgr * manager, const uint8_t * hash ) |
---|
287 | { |
---|
288 | return (Torrent*) tr_ptrArrayFindSorted( manager->torrents, |
---|
289 | hash, |
---|
290 | torrentCompareToHash ); |
---|
291 | } |
---|
292 | |
---|
293 | static int |
---|
294 | peerCompare( const void * va, const void * vb ) |
---|
295 | { |
---|
296 | const tr_peer * a = va; |
---|
297 | const tr_peer * b = vb; |
---|
298 | return compareAddresses( &a->in_addr, &b->in_addr ); |
---|
299 | } |
---|
300 | |
---|
301 | static int |
---|
302 | peerCompareToAddr( const void * va, const void * vb ) |
---|
303 | { |
---|
304 | const tr_peer * a = va; |
---|
305 | return compareAddresses( &a->in_addr, vb ); |
---|
306 | } |
---|
307 | |
---|
308 | static tr_peer* |
---|
309 | getExistingPeer( Torrent * torrent, const struct in_addr * in_addr ) |
---|
310 | { |
---|
311 | assert( torrentIsLocked( torrent ) ); |
---|
312 | assert( in_addr != NULL ); |
---|
313 | |
---|
314 | return (tr_peer*) tr_ptrArrayFindSorted( torrent->peers, |
---|
315 | in_addr, |
---|
316 | peerCompareToAddr ); |
---|
317 | } |
---|
318 | |
---|
319 | static struct peer_atom* |
---|
320 | getExistingAtom( const Torrent * t, const struct in_addr * addr ) |
---|
321 | { |
---|
322 | assert( torrentIsLocked( t ) ); |
---|
323 | return tr_ptrArrayFindSorted( t->pool, addr, comparePeerAtomToAddress ); |
---|
324 | } |
---|
325 | |
---|
326 | static int |
---|
327 | peerIsInUse( const Torrent * ct, const struct in_addr * addr ) |
---|
328 | { |
---|
329 | Torrent * t = (Torrent*) ct; |
---|
330 | |
---|
331 | assert( torrentIsLocked ( t ) ); |
---|
332 | |
---|
333 | return getExistingPeer( t, addr ) |
---|
334 | || getExistingHandshake( t->outgoingHandshakes, addr ) |
---|
335 | || getExistingHandshake( t->manager->incomingHandshakes, addr ); |
---|
336 | } |
---|
337 | |
---|
338 | static tr_peer* |
---|
339 | peerConstructor( const struct in_addr * in_addr ) |
---|
340 | { |
---|
341 | tr_peer * p; |
---|
342 | p = tr_new0( tr_peer, 1 ); |
---|
343 | p->credit = SWIFT_INITIAL_CREDIT; |
---|
344 | p->rcToClient = tr_rcInit( ); |
---|
345 | p->rcToPeer = tr_rcInit( ); |
---|
346 | memcpy( &p->in_addr, in_addr, sizeof(struct in_addr) ); |
---|
347 | return p; |
---|
348 | } |
---|
349 | |
---|
350 | static tr_peer* |
---|
351 | getPeer( Torrent * torrent, const struct in_addr * in_addr ) |
---|
352 | { |
---|
353 | tr_peer * peer; |
---|
354 | |
---|
355 | assert( torrentIsLocked( torrent ) ); |
---|
356 | |
---|
357 | peer = getExistingPeer( torrent, in_addr ); |
---|
358 | |
---|
359 | if( peer == NULL ) { |
---|
360 | peer = peerConstructor( in_addr ); |
---|
361 | tr_ptrArrayInsertSorted( torrent->peers, peer, peerCompare ); |
---|
362 | } |
---|
363 | |
---|
364 | return peer; |
---|
365 | } |
---|
366 | |
---|
367 | static void |
---|
368 | peerDestructor( tr_peer * peer ) |
---|
369 | { |
---|
370 | assert( peer != NULL ); |
---|
371 | assert( peer->msgs != NULL ); |
---|
372 | |
---|
373 | tr_peerMsgsUnsubscribe( peer->msgs, peer->msgsTag ); |
---|
374 | tr_peerMsgsFree( peer->msgs ); |
---|
375 | |
---|
376 | tr_peerIoFree( peer->io ); |
---|
377 | |
---|
378 | tr_bitfieldFree( peer->have ); |
---|
379 | tr_bitfieldFree( peer->blame ); |
---|
380 | tr_rcClose( peer->rcToClient ); |
---|
381 | tr_rcClose( peer->rcToPeer ); |
---|
382 | tr_free( peer->client ); |
---|
383 | tr_free( peer ); |
---|
384 | } |
---|
385 | |
---|
386 | static void |
---|
387 | removePeer( Torrent * t, tr_peer * peer ) |
---|
388 | { |
---|
389 | tr_peer * removed; |
---|
390 | struct peer_atom * atom; |
---|
391 | |
---|
392 | assert( torrentIsLocked( t ) ); |
---|
393 | |
---|
394 | atom = getExistingAtom( t, &peer->in_addr ); |
---|
395 | assert( atom != NULL ); |
---|
396 | atom->time = time( NULL ); |
---|
397 | |
---|
398 | removed = tr_ptrArrayRemoveSorted ( t->peers, peer, peerCompare ); |
---|
399 | assert( removed == peer ); |
---|
400 | peerDestructor( removed ); |
---|
401 | } |
---|
402 | |
---|
403 | static void |
---|
404 | removeAllPeers( Torrent * t ) |
---|
405 | { |
---|
406 | while( !tr_ptrArrayEmpty( t->peers ) ) |
---|
407 | removePeer( t, tr_ptrArrayNth( t->peers, 0 ) ); |
---|
408 | } |
---|
409 | |
---|
410 | static void |
---|
411 | torrentDestructor( Torrent * t ) |
---|
412 | { |
---|
413 | uint8_t hash[SHA_DIGEST_LENGTH]; |
---|
414 | |
---|
415 | assert( t != NULL ); |
---|
416 | assert( !t->isRunning ); |
---|
417 | assert( t->peers != NULL ); |
---|
418 | assert( torrentIsLocked( t ) ); |
---|
419 | assert( tr_ptrArrayEmpty( t->outgoingHandshakes ) ); |
---|
420 | assert( tr_ptrArrayEmpty( t->peers ) ); |
---|
421 | |
---|
422 | memcpy( hash, t->hash, SHA_DIGEST_LENGTH ); |
---|
423 | |
---|
424 | tr_timerFree( &t->reconnectTimer ); |
---|
425 | tr_timerFree( &t->rechokeTimer ); |
---|
426 | tr_timerFree( &t->refillTimer ); |
---|
427 | tr_timerFree( &t->swiftTimer ); |
---|
428 | |
---|
429 | tr_bitfieldFree( t->requested ); |
---|
430 | tr_ptrArrayFree( t->pool, (PtrArrayForeachFunc)tr_free ); |
---|
431 | tr_ptrArrayFree( t->outgoingHandshakes, NULL ); |
---|
432 | tr_ptrArrayFree( t->peers, NULL ); |
---|
433 | |
---|
434 | tr_free( t ); |
---|
435 | } |
---|
436 | |
---|
437 | static Torrent* |
---|
438 | torrentConstructor( tr_peerMgr * manager, tr_torrent * tor ) |
---|
439 | { |
---|
440 | Torrent * t; |
---|
441 | |
---|
442 | t = tr_new0( Torrent, 1 ); |
---|
443 | t->manager = manager; |
---|
444 | t->tor = tor; |
---|
445 | t->pool = tr_ptrArrayNew( ); |
---|
446 | t->peers = tr_ptrArrayNew( ); |
---|
447 | t->outgoingHandshakes = tr_ptrArrayNew( ); |
---|
448 | t->requested = tr_bitfieldNew( tor->blockCount ); |
---|
449 | memcpy( t->hash, tor->info.hash, SHA_DIGEST_LENGTH ); |
---|
450 | |
---|
451 | return t; |
---|
452 | } |
---|
453 | |
---|
454 | /** |
---|
455 | * For explanation, see http://www.bittorrent.org/fast_extensions.html |
---|
456 | * Also see the "test-allowed-set" unit test |
---|
457 | */ |
---|
458 | struct tr_bitfield * |
---|
459 | tr_peerMgrGenerateAllowedSet( const uint32_t k, /* number of pieces in set */ |
---|
460 | const uint32_t sz, /* number of pieces in torrent */ |
---|
461 | const uint8_t * infohash, /* torrent's SHA1 hash*/ |
---|
462 | const struct in_addr * ip ) /* peer's address */ |
---|
463 | { |
---|
464 | uint8_t w[SHA_DIGEST_LENGTH + 4]; |
---|
465 | uint8_t x[SHA_DIGEST_LENGTH]; |
---|
466 | tr_bitfield_t * a; |
---|
467 | uint32_t a_size; |
---|
468 | |
---|
469 | *(uint32_t*)w = ntohl( htonl(ip->s_addr) & 0xffffff00 ); /* (1) */ |
---|
470 | memcpy( w + 4, infohash, SHA_DIGEST_LENGTH ); /* (2) */ |
---|
471 | tr_sha1( x, w, sizeof( w ), NULL ); /* (3) */ |
---|
472 | |
---|
473 | a = tr_bitfieldNew( sz ); |
---|
474 | a_size = 0; |
---|
475 | |
---|
476 | while( a_size < k ) |
---|
477 | { |
---|
478 | int i; |
---|
479 | for ( i=0; i<5 && a_size<k; ++i ) /* (4) */ |
---|
480 | { |
---|
481 | uint32_t j = i * 4; /* (5) */ |
---|
482 | uint32_t y = ntohl(*(uint32_t*)(x+j)); /* (6) */ |
---|
483 | uint32_t index = y % sz; /* (7) */ |
---|
484 | if ( !tr_bitfieldHas( a, index ) ) { /* (8) */ |
---|
485 | tr_bitfieldAdd( a, index ); /* (9) */ |
---|
486 | ++a_size; |
---|
487 | } |
---|
488 | } |
---|
489 | tr_sha1( x, x, sizeof( x ), NULL ); /* (3) */ |
---|
490 | } |
---|
491 | |
---|
492 | return a; |
---|
493 | } |
---|
494 | |
---|
495 | tr_peerMgr* |
---|
496 | tr_peerMgrNew( tr_handle * handle ) |
---|
497 | { |
---|
498 | tr_peerMgr * m = tr_new0( tr_peerMgr, 1 ); |
---|
499 | m->handle = handle; |
---|
500 | m->torrents = tr_ptrArrayNew( ); |
---|
501 | m->incomingHandshakes = tr_ptrArrayNew( ); |
---|
502 | return m; |
---|
503 | } |
---|
504 | |
---|
505 | void |
---|
506 | tr_peerMgrFree( tr_peerMgr * manager ) |
---|
507 | { |
---|
508 | managerLock( manager ); |
---|
509 | |
---|
510 | /* free the handshakes. Abort invokes handshakeDoneCB(), which removes |
---|
511 | * the item from manager->handshakes, so this is a little roundabout... */ |
---|
512 | while( !tr_ptrArrayEmpty( manager->incomingHandshakes ) ) |
---|
513 | tr_handshakeAbort( tr_ptrArrayNth( manager->incomingHandshakes, 0 ) ); |
---|
514 | tr_ptrArrayFree( manager->incomingHandshakes, NULL ); |
---|
515 | |
---|
516 | /* free the torrents. */ |
---|
517 | tr_ptrArrayFree( manager->torrents, (PtrArrayForeachFunc)torrentDestructor ); |
---|
518 | |
---|
519 | managerUnlock( manager ); |
---|
520 | tr_free( manager ); |
---|
521 | } |
---|
522 | |
---|
523 | static tr_peer** |
---|
524 | getConnectedPeers( Torrent * t, int * setmeCount ) |
---|
525 | { |
---|
526 | int i, peerCount, connectionCount; |
---|
527 | tr_peer **peers; |
---|
528 | tr_peer **ret; |
---|
529 | |
---|
530 | assert( torrentIsLocked( t ) ); |
---|
531 | |
---|
532 | peers = (tr_peer **) tr_ptrArrayPeek( t->peers, &peerCount ); |
---|
533 | ret = tr_new( tr_peer*, peerCount ); |
---|
534 | |
---|
535 | for( i=connectionCount=0; i<peerCount; ++i ) |
---|
536 | if( peers[i]->msgs != NULL ) |
---|
537 | ret[connectionCount++] = peers[i]; |
---|
538 | |
---|
539 | *setmeCount = connectionCount; |
---|
540 | return ret; |
---|
541 | } |
---|
542 | |
---|
543 | static int |
---|
544 | clientIsDownloadingFrom( const tr_peer * peer ) |
---|
545 | { |
---|
546 | return peer->clientIsInterested && !peer->clientIsChoked; |
---|
547 | } |
---|
548 | |
---|
549 | static int |
---|
550 | clientIsUploadingTo( const tr_peer * peer ) |
---|
551 | { |
---|
552 | return peer->peerIsInterested && !peer->peerIsChoked; |
---|
553 | } |
---|
554 | |
---|
555 | /*** |
---|
556 | **** |
---|
557 | ***/ |
---|
558 | |
---|
559 | int |
---|
560 | tr_peerMgrPeerIsSeed( const tr_peerMgr * mgr, |
---|
561 | const uint8_t * torrentHash, |
---|
562 | const struct in_addr * addr ) |
---|
563 | { |
---|
564 | int isSeed = FALSE; |
---|
565 | const Torrent * t = NULL; |
---|
566 | const struct peer_atom * atom = NULL; |
---|
567 | |
---|
568 | t = getExistingTorrent( (tr_peerMgr*)mgr, torrentHash ); |
---|
569 | if( t ) |
---|
570 | atom = getExistingAtom( t, addr ); |
---|
571 | if( atom ) |
---|
572 | isSeed = ( atom->flags & ADDED_F_SEED_FLAG ) != 0; |
---|
573 | |
---|
574 | return isSeed; |
---|
575 | } |
---|
576 | |
---|
577 | /*** |
---|
578 | **** Refill |
---|
579 | ***/ |
---|
580 | |
---|
581 | struct tr_refill_piece |
---|
582 | { |
---|
583 | tr_priority_t priority; |
---|
584 | int missingBlockCount; |
---|
585 | uint16_t random; |
---|
586 | uint32_t piece; |
---|
587 | uint32_t peerCount; |
---|
588 | }; |
---|
589 | |
---|
590 | static int |
---|
591 | compareRefillPiece (const void * aIn, const void * bIn) |
---|
592 | { |
---|
593 | const struct tr_refill_piece * a = aIn; |
---|
594 | const struct tr_refill_piece * b = bIn; |
---|
595 | |
---|
596 | /* fewer missing pieces goes first */ |
---|
597 | if( a->missingBlockCount != b->missingBlockCount ) |
---|
598 | return a->missingBlockCount < b->missingBlockCount ? -1 : 1; |
---|
599 | |
---|
600 | /* if one piece has a higher priority, it goes first */ |
---|
601 | if( a->priority != b->priority ) |
---|
602 | return a->priority > b->priority ? -1 : 1; |
---|
603 | |
---|
604 | /* otherwise if one has fewer peers, it goes first */ |
---|
605 | if (a->peerCount != b->peerCount) |
---|
606 | return a->peerCount < b->peerCount ? -1 : 1; |
---|
607 | |
---|
608 | /* otherwise go with our random seed */ |
---|
609 | return tr_compareUint16( a->random, b->random ); |
---|
610 | } |
---|
611 | |
---|
612 | static int |
---|
613 | isPieceInteresting( const tr_torrent * tor, |
---|
614 | tr_piece_index_t piece ) |
---|
615 | { |
---|
616 | if( tor->info.pieces[piece].dnd ) /* we don't want it */ |
---|
617 | return 0; |
---|
618 | |
---|
619 | if( tr_cpPieceIsComplete( tor->completion, piece ) ) /* we have it */ |
---|
620 | return 0; |
---|
621 | |
---|
622 | return 1; |
---|
623 | } |
---|
624 | |
---|
625 | static uint32_t* |
---|
626 | getPreferredPieces( Torrent * t, |
---|
627 | uint32_t * pieceCount ) |
---|
628 | { |
---|
629 | const tr_torrent * tor = t->tor; |
---|
630 | const tr_info * inf = &tor->info; |
---|
631 | tr_piece_index_t i; |
---|
632 | uint32_t poolSize = 0; |
---|
633 | uint32_t * pool = tr_new( uint32_t, inf->pieceCount ); |
---|
634 | int peerCount; |
---|
635 | tr_peer** peers; |
---|
636 | |
---|
637 | assert( torrentIsLocked( t ) ); |
---|
638 | |
---|
639 | peers = getConnectedPeers( t, &peerCount ); |
---|
640 | |
---|
641 | for( i=0; i<inf->pieceCount; ++i ) |
---|
642 | if( isPieceInteresting( tor, i ) ) |
---|
643 | pool[poolSize++] = i; |
---|
644 | |
---|
645 | /* sort the pool from most interesting to least... */ |
---|
646 | if( poolSize > 1 ) |
---|
647 | { |
---|
648 | uint32_t j; |
---|
649 | struct tr_refill_piece * p = tr_new( struct tr_refill_piece, poolSize ); |
---|
650 | |
---|
651 | for( j=0; j<poolSize; ++j ) |
---|
652 | { |
---|
653 | int k; |
---|
654 | const int piece = pool[j]; |
---|
655 | struct tr_refill_piece * setme = p + j; |
---|
656 | |
---|
657 | setme->piece = piece; |
---|
658 | setme->priority = inf->pieces[piece].priority; |
---|
659 | setme->peerCount = 0; |
---|
660 | setme->random = tr_rand( UINT16_MAX ); |
---|
661 | setme->missingBlockCount = tr_cpMissingBlocksInPiece( tor->completion, piece ); |
---|
662 | |
---|
663 | for( k=0; k<peerCount; ++k ) { |
---|
664 | const tr_peer * peer = peers[k]; |
---|
665 | if( peer->peerIsInterested && !peer->clientIsChoked && tr_bitfieldHas( peer->have, piece ) ) |
---|
666 | ++setme->peerCount; |
---|
667 | } |
---|
668 | } |
---|
669 | |
---|
670 | qsort( p, poolSize, sizeof(struct tr_refill_piece), compareRefillPiece ); |
---|
671 | |
---|
672 | for( j=0; j<poolSize; ++j ) |
---|
673 | pool[j] = p[j].piece; |
---|
674 | |
---|
675 | tr_free( p ); |
---|
676 | } |
---|
677 | |
---|
678 | tr_free( peers ); |
---|
679 | |
---|
680 | *pieceCount = poolSize; |
---|
681 | return pool; |
---|
682 | } |
---|
683 | |
---|
684 | static uint64_t* |
---|
685 | getPreferredBlocks( Torrent * t, tr_block_index_t * setmeCount ) |
---|
686 | { |
---|
687 | int s; |
---|
688 | uint32_t i; |
---|
689 | uint32_t pieceCount; |
---|
690 | uint32_t blockCount; |
---|
691 | uint32_t unreqCount[3], reqCount[3]; |
---|
692 | uint32_t * pieces; |
---|
693 | uint64_t * ret, * walk; |
---|
694 | uint64_t * unreq[3], *req[3]; |
---|
695 | const tr_torrent * tor = t->tor; |
---|
696 | |
---|
697 | assert( torrentIsLocked( t ) ); |
---|
698 | |
---|
699 | pieces = getPreferredPieces( t, &pieceCount ); |
---|
700 | |
---|
701 | /** |
---|
702 | * Now we walk through those preferred pieces to find all the blocks |
---|
703 | * are still missing from them. We put unrequested blocks first, |
---|
704 | * of course, but by including requested blocks afterwards, endgame |
---|
705 | * handling happens naturally. |
---|
706 | * |
---|
707 | * By doing this once per priority we also effectively get an endgame |
---|
708 | * mode for each priority level. The helps keep high priority files |
---|
709 | * from getting stuck at 99% due of unresponsive peers. |
---|
710 | */ |
---|
711 | |
---|
712 | /* make temporary bins for the four tiers of blocks */ |
---|
713 | for( i=0; i<3; ++i ) { |
---|
714 | req[i] = tr_new( uint64_t, pieceCount * tor->blockCountInPiece ); |
---|
715 | reqCount[i] = 0; |
---|
716 | unreq[i] = tr_new( uint64_t, pieceCount * tor->blockCountInPiece ); |
---|
717 | unreqCount[i] = 0; |
---|
718 | } |
---|
719 | |
---|
720 | /* sort the blocks into our temp bins */ |
---|
721 | for( i=blockCount=0; i<pieceCount; ++i ) |
---|
722 | { |
---|
723 | const tr_piece_index_t index = pieces[i]; |
---|
724 | const int priorityIndex = tor->info.pieces[index].priority + 1; |
---|
725 | const tr_block_index_t begin = tr_torPieceFirstBlock( tor, index ); |
---|
726 | const tr_block_index_t end = begin + tr_torPieceCountBlocks( tor, index ); |
---|
727 | tr_block_index_t block; |
---|
728 | |
---|
729 | for( block=begin; block<end; ++block ) |
---|
730 | { |
---|
731 | if( tr_cpBlockIsComplete( tor->completion, block ) ) |
---|
732 | continue; |
---|
733 | |
---|
734 | ++blockCount; |
---|
735 | |
---|
736 | if( tr_bitfieldHas( t->requested, block ) ) |
---|
737 | { |
---|
738 | const uint32_t n = reqCount[priorityIndex]++; |
---|
739 | req[priorityIndex][n] = block; |
---|
740 | } |
---|
741 | else |
---|
742 | { |
---|
743 | const uint32_t n = unreqCount[priorityIndex]++; |
---|
744 | unreq[priorityIndex][n] = block; |
---|
745 | } |
---|
746 | } |
---|
747 | } |
---|
748 | |
---|
749 | /* join the bins together, going from highest priority to lowest so |
---|
750 | * the the blocks we want to request first will be first in the list */ |
---|
751 | ret = walk = tr_new( uint64_t, blockCount ); |
---|
752 | for( s=2; s>=0; --s ) { |
---|
753 | memcpy( walk, unreq[s], sizeof(uint64_t) * unreqCount[s] ); |
---|
754 | walk += unreqCount[s]; |
---|
755 | memcpy( walk, req[s], sizeof(uint64_t) * reqCount[s] ); |
---|
756 | walk += reqCount[s]; |
---|
757 | } |
---|
758 | assert( ( walk - ret ) == ( int )blockCount ); |
---|
759 | *setmeCount = blockCount; |
---|
760 | |
---|
761 | /* cleanup */ |
---|
762 | tr_free( pieces ); |
---|
763 | for( i=0; i<3; ++i ) { |
---|
764 | tr_free( unreq[i] ); |
---|
765 | tr_free( req[i] ); |
---|
766 | } |
---|
767 | return ret; |
---|
768 | } |
---|
769 | |
---|
770 | static tr_peer** |
---|
771 | getPeersUploadingToClient( Torrent * t, int * setmeCount ) |
---|
772 | { |
---|
773 | int i; |
---|
774 | int peerCount = 0; |
---|
775 | int retCount = 0; |
---|
776 | tr_peer ** peers = (tr_peer **) tr_ptrArrayPeek( t->peers, &peerCount ); |
---|
777 | tr_peer ** ret = tr_new( tr_peer*, peerCount ); |
---|
778 | |
---|
779 | /* get a list of peers we're downloading from */ |
---|
780 | for( i=0; i<peerCount; ++i ) |
---|
781 | if( clientIsDownloadingFrom( peers[i] ) ) |
---|
782 | ret[retCount++] = peers[i]; |
---|
783 | |
---|
784 | /* pick a different starting point each time so all peers |
---|
785 | * get a chance at the first blocks in the queue */ |
---|
786 | if( retCount ) { |
---|
787 | tr_peer ** tmp = tr_new( tr_peer*, retCount ); |
---|
788 | i = tr_rand( retCount ); |
---|
789 | memcpy( tmp, ret, sizeof(tr_peer*) * retCount ); |
---|
790 | memcpy( ret, tmp+i, sizeof(tr_peer*) * (retCount-i) ); |
---|
791 | memcpy( ret+(retCount-i), tmp, sizeof(tr_peer*) * i ); |
---|
792 | tr_free( tmp ); |
---|
793 | } |
---|
794 | |
---|
795 | *setmeCount = retCount; |
---|
796 | return ret; |
---|
797 | } |
---|
798 | |
---|
799 | static int |
---|
800 | refillPulse( void * vtorrent ) |
---|
801 | { |
---|
802 | Torrent * t = vtorrent; |
---|
803 | tr_torrent * tor = t->tor; |
---|
804 | tr_block_index_t i; |
---|
805 | int peerCount; |
---|
806 | tr_peer ** peers; |
---|
807 | tr_block_index_t blockCount; |
---|
808 | uint64_t * blocks; |
---|
809 | |
---|
810 | if( !t->isRunning ) |
---|
811 | return TRUE; |
---|
812 | if( tr_torrentIsSeed( t->tor ) ) |
---|
813 | return TRUE; |
---|
814 | |
---|
815 | torrentLock( t ); |
---|
816 | tordbg( t, "Refilling Request Buffers..." ); |
---|
817 | |
---|
818 | blocks = getPreferredBlocks( t, &blockCount ); |
---|
819 | peers = getPeersUploadingToClient( t, &peerCount ); |
---|
820 | |
---|
821 | for( i=0; peerCount && i<blockCount; ++i ) |
---|
822 | { |
---|
823 | int j; |
---|
824 | |
---|
825 | const tr_block_index_t block = blocks[i]; |
---|
826 | const tr_piece_index_t index = tr_torBlockPiece( tor, block ); |
---|
827 | const uint32_t begin = (block * tor->blockSize) - (index * tor->info.pieceSize); |
---|
828 | const uint32_t length = tr_torBlockCountBytes( tor, block ); |
---|
829 | |
---|
830 | assert( tr_torrentReqIsValid( tor, index, begin, length ) ); |
---|
831 | assert( _tr_block( tor, index, begin ) == block ); |
---|
832 | assert( begin < tr_torPieceCountBytes( tor, index ) ); |
---|
833 | assert( (begin + length) <= tr_torPieceCountBytes( tor, index ) ); |
---|
834 | |
---|
835 | /* find a peer who can ask for this block */ |
---|
836 | for( j=0; j<peerCount; ) |
---|
837 | { |
---|
838 | const int val = tr_peerMsgsAddRequest( peers[j]->msgs, index, begin, length ); |
---|
839 | switch( val ) |
---|
840 | { |
---|
841 | case TR_ADDREQ_FULL: |
---|
842 | case TR_ADDREQ_CLIENT_CHOKED: |
---|
843 | memmove( peers+j, peers+j+1, sizeof(tr_peer*)*(--peerCount-j) ); |
---|
844 | break; |
---|
845 | |
---|
846 | case TR_ADDREQ_MISSING: |
---|
847 | case TR_ADDREQ_DUPLICATE: |
---|
848 | ++j; |
---|
849 | break; |
---|
850 | |
---|
851 | case TR_ADDREQ_OK: |
---|
852 | tr_bitfieldAdd( t->requested, block ); |
---|
853 | j = peerCount; |
---|
854 | break; |
---|
855 | |
---|
856 | default: |
---|
857 | assert( 0 && "unhandled value" ); |
---|
858 | break; |
---|
859 | } |
---|
860 | } |
---|
861 | } |
---|
862 | |
---|
863 | /* cleanup */ |
---|
864 | tr_free( peers ); |
---|
865 | tr_free( blocks ); |
---|
866 | |
---|
867 | t->refillTimer = NULL; |
---|
868 | torrentUnlock( t ); |
---|
869 | return FALSE; |
---|
870 | } |
---|
871 | |
---|
872 | static void |
---|
873 | broadcastClientHave( Torrent * t, uint32_t index ) |
---|
874 | { |
---|
875 | int i, size; |
---|
876 | tr_peer ** peers; |
---|
877 | |
---|
878 | assert( torrentIsLocked( t ) ); |
---|
879 | |
---|
880 | peers = getConnectedPeers( t, &size ); |
---|
881 | for( i=0; i<size; ++i ) |
---|
882 | tr_peerMsgsHave( peers[i]->msgs, index ); |
---|
883 | tr_free( peers ); |
---|
884 | } |
---|
885 | |
---|
886 | static void |
---|
887 | broadcastGotBlock( Torrent * t, uint32_t index, uint32_t offset, uint32_t length ) |
---|
888 | { |
---|
889 | int i, size; |
---|
890 | tr_peer ** peers; |
---|
891 | |
---|
892 | assert( torrentIsLocked( t ) ); |
---|
893 | |
---|
894 | peers = getConnectedPeers( t, &size ); |
---|
895 | for( i=0; i<size; ++i ) |
---|
896 | tr_peerMsgsCancel( peers[i]->msgs, index, offset, length ); |
---|
897 | tr_free( peers ); |
---|
898 | } |
---|
899 | |
---|
900 | static void |
---|
901 | addStrike( Torrent * t, tr_peer * peer ) |
---|
902 | { |
---|
903 | tordbg( t, "increasing peer %s strike count to %d", tr_peerIoAddrStr(&peer->in_addr,peer->port), peer->strikes+1 ); |
---|
904 | |
---|
905 | if( ++peer->strikes >= MAX_BAD_PIECES_PER_PEER ) |
---|
906 | { |
---|
907 | struct peer_atom * atom = getExistingAtom( t, &peer->in_addr ); |
---|
908 | atom->myflags |= MYFLAG_BANNED; |
---|
909 | peer->doPurge = 1; |
---|
910 | tordbg( t, "banning peer %s", tr_peerIoAddrStr(&atom->addr,atom->port) ); |
---|
911 | } |
---|
912 | } |
---|
913 | |
---|
914 | static void |
---|
915 | msgsCallbackFunc( void * vpeer, void * vevent, void * vt ) |
---|
916 | { |
---|
917 | tr_peer * peer = vpeer; |
---|
918 | Torrent * t = (Torrent *) vt; |
---|
919 | const tr_peermsgs_event * e = (const tr_peermsgs_event *) vevent; |
---|
920 | |
---|
921 | torrentLock( t ); |
---|
922 | |
---|
923 | switch( e->eventType ) |
---|
924 | { |
---|
925 | case TR_PEERMSG_NEED_REQ: |
---|
926 | if( t->refillTimer == NULL ) |
---|
927 | t->refillTimer = tr_timerNew( t->manager->handle, |
---|
928 | refillPulse, t, |
---|
929 | REFILL_PERIOD_MSEC ); |
---|
930 | break; |
---|
931 | |
---|
932 | case TR_PEERMSG_CANCEL: |
---|
933 | tr_bitfieldRem( t->requested, _tr_block( t->tor, e->pieceIndex, e->offset ) ); |
---|
934 | break; |
---|
935 | |
---|
936 | case TR_PEERMSG_PIECE_DATA: { |
---|
937 | struct peer_atom * atom = getExistingAtom( t, &peer->in_addr ); |
---|
938 | atom->piece_data_time = time( NULL ); |
---|
939 | break; |
---|
940 | } |
---|
941 | |
---|
942 | case TR_PEERMSG_CLIENT_HAVE: |
---|
943 | broadcastClientHave( t, e->pieceIndex ); |
---|
944 | tr_torrentRecheckCompleteness( t->tor ); |
---|
945 | break; |
---|
946 | |
---|
947 | case TR_PEERMSG_PEER_PROGRESS: { |
---|
948 | struct peer_atom * atom = getExistingAtom( t, &peer->in_addr ); |
---|
949 | const int peerIsSeed = e->progress >= 1.0; |
---|
950 | if( peerIsSeed ) { |
---|
951 | tordbg( t, "marking peer %s as a seed", tr_peerIoAddrStr(&atom->addr,atom->port) ); |
---|
952 | atom->flags |= ADDED_F_SEED_FLAG; |
---|
953 | } else { |
---|
954 | tordbg( t, "marking peer %s as a non-seed", tr_peerIoAddrStr(&atom->addr,atom->port) ); |
---|
955 | atom->flags &= ~ADDED_F_SEED_FLAG; |
---|
956 | } break; |
---|
957 | } |
---|
958 | |
---|
959 | case TR_PEERMSG_CLIENT_BLOCK: |
---|
960 | broadcastGotBlock( t, e->pieceIndex, e->offset, e->length ); |
---|
961 | break; |
---|
962 | |
---|
963 | case TR_PEERMSG_ERROR: |
---|
964 | if( TR_ERROR_IS_IO( e->err ) ) { |
---|
965 | t->tor->error = e->err; |
---|
966 | strlcpy( t->tor->errorString, tr_errorString( e->err ), sizeof(t->tor->errorString) ); |
---|
967 | tr_torrentStop( t->tor ); |
---|
968 | } else if( e->err == TR_ERROR_ASSERT ) { |
---|
969 | addStrike( t, peer ); |
---|
970 | } |
---|
971 | peer->doPurge = 1; |
---|
972 | break; |
---|
973 | |
---|
974 | default: |
---|
975 | assert(0); |
---|
976 | } |
---|
977 | |
---|
978 | torrentUnlock( t ); |
---|
979 | } |
---|
980 | |
---|
981 | static void |
---|
982 | ensureAtomExists( Torrent * t, const struct in_addr * addr, uint16_t port, uint8_t flags, uint8_t from ) |
---|
983 | { |
---|
984 | if( getExistingAtom( t, addr ) == NULL ) |
---|
985 | { |
---|
986 | struct peer_atom * a; |
---|
987 | a = tr_new0( struct peer_atom, 1 ); |
---|
988 | a->addr = *addr; |
---|
989 | a->port = port; |
---|
990 | a->flags = flags; |
---|
991 | a->from = from; |
---|
992 | tordbg( t, "got a new atom: %s", tr_peerIoAddrStr(&a->addr,a->port) ); |
---|
993 | tr_ptrArrayInsertSorted( t->pool, a, comparePeerAtoms ); |
---|
994 | } |
---|
995 | } |
---|
996 | |
---|
997 | static void |
---|
998 | maybeEnsureAtomExists( Torrent * t, const struct in_addr * addr, uint16_t port, uint8_t flags, uint8_t from ) |
---|
999 | { |
---|
1000 | if( tr_blocklistHasAddress( t->manager->handle, addr ) ) |
---|
1001 | { |
---|
1002 | char * fmt = NULL; |
---|
1003 | switch( from ) { |
---|
1004 | case TR_PEER_FROM_TRACKER: fmt = _( "Banned IP address \"%s\" was given to us by the tracker" ); break; |
---|
1005 | case TR_PEER_FROM_CACHE: fmt = _( "Banned IP address \"%s\" was found in the cache" ); break; |
---|
1006 | case TR_PEER_FROM_PEX: fmt = _( "Banned IP address \"%s\" was given to us by another peer" ); break; |
---|
1007 | case TR_PEER_FROM_INCOMING: fmt = _( "Banned IP address \"%s\" tried to connect to us" ); break; |
---|
1008 | } |
---|
1009 | tr_torinf( t->tor, fmt, inet_ntoa( *addr ) ); |
---|
1010 | } |
---|
1011 | else |
---|
1012 | { |
---|
1013 | ensureAtomExists( t, addr, port, flags, from ); |
---|
1014 | } |
---|
1015 | } |
---|
1016 | |
---|
1017 | static int |
---|
1018 | getMaxPeerCount( const tr_torrent * tor UNUSED ) |
---|
1019 | { |
---|
1020 | return tor->maxConnectedPeers; |
---|
1021 | } |
---|
1022 | |
---|
1023 | /* FIXME: this is kind of a mess. */ |
---|
1024 | static void |
---|
1025 | myHandshakeDoneCB( tr_handshake * handshake, |
---|
1026 | tr_peerIo * io, |
---|
1027 | int isConnected, |
---|
1028 | const uint8_t * peer_id, |
---|
1029 | void * vmanager ) |
---|
1030 | { |
---|
1031 | int ok = isConnected; |
---|
1032 | uint16_t port; |
---|
1033 | const struct in_addr * addr; |
---|
1034 | tr_peerMgr * manager = (tr_peerMgr*) vmanager; |
---|
1035 | Torrent * t; |
---|
1036 | tr_handshake * ours; |
---|
1037 | |
---|
1038 | assert( io != NULL ); |
---|
1039 | assert( isConnected==0 || isConnected==1 ); |
---|
1040 | |
---|
1041 | t = tr_peerIoHasTorrentHash( io ) |
---|
1042 | ? getExistingTorrent( manager, tr_peerIoGetTorrentHash( io ) ) |
---|
1043 | : NULL; |
---|
1044 | |
---|
1045 | if( tr_peerIoIsIncoming ( io ) ) |
---|
1046 | ours = tr_ptrArrayRemoveSorted( manager->incomingHandshakes, |
---|
1047 | handshake, handshakeCompare ); |
---|
1048 | else if( t != NULL ) |
---|
1049 | ours = tr_ptrArrayRemoveSorted( t->outgoingHandshakes, |
---|
1050 | handshake, handshakeCompare ); |
---|
1051 | else |
---|
1052 | ours = handshake; |
---|
1053 | |
---|
1054 | assert( ours != NULL ); |
---|
1055 | assert( ours == handshake ); |
---|
1056 | |
---|
1057 | if( t != NULL ) |
---|
1058 | torrentLock( t ); |
---|
1059 | |
---|
1060 | addr = tr_peerIoGetAddress( io, &port ); |
---|
1061 | |
---|
1062 | if( !ok || !t || !t->isRunning ) |
---|
1063 | { |
---|
1064 | if( t ) { |
---|
1065 | struct peer_atom * atom = getExistingAtom( t, addr ); |
---|
1066 | if( atom ) |
---|
1067 | ++atom->numFails; |
---|
1068 | } |
---|
1069 | |
---|
1070 | tr_peerIoFree( io ); |
---|
1071 | } |
---|
1072 | else /* looking good */ |
---|
1073 | { |
---|
1074 | struct peer_atom * atom; |
---|
1075 | ensureAtomExists( t, addr, port, 0, TR_PEER_FROM_INCOMING ); |
---|
1076 | atom = getExistingAtom( t, addr ); |
---|
1077 | |
---|
1078 | if( atom->myflags & MYFLAG_BANNED ) |
---|
1079 | { |
---|
1080 | tordbg( t, "banned peer %s tried to reconnect", tr_peerIoAddrStr(&atom->addr,atom->port) ); |
---|
1081 | tr_peerIoFree( io ); |
---|
1082 | } |
---|
1083 | else if( tr_ptrArraySize( t->peers ) >= getMaxPeerCount( t->tor ) ) |
---|
1084 | { |
---|
1085 | tr_peerIoFree( io ); |
---|
1086 | } |
---|
1087 | else |
---|
1088 | { |
---|
1089 | tr_peer * peer = getExistingPeer( t, addr ); |
---|
1090 | |
---|
1091 | if( peer != NULL ) /* we already have this peer */ |
---|
1092 | { |
---|
1093 | tr_peerIoFree( io ); |
---|
1094 | } |
---|
1095 | else |
---|
1096 | { |
---|
1097 | peer = getPeer( t, addr ); |
---|
1098 | tr_free( peer->client ); |
---|
1099 | peer->client = peer_id ? tr_clientForId( peer_id ) : NULL; |
---|
1100 | peer->port = port; |
---|
1101 | peer->io = io; |
---|
1102 | peer->msgs = tr_peerMsgsNew( t->tor, peer, msgsCallbackFunc, t, &peer->msgsTag ); |
---|
1103 | atom->time = time( NULL ); |
---|
1104 | } |
---|
1105 | } |
---|
1106 | } |
---|
1107 | |
---|
1108 | if( t != NULL ) |
---|
1109 | torrentUnlock( t ); |
---|
1110 | } |
---|
1111 | |
---|
1112 | void |
---|
1113 | tr_peerMgrAddIncoming( tr_peerMgr * manager, |
---|
1114 | struct in_addr * addr, |
---|
1115 | uint16_t port, |
---|
1116 | int socket ) |
---|
1117 | { |
---|
1118 | managerLock( manager ); |
---|
1119 | |
---|
1120 | if( tr_blocklistHasAddress( manager->handle, addr ) ) |
---|
1121 | { |
---|
1122 | tr_inf( _( "Banned IP address \"%s\" tried to connect to us" ), |
---|
1123 | inet_ntoa( *addr ) ); |
---|
1124 | tr_netClose( socket ); |
---|
1125 | } |
---|
1126 | else if( getExistingHandshake( manager->incomingHandshakes, addr ) ) |
---|
1127 | { |
---|
1128 | tr_netClose( socket ); |
---|
1129 | } |
---|
1130 | else /* we don't have a connetion to them yet... */ |
---|
1131 | { |
---|
1132 | tr_peerIo * io; |
---|
1133 | tr_handshake * handshake; |
---|
1134 | |
---|
1135 | tordbg( NULL, "Got an INCOMING connection with %s", tr_peerIoAddrStr( addr, port ) ); |
---|
1136 | |
---|
1137 | io = tr_peerIoNewIncoming( manager->handle, addr, port, socket ); |
---|
1138 | |
---|
1139 | handshake = tr_handshakeNew( io, |
---|
1140 | manager->handle->encryptionMode, |
---|
1141 | myHandshakeDoneCB, |
---|
1142 | manager ); |
---|
1143 | |
---|
1144 | tr_ptrArrayInsertSorted( manager->incomingHandshakes, handshake, handshakeCompare ); |
---|
1145 | } |
---|
1146 | |
---|
1147 | managerUnlock( manager ); |
---|
1148 | } |
---|
1149 | |
---|
1150 | void |
---|
1151 | tr_peerMgrAddPex( tr_peerMgr * manager, |
---|
1152 | const uint8_t * torrentHash, |
---|
1153 | uint8_t from, |
---|
1154 | const tr_pex * pex ) |
---|
1155 | { |
---|
1156 | Torrent * t; |
---|
1157 | managerLock( manager ); |
---|
1158 | |
---|
1159 | t = getExistingTorrent( manager, torrentHash ); |
---|
1160 | maybeEnsureAtomExists( t, &pex->in_addr, pex->port, pex->flags, from ); |
---|
1161 | |
---|
1162 | managerUnlock( manager ); |
---|
1163 | } |
---|
1164 | |
---|
1165 | tr_pex * |
---|
1166 | tr_peerMgrCompactToPex( const void * compact, |
---|
1167 | size_t compactLen, |
---|
1168 | const char * added_f, |
---|
1169 | size_t * pexCount ) |
---|
1170 | { |
---|
1171 | size_t i; |
---|
1172 | size_t n = compactLen / 6; |
---|
1173 | const uint8_t * walk = compact; |
---|
1174 | tr_pex * pex = tr_new0( tr_pex, n ); |
---|
1175 | for( i=0; i<n; ++i ) { |
---|
1176 | memcpy( &pex[i].in_addr, walk, 4 ); walk += 4; |
---|
1177 | memcpy( &pex[i].port, walk, 2 ); walk += 2; |
---|
1178 | if( added_f ) |
---|
1179 | pex[i].flags = added_f[i]; |
---|
1180 | } |
---|
1181 | *pexCount = n; |
---|
1182 | return pex; |
---|
1183 | } |
---|
1184 | |
---|
1185 | /** |
---|
1186 | *** |
---|
1187 | **/ |
---|
1188 | |
---|
1189 | void |
---|
1190 | tr_peerMgrSetBlame( tr_peerMgr * manager, |
---|
1191 | const uint8_t * torrentHash, |
---|
1192 | int pieceIndex, |
---|
1193 | int success ) |
---|
1194 | { |
---|
1195 | if( !success ) |
---|
1196 | { |
---|
1197 | int peerCount, i; |
---|
1198 | Torrent * t = getExistingTorrent( manager, torrentHash ); |
---|
1199 | tr_peer ** peers; |
---|
1200 | |
---|
1201 | assert( torrentIsLocked( t ) ); |
---|
1202 | |
---|
1203 | peers = (tr_peer **) tr_ptrArrayPeek( t->peers, &peerCount ); |
---|
1204 | for( i=0; i<peerCount; ++i ) |
---|
1205 | { |
---|
1206 | tr_peer * peer = peers[i]; |
---|
1207 | if( tr_bitfieldHas( peer->blame, pieceIndex ) ) |
---|
1208 | { |
---|
1209 | tordbg( t, "peer %s contributed to corrupt piece (%d); now has %d strikes", |
---|
1210 | tr_peerIoAddrStr(&peer->in_addr,peer->port), |
---|
1211 | pieceIndex, (int)peer->strikes+1 ); |
---|
1212 | addStrike( t, peer ); |
---|
1213 | } |
---|
1214 | } |
---|
1215 | } |
---|
1216 | } |
---|
1217 | |
---|
1218 | int |
---|
1219 | tr_pexCompare( const void * va, const void * vb ) |
---|
1220 | { |
---|
1221 | const tr_pex * a = (const tr_pex *) va; |
---|
1222 | const tr_pex * b = (const tr_pex *) vb; |
---|
1223 | int i = memcmp( &a->in_addr, &b->in_addr, sizeof(struct in_addr) ); |
---|
1224 | if( i ) return i; |
---|
1225 | if( a->port < b->port ) return -1; |
---|
1226 | if( a->port > b->port ) return 1; |
---|
1227 | return 0; |
---|
1228 | } |
---|
1229 | |
---|
1230 | int tr_pexCompare( const void * a, const void * b ); |
---|
1231 | |
---|
1232 | static int |
---|
1233 | peerPrefersCrypto( const tr_peer * peer ) |
---|
1234 | { |
---|
1235 | if( peer->encryption_preference == ENCRYPTION_PREFERENCE_YES ) |
---|
1236 | return TRUE; |
---|
1237 | |
---|
1238 | if( peer->encryption_preference == ENCRYPTION_PREFERENCE_NO ) |
---|
1239 | return FALSE; |
---|
1240 | |
---|
1241 | return tr_peerIoIsEncrypted( peer->io ); |
---|
1242 | }; |
---|
1243 | |
---|
1244 | int |
---|
1245 | tr_peerMgrGetPeers( tr_peerMgr * manager, |
---|
1246 | const uint8_t * torrentHash, |
---|
1247 | tr_pex ** setme_pex ) |
---|
1248 | { |
---|
1249 | const Torrent * t = getExistingTorrent( (tr_peerMgr*)manager, torrentHash ); |
---|
1250 | int i, peerCount; |
---|
1251 | const tr_peer ** peers; |
---|
1252 | tr_pex * pex; |
---|
1253 | tr_pex * walk; |
---|
1254 | |
---|
1255 | managerLock( manager ); |
---|
1256 | |
---|
1257 | peers = (const tr_peer **) tr_ptrArrayPeek( t->peers, &peerCount ); |
---|
1258 | pex = walk = tr_new( tr_pex, peerCount ); |
---|
1259 | |
---|
1260 | for( i=0; i<peerCount; ++i, ++walk ) |
---|
1261 | { |
---|
1262 | const tr_peer * peer = peers[i]; |
---|
1263 | |
---|
1264 | walk->in_addr = peer->in_addr; |
---|
1265 | |
---|
1266 | walk->port = peer->port; |
---|
1267 | |
---|
1268 | walk->flags = 0; |
---|
1269 | if( peerPrefersCrypto(peer) ) walk->flags |= ADDED_F_ENCRYPTION_FLAG; |
---|
1270 | if( peer->progress >= 1.0 ) walk->flags |= ADDED_F_SEED_FLAG; |
---|
1271 | } |
---|
1272 | |
---|
1273 | assert( ( walk - pex ) == peerCount ); |
---|
1274 | qsort( pex, peerCount, sizeof(tr_pex), tr_pexCompare ); |
---|
1275 | *setme_pex = pex; |
---|
1276 | |
---|
1277 | managerUnlock( manager ); |
---|
1278 | |
---|
1279 | return peerCount; |
---|
1280 | } |
---|
1281 | |
---|
1282 | static int reconnectPulse( void * vtorrent ); |
---|
1283 | static int rechokePulse( void * vtorrent ); |
---|
1284 | static int swiftPulse( void * vtorrent ); |
---|
1285 | |
---|
1286 | void |
---|
1287 | tr_peerMgrStartTorrent( tr_peerMgr * manager, |
---|
1288 | const uint8_t * torrentHash ) |
---|
1289 | { |
---|
1290 | Torrent * t; |
---|
1291 | |
---|
1292 | managerLock( manager ); |
---|
1293 | |
---|
1294 | t = getExistingTorrent( manager, torrentHash ); |
---|
1295 | |
---|
1296 | assert( t != NULL ); |
---|
1297 | assert( ( t->isRunning != 0 ) == ( t->reconnectTimer != NULL ) ); |
---|
1298 | assert( ( t->isRunning != 0 ) == ( t->rechokeTimer != NULL ) ); |
---|
1299 | assert( ( t->isRunning != 0 ) == ( t->swiftTimer != NULL ) ); |
---|
1300 | |
---|
1301 | if( !t->isRunning ) |
---|
1302 | { |
---|
1303 | t->isRunning = 1; |
---|
1304 | |
---|
1305 | t->reconnectTimer = tr_timerNew( t->manager->handle, |
---|
1306 | reconnectPulse, t, |
---|
1307 | RECONNECT_PERIOD_MSEC ); |
---|
1308 | |
---|
1309 | t->rechokeTimer = tr_timerNew( t->manager->handle, |
---|
1310 | rechokePulse, t, |
---|
1311 | RECHOKE_PERIOD_MSEC ); |
---|
1312 | |
---|
1313 | t->swiftTimer = tr_timerNew( t->manager->handle, |
---|
1314 | swiftPulse, t, |
---|
1315 | SWIFT_PERIOD_MSEC ); |
---|
1316 | |
---|
1317 | reconnectPulse( t ); |
---|
1318 | |
---|
1319 | rechokePulse( t ); |
---|
1320 | |
---|
1321 | swiftPulse( t ); |
---|
1322 | } |
---|
1323 | |
---|
1324 | managerUnlock( manager ); |
---|
1325 | } |
---|
1326 | |
---|
1327 | static void |
---|
1328 | stopTorrent( Torrent * t ) |
---|
1329 | { |
---|
1330 | assert( torrentIsLocked( t ) ); |
---|
1331 | |
---|
1332 | t->isRunning = 0; |
---|
1333 | tr_timerFree( &t->rechokeTimer ); |
---|
1334 | tr_timerFree( &t->reconnectTimer ); |
---|
1335 | tr_timerFree( &t->swiftTimer ); |
---|
1336 | |
---|
1337 | /* disconnect the peers. */ |
---|
1338 | tr_ptrArrayForeach( t->peers, (PtrArrayForeachFunc)peerDestructor ); |
---|
1339 | tr_ptrArrayClear( t->peers ); |
---|
1340 | |
---|
1341 | /* disconnect the handshakes. handshakeAbort calls handshakeDoneCB(), |
---|
1342 | * which removes the handshake from t->outgoingHandshakes... */ |
---|
1343 | while( !tr_ptrArrayEmpty( t->outgoingHandshakes ) ) |
---|
1344 | tr_handshakeAbort( tr_ptrArrayNth( t->outgoingHandshakes, 0 ) ); |
---|
1345 | } |
---|
1346 | void |
---|
1347 | tr_peerMgrStopTorrent( tr_peerMgr * manager, |
---|
1348 | const uint8_t * torrentHash) |
---|
1349 | { |
---|
1350 | managerLock( manager ); |
---|
1351 | |
---|
1352 | stopTorrent( getExistingTorrent( manager, torrentHash ) ); |
---|
1353 | |
---|
1354 | managerUnlock( manager ); |
---|
1355 | } |
---|
1356 | |
---|
1357 | void |
---|
1358 | tr_peerMgrAddTorrent( tr_peerMgr * manager, |
---|
1359 | tr_torrent * tor ) |
---|
1360 | { |
---|
1361 | Torrent * t; |
---|
1362 | |
---|
1363 | managerLock( manager ); |
---|
1364 | |
---|
1365 | assert( tor != NULL ); |
---|
1366 | assert( getExistingTorrent( manager, tor->info.hash ) == NULL ); |
---|
1367 | |
---|
1368 | t = torrentConstructor( manager, tor ); |
---|
1369 | tr_ptrArrayInsertSorted( manager->torrents, t, torrentCompare ); |
---|
1370 | |
---|
1371 | managerUnlock( manager ); |
---|
1372 | } |
---|
1373 | |
---|
1374 | void |
---|
1375 | tr_peerMgrRemoveTorrent( tr_peerMgr * manager, |
---|
1376 | const uint8_t * torrentHash ) |
---|
1377 | { |
---|
1378 | Torrent * t; |
---|
1379 | |
---|
1380 | managerLock( manager ); |
---|
1381 | |
---|
1382 | t = getExistingTorrent( manager, torrentHash ); |
---|
1383 | assert( t != NULL ); |
---|
1384 | stopTorrent( t ); |
---|
1385 | tr_ptrArrayRemoveSorted( manager->torrents, t, torrentCompare ); |
---|
1386 | torrentDestructor( t ); |
---|
1387 | |
---|
1388 | managerUnlock( manager ); |
---|
1389 | } |
---|
1390 | |
---|
1391 | void |
---|
1392 | tr_peerMgrTorrentAvailability( const tr_peerMgr * manager, |
---|
1393 | const uint8_t * torrentHash, |
---|
1394 | int8_t * tab, |
---|
1395 | int tabCount ) |
---|
1396 | { |
---|
1397 | int i; |
---|
1398 | const Torrent * t; |
---|
1399 | const tr_torrent * tor; |
---|
1400 | float interval; |
---|
1401 | |
---|
1402 | managerLock( (tr_peerMgr*)manager ); |
---|
1403 | |
---|
1404 | t = getExistingTorrent( (tr_peerMgr*)manager, torrentHash ); |
---|
1405 | tor = t->tor; |
---|
1406 | interval = tor->info.pieceCount / (float)tabCount; |
---|
1407 | |
---|
1408 | memset( tab, 0, tabCount ); |
---|
1409 | |
---|
1410 | for( i=0; i<tabCount; ++i ) |
---|
1411 | { |
---|
1412 | const int piece = i * interval; |
---|
1413 | |
---|
1414 | if( tor == NULL ) |
---|
1415 | tab[i] = 0; |
---|
1416 | else if( tr_cpPieceIsComplete( tor->completion, piece ) ) |
---|
1417 | tab[i] = -1; |
---|
1418 | else { |
---|
1419 | int j, peerCount; |
---|
1420 | const tr_peer ** peers = (const tr_peer **) tr_ptrArrayPeek( t->peers, &peerCount ); |
---|
1421 | for( j=0; j<peerCount; ++j ) |
---|
1422 | if( tr_bitfieldHas( peers[j]->have, i ) ) |
---|
1423 | ++tab[i]; |
---|
1424 | } |
---|
1425 | } |
---|
1426 | |
---|
1427 | managerUnlock( (tr_peerMgr*)manager ); |
---|
1428 | } |
---|
1429 | |
---|
1430 | /* Returns the pieces that are available from peers */ |
---|
1431 | tr_bitfield* |
---|
1432 | tr_peerMgrGetAvailable( const tr_peerMgr * manager, |
---|
1433 | const uint8_t * torrentHash ) |
---|
1434 | { |
---|
1435 | int i, size; |
---|
1436 | Torrent * t; |
---|
1437 | tr_peer ** peers; |
---|
1438 | tr_bitfield * pieces; |
---|
1439 | managerLock( (tr_peerMgr*)manager ); |
---|
1440 | |
---|
1441 | t = getExistingTorrent( (tr_peerMgr*)manager, torrentHash ); |
---|
1442 | pieces = tr_bitfieldNew( t->tor->info.pieceCount ); |
---|
1443 | peers = getConnectedPeers( t, &size ); |
---|
1444 | for( i=0; i<size; ++i ) |
---|
1445 | tr_bitfieldOr( pieces, peers[i]->have ); |
---|
1446 | |
---|
1447 | managerUnlock( (tr_peerMgr*)manager ); |
---|
1448 | tr_free( peers ); |
---|
1449 | return pieces; |
---|
1450 | } |
---|
1451 | |
---|
1452 | int |
---|
1453 | tr_peerMgrHasConnections( const tr_peerMgr * manager, |
---|
1454 | const uint8_t * torrentHash ) |
---|
1455 | { |
---|
1456 | int ret; |
---|
1457 | const Torrent * t; |
---|
1458 | managerLock( (tr_peerMgr*)manager ); |
---|
1459 | |
---|
1460 | t = getExistingTorrent( (tr_peerMgr*)manager, torrentHash ); |
---|
1461 | ret = t && tr_ptrArraySize( t->peers ); |
---|
1462 | |
---|
1463 | managerUnlock( (tr_peerMgr*)manager ); |
---|
1464 | return ret; |
---|
1465 | } |
---|
1466 | |
---|
1467 | void |
---|
1468 | tr_peerMgrTorrentStats( const tr_peerMgr * manager, |
---|
1469 | const uint8_t * torrentHash, |
---|
1470 | int * setmePeersKnown, |
---|
1471 | int * setmePeersConnected, |
---|
1472 | int * setmePeersSendingToUs, |
---|
1473 | int * setmePeersGettingFromUs, |
---|
1474 | int * setmePeersFrom ) |
---|
1475 | { |
---|
1476 | int i, size; |
---|
1477 | const Torrent * t; |
---|
1478 | const tr_peer ** peers; |
---|
1479 | |
---|
1480 | managerLock( (tr_peerMgr*)manager ); |
---|
1481 | |
---|
1482 | t = getExistingTorrent( (tr_peerMgr*)manager, torrentHash ); |
---|
1483 | peers = (const tr_peer **) tr_ptrArrayPeek( t->peers, &size ); |
---|
1484 | |
---|
1485 | *setmePeersKnown = tr_ptrArraySize( t->pool ); |
---|
1486 | *setmePeersConnected = 0; |
---|
1487 | *setmePeersSendingToUs = 0; |
---|
1488 | *setmePeersGettingFromUs = 0; |
---|
1489 | |
---|
1490 | for( i=0; i<TR_PEER_FROM__MAX; ++i ) |
---|
1491 | setmePeersFrom[i] = 0; |
---|
1492 | |
---|
1493 | for( i=0; i<size; ++i ) |
---|
1494 | { |
---|
1495 | const tr_peer * peer = peers[i]; |
---|
1496 | const struct peer_atom * atom = getExistingAtom( t, &peer->in_addr ); |
---|
1497 | |
---|
1498 | if( peer->io == NULL ) /* not connected */ |
---|
1499 | continue; |
---|
1500 | |
---|
1501 | ++*setmePeersConnected; |
---|
1502 | |
---|
1503 | ++setmePeersFrom[atom->from]; |
---|
1504 | |
---|
1505 | if( clientIsDownloadingFrom( peer ) ) |
---|
1506 | ++*setmePeersSendingToUs; |
---|
1507 | |
---|
1508 | if( clientIsUploadingTo( peer ) ) |
---|
1509 | ++*setmePeersGettingFromUs; |
---|
1510 | } |
---|
1511 | |
---|
1512 | managerUnlock( (tr_peerMgr*)manager ); |
---|
1513 | } |
---|
1514 | |
---|
1515 | struct tr_peer_stat * |
---|
1516 | tr_peerMgrPeerStats( const tr_peerMgr * manager, |
---|
1517 | const uint8_t * torrentHash, |
---|
1518 | int * setmeCount UNUSED ) |
---|
1519 | { |
---|
1520 | int i, size; |
---|
1521 | const Torrent * t; |
---|
1522 | tr_peer ** peers; |
---|
1523 | tr_peer_stat * ret; |
---|
1524 | |
---|
1525 | assert( manager != NULL ); |
---|
1526 | managerLock( (tr_peerMgr*)manager ); |
---|
1527 | |
---|
1528 | t = getExistingTorrent( (tr_peerMgr*)manager, torrentHash ); |
---|
1529 | peers = getConnectedPeers( (Torrent*)t, &size ); |
---|
1530 | ret = tr_new0( tr_peer_stat, size ); |
---|
1531 | |
---|
1532 | for( i=0; i<size; ++i ) |
---|
1533 | { |
---|
1534 | char * pch; |
---|
1535 | const tr_peer * peer = peers[i]; |
---|
1536 | const struct peer_atom * atom = getExistingAtom( t, &peer->in_addr ); |
---|
1537 | tr_peer_stat * stat = ret + i; |
---|
1538 | |
---|
1539 | tr_netNtop( &peer->in_addr, stat->addr, sizeof(stat->addr) ); |
---|
1540 | strlcpy( stat->client, (peer->client ? peer->client : ""), sizeof(stat->client) ); |
---|
1541 | stat->port = peer->port; |
---|
1542 | stat->from = atom->from; |
---|
1543 | stat->progress = peer->progress; |
---|
1544 | stat->isEncrypted = tr_peerIoIsEncrypted( peer->io ) ? 1 : 0; |
---|
1545 | stat->uploadToRate = peer->rateToPeer; |
---|
1546 | stat->downloadFromRate = peer->rateToClient; |
---|
1547 | stat->peerIsChoked = peer->peerIsChoked; |
---|
1548 | stat->peerIsInterested = peer->peerIsInterested; |
---|
1549 | stat->clientIsChoked = peer->clientIsChoked; |
---|
1550 | stat->clientIsInterested = peer->clientIsInterested; |
---|
1551 | stat->isIncoming = tr_peerIoIsIncoming( peer->io ); |
---|
1552 | stat->isDownloadingFrom = clientIsDownloadingFrom( peer ); |
---|
1553 | stat->isUploadingTo = clientIsUploadingTo( peer ); |
---|
1554 | |
---|
1555 | pch = stat->flagStr; |
---|
1556 | if( t->optimistic == peer ) *pch++ = 'O'; |
---|
1557 | if( stat->isDownloadingFrom ) *pch++ = 'D'; |
---|
1558 | else if( stat->clientIsInterested ) *pch++ = 'd'; |
---|
1559 | if( stat->isUploadingTo ) *pch++ = 'U'; |
---|
1560 | else if( stat->peerIsInterested ) *pch++ = 'u'; |
---|
1561 | if( !stat->clientIsChoked && !stat->clientIsInterested ) *pch++ = 'K'; |
---|
1562 | if( !stat->peerIsChoked && !stat->peerIsInterested ) *pch++ = '?'; |
---|
1563 | if( stat->isEncrypted ) *pch++ = 'E'; |
---|
1564 | if( stat->from == TR_PEER_FROM_PEX ) *pch++ = 'X'; |
---|
1565 | if( stat->isIncoming ) *pch++ = 'I'; |
---|
1566 | *pch = '\0'; |
---|
1567 | } |
---|
1568 | |
---|
1569 | *setmeCount = size; |
---|
1570 | tr_free( peers ); |
---|
1571 | |
---|
1572 | managerUnlock( (tr_peerMgr*)manager ); |
---|
1573 | return ret; |
---|
1574 | } |
---|
1575 | |
---|
1576 | /** |
---|
1577 | *** |
---|
1578 | **/ |
---|
1579 | |
---|
1580 | struct ChokeData |
---|
1581 | { |
---|
1582 | uint8_t doUnchoke; |
---|
1583 | uint8_t isInterested; |
---|
1584 | uint32_t rate; |
---|
1585 | tr_peer * peer; |
---|
1586 | }; |
---|
1587 | |
---|
1588 | static int |
---|
1589 | compareChoke( const void * va, const void * vb ) |
---|
1590 | { |
---|
1591 | const struct ChokeData * a = va; |
---|
1592 | const struct ChokeData * b = vb; |
---|
1593 | return -tr_compareUint32( a->rate, b->rate ); |
---|
1594 | } |
---|
1595 | |
---|
1596 | static int |
---|
1597 | isNew( const tr_peer * peer ) |
---|
1598 | { |
---|
1599 | return peer && peer->io && tr_peerIoGetAge( peer->io ) < 45; |
---|
1600 | } |
---|
1601 | |
---|
1602 | static int |
---|
1603 | isSame( const tr_peer * peer ) |
---|
1604 | { |
---|
1605 | return peer && peer->client && strstr( peer->client, "Transmission" ); |
---|
1606 | } |
---|
1607 | |
---|
1608 | /** |
---|
1609 | *** |
---|
1610 | **/ |
---|
1611 | |
---|
1612 | static double |
---|
1613 | getWeightedRate( const tr_peer * peer, int clientIsSeed ) |
---|
1614 | { |
---|
1615 | return (int)( 10.0 * ( clientIsSeed ? peer->rateToPeer |
---|
1616 | : peer->rateToClient ) ); |
---|
1617 | } |
---|
1618 | |
---|
1619 | static void |
---|
1620 | rechoke( Torrent * t ) |
---|
1621 | { |
---|
1622 | int i, n, peerCount, size, unchokedInterested; |
---|
1623 | tr_peer ** peers = getConnectedPeers( t, &peerCount ); |
---|
1624 | struct ChokeData * choke = tr_new0( struct ChokeData, peerCount ); |
---|
1625 | const int clientIsSeed = tr_torrentIsSeed( t->tor ); |
---|
1626 | |
---|
1627 | assert( torrentIsLocked( t ) ); |
---|
1628 | |
---|
1629 | /* sort the peers by preference and rate */ |
---|
1630 | for( i=0, size=0; i<peerCount; ++i ) |
---|
1631 | { |
---|
1632 | tr_peer * peer = peers[i]; |
---|
1633 | if( peer->progress >= 1.0 ) /* choke all seeds */ |
---|
1634 | tr_peerMsgsSetChoke( peer->msgs, TRUE ); |
---|
1635 | else { |
---|
1636 | struct ChokeData * node = &choke[size++]; |
---|
1637 | node->peer = peer; |
---|
1638 | node->isInterested = peer->peerIsInterested; |
---|
1639 | node->rate = getWeightedRate( peer, clientIsSeed ); |
---|
1640 | } |
---|
1641 | } |
---|
1642 | |
---|
1643 | qsort( choke, size, sizeof(struct ChokeData), compareChoke ); |
---|
1644 | |
---|
1645 | /** |
---|
1646 | * Reciprocation and number of uploads capping is managed by unchoking |
---|
1647 | * the N peers which have the best upload rate and are interested. |
---|
1648 | * This maximizes the client's download rate. These N peers are |
---|
1649 | * referred to as downloaders, because they are interested in downloading |
---|
1650 | * from the client. |
---|
1651 | * |
---|
1652 | * Peers which have a better upload rate (as compared to the downloaders) |
---|
1653 | * but aren't interested get unchoked. If they become interested, the |
---|
1654 | * downloader with the worst upload rate gets choked. If a client has |
---|
1655 | * a complete file, it uses its upload rate rather than its download |
---|
1656 | * rate to decide which peers to unchoke. |
---|
1657 | */ |
---|
1658 | unchokedInterested = 0; |
---|
1659 | for( i=0; i<size && unchokedInterested<MAX_UNCHOKED_PEERS; ++i ) { |
---|
1660 | choke[i].doUnchoke = 1; |
---|
1661 | if( choke[i].isInterested ) |
---|
1662 | ++unchokedInterested; |
---|
1663 | } |
---|
1664 | n = i; |
---|
1665 | while( i<size ) |
---|
1666 | choke[i++].doUnchoke = 0; |
---|
1667 | |
---|
1668 | /* optimistic unchoke */ |
---|
1669 | if( i < size ) |
---|
1670 | { |
---|
1671 | struct ChokeData * c; |
---|
1672 | tr_ptrArray * randPool = tr_ptrArrayNew( ); |
---|
1673 | for( ; i<size; ++i ) |
---|
1674 | { |
---|
1675 | const tr_peer * peer = choke[i].peer; |
---|
1676 | int x=1, y; |
---|
1677 | if( isNew( peer ) ) x *= 3; |
---|
1678 | if( isSame( peer ) ) x *= 3; |
---|
1679 | for( y=0; y<x; ++y ) |
---|
1680 | tr_ptrArrayAppend( randPool, choke ); |
---|
1681 | } |
---|
1682 | i = tr_rand( tr_ptrArraySize( randPool ) ); |
---|
1683 | c = ( struct ChokeData* )tr_ptrArrayNth( randPool, i); |
---|
1684 | c->doUnchoke = 1; |
---|
1685 | t->optimistic = c->peer; |
---|
1686 | tr_ptrArrayFree( randPool, NULL ); |
---|
1687 | } |
---|
1688 | |
---|
1689 | for( i=0; i<size; ++i ) |
---|
1690 | tr_peerMsgsSetChoke( choke[i].peer->msgs, !choke[i].doUnchoke ); |
---|
1691 | |
---|
1692 | /* cleanup */ |
---|
1693 | tr_free( choke ); |
---|
1694 | tr_free( peers ); |
---|
1695 | } |
---|
1696 | |
---|
1697 | static int |
---|
1698 | rechokePulse( void * vtorrent ) |
---|
1699 | { |
---|
1700 | Torrent * t = vtorrent; |
---|
1701 | torrentLock( t ); |
---|
1702 | rechoke( t ); |
---|
1703 | torrentUnlock( t ); |
---|
1704 | return TRUE; |
---|
1705 | } |
---|
1706 | |
---|
1707 | /*** |
---|
1708 | **** |
---|
1709 | ***/ |
---|
1710 | |
---|
1711 | static int |
---|
1712 | swiftPulse( void * vtorrent ) |
---|
1713 | { |
---|
1714 | Torrent * t = vtorrent; |
---|
1715 | torrentLock( t ); |
---|
1716 | |
---|
1717 | if( !tr_torrentIsSeed( t->tor ) ) |
---|
1718 | { |
---|
1719 | int i; |
---|
1720 | int peerCount = 0; |
---|
1721 | int deadbeatCount = 0; |
---|
1722 | tr_peer ** peers = getConnectedPeers( t, &peerCount ); |
---|
1723 | tr_peer ** deadbeats = tr_new( tr_peer*, peerCount ); |
---|
1724 | |
---|
1725 | const double ul_KiBsec = tr_rcRate( t->tor->upload ); |
---|
1726 | const double ul_KiB = ul_KiBsec * (SWIFT_PERIOD_MSEC/1000.0); |
---|
1727 | const double ul_bytes = ul_KiB * 1024; |
---|
1728 | const double freeCreditTotal = ul_bytes * SWIFT_LARGESSE; |
---|
1729 | int freeCreditPerPeer; |
---|
1730 | |
---|
1731 | for( i=0; i<peerCount; ++i ) { |
---|
1732 | tr_peer * peer = peers[i]; |
---|
1733 | if( peer->credit <= 0 ) |
---|
1734 | deadbeats[deadbeatCount++] = peer; |
---|
1735 | } |
---|
1736 | |
---|
1737 | freeCreditPerPeer = (int)( freeCreditTotal / deadbeatCount ); |
---|
1738 | for( i=0; i<deadbeatCount; ++i ) |
---|
1739 | deadbeats[i]->credit = freeCreditPerPeer; |
---|
1740 | |
---|
1741 | tordbg( t, "%d deadbeats, " |
---|
1742 | "who are each being granted %d bytes' credit " |
---|
1743 | "for a total of %.1f KiB, " |
---|
1744 | "%d%% of the torrent's ul speed %.1f\n", |
---|
1745 | deadbeatCount, freeCreditPerPeer, |
---|
1746 | ul_KiBsec*SWIFT_LARGESSE, (int)(SWIFT_LARGESSE*100), ul_KiBsec ); |
---|
1747 | |
---|
1748 | tr_free( deadbeats ); |
---|
1749 | tr_free( peers ); |
---|
1750 | } |
---|
1751 | |
---|
1752 | torrentUnlock( t ); |
---|
1753 | return TRUE; |
---|
1754 | } |
---|
1755 | |
---|
1756 | /*** |
---|
1757 | **** |
---|
1758 | **** Life and Death |
---|
1759 | **** |
---|
1760 | ***/ |
---|
1761 | |
---|
1762 | static int |
---|
1763 | shouldPeerBeClosed( const Torrent * t, const tr_peer * peer, int peerCount ) |
---|
1764 | { |
---|
1765 | const tr_torrent * tor = t->tor; |
---|
1766 | const time_t now = time( NULL ); |
---|
1767 | const struct peer_atom * atom = getExistingAtom( t, &peer->in_addr ); |
---|
1768 | |
---|
1769 | /* if it's marked for purging, close it */ |
---|
1770 | if( peer->doPurge ) { |
---|
1771 | tordbg( t, "purging peer %s because its doPurge flag is set", tr_peerIoAddrStr(&atom->addr,atom->port) ); |
---|
1772 | return TRUE; |
---|
1773 | } |
---|
1774 | |
---|
1775 | /* if we're both seeds and it's been long enough for a pex exchange, close it */ |
---|
1776 | if( 1 ) { |
---|
1777 | const int clientIsSeed = tr_torrentIsSeed( tor ); |
---|
1778 | const int peerIsSeed = atom->flags & ADDED_F_SEED_FLAG; |
---|
1779 | if( peerIsSeed && clientIsSeed && ( !tr_torrentAllowsPex(tor) || (now-atom->time>=30) ) ) { |
---|
1780 | tordbg( t, "purging peer %s because we're both seeds", tr_peerIoAddrStr(&atom->addr,atom->port) ); |
---|
1781 | return TRUE; |
---|
1782 | } |
---|
1783 | } |
---|
1784 | |
---|
1785 | /* disconnect if it's been too long since piece data has been transferred. |
---|
1786 | * this is on a sliding scale based on number of available peers... */ |
---|
1787 | if( 1 ) { |
---|
1788 | const int relaxStrictnessIfFewerThanN = (int)((getMaxPeerCount(tor) * 0.9) + 0.5); |
---|
1789 | /* if we have >= relaxIfFewerThan, strictness is 100%. |
---|
1790 | * if we have zero connections, strictness is 0% */ |
---|
1791 | const double strictness = peerCount >= relaxStrictnessIfFewerThanN |
---|
1792 | ? 1.0 |
---|
1793 | : peerCount / (double)relaxStrictnessIfFewerThanN; |
---|
1794 | const int lo = MIN_UPLOAD_IDLE_SECS; |
---|
1795 | const int hi = MAX_UPLOAD_IDLE_SECS; |
---|
1796 | const int limit = lo + ((hi-lo) * strictness); |
---|
1797 | const time_t then = peer->pieceDataActivityDate; |
---|
1798 | const int idleTime = then ? (now-then) : 0; |
---|
1799 | if( idleTime > limit ) { |
---|
1800 | tordbg( t, "purging peer %s because it's been %d secs since we shared anything", |
---|
1801 | tr_peerIoAddrStr(&atom->addr,atom->port), idleTime ); |
---|
1802 | return TRUE; |
---|
1803 | } |
---|
1804 | } |
---|
1805 | |
---|
1806 | return FALSE; |
---|
1807 | } |
---|
1808 | |
---|
1809 | static tr_peer ** |
---|
1810 | getPeersToClose( Torrent * t, int * setmeSize ) |
---|
1811 | { |
---|
1812 | int i, peerCount, outsize; |
---|
1813 | tr_peer ** peers = (tr_peer**) tr_ptrArrayPeek( t->peers, &peerCount ); |
---|
1814 | struct tr_peer ** ret = tr_new( tr_peer*, peerCount ); |
---|
1815 | |
---|
1816 | assert( torrentIsLocked( t ) ); |
---|
1817 | |
---|
1818 | for( i=outsize=0; i<peerCount; ++i ) |
---|
1819 | if( shouldPeerBeClosed( t, peers[i], peerCount ) ) |
---|
1820 | ret[outsize++] = peers[i]; |
---|
1821 | |
---|
1822 | *setmeSize = outsize; |
---|
1823 | return ret; |
---|
1824 | } |
---|
1825 | |
---|
1826 | static int |
---|
1827 | compareCandidates( const void * va, const void * vb ) |
---|
1828 | { |
---|
1829 | const struct peer_atom * a = * (const struct peer_atom**) va; |
---|
1830 | const struct peer_atom * b = * (const struct peer_atom**) vb; |
---|
1831 | int i; |
---|
1832 | |
---|
1833 | if( a->piece_data_time > b->piece_data_time ) return -1; |
---|
1834 | if( a->piece_data_time < b->piece_data_time ) return 1; |
---|
1835 | |
---|
1836 | if(( i = tr_compareUint16( a->numFails, b->numFails ))) |
---|
1837 | return i; |
---|
1838 | |
---|
1839 | if( a->time != b->time ) |
---|
1840 | return a->time < b->time ? -1 : 1; |
---|
1841 | |
---|
1842 | return 0; |
---|
1843 | } |
---|
1844 | |
---|
1845 | static struct peer_atom ** |
---|
1846 | getPeerCandidates( Torrent * t, int * setmeSize ) |
---|
1847 | { |
---|
1848 | int i, atomCount, retCount; |
---|
1849 | struct peer_atom ** atoms; |
---|
1850 | struct peer_atom ** ret; |
---|
1851 | const time_t now = time( NULL ); |
---|
1852 | const int seed = tr_torrentIsSeed( t->tor ); |
---|
1853 | |
---|
1854 | assert( torrentIsLocked( t ) ); |
---|
1855 | |
---|
1856 | atoms = (struct peer_atom**) tr_ptrArrayPeek( t->pool, &atomCount ); |
---|
1857 | ret = tr_new( struct peer_atom*, atomCount ); |
---|
1858 | for( i=retCount=0; i<atomCount; ++i ) |
---|
1859 | { |
---|
1860 | struct peer_atom * atom = atoms[i]; |
---|
1861 | |
---|
1862 | /* peer fed us too much bad data ... we only keep it around |
---|
1863 | * now to weed it out in case someone sends it to us via pex */ |
---|
1864 | if( atom->myflags & MYFLAG_BANNED ) |
---|
1865 | continue; |
---|
1866 | |
---|
1867 | /* peer was unconnectable before, so we're not going to keep trying. |
---|
1868 | * this is needs a separate flag from `banned', since if they try |
---|
1869 | * to connect to us later, we'll let them in */ |
---|
1870 | if( atom->myflags & MYFLAG_UNREACHABLE ) |
---|
1871 | continue; |
---|
1872 | |
---|
1873 | /* we don't need two connections to the same peer... */ |
---|
1874 | if( peerIsInUse( t, &atom->addr ) ) |
---|
1875 | continue; |
---|
1876 | |
---|
1877 | /* no need to connect if we're both seeds... */ |
---|
1878 | if( seed && (atom->flags & ADDED_F_SEED_FLAG) ) |
---|
1879 | continue; |
---|
1880 | |
---|
1881 | /* we're wasting our time trying to connect to this bozo. */ |
---|
1882 | if( atom->numFails > 3 ) |
---|
1883 | continue; |
---|
1884 | |
---|
1885 | /* If we were connected to this peer recently and transferring |
---|
1886 | * piece data, try to reconnect -- network troubles may have |
---|
1887 | * disconnected us. but if we weren't sharing piece data, |
---|
1888 | * hold off on this peer to give another one a try instead */ |
---|
1889 | if( ( now - atom->piece_data_time ) > 30 ) |
---|
1890 | { |
---|
1891 | int minWait = (60 * 10); /* ten minutes */ |
---|
1892 | int maxWait = (60 * 30); /* thirty minutes */ |
---|
1893 | int wait = atom->numFails * minWait; |
---|
1894 | if( wait < minWait ) wait = minWait; |
---|
1895 | if( wait > maxWait ) wait = maxWait; |
---|
1896 | if( ( now - atom->time ) < wait ) { |
---|
1897 | tordbg( t, "RECONNECT peer %d (%s) is in its grace period of %d seconds..", |
---|
1898 | i, tr_peerIoAddrStr(&atom->addr,atom->port), wait ); |
---|
1899 | continue; |
---|
1900 | } |
---|
1901 | } |
---|
1902 | |
---|
1903 | /* Don't connect to peers in our blocklist */ |
---|
1904 | if( tr_blocklistHasAddress( t->manager->handle, &atom->addr ) ) |
---|
1905 | continue; |
---|
1906 | |
---|
1907 | ret[retCount++] = atom; |
---|
1908 | } |
---|
1909 | |
---|
1910 | qsort( ret, retCount, sizeof(struct peer_atom*), compareCandidates ); |
---|
1911 | *setmeSize = retCount; |
---|
1912 | return ret; |
---|
1913 | } |
---|
1914 | |
---|
1915 | static int |
---|
1916 | reconnectPulse( void * vtorrent ) |
---|
1917 | { |
---|
1918 | Torrent * t = vtorrent; |
---|
1919 | static time_t prevTime = 0; |
---|
1920 | static int newConnectionsThisSecond = 0; |
---|
1921 | time_t now; |
---|
1922 | |
---|
1923 | torrentLock( t ); |
---|
1924 | |
---|
1925 | now = time( NULL ); |
---|
1926 | if( prevTime != now ) |
---|
1927 | { |
---|
1928 | prevTime = now; |
---|
1929 | newConnectionsThisSecond = 0; |
---|
1930 | } |
---|
1931 | |
---|
1932 | if( !t->isRunning ) |
---|
1933 | { |
---|
1934 | removeAllPeers( t ); |
---|
1935 | } |
---|
1936 | else |
---|
1937 | { |
---|
1938 | int i, nCandidates, nBad; |
---|
1939 | struct peer_atom ** candidates = getPeerCandidates( t, &nCandidates ); |
---|
1940 | struct tr_peer ** connections = getPeersToClose( t, &nBad ); |
---|
1941 | |
---|
1942 | if( nBad || nCandidates ) |
---|
1943 | tordbg( t, "reconnect pulse for [%s]: %d bad connections, " |
---|
1944 | "%d connection candidates, %d atoms, max per pulse is %d", |
---|
1945 | t->tor->info.name, nBad, nCandidates, |
---|
1946 | tr_ptrArraySize(t->pool), |
---|
1947 | (int)MAX_RECONNECTIONS_PER_PULSE ); |
---|
1948 | |
---|
1949 | /* disconnect some peers. |
---|
1950 | if we got transferred piece data, then they might be good peers, |
---|
1951 | so reset their `numFails' weight to zero. otherwise we connected |
---|
1952 | to them fruitlessly, so mark it as another fail */ |
---|
1953 | for( i=0; i<nBad; ++i ) { |
---|
1954 | tr_peer * peer = connections[i]; |
---|
1955 | struct peer_atom * atom = getExistingAtom( t, &peer->in_addr ); |
---|
1956 | if( peer->pieceDataActivityDate ) |
---|
1957 | atom->numFails = 0; |
---|
1958 | else |
---|
1959 | ++atom->numFails; |
---|
1960 | removePeer( t, peer ); |
---|
1961 | } |
---|
1962 | |
---|
1963 | /* add some new ones */ |
---|
1964 | for( i=0; i < nCandidates |
---|
1965 | && i < MAX_RECONNECTIONS_PER_PULSE |
---|
1966 | && newConnectionsThisSecond < MAX_CONNECTIONS_PER_SECOND; ++i ) |
---|
1967 | { |
---|
1968 | tr_peerMgr * mgr = t->manager; |
---|
1969 | struct peer_atom * atom = candidates[i]; |
---|
1970 | tr_peerIo * io; |
---|
1971 | |
---|
1972 | tordbg( t, "Starting an OUTGOING connection with %s", |
---|
1973 | tr_peerIoAddrStr( &atom->addr, atom->port ) ); |
---|
1974 | |
---|
1975 | io = tr_peerIoNewOutgoing( mgr->handle, &atom->addr, atom->port, t->hash ); |
---|
1976 | if( io == NULL ) |
---|
1977 | { |
---|
1978 | atom->myflags |= MYFLAG_UNREACHABLE; |
---|
1979 | } |
---|
1980 | else |
---|
1981 | { |
---|
1982 | tr_handshake * handshake = tr_handshakeNew( io, |
---|
1983 | mgr->handle->encryptionMode, |
---|
1984 | myHandshakeDoneCB, |
---|
1985 | mgr ); |
---|
1986 | |
---|
1987 | assert( tr_peerIoGetTorrentHash( io ) != NULL ); |
---|
1988 | |
---|
1989 | ++newConnectionsThisSecond; |
---|
1990 | |
---|
1991 | tr_ptrArrayInsertSorted( t->outgoingHandshakes, handshake, handshakeCompare ); |
---|
1992 | } |
---|
1993 | |
---|
1994 | atom->time = time( NULL ); |
---|
1995 | } |
---|
1996 | |
---|
1997 | /* cleanup */ |
---|
1998 | tr_free( connections ); |
---|
1999 | tr_free( candidates ); |
---|
2000 | } |
---|
2001 | |
---|
2002 | torrentUnlock( t ); |
---|
2003 | return TRUE; |
---|
2004 | } |
---|