1 | /* |
---|
2 | * This file Copyright (C) 2007-2009 Charles Kerr <charles@transmissionbt.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 9544 2009-11-22 03:57:36Z charles $ |
---|
11 | */ |
---|
12 | |
---|
13 | #include <assert.h> |
---|
14 | #include <errno.h> |
---|
15 | #include <string.h> /* memcpy, memcmp, strstr */ |
---|
16 | #include <stdlib.h> /* qsort */ |
---|
17 | #include <limits.h> /* INT_MAX */ |
---|
18 | |
---|
19 | #include <event.h> |
---|
20 | |
---|
21 | #include "transmission.h" |
---|
22 | #include "bandwidth.h" |
---|
23 | #include "bencode.h" |
---|
24 | #include "blocklist.h" |
---|
25 | #include "clients.h" |
---|
26 | #include "completion.h" |
---|
27 | #include "crypto.h" |
---|
28 | #include "handshake.h" |
---|
29 | #include "inout.h" /* tr_ioTestPiece */ |
---|
30 | #include "net.h" |
---|
31 | #include "peer-io.h" |
---|
32 | #include "peer-mgr.h" |
---|
33 | #include "peer-msgs.h" |
---|
34 | #include "ptrarray.h" |
---|
35 | #include "session.h" |
---|
36 | #include "stats.h" /* tr_statsAddUploaded, tr_statsAddDownloaded */ |
---|
37 | #include "torrent.h" |
---|
38 | #include "trevent.h" |
---|
39 | #include "utils.h" |
---|
40 | #include "webseed.h" |
---|
41 | |
---|
42 | enum |
---|
43 | { |
---|
44 | /* how frequently to change which peers are choked */ |
---|
45 | RECHOKE_PERIOD_MSEC = ( 10 * 1000 ), |
---|
46 | |
---|
47 | /* minimum interval for refilling peers' request lists */ |
---|
48 | REFILL_PERIOD_MSEC = 400, |
---|
49 | |
---|
50 | /* how frequently to reallocate bandwidth */ |
---|
51 | BANDWIDTH_PERIOD_MSEC = 500, |
---|
52 | |
---|
53 | /* how frequently to age out old piece request lists */ |
---|
54 | REFILL_UPKEEP_PERIOD_MSEC = ( 10 * 1000 ), |
---|
55 | |
---|
56 | /* how frequently to decide which peers live and die */ |
---|
57 | RECONNECT_PERIOD_MSEC = 500, |
---|
58 | |
---|
59 | /* when many peers are available, keep idle ones this long */ |
---|
60 | MIN_UPLOAD_IDLE_SECS = ( 60 ), |
---|
61 | |
---|
62 | /* when few peers are available, keep idle ones this long */ |
---|
63 | MAX_UPLOAD_IDLE_SECS = ( 60 * 5 ), |
---|
64 | |
---|
65 | /* max # of peers to ask fer per torrent per reconnect pulse */ |
---|
66 | MAX_RECONNECTIONS_PER_PULSE = 8, |
---|
67 | |
---|
68 | /* max number of peers to ask for per second overall. |
---|
69 | * this throttle is to avoid overloading the router */ |
---|
70 | MAX_CONNECTIONS_PER_SECOND = 16, |
---|
71 | |
---|
72 | /* number of bad pieces a peer is allowed to send before we ban them */ |
---|
73 | MAX_BAD_PIECES_PER_PEER = 5, |
---|
74 | |
---|
75 | /* amount of time to keep a list of request pieces lying around |
---|
76 | before it's considered too old and needs to be rebuilt */ |
---|
77 | PIECE_LIST_SHELF_LIFE_SECS = 60, |
---|
78 | |
---|
79 | /* use for bitwise operations w/peer_atom.myflags */ |
---|
80 | MYFLAG_BANNED = 1, |
---|
81 | |
---|
82 | /* use for bitwise operations w/peer_atom.myflags */ |
---|
83 | /* unreachable for now... but not banned. |
---|
84 | * if they try to connect to us it's okay */ |
---|
85 | MYFLAG_UNREACHABLE = 2, |
---|
86 | |
---|
87 | /* the minimum we'll wait before attempting to reconnect to a peer */ |
---|
88 | MINIMUM_RECONNECT_INTERVAL_SECS = 5 |
---|
89 | }; |
---|
90 | |
---|
91 | |
---|
92 | /** |
---|
93 | *** |
---|
94 | **/ |
---|
95 | |
---|
96 | enum |
---|
97 | { |
---|
98 | UPLOAD_ONLY_UKNOWN, |
---|
99 | UPLOAD_ONLY_YES, |
---|
100 | UPLOAD_ONLY_NO |
---|
101 | }; |
---|
102 | |
---|
103 | /** |
---|
104 | * Peer information that should be kept even before we've connected and |
---|
105 | * after we've disconnected. These are kept in a pool of peer_atoms to decide |
---|
106 | * which ones would make good candidates for connecting to, and to watch out |
---|
107 | * for banned peers. |
---|
108 | * |
---|
109 | * @see tr_peer |
---|
110 | * @see tr_peermsgs |
---|
111 | */ |
---|
112 | struct peer_atom |
---|
113 | { |
---|
114 | uint8_t from; |
---|
115 | uint8_t flags; /* these match the added_f flags */ |
---|
116 | uint8_t myflags; /* flags that aren't defined in added_f */ |
---|
117 | uint8_t uploadOnly; /* UPLOAD_ONLY_ */ |
---|
118 | tr_port port; |
---|
119 | uint16_t numFails; |
---|
120 | tr_address addr; |
---|
121 | time_t time; /* when the peer's connection status last changed */ |
---|
122 | time_t piece_data_time; |
---|
123 | }; |
---|
124 | |
---|
125 | static tr_bool |
---|
126 | tr_isAtom( const struct peer_atom * atom ) |
---|
127 | { |
---|
128 | return ( atom != NULL ) |
---|
129 | && ( atom->from < TR_PEER_FROM__MAX ) |
---|
130 | && ( tr_isAddress( &atom->addr ) ); |
---|
131 | } |
---|
132 | |
---|
133 | static const char* |
---|
134 | tr_atomAddrStr( const struct peer_atom * atom ) |
---|
135 | { |
---|
136 | return tr_peerIoAddrStr( &atom->addr, atom->port ); |
---|
137 | } |
---|
138 | |
---|
139 | struct block_request |
---|
140 | { |
---|
141 | tr_block_index_t block; |
---|
142 | tr_peer * peer; |
---|
143 | time_t sentAt; |
---|
144 | }; |
---|
145 | |
---|
146 | struct weighted_piece |
---|
147 | { |
---|
148 | tr_piece_index_t index; |
---|
149 | int16_t salt; |
---|
150 | int16_t requestCount; |
---|
151 | }; |
---|
152 | |
---|
153 | typedef struct tr_torrent_peers |
---|
154 | { |
---|
155 | struct event refillTimer; |
---|
156 | |
---|
157 | tr_ptrArray outgoingHandshakes; /* tr_handshake */ |
---|
158 | tr_ptrArray pool; /* struct peer_atom */ |
---|
159 | tr_ptrArray peers; /* tr_peer */ |
---|
160 | tr_ptrArray webseeds; /* tr_webseed */ |
---|
161 | |
---|
162 | tr_torrent * tor; |
---|
163 | tr_peer * optimistic; /* the optimistic peer, or NULL if none */ |
---|
164 | struct tr_peerMgr * manager; |
---|
165 | //int * pendingRequestCount; |
---|
166 | |
---|
167 | tr_bool isRunning; |
---|
168 | tr_bool needsCompletenessCheck; |
---|
169 | |
---|
170 | struct block_request * requests; |
---|
171 | int requestsSort; |
---|
172 | int requestCount; |
---|
173 | int requestAlloc; |
---|
174 | |
---|
175 | struct weighted_piece * pieces; |
---|
176 | int piecesSort; |
---|
177 | int pieceCount; |
---|
178 | |
---|
179 | tr_bool isInEndgame; |
---|
180 | } |
---|
181 | Torrent; |
---|
182 | |
---|
183 | struct tr_peerMgr |
---|
184 | { |
---|
185 | tr_session * session; |
---|
186 | tr_ptrArray incomingHandshakes; /* tr_handshake */ |
---|
187 | tr_timer * bandwidthTimer; |
---|
188 | tr_timer * rechokeTimer; |
---|
189 | tr_timer * reconnectTimer; |
---|
190 | tr_timer * refillUpkeepTimer; |
---|
191 | }; |
---|
192 | |
---|
193 | #define tordbg( t, ... ) \ |
---|
194 | do { \ |
---|
195 | if( tr_deepLoggingIsActive( ) ) \ |
---|
196 | tr_deepLog( __FILE__, __LINE__, tr_torrentName( t->tor ), __VA_ARGS__ ); \ |
---|
197 | } while( 0 ) |
---|
198 | |
---|
199 | #define dbgmsg( ... ) \ |
---|
200 | do { \ |
---|
201 | if( tr_deepLoggingIsActive( ) ) \ |
---|
202 | tr_deepLog( __FILE__, __LINE__, NULL, __VA_ARGS__ ); \ |
---|
203 | } while( 0 ) |
---|
204 | |
---|
205 | /** |
---|
206 | *** |
---|
207 | **/ |
---|
208 | |
---|
209 | static TR_INLINE void |
---|
210 | managerLock( const struct tr_peerMgr * manager ) |
---|
211 | { |
---|
212 | tr_globalLock( manager->session ); |
---|
213 | } |
---|
214 | |
---|
215 | static TR_INLINE void |
---|
216 | managerUnlock( const struct tr_peerMgr * manager ) |
---|
217 | { |
---|
218 | tr_globalUnlock( manager->session ); |
---|
219 | } |
---|
220 | |
---|
221 | static TR_INLINE void |
---|
222 | torrentLock( Torrent * torrent ) |
---|
223 | { |
---|
224 | managerLock( torrent->manager ); |
---|
225 | } |
---|
226 | |
---|
227 | static TR_INLINE void |
---|
228 | torrentUnlock( Torrent * torrent ) |
---|
229 | { |
---|
230 | managerUnlock( torrent->manager ); |
---|
231 | } |
---|
232 | |
---|
233 | static TR_INLINE int |
---|
234 | torrentIsLocked( const Torrent * t ) |
---|
235 | { |
---|
236 | return tr_globalIsLocked( t->manager->session ); |
---|
237 | } |
---|
238 | |
---|
239 | /** |
---|
240 | *** |
---|
241 | **/ |
---|
242 | |
---|
243 | static int |
---|
244 | handshakeCompareToAddr( const void * va, const void * vb ) |
---|
245 | { |
---|
246 | const tr_handshake * a = va; |
---|
247 | |
---|
248 | return tr_compareAddresses( tr_handshakeGetAddr( a, NULL ), vb ); |
---|
249 | } |
---|
250 | |
---|
251 | static int |
---|
252 | handshakeCompare( const void * a, const void * b ) |
---|
253 | { |
---|
254 | return handshakeCompareToAddr( a, tr_handshakeGetAddr( b, NULL ) ); |
---|
255 | } |
---|
256 | |
---|
257 | static tr_handshake* |
---|
258 | getExistingHandshake( tr_ptrArray * handshakes, |
---|
259 | const tr_address * addr ) |
---|
260 | { |
---|
261 | return tr_ptrArrayFindSorted( handshakes, addr, handshakeCompareToAddr ); |
---|
262 | } |
---|
263 | |
---|
264 | static int |
---|
265 | comparePeerAtomToAddress( const void * va, const void * vb ) |
---|
266 | { |
---|
267 | const struct peer_atom * a = va; |
---|
268 | |
---|
269 | return tr_compareAddresses( &a->addr, vb ); |
---|
270 | } |
---|
271 | |
---|
272 | static int |
---|
273 | comparePeerAtoms( const void * va, const void * vb ) |
---|
274 | { |
---|
275 | const struct peer_atom * b = vb; |
---|
276 | |
---|
277 | assert( tr_isAtom( b ) ); |
---|
278 | |
---|
279 | return comparePeerAtomToAddress( va, &b->addr ); |
---|
280 | } |
---|
281 | |
---|
282 | /** |
---|
283 | *** |
---|
284 | **/ |
---|
285 | |
---|
286 | const tr_address * |
---|
287 | tr_peerAddress( const tr_peer * peer ) |
---|
288 | { |
---|
289 | return &peer->atom->addr; |
---|
290 | } |
---|
291 | |
---|
292 | static Torrent* |
---|
293 | getExistingTorrent( tr_peerMgr * manager, |
---|
294 | const uint8_t * hash ) |
---|
295 | { |
---|
296 | tr_torrent * tor = tr_torrentFindFromHash( manager->session, hash ); |
---|
297 | |
---|
298 | return tor == NULL ? NULL : tor->torrentPeers; |
---|
299 | } |
---|
300 | |
---|
301 | static int |
---|
302 | peerCompare( const void * a, const void * b ) |
---|
303 | { |
---|
304 | return tr_compareAddresses( tr_peerAddress( a ), tr_peerAddress( b ) ); |
---|
305 | } |
---|
306 | |
---|
307 | static int |
---|
308 | peerCompareToAddr( const void * a, const void * vb ) |
---|
309 | { |
---|
310 | return tr_compareAddresses( tr_peerAddress( a ), vb ); |
---|
311 | } |
---|
312 | |
---|
313 | static tr_peer* |
---|
314 | getExistingPeer( Torrent * torrent, |
---|
315 | const tr_address * addr ) |
---|
316 | { |
---|
317 | assert( torrentIsLocked( torrent ) ); |
---|
318 | assert( addr ); |
---|
319 | |
---|
320 | return tr_ptrArrayFindSorted( &torrent->peers, addr, peerCompareToAddr ); |
---|
321 | } |
---|
322 | |
---|
323 | static struct peer_atom* |
---|
324 | getExistingAtom( const Torrent * t, |
---|
325 | const tr_address * addr ) |
---|
326 | { |
---|
327 | Torrent * tt = (Torrent*)t; |
---|
328 | assert( torrentIsLocked( t ) ); |
---|
329 | return tr_ptrArrayFindSorted( &tt->pool, addr, comparePeerAtomToAddress ); |
---|
330 | } |
---|
331 | |
---|
332 | static tr_bool |
---|
333 | peerIsInUse( const Torrent * ct, |
---|
334 | const tr_address * addr ) |
---|
335 | { |
---|
336 | Torrent * t = (Torrent*) ct; |
---|
337 | |
---|
338 | assert( torrentIsLocked ( t ) ); |
---|
339 | |
---|
340 | return getExistingPeer( t, addr ) |
---|
341 | || getExistingHandshake( &t->outgoingHandshakes, addr ) |
---|
342 | || getExistingHandshake( &t->manager->incomingHandshakes, addr ); |
---|
343 | } |
---|
344 | |
---|
345 | static tr_peer* |
---|
346 | peerConstructor( struct peer_atom * atom ) |
---|
347 | { |
---|
348 | tr_peer * peer = tr_new0( tr_peer, 1 ); |
---|
349 | peer->atom = atom; |
---|
350 | return peer; |
---|
351 | } |
---|
352 | |
---|
353 | static tr_peer* |
---|
354 | getPeer( Torrent * torrent, struct peer_atom * atom ) |
---|
355 | { |
---|
356 | tr_peer * peer; |
---|
357 | |
---|
358 | assert( torrentIsLocked( torrent ) ); |
---|
359 | |
---|
360 | peer = getExistingPeer( torrent, &atom->addr ); |
---|
361 | |
---|
362 | if( peer == NULL ) |
---|
363 | { |
---|
364 | peer = peerConstructor( atom ); |
---|
365 | tr_ptrArrayInsertSorted( &torrent->peers, peer, peerCompare ); |
---|
366 | } |
---|
367 | |
---|
368 | return peer; |
---|
369 | } |
---|
370 | |
---|
371 | static void peerDeclinedAllRequests( Torrent *, const tr_peer * ); |
---|
372 | |
---|
373 | static void |
---|
374 | peerDestructor( Torrent * t, tr_peer * peer ) |
---|
375 | { |
---|
376 | assert( peer != NULL ); |
---|
377 | |
---|
378 | peerDeclinedAllRequests( t, peer ); |
---|
379 | |
---|
380 | if( peer->msgs != NULL ) |
---|
381 | { |
---|
382 | tr_peerMsgsUnsubscribe( peer->msgs, peer->msgsTag ); |
---|
383 | tr_peerMsgsFree( peer->msgs ); |
---|
384 | } |
---|
385 | |
---|
386 | tr_peerIoClear( peer->io ); |
---|
387 | tr_peerIoUnref( peer->io ); /* balanced by the ref in handshakeDoneCB() */ |
---|
388 | |
---|
389 | tr_bitfieldFree( peer->have ); |
---|
390 | tr_bitfieldFree( peer->blame ); |
---|
391 | tr_free( peer->client ); |
---|
392 | |
---|
393 | tr_free( peer ); |
---|
394 | } |
---|
395 | |
---|
396 | static void |
---|
397 | removePeer( Torrent * t, tr_peer * peer ) |
---|
398 | { |
---|
399 | tr_peer * removed; |
---|
400 | struct peer_atom * atom = peer->atom; |
---|
401 | |
---|
402 | assert( torrentIsLocked( t ) ); |
---|
403 | assert( atom ); |
---|
404 | |
---|
405 | atom->time = time( NULL ); |
---|
406 | |
---|
407 | removed = tr_ptrArrayRemoveSorted( &t->peers, peer, peerCompare ); |
---|
408 | assert( removed == peer ); |
---|
409 | peerDestructor( t, removed ); |
---|
410 | } |
---|
411 | |
---|
412 | static void |
---|
413 | removeAllPeers( Torrent * t ) |
---|
414 | { |
---|
415 | while( !tr_ptrArrayEmpty( &t->peers ) ) |
---|
416 | removePeer( t, tr_ptrArrayNth( &t->peers, 0 ) ); |
---|
417 | } |
---|
418 | |
---|
419 | static void |
---|
420 | torrentDestructor( void * vt ) |
---|
421 | { |
---|
422 | Torrent * t = vt; |
---|
423 | |
---|
424 | assert( t ); |
---|
425 | assert( !t->isRunning ); |
---|
426 | assert( torrentIsLocked( t ) ); |
---|
427 | assert( tr_ptrArrayEmpty( &t->outgoingHandshakes ) ); |
---|
428 | assert( tr_ptrArrayEmpty( &t->peers ) ); |
---|
429 | |
---|
430 | evtimer_del( &t->refillTimer ); |
---|
431 | |
---|
432 | tr_ptrArrayDestruct( &t->webseeds, (PtrArrayForeachFunc)tr_webseedFree ); |
---|
433 | tr_ptrArrayDestruct( &t->pool, (PtrArrayForeachFunc)tr_free ); |
---|
434 | tr_ptrArrayDestruct( &t->outgoingHandshakes, NULL ); |
---|
435 | tr_ptrArrayDestruct( &t->peers, NULL ); |
---|
436 | |
---|
437 | tr_free( t->requests ); |
---|
438 | tr_free( t->pieces ); |
---|
439 | tr_free( t ); |
---|
440 | } |
---|
441 | |
---|
442 | |
---|
443 | //static void refillPulse( int, short, void* ); |
---|
444 | |
---|
445 | static void peerCallbackFunc( void * vpeer, |
---|
446 | void * vevent, |
---|
447 | void * vt ); |
---|
448 | |
---|
449 | static Torrent* |
---|
450 | torrentConstructor( tr_peerMgr * manager, |
---|
451 | tr_torrent * tor ) |
---|
452 | { |
---|
453 | int i; |
---|
454 | Torrent * t; |
---|
455 | |
---|
456 | t = tr_new0( Torrent, 1 ); |
---|
457 | t->manager = manager; |
---|
458 | t->tor = tor; |
---|
459 | t->pool = TR_PTR_ARRAY_INIT; |
---|
460 | t->peers = TR_PTR_ARRAY_INIT; |
---|
461 | t->webseeds = TR_PTR_ARRAY_INIT; |
---|
462 | t->outgoingHandshakes = TR_PTR_ARRAY_INIT; |
---|
463 | t->requests = 0; |
---|
464 | //evtimer_set( &t->refillTimer, refillPulse, t ); |
---|
465 | |
---|
466 | |
---|
467 | for( i = 0; i < tor->info.webseedCount; ++i ) |
---|
468 | { |
---|
469 | tr_webseed * w = |
---|
470 | tr_webseedNew( tor, tor->info.webseeds[i], peerCallbackFunc, t ); |
---|
471 | tr_ptrArrayAppend( &t->webseeds, w ); |
---|
472 | } |
---|
473 | |
---|
474 | return t; |
---|
475 | } |
---|
476 | |
---|
477 | |
---|
478 | static int bandwidthPulse ( void * vmgr ); |
---|
479 | static int rechokePulse ( void * vmgr ); |
---|
480 | static int reconnectPulse ( void * vmgr ); |
---|
481 | static int refillUpkeep ( void * vmgr ); |
---|
482 | |
---|
483 | tr_peerMgr* |
---|
484 | tr_peerMgrNew( tr_session * session ) |
---|
485 | { |
---|
486 | tr_peerMgr * m = tr_new0( tr_peerMgr, 1 ); |
---|
487 | m->session = session; |
---|
488 | m->incomingHandshakes = TR_PTR_ARRAY_INIT; |
---|
489 | return m; |
---|
490 | } |
---|
491 | |
---|
492 | static void |
---|
493 | deleteTimers( struct tr_peerMgr * m ) |
---|
494 | { |
---|
495 | if( m->bandwidthTimer ) |
---|
496 | tr_timerFree( &m->bandwidthTimer ); |
---|
497 | |
---|
498 | if( m->rechokeTimer ) |
---|
499 | tr_timerFree( &m->rechokeTimer ); |
---|
500 | |
---|
501 | if( m->reconnectTimer ) |
---|
502 | tr_timerFree( &m->reconnectTimer ); |
---|
503 | |
---|
504 | if( m->refillUpkeepTimer ) |
---|
505 | tr_timerFree( &m->refillUpkeepTimer ); |
---|
506 | } |
---|
507 | |
---|
508 | void |
---|
509 | tr_peerMgrFree( tr_peerMgr * manager ) |
---|
510 | { |
---|
511 | managerLock( manager ); |
---|
512 | |
---|
513 | deleteTimers( manager ); |
---|
514 | |
---|
515 | /* free the handshakes. Abort invokes handshakeDoneCB(), which removes |
---|
516 | * the item from manager->handshakes, so this is a little roundabout... */ |
---|
517 | while( !tr_ptrArrayEmpty( &manager->incomingHandshakes ) ) |
---|
518 | tr_handshakeAbort( tr_ptrArrayNth( &manager->incomingHandshakes, 0 ) ); |
---|
519 | |
---|
520 | tr_ptrArrayDestruct( &manager->incomingHandshakes, NULL ); |
---|
521 | |
---|
522 | managerUnlock( manager ); |
---|
523 | tr_free( manager ); |
---|
524 | } |
---|
525 | |
---|
526 | static int |
---|
527 | clientIsDownloadingFrom( const tr_peer * peer ) |
---|
528 | { |
---|
529 | return peer->clientIsInterested && !peer->clientIsChoked; |
---|
530 | } |
---|
531 | |
---|
532 | static int |
---|
533 | clientIsUploadingTo( const tr_peer * peer ) |
---|
534 | { |
---|
535 | return peer->peerIsInterested && !peer->peerIsChoked; |
---|
536 | } |
---|
537 | |
---|
538 | /*** |
---|
539 | **** |
---|
540 | ***/ |
---|
541 | |
---|
542 | tr_bool |
---|
543 | tr_peerMgrPeerIsSeed( const tr_torrent * tor, |
---|
544 | const tr_address * addr ) |
---|
545 | { |
---|
546 | tr_bool isSeed = FALSE; |
---|
547 | const Torrent * t = tor->torrentPeers; |
---|
548 | const struct peer_atom * atom = getExistingAtom( t, addr ); |
---|
549 | |
---|
550 | if( atom ) |
---|
551 | isSeed = ( atom->flags & ADDED_F_SEED_FLAG ) != 0; |
---|
552 | |
---|
553 | return isSeed; |
---|
554 | } |
---|
555 | |
---|
556 | /** |
---|
557 | *** REQUESTS |
---|
558 | *** |
---|
559 | *** There are two data structures associated with managing block requests: |
---|
560 | *** |
---|
561 | *** 1. Torrent::requests, an array of "struct block_request" which keeps |
---|
562 | *** track of which blocks have been requested, and when, and by which peers. |
---|
563 | *** This is list is used for (a) cancelling requests that have been pending |
---|
564 | *** for too long and (b) avoiding duplicate requests before endgame. |
---|
565 | *** |
---|
566 | *** 2. Torrent::pieces, an array of "struct weighted_piece" which lists the |
---|
567 | *** pieces that we want to request. It's used to decide which pieces to |
---|
568 | *** return next when tr_peerMgrGetBlockRequests() is called. |
---|
569 | **/ |
---|
570 | |
---|
571 | /** |
---|
572 | *** struct block_request |
---|
573 | **/ |
---|
574 | |
---|
575 | enum |
---|
576 | { |
---|
577 | REQ_UNSORTED, |
---|
578 | REQ_SORTED_BY_BLOCK, |
---|
579 | REQ_SORTED_BY_TIME |
---|
580 | }; |
---|
581 | |
---|
582 | static int |
---|
583 | compareReqByBlock( const void * va, const void * vb ) |
---|
584 | { |
---|
585 | const struct block_request * a = va; |
---|
586 | const struct block_request * b = vb; |
---|
587 | if( a->block < b->block ) return -1; |
---|
588 | if( a->block > b->block ) return 1; |
---|
589 | return 0; |
---|
590 | } |
---|
591 | |
---|
592 | static int |
---|
593 | compareReqByTime( const void * va, const void * vb ) |
---|
594 | { |
---|
595 | const struct block_request * a = va; |
---|
596 | const struct block_request * b = vb; |
---|
597 | if( a->sentAt < b->sentAt ) return -1; |
---|
598 | if( a->sentAt > b->sentAt ) return 1; |
---|
599 | return 0; |
---|
600 | } |
---|
601 | |
---|
602 | static void |
---|
603 | requestListSort( Torrent * t, int mode ) |
---|
604 | { |
---|
605 | assert( mode==REQ_SORTED_BY_BLOCK || mode==REQ_SORTED_BY_TIME ); |
---|
606 | |
---|
607 | if( t->requestsSort != mode ) |
---|
608 | { |
---|
609 | int(*compar)(const void *, const void *); |
---|
610 | |
---|
611 | t->requestsSort = mode; |
---|
612 | |
---|
613 | switch( mode ) { |
---|
614 | case REQ_SORTED_BY_BLOCK: compar = compareReqByBlock; break; |
---|
615 | case REQ_SORTED_BY_TIME: compar = compareReqByTime; break; |
---|
616 | default: assert( 0 && "unhandled" ); |
---|
617 | } |
---|
618 | |
---|
619 | //fprintf( stderr, "sorting requests by %s\n", (mode==REQ_SORTED_BY_BLOCK)?"block":"time" ); |
---|
620 | qsort( t->requests, t->requestCount, |
---|
621 | sizeof( struct block_request ), compar ); |
---|
622 | } |
---|
623 | } |
---|
624 | |
---|
625 | static void |
---|
626 | requestListAdd( Torrent * t, const time_t now, tr_block_index_t block, tr_peer * peer ) |
---|
627 | { |
---|
628 | struct block_request key; |
---|
629 | |
---|
630 | /* ensure enough room is available... */ |
---|
631 | if( t->requestCount + 1 >= t->requestAlloc ) |
---|
632 | { |
---|
633 | const int CHUNK_SIZE = 128; |
---|
634 | t->requestAlloc += CHUNK_SIZE; |
---|
635 | t->requests = tr_renew( struct block_request, |
---|
636 | t->requests, t->requestAlloc ); |
---|
637 | } |
---|
638 | |
---|
639 | /* populate the record we're inserting */ |
---|
640 | key.block = block; |
---|
641 | key.peer = peer; |
---|
642 | key.sentAt = now; |
---|
643 | |
---|
644 | /* insert the request to our array... */ |
---|
645 | switch( t->requestsSort ) |
---|
646 | { |
---|
647 | case REQ_UNSORTED: |
---|
648 | case REQ_SORTED_BY_TIME: |
---|
649 | t->requests[t->requestCount++] = key; |
---|
650 | break; |
---|
651 | |
---|
652 | case REQ_SORTED_BY_BLOCK: { |
---|
653 | tr_bool exact; |
---|
654 | const int pos = tr_lowerBound( &key, t->requests, t->requestCount, |
---|
655 | sizeof( struct block_request ), |
---|
656 | compareReqByBlock, &exact ); |
---|
657 | assert( !exact ); |
---|
658 | memmove( t->requests + pos + 1, |
---|
659 | t->requests + pos, |
---|
660 | sizeof( struct block_request ) * ( t->requestCount++ - pos ) ); |
---|
661 | t->requests[pos] = key; |
---|
662 | break; |
---|
663 | } |
---|
664 | } |
---|
665 | } |
---|
666 | |
---|
667 | static struct block_request * |
---|
668 | requestListLookup( Torrent * t, tr_block_index_t block ) |
---|
669 | { |
---|
670 | struct block_request key; |
---|
671 | key.block = block; |
---|
672 | |
---|
673 | requestListSort( t, REQ_SORTED_BY_BLOCK ); |
---|
674 | |
---|
675 | return bsearch( &key, t->requests, t->requestCount, |
---|
676 | sizeof( struct block_request ), |
---|
677 | compareReqByBlock ); |
---|
678 | } |
---|
679 | |
---|
680 | static void |
---|
681 | requestListRemove( Torrent * t, tr_block_index_t block ) |
---|
682 | { |
---|
683 | const struct block_request * b = requestListLookup( t, block ); |
---|
684 | if( b != NULL ) |
---|
685 | { |
---|
686 | const int pos = b - t->requests; |
---|
687 | assert( pos < t->requestCount ); |
---|
688 | memmove( t->requests + pos, |
---|
689 | t->requests + pos + 1, |
---|
690 | sizeof( struct block_request ) * ( --t->requestCount - pos ) ); |
---|
691 | } |
---|
692 | } |
---|
693 | |
---|
694 | /** |
---|
695 | *** struct weighted_piece |
---|
696 | **/ |
---|
697 | |
---|
698 | enum |
---|
699 | { |
---|
700 | PIECES_UNSORTED, |
---|
701 | PIECES_SORTED_BY_INDEX, |
---|
702 | PIECES_SORTED_BY_WEIGHT |
---|
703 | }; |
---|
704 | |
---|
705 | const tr_torrent * weightTorrent; |
---|
706 | |
---|
707 | /* we try to create a "weight" s.t. high-priority pieces come before others, |
---|
708 | * and that partially-complete pieces come before empty ones. */ |
---|
709 | static int |
---|
710 | comparePieceByWeight( const void * va, const void * vb ) |
---|
711 | { |
---|
712 | const struct weighted_piece * a = va; |
---|
713 | const struct weighted_piece * b = vb; |
---|
714 | int ia, ib, missing, pending; |
---|
715 | const tr_torrent * tor = weightTorrent; |
---|
716 | |
---|
717 | /* primary key: weight */ |
---|
718 | missing = tr_cpMissingBlocksInPiece( &tor->completion, a->index ); |
---|
719 | pending = a->requestCount; |
---|
720 | ia = missing > pending ? missing - pending : (int)(tor->blockCountInPiece + pending); |
---|
721 | missing = tr_cpMissingBlocksInPiece( &tor->completion, b->index ); |
---|
722 | pending = b->requestCount; |
---|
723 | ib = missing > pending ? missing - pending : (int)(tor->blockCountInPiece + pending); |
---|
724 | if( ia < ib ) return -1; |
---|
725 | if( ia > ib ) return 1; |
---|
726 | |
---|
727 | /* secondary key: higher priorities go first */ |
---|
728 | ia = tor->info.pieces[a->index].priority; |
---|
729 | ib = tor->info.pieces[b->index].priority; |
---|
730 | if( ia > ib ) return -1; |
---|
731 | if( ia < ib ) return 1; |
---|
732 | |
---|
733 | /* tertiary key: random */ |
---|
734 | return a->salt - b->salt; |
---|
735 | } |
---|
736 | |
---|
737 | static int |
---|
738 | comparePieceByIndex( const void * va, const void * vb ) |
---|
739 | { |
---|
740 | const struct weighted_piece * a = va; |
---|
741 | const struct weighted_piece * b = vb; |
---|
742 | if( a->index < b->index ) return -1; |
---|
743 | if( a->index > b->index ) return 1; |
---|
744 | return 0; |
---|
745 | } |
---|
746 | |
---|
747 | static void |
---|
748 | pieceListSort( Torrent * t, int mode ) |
---|
749 | { |
---|
750 | int(*compar)(const void *, const void *); |
---|
751 | |
---|
752 | assert( mode==PIECES_SORTED_BY_INDEX |
---|
753 | || mode==PIECES_SORTED_BY_WEIGHT ); |
---|
754 | |
---|
755 | if( t->piecesSort != mode ) |
---|
756 | { |
---|
757 | //fprintf( stderr, "sort mode was %d, is now %d\n", t->piecesSort, mode ); |
---|
758 | t->piecesSort = mode; |
---|
759 | |
---|
760 | switch( mode ) { |
---|
761 | case PIECES_SORTED_BY_WEIGHT: compar = comparePieceByWeight; break; |
---|
762 | case PIECES_SORTED_BY_INDEX: compar = comparePieceByIndex; break; |
---|
763 | default: assert( 0 && "unhandled" ); break; |
---|
764 | } |
---|
765 | |
---|
766 | //fprintf( stderr, "sorting pieces by %s...\n", (mode==PIECES_SORTED_BY_WEIGHT)?"weight":"index" ); |
---|
767 | weightTorrent = t->tor; |
---|
768 | qsort( t->pieces, t->pieceCount, |
---|
769 | sizeof( struct weighted_piece ), compar ); |
---|
770 | } |
---|
771 | |
---|
772 | /* Also, as long as we've got the pieces sorted by weight, |
---|
773 | * let's also update t.isInEndgame */ |
---|
774 | if( t->piecesSort == PIECES_SORTED_BY_WEIGHT ) |
---|
775 | { |
---|
776 | tr_bool endgame = TRUE; |
---|
777 | |
---|
778 | if( ( t->pieces != NULL ) && ( t->pieceCount > 0 ) ) |
---|
779 | { |
---|
780 | const tr_completion * cp = &t->tor->completion; |
---|
781 | const struct weighted_piece * p = t->pieces; |
---|
782 | const int pending = p->requestCount; |
---|
783 | const int missing = tr_cpMissingBlocksInPiece( cp, p->index ); |
---|
784 | endgame = pending >= missing; |
---|
785 | } |
---|
786 | |
---|
787 | t->isInEndgame = endgame; |
---|
788 | } |
---|
789 | } |
---|
790 | |
---|
791 | static struct weighted_piece * |
---|
792 | pieceListLookup( Torrent * t, tr_piece_index_t index ) |
---|
793 | { |
---|
794 | struct weighted_piece key; |
---|
795 | key.index = index; |
---|
796 | |
---|
797 | pieceListSort( t, PIECES_SORTED_BY_INDEX ); |
---|
798 | |
---|
799 | return bsearch( &key, t->pieces, t->pieceCount, |
---|
800 | sizeof( struct weighted_piece ), |
---|
801 | comparePieceByIndex ); |
---|
802 | } |
---|
803 | |
---|
804 | static void |
---|
805 | pieceListRebuild( Torrent * t ) |
---|
806 | { |
---|
807 | if( !tr_torrentIsSeed( t->tor ) ) |
---|
808 | { |
---|
809 | tr_piece_index_t i; |
---|
810 | tr_piece_index_t * pool; |
---|
811 | tr_piece_index_t poolCount = 0; |
---|
812 | const tr_torrent * tor = t->tor; |
---|
813 | const tr_info * inf = tr_torrentInfo( tor ); |
---|
814 | struct weighted_piece * pieces; |
---|
815 | int pieceCount; |
---|
816 | |
---|
817 | /* build the new list */ |
---|
818 | pool = tr_new( tr_piece_index_t, inf->pieceCount ); |
---|
819 | for( i=0; i<inf->pieceCount; ++i ) |
---|
820 | if( !inf->pieces[i].dnd ) |
---|
821 | if( !tr_cpPieceIsComplete( &tor->completion, i ) ) |
---|
822 | pool[poolCount++] = i; |
---|
823 | pieceCount = poolCount; |
---|
824 | pieces = tr_new0( struct weighted_piece, pieceCount ); |
---|
825 | for( i=0; i<poolCount; ++i ) { |
---|
826 | struct weighted_piece * piece = pieces + i; |
---|
827 | piece->index = pool[i]; |
---|
828 | piece->requestCount = 0; |
---|
829 | piece->salt = tr_cryptoWeakRandInt( 255 ); |
---|
830 | } |
---|
831 | |
---|
832 | /* if we already had a list of pieces, merge it into |
---|
833 | * the new list so we don't lose its requestCounts */ |
---|
834 | if( t->pieces != NULL ) |
---|
835 | { |
---|
836 | struct weighted_piece * o = t->pieces; |
---|
837 | struct weighted_piece * oend = o + t->pieceCount; |
---|
838 | struct weighted_piece * n = pieces; |
---|
839 | struct weighted_piece * nend = n + pieceCount; |
---|
840 | |
---|
841 | pieceListSort( t, PIECES_SORTED_BY_INDEX ); |
---|
842 | |
---|
843 | while( o!=oend && n!=nend ) { |
---|
844 | if( o->index < n->index ) |
---|
845 | ++o; |
---|
846 | else if( o->index > n->index ) |
---|
847 | ++n; |
---|
848 | else |
---|
849 | *n++ = *o++; |
---|
850 | } |
---|
851 | |
---|
852 | tr_free( t->pieces ); |
---|
853 | } |
---|
854 | |
---|
855 | t->pieces = pieces; |
---|
856 | t->pieceCount = pieceCount; |
---|
857 | t->piecesSort = PIECES_SORTED_BY_INDEX; |
---|
858 | |
---|
859 | /* cleanup */ |
---|
860 | tr_free( pool ); |
---|
861 | } |
---|
862 | } |
---|
863 | |
---|
864 | static void |
---|
865 | pieceListRemovePiece( Torrent * t, tr_piece_index_t piece ) |
---|
866 | { |
---|
867 | struct weighted_piece * p = pieceListLookup( t, piece ); |
---|
868 | |
---|
869 | if( p != NULL ) |
---|
870 | { |
---|
871 | const int pos = p - t->pieces; |
---|
872 | |
---|
873 | memmove( t->pieces + pos, |
---|
874 | t->pieces + pos + 1, |
---|
875 | sizeof( struct weighted_piece ) * ( --t->pieceCount - pos ) ); |
---|
876 | |
---|
877 | if( t->pieceCount == 0 ) |
---|
878 | { |
---|
879 | tr_free( t->pieces ); |
---|
880 | t->pieces = NULL; |
---|
881 | } |
---|
882 | } |
---|
883 | } |
---|
884 | |
---|
885 | static void |
---|
886 | pieceListRemoveRequest( Torrent * t, tr_block_index_t block ) |
---|
887 | { |
---|
888 | struct weighted_piece * p; |
---|
889 | const tr_piece_index_t index = tr_torBlockPiece( t->tor, block ); |
---|
890 | |
---|
891 | if(( p = pieceListLookup( t, index ))) |
---|
892 | if( p->requestCount > 0 ) |
---|
893 | --p->requestCount; |
---|
894 | |
---|
895 | /* note: this invalidates the weighted.piece.weight field, |
---|
896 | * but that's OK since the call to pieceListLookup ensured |
---|
897 | * that we were sorted by index anyway.. next time we resort |
---|
898 | * by weight, pieceListSort() will update the weights */ |
---|
899 | } |
---|
900 | |
---|
901 | /** |
---|
902 | *** |
---|
903 | **/ |
---|
904 | |
---|
905 | void |
---|
906 | tr_peerMgrRebuildRequests( tr_torrent * tor ) |
---|
907 | { |
---|
908 | assert( tr_isTorrent( tor ) ); |
---|
909 | |
---|
910 | pieceListRebuild( tor->torrentPeers ); |
---|
911 | } |
---|
912 | |
---|
913 | void |
---|
914 | tr_peerMgrGetNextRequests( tr_torrent * tor, |
---|
915 | tr_peer * peer, |
---|
916 | int numwant, |
---|
917 | tr_block_index_t * setme, |
---|
918 | int * numgot ) |
---|
919 | { |
---|
920 | int i; |
---|
921 | int got; |
---|
922 | Torrent * t; |
---|
923 | struct weighted_piece * pieces; |
---|
924 | const tr_bitfield * have = peer->have; |
---|
925 | const time_t now = time( NULL ); |
---|
926 | |
---|
927 | /* sanity clause */ |
---|
928 | assert( tr_isTorrent( tor ) ); |
---|
929 | assert( numwant > 0 ); |
---|
930 | |
---|
931 | /* walk through the pieces and find blocks that should be requested */ |
---|
932 | got = 0; |
---|
933 | t = tor->torrentPeers; |
---|
934 | |
---|
935 | /* prep the pieces list */ |
---|
936 | if( t->pieces == NULL ) |
---|
937 | pieceListRebuild( t ); |
---|
938 | pieceListSort( t, PIECES_SORTED_BY_WEIGHT ); |
---|
939 | //if( t->isInEndgame ) fprintf( stderr, "endgame\n" ); |
---|
940 | |
---|
941 | #if 0 |
---|
942 | { |
---|
943 | int i=0, n=MIN(10,t->pieceCount); |
---|
944 | fprintf( stderr, "the next pieces we want to request are " ); |
---|
945 | for( i=0; i<n; i++ ) fprintf( stderr, "%d(weight:%d) ", (int)t->pieces[i].index, (int)t->pieces[i].weight ); |
---|
946 | fprintf( stderr, "\n" ); |
---|
947 | } |
---|
948 | #endif |
---|
949 | |
---|
950 | pieces = t->pieces; |
---|
951 | for( i=0; i<t->pieceCount && got<numwant; ++i ) |
---|
952 | { |
---|
953 | struct weighted_piece * p = pieces + i; |
---|
954 | |
---|
955 | /* if the peer has this piece that we want... */ |
---|
956 | if( tr_bitfieldHasFast( have, p->index ) ) |
---|
957 | { |
---|
958 | tr_block_index_t b = tr_torPieceFirstBlock( tor, p->index ); |
---|
959 | const tr_block_index_t e = b + tr_torPieceCountBlocks( tor, p->index ); |
---|
960 | |
---|
961 | for( ; b!=e && got<numwant; ++b ) |
---|
962 | { |
---|
963 | struct block_request * breq; |
---|
964 | |
---|
965 | /* don't request blocks we've already got */ |
---|
966 | if( tr_cpBlockIsCompleteFast( &tor->completion, b ) ) |
---|
967 | continue; |
---|
968 | |
---|
969 | /* don't request blocks we've already requested (FIXME) */ |
---|
970 | breq = requestListLookup( t, b ); |
---|
971 | if( breq != NULL ) { |
---|
972 | assert( breq->peer != NULL ); |
---|
973 | if( breq->peer == peer ) continue; |
---|
974 | if( !t->isInEndgame ) continue; |
---|
975 | } |
---|
976 | |
---|
977 | setme[got++] = b; |
---|
978 | //fprintf( stderr, "peer %p is requesting block %"PRIu64"\n", peer, b ); |
---|
979 | |
---|
980 | /* update our own tables */ |
---|
981 | if( breq == NULL ) |
---|
982 | requestListAdd( t, now, b, peer ); |
---|
983 | ++p->requestCount; |
---|
984 | } |
---|
985 | } |
---|
986 | } |
---|
987 | |
---|
988 | /* We almost always change only a handful of pieces in the array. |
---|
989 | * In these cases, it's cheaper to sort those changed pieces and merge, |
---|
990 | * than qsort()ing the whole array again */ |
---|
991 | if( got > 0 ) |
---|
992 | { |
---|
993 | struct weighted_piece * p; |
---|
994 | struct weighted_piece * pieces; |
---|
995 | struct weighted_piece * a = t->pieces; |
---|
996 | struct weighted_piece * a_end = t->pieces + i; |
---|
997 | struct weighted_piece * b = a_end; |
---|
998 | struct weighted_piece * b_end = t->pieces + t->pieceCount; |
---|
999 | |
---|
1000 | /* rescore the pieces that we changed */ |
---|
1001 | weightTorrent = t->tor; |
---|
1002 | //fprintf( stderr, "sorting %d changed pieces...\n", (int)(a_end-a) ); |
---|
1003 | qsort( a, a_end-a, sizeof( struct weighted_piece ), comparePieceByWeight ); |
---|
1004 | |
---|
1005 | /* allocate a new array */ |
---|
1006 | p = pieces = tr_new( struct weighted_piece, t->pieceCount ); |
---|
1007 | |
---|
1008 | /* merge the two sorted arrays into this new array */ |
---|
1009 | weightTorrent = t->tor; |
---|
1010 | while( a!=a_end && b!=b_end ) |
---|
1011 | *p++ = comparePieceByWeight( a, b ) < 0 ? *a++ : *b++; |
---|
1012 | while( a!=a_end ) *p++ = *a++; |
---|
1013 | while( b!=b_end ) *p++ = *b++; |
---|
1014 | |
---|
1015 | #if 0 |
---|
1016 | /* make sure we did it right */ |
---|
1017 | assert( p - pieces == t->pieceCount ); |
---|
1018 | for( it=pieces; it+1<p; ++it ) |
---|
1019 | assert( it->weight <= it[1].weight ); |
---|
1020 | #endif |
---|
1021 | |
---|
1022 | /* update */ |
---|
1023 | tr_free( t->pieces ); |
---|
1024 | t->pieces = pieces; |
---|
1025 | } |
---|
1026 | |
---|
1027 | //fprintf( stderr, "peer %p wanted %d requests; got %d\n", peer, numwant, got ); |
---|
1028 | *numgot = got; |
---|
1029 | } |
---|
1030 | |
---|
1031 | tr_bool |
---|
1032 | tr_peerMgrDidPeerRequest( const tr_torrent * tor, |
---|
1033 | const tr_peer * peer, |
---|
1034 | tr_block_index_t block ) |
---|
1035 | { |
---|
1036 | const Torrent * t = tor->torrentPeers; |
---|
1037 | const struct block_request * b = requestListLookup( (Torrent*)t, block ); |
---|
1038 | if( b == NULL ) return FALSE; |
---|
1039 | if( b->peer == peer ) return TRUE; |
---|
1040 | if( t->isInEndgame ) return TRUE; |
---|
1041 | return FALSE; |
---|
1042 | } |
---|
1043 | |
---|
1044 | /* cancel requests that are too old */ |
---|
1045 | static int |
---|
1046 | refillUpkeep( void * vmgr ) |
---|
1047 | { |
---|
1048 | time_t now; |
---|
1049 | time_t too_old; |
---|
1050 | tr_torrent * tor; |
---|
1051 | tr_peerMgr * mgr = vmgr; |
---|
1052 | managerLock( mgr ); |
---|
1053 | |
---|
1054 | now = time( NULL ); |
---|
1055 | too_old = now - REQUEST_TTL_SECS; |
---|
1056 | |
---|
1057 | tor = NULL; |
---|
1058 | while(( tor = tr_torrentNext( mgr->session, tor ))) |
---|
1059 | { |
---|
1060 | Torrent * t = tor->torrentPeers; |
---|
1061 | const int n = t->requestCount; |
---|
1062 | if( n > 0 ) |
---|
1063 | { |
---|
1064 | int keepCount = 0; |
---|
1065 | int cancelCount = 0; |
---|
1066 | struct block_request * keep = tr_new( struct block_request, n ); |
---|
1067 | struct block_request * cancel = tr_new( struct block_request, n ); |
---|
1068 | const struct block_request * it; |
---|
1069 | const struct block_request * end; |
---|
1070 | |
---|
1071 | for( it=t->requests, end=it+n; it!=end; ++it ) |
---|
1072 | if( it->sentAt <= too_old ) |
---|
1073 | cancel[cancelCount++] = *it; |
---|
1074 | else |
---|
1075 | keep[keepCount++] = *it; |
---|
1076 | |
---|
1077 | /* prune out the ones we aren't keeping */ |
---|
1078 | tr_free( t->requests ); |
---|
1079 | t->requests = keep; |
---|
1080 | t->requestCount = keepCount; |
---|
1081 | t->requestAlloc = n; |
---|
1082 | |
---|
1083 | /* send cancel messages for all the "cancel" ones */ |
---|
1084 | for( it=cancel, end=it+cancelCount; it!=end; ++it ) |
---|
1085 | if( ( it->peer != NULL ) && ( it->peer->msgs != NULL ) ) |
---|
1086 | tr_peerMsgsCancel( it->peer->msgs, it->block ); |
---|
1087 | |
---|
1088 | /* decrement the pending request counts for the timed-out blocks */ |
---|
1089 | for( it=cancel, end=it+cancelCount; it!=end; ++it ) |
---|
1090 | pieceListRemoveRequest( t, it->block ); |
---|
1091 | |
---|
1092 | /* cleanup loop */ |
---|
1093 | tr_free( cancel ); |
---|
1094 | } |
---|
1095 | } |
---|
1096 | |
---|
1097 | managerUnlock( mgr ); |
---|
1098 | return TRUE; |
---|
1099 | } |
---|
1100 | |
---|
1101 | static void |
---|
1102 | addStrike( Torrent * t, tr_peer * peer ) |
---|
1103 | { |
---|
1104 | tordbg( t, "increasing peer %s strike count to %d", |
---|
1105 | tr_atomAddrStr( peer->atom ), peer->strikes + 1 ); |
---|
1106 | |
---|
1107 | if( ++peer->strikes >= MAX_BAD_PIECES_PER_PEER ) |
---|
1108 | { |
---|
1109 | struct peer_atom * atom = peer->atom; |
---|
1110 | atom->myflags |= MYFLAG_BANNED; |
---|
1111 | peer->doPurge = 1; |
---|
1112 | tordbg( t, "banning peer %s", tr_atomAddrStr( atom ) ); |
---|
1113 | } |
---|
1114 | } |
---|
1115 | |
---|
1116 | static void |
---|
1117 | gotBadPiece( Torrent * t, tr_piece_index_t pieceIndex ) |
---|
1118 | { |
---|
1119 | tr_torrent * tor = t->tor; |
---|
1120 | const uint32_t byteCount = tr_torPieceCountBytes( tor, pieceIndex ); |
---|
1121 | |
---|
1122 | tor->corruptCur += byteCount; |
---|
1123 | tor->downloadedCur -= MIN( tor->downloadedCur, byteCount ); |
---|
1124 | } |
---|
1125 | |
---|
1126 | static void |
---|
1127 | peerSuggestedPiece( Torrent * t UNUSED, |
---|
1128 | tr_peer * peer UNUSED, |
---|
1129 | tr_piece_index_t pieceIndex UNUSED, |
---|
1130 | int isFastAllowed UNUSED ) |
---|
1131 | { |
---|
1132 | #if 0 |
---|
1133 | assert( t ); |
---|
1134 | assert( peer ); |
---|
1135 | assert( peer->msgs ); |
---|
1136 | |
---|
1137 | /* is this a valid piece? */ |
---|
1138 | if( pieceIndex >= t->tor->info.pieceCount ) |
---|
1139 | return; |
---|
1140 | |
---|
1141 | /* don't ask for it if we've already got it */ |
---|
1142 | if( tr_cpPieceIsComplete( t->tor->completion, pieceIndex ) ) |
---|
1143 | return; |
---|
1144 | |
---|
1145 | /* don't ask for it if they don't have it */ |
---|
1146 | if( !tr_bitfieldHas( peer->have, pieceIndex ) ) |
---|
1147 | return; |
---|
1148 | |
---|
1149 | /* don't ask for it if we're choked and it's not fast */ |
---|
1150 | if( !isFastAllowed && peer->clientIsChoked ) |
---|
1151 | return; |
---|
1152 | |
---|
1153 | /* request the blocks that we don't have in this piece */ |
---|
1154 | { |
---|
1155 | tr_block_index_t block; |
---|
1156 | const tr_torrent * tor = t->tor; |
---|
1157 | const tr_block_index_t start = tr_torPieceFirstBlock( tor, pieceIndex ); |
---|
1158 | const tr_block_index_t end = start + tr_torPieceCountBlocks( tor, pieceIndex ); |
---|
1159 | |
---|
1160 | for( block=start; block<end; ++block ) |
---|
1161 | { |
---|
1162 | if( !tr_cpBlockIsComplete( tor->completion, block ) ) |
---|
1163 | { |
---|
1164 | const uint32_t offset = getBlockOffsetInPiece( tor, block ); |
---|
1165 | const uint32_t length = tr_torBlockCountBytes( tor, block ); |
---|
1166 | tr_peerMsgsAddRequest( peer->msgs, pieceIndex, offset, length ); |
---|
1167 | incrementPieceRequests( t, pieceIndex ); |
---|
1168 | } |
---|
1169 | } |
---|
1170 | } |
---|
1171 | #endif |
---|
1172 | } |
---|
1173 | |
---|
1174 | static void |
---|
1175 | decrementDownloadedCount( tr_torrent * tor, uint32_t byteCount ) |
---|
1176 | { |
---|
1177 | tor->downloadedCur -= MIN( tor->downloadedCur, byteCount ); |
---|
1178 | } |
---|
1179 | |
---|
1180 | static void |
---|
1181 | clientGotUnwantedBlock( tr_torrent * tor, tr_block_index_t block ) |
---|
1182 | { |
---|
1183 | decrementDownloadedCount( tor, tr_torBlockCountBytes( tor, block ) ); |
---|
1184 | } |
---|
1185 | |
---|
1186 | static void |
---|
1187 | removeRequestFromTables( Torrent * t, tr_block_index_t block ) |
---|
1188 | { |
---|
1189 | requestListRemove( t, block ); |
---|
1190 | pieceListRemoveRequest( t, block ); |
---|
1191 | } |
---|
1192 | |
---|
1193 | /* peer choked us, or maybe it disconnected. |
---|
1194 | either way we need to remove all its requests */ |
---|
1195 | static void |
---|
1196 | peerDeclinedAllRequests( Torrent * t, const tr_peer * peer ) |
---|
1197 | { |
---|
1198 | int i, n; |
---|
1199 | tr_block_index_t * blocks = tr_new( tr_block_index_t, t->requestCount ); |
---|
1200 | |
---|
1201 | for( i=n=0; i<t->requestCount; ++i ) |
---|
1202 | if( peer == t->requests[i].peer ) |
---|
1203 | blocks[n++] = t->requests[i].block; |
---|
1204 | |
---|
1205 | for( i=0; i<n; ++i ) |
---|
1206 | removeRequestFromTables( t, blocks[i] ); |
---|
1207 | |
---|
1208 | tr_free( blocks ); |
---|
1209 | } |
---|
1210 | |
---|
1211 | static void |
---|
1212 | peerCallbackFunc( void * vpeer, void * vevent, void * vt ) |
---|
1213 | { |
---|
1214 | tr_peer * peer = vpeer; /* may be NULL if peer is a webseed */ |
---|
1215 | Torrent * t = vt; |
---|
1216 | const tr_peer_event * e = vevent; |
---|
1217 | |
---|
1218 | torrentLock( t ); |
---|
1219 | |
---|
1220 | switch( e->eventType ) |
---|
1221 | { |
---|
1222 | case TR_PEER_UPLOAD_ONLY: |
---|
1223 | /* update our atom */ |
---|
1224 | if( peer ) { |
---|
1225 | if( e->uploadOnly ) { |
---|
1226 | peer->atom->uploadOnly = UPLOAD_ONLY_YES; |
---|
1227 | peer->atom->flags |= ADDED_F_SEED_FLAG; |
---|
1228 | } else { |
---|
1229 | peer->atom->uploadOnly = UPLOAD_ONLY_NO; |
---|
1230 | peer->atom->flags &= ~ADDED_F_SEED_FLAG; |
---|
1231 | } |
---|
1232 | } |
---|
1233 | break; |
---|
1234 | |
---|
1235 | case TR_PEER_PEER_GOT_DATA: |
---|
1236 | { |
---|
1237 | const time_t now = time( NULL ); |
---|
1238 | tr_torrent * tor = t->tor; |
---|
1239 | |
---|
1240 | tr_torrentSetActivityDate( tor, now ); |
---|
1241 | |
---|
1242 | if( e->wasPieceData ) { |
---|
1243 | tor->uploadedCur += e->length; |
---|
1244 | tr_torrentSetDirty( tor ); |
---|
1245 | } |
---|
1246 | |
---|
1247 | /* update the stats */ |
---|
1248 | if( e->wasPieceData ) |
---|
1249 | tr_statsAddUploaded( tor->session, e->length ); |
---|
1250 | |
---|
1251 | /* update our atom */ |
---|
1252 | if( peer && e->wasPieceData ) |
---|
1253 | peer->atom->piece_data_time = now; |
---|
1254 | |
---|
1255 | tor->needsSeedRatioCheck = TRUE; |
---|
1256 | |
---|
1257 | break; |
---|
1258 | } |
---|
1259 | |
---|
1260 | case TR_PEER_CLIENT_GOT_REJ: |
---|
1261 | removeRequestFromTables( t, _tr_block( t->tor, e->pieceIndex, e->offset ) ); |
---|
1262 | break; |
---|
1263 | |
---|
1264 | case TR_PEER_CLIENT_GOT_CHOKE: |
---|
1265 | peerDeclinedAllRequests( t, peer ); |
---|
1266 | break; |
---|
1267 | |
---|
1268 | case TR_PEER_CLIENT_GOT_PORT: |
---|
1269 | if( peer ) |
---|
1270 | peer->atom->port = e->port; |
---|
1271 | break; |
---|
1272 | |
---|
1273 | case TR_PEER_CLIENT_GOT_SUGGEST: |
---|
1274 | if( peer ) |
---|
1275 | peerSuggestedPiece( t, peer, e->pieceIndex, FALSE ); |
---|
1276 | break; |
---|
1277 | |
---|
1278 | case TR_PEER_CLIENT_GOT_ALLOWED_FAST: |
---|
1279 | if( peer ) |
---|
1280 | peerSuggestedPiece( t, peer, e->pieceIndex, TRUE ); |
---|
1281 | break; |
---|
1282 | |
---|
1283 | case TR_PEER_CLIENT_GOT_DATA: |
---|
1284 | { |
---|
1285 | const time_t now = time( NULL ); |
---|
1286 | tr_torrent * tor = t->tor; |
---|
1287 | |
---|
1288 | tr_torrentSetActivityDate( tor, now ); |
---|
1289 | |
---|
1290 | /* only add this to downloadedCur if we got it from a peer -- |
---|
1291 | * webseeds shouldn't count against our ratio. As one tracker |
---|
1292 | * admin put it, "Those pieces are downloaded directly from the |
---|
1293 | * content distributor, not the peers, it is the tracker's job |
---|
1294 | * to manage the swarms, not the web server and does not fit |
---|
1295 | * into the jurisdiction of the tracker." */ |
---|
1296 | if( peer && e->wasPieceData ) { |
---|
1297 | tor->downloadedCur += e->length; |
---|
1298 | tr_torrentSetDirty( tor ); |
---|
1299 | } |
---|
1300 | |
---|
1301 | /* update the stats */ |
---|
1302 | if( e->wasPieceData ) |
---|
1303 | tr_statsAddDownloaded( tor->session, e->length ); |
---|
1304 | |
---|
1305 | /* update our atom */ |
---|
1306 | if( peer && e->wasPieceData ) |
---|
1307 | peer->atom->piece_data_time = now; |
---|
1308 | |
---|
1309 | break; |
---|
1310 | } |
---|
1311 | |
---|
1312 | case TR_PEER_PEER_PROGRESS: |
---|
1313 | { |
---|
1314 | if( peer ) |
---|
1315 | { |
---|
1316 | struct peer_atom * atom = peer->atom; |
---|
1317 | if( e->progress >= 1.0 ) { |
---|
1318 | tordbg( t, "marking peer %s as a seed", |
---|
1319 | tr_atomAddrStr( atom ) ); |
---|
1320 | atom->flags |= ADDED_F_SEED_FLAG; |
---|
1321 | } |
---|
1322 | } |
---|
1323 | break; |
---|
1324 | } |
---|
1325 | |
---|
1326 | case TR_PEER_CLIENT_GOT_BLOCK: |
---|
1327 | { |
---|
1328 | tr_torrent * tor = t->tor; |
---|
1329 | tr_block_index_t block = _tr_block( tor, e->pieceIndex, e->offset ); |
---|
1330 | //static int numBlocks = 0; |
---|
1331 | //fprintf( stderr, "got a total of %d blocks\n", ++numBlocks ); |
---|
1332 | |
---|
1333 | requestListRemove( t, block ); |
---|
1334 | pieceListRemoveRequest( t, block ); |
---|
1335 | |
---|
1336 | if( tr_cpBlockIsComplete( &tor->completion, block ) ) |
---|
1337 | { |
---|
1338 | tordbg( t, "we have this block already..." ); |
---|
1339 | clientGotUnwantedBlock( tor, block ); |
---|
1340 | } |
---|
1341 | else |
---|
1342 | { |
---|
1343 | tr_cpBlockAdd( &tor->completion, block ); |
---|
1344 | tr_torrentSetDirty( tor ); |
---|
1345 | |
---|
1346 | if( tr_cpPieceIsComplete( &tor->completion, e->pieceIndex ) ) |
---|
1347 | { |
---|
1348 | const tr_piece_index_t p = e->pieceIndex; |
---|
1349 | const tr_bool ok = tr_ioTestPiece( tor, p, NULL, 0 ); |
---|
1350 | //fprintf( stderr, "we now have piece #%d\n", (int)p ); |
---|
1351 | |
---|
1352 | if( !ok ) |
---|
1353 | { |
---|
1354 | tr_torerr( tor, _( "Piece %lu, which was just downloaded, failed its checksum test" ), |
---|
1355 | (unsigned long)p ); |
---|
1356 | } |
---|
1357 | |
---|
1358 | tr_torrentSetHasPiece( tor, p, ok ); |
---|
1359 | tr_torrentSetPieceChecked( tor, p, TRUE ); |
---|
1360 | tr_peerMgrSetBlame( tor, p, ok ); |
---|
1361 | |
---|
1362 | if( !ok ) |
---|
1363 | { |
---|
1364 | gotBadPiece( t, p ); |
---|
1365 | } |
---|
1366 | else |
---|
1367 | { |
---|
1368 | int i; |
---|
1369 | int peerCount; |
---|
1370 | tr_peer ** peers; |
---|
1371 | tr_file_index_t fileIndex; |
---|
1372 | |
---|
1373 | peerCount = tr_ptrArraySize( &t->peers ); |
---|
1374 | peers = (tr_peer**) tr_ptrArrayBase( &t->peers ); |
---|
1375 | for( i=0; i<peerCount; ++i ) |
---|
1376 | tr_peerMsgsHave( peers[i]->msgs, p ); |
---|
1377 | |
---|
1378 | for( fileIndex=0; fileIndex<tor->info.fileCount; ++fileIndex ) { |
---|
1379 | const tr_file * file = &tor->info.files[fileIndex]; |
---|
1380 | if( ( file->firstPiece <= p ) && ( p <= file->lastPiece ) ) |
---|
1381 | if( tr_cpFileIsComplete( &tor->completion, fileIndex ) ) |
---|
1382 | tr_torrentFileCompleted( tor, fileIndex ); |
---|
1383 | } |
---|
1384 | |
---|
1385 | pieceListRemovePiece( t, p ); |
---|
1386 | } |
---|
1387 | } |
---|
1388 | |
---|
1389 | t->needsCompletenessCheck = TRUE; |
---|
1390 | } |
---|
1391 | break; |
---|
1392 | } |
---|
1393 | |
---|
1394 | case TR_PEER_ERROR: |
---|
1395 | if( ( e->err == ERANGE ) || ( e->err == EMSGSIZE ) || ( e->err == ENOTCONN ) ) |
---|
1396 | { |
---|
1397 | /* some protocol error from the peer */ |
---|
1398 | peer->doPurge = 1; |
---|
1399 | tordbg( t, "setting %s doPurge flag because we got an ERANGE, EMSGSIZE, or ENOTCONN error", |
---|
1400 | tr_atomAddrStr( peer->atom ) ); |
---|
1401 | } |
---|
1402 | else |
---|
1403 | { |
---|
1404 | tordbg( t, "unhandled error: %s", tr_strerror( e->err ) ); |
---|
1405 | } |
---|
1406 | break; |
---|
1407 | |
---|
1408 | default: |
---|
1409 | assert( 0 ); |
---|
1410 | } |
---|
1411 | |
---|
1412 | torrentUnlock( t ); |
---|
1413 | } |
---|
1414 | |
---|
1415 | static void |
---|
1416 | ensureAtomExists( Torrent * t, |
---|
1417 | const tr_address * addr, |
---|
1418 | tr_port port, |
---|
1419 | uint8_t flags, |
---|
1420 | uint8_t from ) |
---|
1421 | { |
---|
1422 | assert( tr_isAddress( addr ) ); |
---|
1423 | assert( from < TR_PEER_FROM__MAX ); |
---|
1424 | |
---|
1425 | if( getExistingAtom( t, addr ) == NULL ) |
---|
1426 | { |
---|
1427 | struct peer_atom * a; |
---|
1428 | a = tr_new0( struct peer_atom, 1 ); |
---|
1429 | a->addr = *addr; |
---|
1430 | a->port = port; |
---|
1431 | a->flags = flags; |
---|
1432 | a->from = from; |
---|
1433 | tordbg( t, "got a new atom: %s", tr_atomAddrStr( a ) ); |
---|
1434 | tr_ptrArrayInsertSorted( &t->pool, a, comparePeerAtoms ); |
---|
1435 | } |
---|
1436 | } |
---|
1437 | |
---|
1438 | static int |
---|
1439 | getMaxPeerCount( const tr_torrent * tor ) |
---|
1440 | { |
---|
1441 | return tor->maxConnectedPeers; |
---|
1442 | } |
---|
1443 | |
---|
1444 | static int |
---|
1445 | getPeerCount( const Torrent * t ) |
---|
1446 | { |
---|
1447 | return tr_ptrArraySize( &t->peers );/* + tr_ptrArraySize( &t->outgoingHandshakes ); */ |
---|
1448 | } |
---|
1449 | |
---|
1450 | /* FIXME: this is kind of a mess. */ |
---|
1451 | static tr_bool |
---|
1452 | myHandshakeDoneCB( tr_handshake * handshake, |
---|
1453 | tr_peerIo * io, |
---|
1454 | tr_bool isConnected, |
---|
1455 | const uint8_t * peer_id, |
---|
1456 | void * vmanager ) |
---|
1457 | { |
---|
1458 | tr_bool ok = isConnected; |
---|
1459 | tr_bool success = FALSE; |
---|
1460 | tr_port port; |
---|
1461 | const tr_address * addr; |
---|
1462 | tr_peerMgr * manager = vmanager; |
---|
1463 | Torrent * t; |
---|
1464 | tr_handshake * ours; |
---|
1465 | |
---|
1466 | assert( io ); |
---|
1467 | assert( tr_isBool( ok ) ); |
---|
1468 | |
---|
1469 | t = tr_peerIoHasTorrentHash( io ) |
---|
1470 | ? getExistingTorrent( manager, tr_peerIoGetTorrentHash( io ) ) |
---|
1471 | : NULL; |
---|
1472 | |
---|
1473 | if( tr_peerIoIsIncoming ( io ) ) |
---|
1474 | ours = tr_ptrArrayRemoveSorted( &manager->incomingHandshakes, |
---|
1475 | handshake, handshakeCompare ); |
---|
1476 | else if( t ) |
---|
1477 | ours = tr_ptrArrayRemoveSorted( &t->outgoingHandshakes, |
---|
1478 | handshake, handshakeCompare ); |
---|
1479 | else |
---|
1480 | ours = handshake; |
---|
1481 | |
---|
1482 | assert( ours ); |
---|
1483 | assert( ours == handshake ); |
---|
1484 | |
---|
1485 | if( t ) |
---|
1486 | torrentLock( t ); |
---|
1487 | |
---|
1488 | addr = tr_peerIoGetAddress( io, &port ); |
---|
1489 | |
---|
1490 | if( !ok || !t || !t->isRunning ) |
---|
1491 | { |
---|
1492 | if( t ) |
---|
1493 | { |
---|
1494 | struct peer_atom * atom = getExistingAtom( t, addr ); |
---|
1495 | if( atom ) |
---|
1496 | ++atom->numFails; |
---|
1497 | } |
---|
1498 | } |
---|
1499 | else /* looking good */ |
---|
1500 | { |
---|
1501 | struct peer_atom * atom; |
---|
1502 | ensureAtomExists( t, addr, port, 0, TR_PEER_FROM_INCOMING ); |
---|
1503 | atom = getExistingAtom( t, addr ); |
---|
1504 | atom->time = time( NULL ); |
---|
1505 | atom->piece_data_time = 0; |
---|
1506 | |
---|
1507 | if( atom->myflags & MYFLAG_BANNED ) |
---|
1508 | { |
---|
1509 | tordbg( t, "banned peer %s tried to reconnect", |
---|
1510 | tr_atomAddrStr( atom ) ); |
---|
1511 | } |
---|
1512 | else if( tr_peerIoIsIncoming( io ) |
---|
1513 | && ( getPeerCount( t ) >= getMaxPeerCount( t->tor ) ) ) |
---|
1514 | |
---|
1515 | { |
---|
1516 | } |
---|
1517 | else |
---|
1518 | { |
---|
1519 | tr_peer * peer = getExistingPeer( t, addr ); |
---|
1520 | |
---|
1521 | if( peer ) /* we already have this peer */ |
---|
1522 | { |
---|
1523 | } |
---|
1524 | else |
---|
1525 | { |
---|
1526 | peer = getPeer( t, atom ); |
---|
1527 | tr_free( peer->client ); |
---|
1528 | |
---|
1529 | if( !peer_id ) |
---|
1530 | peer->client = NULL; |
---|
1531 | else { |
---|
1532 | char client[128]; |
---|
1533 | tr_clientForId( client, sizeof( client ), peer_id ); |
---|
1534 | peer->client = tr_strdup( client ); |
---|
1535 | } |
---|
1536 | |
---|
1537 | peer->io = tr_handshakeStealIO( handshake ); /* this steals its refcount too, which is |
---|
1538 | balanced by our unref in peerDestructor() */ |
---|
1539 | tr_peerIoSetParent( peer->io, t->tor->bandwidth ); |
---|
1540 | tr_peerMsgsNew( t->tor, peer, peerCallbackFunc, t, &peer->msgsTag ); |
---|
1541 | |
---|
1542 | success = TRUE; |
---|
1543 | } |
---|
1544 | } |
---|
1545 | } |
---|
1546 | |
---|
1547 | if( t ) |
---|
1548 | torrentUnlock( t ); |
---|
1549 | |
---|
1550 | return success; |
---|
1551 | } |
---|
1552 | |
---|
1553 | void |
---|
1554 | tr_peerMgrAddIncoming( tr_peerMgr * manager, |
---|
1555 | tr_address * addr, |
---|
1556 | tr_port port, |
---|
1557 | int socket ) |
---|
1558 | { |
---|
1559 | tr_session * session; |
---|
1560 | |
---|
1561 | managerLock( manager ); |
---|
1562 | |
---|
1563 | assert( tr_isSession( manager->session ) ); |
---|
1564 | session = manager->session; |
---|
1565 | |
---|
1566 | if( tr_sessionIsAddressBlocked( session, addr ) ) |
---|
1567 | { |
---|
1568 | tr_dbg( "Banned IP address \"%s\" tried to connect to us", tr_ntop_non_ts( addr ) ); |
---|
1569 | tr_netClose( session, socket ); |
---|
1570 | } |
---|
1571 | else if( getExistingHandshake( &manager->incomingHandshakes, addr ) ) |
---|
1572 | { |
---|
1573 | tr_netClose( session, socket ); |
---|
1574 | } |
---|
1575 | else /* we don't have a connetion to them yet... */ |
---|
1576 | { |
---|
1577 | tr_peerIo * io; |
---|
1578 | tr_handshake * handshake; |
---|
1579 | |
---|
1580 | io = tr_peerIoNewIncoming( session, session->bandwidth, addr, port, socket ); |
---|
1581 | |
---|
1582 | handshake = tr_handshakeNew( io, |
---|
1583 | session->encryptionMode, |
---|
1584 | myHandshakeDoneCB, |
---|
1585 | manager ); |
---|
1586 | |
---|
1587 | tr_peerIoUnref( io ); /* balanced by the implicit ref in tr_peerIoNewIncoming() */ |
---|
1588 | |
---|
1589 | tr_ptrArrayInsertSorted( &manager->incomingHandshakes, handshake, |
---|
1590 | handshakeCompare ); |
---|
1591 | } |
---|
1592 | |
---|
1593 | managerUnlock( manager ); |
---|
1594 | } |
---|
1595 | |
---|
1596 | static tr_bool |
---|
1597 | tr_isPex( const tr_pex * pex ) |
---|
1598 | { |
---|
1599 | return pex && tr_isAddress( &pex->addr ); |
---|
1600 | } |
---|
1601 | |
---|
1602 | void |
---|
1603 | tr_peerMgrAddPex( tr_torrent * tor, |
---|
1604 | uint8_t from, |
---|
1605 | const tr_pex * pex ) |
---|
1606 | { |
---|
1607 | if( tr_isPex( pex ) ) /* safeguard against corrupt data */ |
---|
1608 | { |
---|
1609 | Torrent * t = tor->torrentPeers; |
---|
1610 | managerLock( t->manager ); |
---|
1611 | |
---|
1612 | if( !tr_sessionIsAddressBlocked( t->manager->session, &pex->addr ) ) |
---|
1613 | if( tr_isValidPeerAddress( &pex->addr, pex->port ) ) |
---|
1614 | ensureAtomExists( t, &pex->addr, pex->port, pex->flags, from ); |
---|
1615 | |
---|
1616 | managerUnlock( t->manager ); |
---|
1617 | } |
---|
1618 | } |
---|
1619 | |
---|
1620 | tr_pex * |
---|
1621 | tr_peerMgrCompactToPex( const void * compact, |
---|
1622 | size_t compactLen, |
---|
1623 | const uint8_t * added_f, |
---|
1624 | size_t added_f_len, |
---|
1625 | size_t * pexCount ) |
---|
1626 | { |
---|
1627 | size_t i; |
---|
1628 | size_t n = compactLen / 6; |
---|
1629 | const uint8_t * walk = compact; |
---|
1630 | tr_pex * pex = tr_new0( tr_pex, n ); |
---|
1631 | |
---|
1632 | for( i = 0; i < n; ++i ) |
---|
1633 | { |
---|
1634 | pex[i].addr.type = TR_AF_INET; |
---|
1635 | memcpy( &pex[i].addr.addr, walk, 4 ); walk += 4; |
---|
1636 | memcpy( &pex[i].port, walk, 2 ); walk += 2; |
---|
1637 | if( added_f && ( n == added_f_len ) ) |
---|
1638 | pex[i].flags = added_f[i]; |
---|
1639 | } |
---|
1640 | |
---|
1641 | *pexCount = n; |
---|
1642 | return pex; |
---|
1643 | } |
---|
1644 | |
---|
1645 | tr_pex * |
---|
1646 | tr_peerMgrCompact6ToPex( const void * compact, |
---|
1647 | size_t compactLen, |
---|
1648 | const uint8_t * added_f, |
---|
1649 | size_t added_f_len, |
---|
1650 | size_t * pexCount ) |
---|
1651 | { |
---|
1652 | size_t i; |
---|
1653 | size_t n = compactLen / 18; |
---|
1654 | const uint8_t * walk = compact; |
---|
1655 | tr_pex * pex = tr_new0( tr_pex, n ); |
---|
1656 | |
---|
1657 | for( i = 0; i < n; ++i ) |
---|
1658 | { |
---|
1659 | pex[i].addr.type = TR_AF_INET6; |
---|
1660 | memcpy( &pex[i].addr.addr.addr6.s6_addr, walk, 16 ); walk += 16; |
---|
1661 | memcpy( &pex[i].port, walk, 2 ); walk += 2; |
---|
1662 | if( added_f && ( n == added_f_len ) ) |
---|
1663 | pex[i].flags = added_f[i]; |
---|
1664 | } |
---|
1665 | |
---|
1666 | *pexCount = n; |
---|
1667 | return pex; |
---|
1668 | } |
---|
1669 | |
---|
1670 | tr_pex * |
---|
1671 | tr_peerMgrArrayToPex( const void * array, |
---|
1672 | size_t arrayLen, |
---|
1673 | size_t * pexCount ) |
---|
1674 | { |
---|
1675 | size_t i; |
---|
1676 | size_t n = arrayLen / ( sizeof( tr_address ) + 2 ); |
---|
1677 | /*size_t n = arrayLen / sizeof( tr_peerArrayElement );*/ |
---|
1678 | const uint8_t * walk = array; |
---|
1679 | tr_pex * pex = tr_new0( tr_pex, n ); |
---|
1680 | |
---|
1681 | for( i = 0 ; i < n ; i++ ) { |
---|
1682 | memcpy( &pex[i].addr, walk, sizeof( tr_address ) ); |
---|
1683 | memcpy( &pex[i].port, walk + sizeof( tr_address ), 2 ); |
---|
1684 | pex[i].flags = 0x00; |
---|
1685 | walk += sizeof( tr_address ) + 2; |
---|
1686 | } |
---|
1687 | |
---|
1688 | *pexCount = n; |
---|
1689 | return pex; |
---|
1690 | } |
---|
1691 | |
---|
1692 | /** |
---|
1693 | *** |
---|
1694 | **/ |
---|
1695 | |
---|
1696 | void |
---|
1697 | tr_peerMgrSetBlame( tr_torrent * tor, |
---|
1698 | tr_piece_index_t pieceIndex, |
---|
1699 | int success ) |
---|
1700 | { |
---|
1701 | if( !success ) |
---|
1702 | { |
---|
1703 | int peerCount, i; |
---|
1704 | Torrent * t = tor->torrentPeers; |
---|
1705 | tr_peer ** peers; |
---|
1706 | |
---|
1707 | assert( torrentIsLocked( t ) ); |
---|
1708 | |
---|
1709 | peers = (tr_peer **) tr_ptrArrayPeek( &t->peers, &peerCount ); |
---|
1710 | for( i = 0; i < peerCount; ++i ) |
---|
1711 | { |
---|
1712 | tr_peer * peer = peers[i]; |
---|
1713 | if( tr_bitfieldHas( peer->blame, pieceIndex ) ) |
---|
1714 | { |
---|
1715 | tordbg( t, "peer %s contributed to corrupt piece (%d); now has %d strikes", |
---|
1716 | tr_atomAddrStr( peer->atom ), |
---|
1717 | pieceIndex, (int)peer->strikes + 1 ); |
---|
1718 | addStrike( t, peer ); |
---|
1719 | } |
---|
1720 | } |
---|
1721 | } |
---|
1722 | } |
---|
1723 | |
---|
1724 | int |
---|
1725 | tr_pexCompare( const void * va, const void * vb ) |
---|
1726 | { |
---|
1727 | const tr_pex * a = va; |
---|
1728 | const tr_pex * b = vb; |
---|
1729 | int i; |
---|
1730 | |
---|
1731 | assert( tr_isPex( a ) ); |
---|
1732 | assert( tr_isPex( b ) ); |
---|
1733 | |
---|
1734 | if(( i = tr_compareAddresses( &a->addr, &b->addr ))) |
---|
1735 | return i; |
---|
1736 | |
---|
1737 | if( a->port != b->port ) |
---|
1738 | return a->port < b->port ? -1 : 1; |
---|
1739 | |
---|
1740 | return 0; |
---|
1741 | } |
---|
1742 | |
---|
1743 | #if 0 |
---|
1744 | static int |
---|
1745 | peerPrefersCrypto( const tr_peer * peer ) |
---|
1746 | { |
---|
1747 | if( peer->encryption_preference == ENCRYPTION_PREFERENCE_YES ) |
---|
1748 | return TRUE; |
---|
1749 | |
---|
1750 | if( peer->encryption_preference == ENCRYPTION_PREFERENCE_NO ) |
---|
1751 | return FALSE; |
---|
1752 | |
---|
1753 | return tr_peerIoIsEncrypted( peer->io ); |
---|
1754 | } |
---|
1755 | #endif |
---|
1756 | |
---|
1757 | /* better goes first */ |
---|
1758 | static int |
---|
1759 | compareAtomsByUsefulness( const void * va, const void *vb ) |
---|
1760 | { |
---|
1761 | const struct peer_atom * a = * (const struct peer_atom**) va; |
---|
1762 | const struct peer_atom * b = * (const struct peer_atom**) vb; |
---|
1763 | |
---|
1764 | assert( tr_isAtom( a ) ); |
---|
1765 | assert( tr_isAtom( b ) ); |
---|
1766 | |
---|
1767 | if( a->piece_data_time != b->piece_data_time ) |
---|
1768 | return a->piece_data_time > b->piece_data_time ? -1 : 1; |
---|
1769 | if( a->from != b->from ) |
---|
1770 | return a->from < b->from ? -1 : 1; |
---|
1771 | if( a->numFails != b->numFails ) |
---|
1772 | return a->numFails < b->numFails ? -1 : 1; |
---|
1773 | |
---|
1774 | return 0; |
---|
1775 | } |
---|
1776 | |
---|
1777 | int |
---|
1778 | tr_peerMgrGetPeers( tr_torrent * tor, |
---|
1779 | tr_pex ** setme_pex, |
---|
1780 | uint8_t af, |
---|
1781 | uint8_t list_mode, |
---|
1782 | int maxCount ) |
---|
1783 | { |
---|
1784 | int i; |
---|
1785 | int n; |
---|
1786 | int count = 0; |
---|
1787 | int atomCount = 0; |
---|
1788 | const Torrent * t = tor->torrentPeers; |
---|
1789 | struct peer_atom ** atoms = NULL; |
---|
1790 | tr_pex * pex; |
---|
1791 | tr_pex * walk; |
---|
1792 | |
---|
1793 | assert( tr_isTorrent( tor ) ); |
---|
1794 | assert( setme_pex != NULL ); |
---|
1795 | assert( af==TR_AF_INET || af==TR_AF_INET6 ); |
---|
1796 | assert( list_mode==TR_PEERS_CONNECTED || list_mode==TR_PEERS_ALL ); |
---|
1797 | |
---|
1798 | managerLock( t->manager ); |
---|
1799 | |
---|
1800 | /** |
---|
1801 | *** build a list of atoms |
---|
1802 | **/ |
---|
1803 | |
---|
1804 | if( list_mode == TR_PEERS_CONNECTED ) /* connected peers only */ |
---|
1805 | { |
---|
1806 | int i; |
---|
1807 | const tr_peer ** peers = (const tr_peer **) tr_ptrArrayBase( &t->peers ); |
---|
1808 | atomCount = tr_ptrArraySize( &t->peers ); |
---|
1809 | atoms = tr_new( struct peer_atom *, atomCount ); |
---|
1810 | for( i=0; i<atomCount; ++i ) |
---|
1811 | atoms[i] = peers[i]->atom; |
---|
1812 | } |
---|
1813 | else /* TR_PEERS_ALL */ |
---|
1814 | { |
---|
1815 | const struct peer_atom ** atomsBase = (const struct peer_atom**) tr_ptrArrayBase( &t->pool ); |
---|
1816 | atomCount = tr_ptrArraySize( &t->pool ); |
---|
1817 | atoms = tr_memdup( atomsBase, atomCount * sizeof( struct peer_atom * ) ); |
---|
1818 | } |
---|
1819 | |
---|
1820 | qsort( atoms, atomCount, sizeof( struct peer_atom * ), compareAtomsByUsefulness ); |
---|
1821 | |
---|
1822 | /** |
---|
1823 | *** add the first N of them into our return list |
---|
1824 | **/ |
---|
1825 | |
---|
1826 | n = MIN( atomCount, maxCount ); |
---|
1827 | pex = walk = tr_new0( tr_pex, n ); |
---|
1828 | |
---|
1829 | for( i=0; i<atomCount && count<n; ++i ) |
---|
1830 | { |
---|
1831 | const struct peer_atom * atom = atoms[i]; |
---|
1832 | if( atom->addr.type == af ) |
---|
1833 | { |
---|
1834 | assert( tr_isAddress( &atom->addr ) ); |
---|
1835 | walk->addr = atom->addr; |
---|
1836 | walk->port = atom->port; |
---|
1837 | walk->flags = atom->flags; |
---|
1838 | ++count; |
---|
1839 | ++walk; |
---|
1840 | } |
---|
1841 | } |
---|
1842 | |
---|
1843 | qsort( pex, count, sizeof( tr_pex ), tr_pexCompare ); |
---|
1844 | |
---|
1845 | assert( ( walk - pex ) == count ); |
---|
1846 | *setme_pex = pex; |
---|
1847 | |
---|
1848 | /* cleanup */ |
---|
1849 | tr_free( atoms ); |
---|
1850 | managerUnlock( t->manager ); |
---|
1851 | return count; |
---|
1852 | } |
---|
1853 | |
---|
1854 | static void |
---|
1855 | ensureMgrTimersExist( struct tr_peerMgr * m ) |
---|
1856 | { |
---|
1857 | tr_session * s = m->session; |
---|
1858 | |
---|
1859 | if( m->bandwidthTimer == NULL ) |
---|
1860 | m->bandwidthTimer = tr_timerNew( s, bandwidthPulse, m, BANDWIDTH_PERIOD_MSEC ); |
---|
1861 | |
---|
1862 | if( m->rechokeTimer == NULL ) |
---|
1863 | m->rechokeTimer = tr_timerNew( s, rechokePulse, m, RECHOKE_PERIOD_MSEC ); |
---|
1864 | |
---|
1865 | if( m->reconnectTimer == NULL ) |
---|
1866 | m->reconnectTimer = tr_timerNew( s, reconnectPulse, m, RECONNECT_PERIOD_MSEC ); |
---|
1867 | |
---|
1868 | if( m->refillUpkeepTimer == NULL ) |
---|
1869 | m->refillUpkeepTimer = tr_timerNew( s, refillUpkeep, m, REFILL_UPKEEP_PERIOD_MSEC ); |
---|
1870 | } |
---|
1871 | |
---|
1872 | void |
---|
1873 | tr_peerMgrStartTorrent( tr_torrent * tor ) |
---|
1874 | { |
---|
1875 | Torrent * t = tor->torrentPeers; |
---|
1876 | |
---|
1877 | assert( t != NULL ); |
---|
1878 | managerLock( t->manager ); |
---|
1879 | ensureMgrTimersExist( t->manager ); |
---|
1880 | |
---|
1881 | t->isRunning = TRUE; |
---|
1882 | |
---|
1883 | rechokePulse( t->manager ); |
---|
1884 | managerUnlock( t->manager ); |
---|
1885 | } |
---|
1886 | |
---|
1887 | static void |
---|
1888 | stopTorrent( Torrent * t ) |
---|
1889 | { |
---|
1890 | int i, n; |
---|
1891 | |
---|
1892 | assert( torrentIsLocked( t ) ); |
---|
1893 | |
---|
1894 | t->isRunning = FALSE; |
---|
1895 | |
---|
1896 | /* disconnect the peers. */ |
---|
1897 | for( i=0, n=tr_ptrArraySize( &t->peers ); i<n; ++i ) |
---|
1898 | peerDestructor( t, tr_ptrArrayNth( &t->peers, i ) ); |
---|
1899 | tr_ptrArrayClear( &t->peers ); |
---|
1900 | |
---|
1901 | /* disconnect the handshakes. handshakeAbort calls handshakeDoneCB(), |
---|
1902 | * which removes the handshake from t->outgoingHandshakes... */ |
---|
1903 | while( !tr_ptrArrayEmpty( &t->outgoingHandshakes ) ) |
---|
1904 | tr_handshakeAbort( tr_ptrArrayNth( &t->outgoingHandshakes, 0 ) ); |
---|
1905 | } |
---|
1906 | |
---|
1907 | void |
---|
1908 | tr_peerMgrStopTorrent( tr_torrent * tor ) |
---|
1909 | { |
---|
1910 | Torrent * t = tor->torrentPeers; |
---|
1911 | |
---|
1912 | managerLock( t->manager ); |
---|
1913 | |
---|
1914 | stopTorrent( t ); |
---|
1915 | |
---|
1916 | managerUnlock( t->manager ); |
---|
1917 | } |
---|
1918 | |
---|
1919 | void |
---|
1920 | tr_peerMgrAddTorrent( tr_peerMgr * manager, |
---|
1921 | tr_torrent * tor ) |
---|
1922 | { |
---|
1923 | managerLock( manager ); |
---|
1924 | |
---|
1925 | assert( tor ); |
---|
1926 | assert( tor->torrentPeers == NULL ); |
---|
1927 | |
---|
1928 | tor->torrentPeers = torrentConstructor( manager, tor ); |
---|
1929 | |
---|
1930 | managerUnlock( manager ); |
---|
1931 | } |
---|
1932 | |
---|
1933 | void |
---|
1934 | tr_peerMgrRemoveTorrent( tr_torrent * tor ) |
---|
1935 | { |
---|
1936 | tr_torrentLock( tor ); |
---|
1937 | |
---|
1938 | stopTorrent( tor->torrentPeers ); |
---|
1939 | torrentDestructor( tor->torrentPeers ); |
---|
1940 | |
---|
1941 | tr_torrentUnlock( tor ); |
---|
1942 | } |
---|
1943 | |
---|
1944 | void |
---|
1945 | tr_peerMgrTorrentAvailability( const tr_torrent * tor, |
---|
1946 | int8_t * tab, |
---|
1947 | unsigned int tabCount ) |
---|
1948 | { |
---|
1949 | tr_piece_index_t i; |
---|
1950 | const Torrent * t; |
---|
1951 | float interval; |
---|
1952 | tr_bool isSeed; |
---|
1953 | int peerCount; |
---|
1954 | const tr_peer ** peers; |
---|
1955 | tr_torrentLock( tor ); |
---|
1956 | |
---|
1957 | t = tor->torrentPeers; |
---|
1958 | tor = t->tor; |
---|
1959 | interval = tor->info.pieceCount / (float)tabCount; |
---|
1960 | isSeed = tor && ( tr_cpGetStatus ( &tor->completion ) == TR_SEED ); |
---|
1961 | peers = (const tr_peer **) tr_ptrArrayBase( &t->peers ); |
---|
1962 | peerCount = tr_ptrArraySize( &t->peers ); |
---|
1963 | |
---|
1964 | memset( tab, 0, tabCount ); |
---|
1965 | |
---|
1966 | for( i = 0; tor && i < tabCount; ++i ) |
---|
1967 | { |
---|
1968 | const int piece = i * interval; |
---|
1969 | |
---|
1970 | if( isSeed || tr_cpPieceIsComplete( &tor->completion, piece ) ) |
---|
1971 | tab[i] = -1; |
---|
1972 | else if( peerCount ) { |
---|
1973 | int j; |
---|
1974 | for( j = 0; j < peerCount; ++j ) |
---|
1975 | if( tr_bitfieldHas( peers[j]->have, i ) ) |
---|
1976 | ++tab[i]; |
---|
1977 | } |
---|
1978 | } |
---|
1979 | |
---|
1980 | tr_torrentUnlock( tor ); |
---|
1981 | } |
---|
1982 | |
---|
1983 | /* Returns the pieces that are available from peers */ |
---|
1984 | tr_bitfield* |
---|
1985 | tr_peerMgrGetAvailable( const tr_torrent * tor ) |
---|
1986 | { |
---|
1987 | int i; |
---|
1988 | int peerCount; |
---|
1989 | Torrent * t = tor->torrentPeers; |
---|
1990 | const tr_peer ** peers; |
---|
1991 | tr_bitfield * pieces; |
---|
1992 | managerLock( t->manager ); |
---|
1993 | |
---|
1994 | pieces = tr_bitfieldNew( t->tor->info.pieceCount ); |
---|
1995 | peerCount = tr_ptrArraySize( &t->peers ); |
---|
1996 | peers = (const tr_peer**) tr_ptrArrayBase( &t->peers ); |
---|
1997 | for( i=0; i<peerCount; ++i ) |
---|
1998 | tr_bitfieldOr( pieces, peers[i]->have ); |
---|
1999 | |
---|
2000 | managerUnlock( t->manager ); |
---|
2001 | return pieces; |
---|
2002 | } |
---|
2003 | |
---|
2004 | void |
---|
2005 | tr_peerMgrTorrentStats( tr_torrent * tor, |
---|
2006 | int * setmePeersKnown, |
---|
2007 | int * setmePeersConnected, |
---|
2008 | int * setmeSeedsConnected, |
---|
2009 | int * setmeWebseedsSendingToUs, |
---|
2010 | int * setmePeersSendingToUs, |
---|
2011 | int * setmePeersGettingFromUs, |
---|
2012 | int * setmePeersFrom ) |
---|
2013 | { |
---|
2014 | int i, size; |
---|
2015 | const Torrent * t = tor->torrentPeers; |
---|
2016 | const tr_peer ** peers; |
---|
2017 | const tr_webseed ** webseeds; |
---|
2018 | |
---|
2019 | managerLock( t->manager ); |
---|
2020 | |
---|
2021 | peers = (const tr_peer **) tr_ptrArrayBase( &t->peers ); |
---|
2022 | size = tr_ptrArraySize( &t->peers ); |
---|
2023 | |
---|
2024 | *setmePeersKnown = tr_ptrArraySize( &t->pool ); |
---|
2025 | *setmePeersConnected = 0; |
---|
2026 | *setmeSeedsConnected = 0; |
---|
2027 | *setmePeersGettingFromUs = 0; |
---|
2028 | *setmePeersSendingToUs = 0; |
---|
2029 | *setmeWebseedsSendingToUs = 0; |
---|
2030 | |
---|
2031 | for( i=0; i<TR_PEER_FROM__MAX; ++i ) |
---|
2032 | setmePeersFrom[i] = 0; |
---|
2033 | |
---|
2034 | for( i=0; i<size; ++i ) |
---|
2035 | { |
---|
2036 | const tr_peer * peer = peers[i]; |
---|
2037 | const struct peer_atom * atom = peer->atom; |
---|
2038 | |
---|
2039 | if( peer->io == NULL ) /* not connected */ |
---|
2040 | continue; |
---|
2041 | |
---|
2042 | ++*setmePeersConnected; |
---|
2043 | |
---|
2044 | ++setmePeersFrom[atom->from]; |
---|
2045 | |
---|
2046 | if( clientIsDownloadingFrom( peer ) ) |
---|
2047 | ++*setmePeersSendingToUs; |
---|
2048 | |
---|
2049 | if( clientIsUploadingTo( peer ) ) |
---|
2050 | ++*setmePeersGettingFromUs; |
---|
2051 | |
---|
2052 | if( atom->flags & ADDED_F_SEED_FLAG ) |
---|
2053 | ++*setmeSeedsConnected; |
---|
2054 | } |
---|
2055 | |
---|
2056 | webseeds = (const tr_webseed**) tr_ptrArrayBase( &t->webseeds ); |
---|
2057 | size = tr_ptrArraySize( &t->webseeds ); |
---|
2058 | for( i=0; i<size; ++i ) |
---|
2059 | if( tr_webseedIsActive( webseeds[i] ) ) |
---|
2060 | ++*setmeWebseedsSendingToUs; |
---|
2061 | |
---|
2062 | managerUnlock( t->manager ); |
---|
2063 | } |
---|
2064 | |
---|
2065 | float |
---|
2066 | tr_peerMgrGetWebseedSpeed( const tr_torrent * tor, uint64_t now ) |
---|
2067 | { |
---|
2068 | int i; |
---|
2069 | float tmp; |
---|
2070 | float ret = 0; |
---|
2071 | |
---|
2072 | const Torrent * t = tor->torrentPeers; |
---|
2073 | const int n = tr_ptrArraySize( &t->webseeds ); |
---|
2074 | const tr_webseed ** webseeds = (const tr_webseed**) tr_ptrArrayBase( &t->webseeds ); |
---|
2075 | |
---|
2076 | for( i=0; i<n; ++i ) |
---|
2077 | if( tr_webseedGetSpeed( webseeds[i], now, &tmp ) ) |
---|
2078 | ret += tmp; |
---|
2079 | |
---|
2080 | return ret; |
---|
2081 | } |
---|
2082 | |
---|
2083 | |
---|
2084 | float* |
---|
2085 | tr_peerMgrWebSpeeds( const tr_torrent * tor ) |
---|
2086 | { |
---|
2087 | const Torrent * t = tor->torrentPeers; |
---|
2088 | const tr_webseed ** webseeds; |
---|
2089 | int i; |
---|
2090 | int webseedCount; |
---|
2091 | float * ret; |
---|
2092 | uint64_t now; |
---|
2093 | |
---|
2094 | assert( t->manager ); |
---|
2095 | managerLock( t->manager ); |
---|
2096 | |
---|
2097 | webseeds = (const tr_webseed**) tr_ptrArrayBase( &t->webseeds ); |
---|
2098 | webseedCount = tr_ptrArraySize( &t->webseeds ); |
---|
2099 | assert( webseedCount == tor->info.webseedCount ); |
---|
2100 | ret = tr_new0( float, webseedCount ); |
---|
2101 | now = tr_date( ); |
---|
2102 | |
---|
2103 | for( i=0; i<webseedCount; ++i ) |
---|
2104 | if( !tr_webseedGetSpeed( webseeds[i], now, &ret[i] ) ) |
---|
2105 | ret[i] = -1.0; |
---|
2106 | |
---|
2107 | managerUnlock( t->manager ); |
---|
2108 | return ret; |
---|
2109 | } |
---|
2110 | |
---|
2111 | double |
---|
2112 | tr_peerGetPieceSpeed( const tr_peer * peer, uint64_t now, tr_direction direction ) |
---|
2113 | { |
---|
2114 | return peer->io ? tr_peerIoGetPieceSpeed( peer->io, now, direction ) : 0.0; |
---|
2115 | } |
---|
2116 | |
---|
2117 | |
---|
2118 | struct tr_peer_stat * |
---|
2119 | tr_peerMgrPeerStats( const tr_torrent * tor, |
---|
2120 | int * setmeCount ) |
---|
2121 | { |
---|
2122 | int i, size; |
---|
2123 | const Torrent * t = tor->torrentPeers; |
---|
2124 | const tr_peer ** peers; |
---|
2125 | tr_peer_stat * ret; |
---|
2126 | uint64_t now; |
---|
2127 | |
---|
2128 | assert( t->manager ); |
---|
2129 | managerLock( t->manager ); |
---|
2130 | |
---|
2131 | size = tr_ptrArraySize( &t->peers ); |
---|
2132 | peers = (const tr_peer**) tr_ptrArrayBase( &t->peers ); |
---|
2133 | ret = tr_new0( tr_peer_stat, size ); |
---|
2134 | now = tr_date( ); |
---|
2135 | |
---|
2136 | for( i=0; i<size; ++i ) |
---|
2137 | { |
---|
2138 | char * pch; |
---|
2139 | const tr_peer * peer = peers[i]; |
---|
2140 | const struct peer_atom * atom = peer->atom; |
---|
2141 | tr_peer_stat * stat = ret + i; |
---|
2142 | |
---|
2143 | tr_ntop( &atom->addr, stat->addr, sizeof( stat->addr ) ); |
---|
2144 | tr_strlcpy( stat->client, ( peer->client ? peer->client : "" ), |
---|
2145 | sizeof( stat->client ) ); |
---|
2146 | stat->port = ntohs( peer->atom->port ); |
---|
2147 | stat->from = atom->from; |
---|
2148 | stat->progress = peer->progress; |
---|
2149 | stat->isEncrypted = tr_peerIoIsEncrypted( peer->io ) ? 1 : 0; |
---|
2150 | stat->rateToPeer = tr_peerGetPieceSpeed( peer, now, TR_CLIENT_TO_PEER ); |
---|
2151 | stat->rateToClient = tr_peerGetPieceSpeed( peer, now, TR_PEER_TO_CLIENT ); |
---|
2152 | stat->peerIsChoked = peer->peerIsChoked; |
---|
2153 | stat->peerIsInterested = peer->peerIsInterested; |
---|
2154 | stat->clientIsChoked = peer->clientIsChoked; |
---|
2155 | stat->clientIsInterested = peer->clientIsInterested; |
---|
2156 | stat->isIncoming = tr_peerIoIsIncoming( peer->io ); |
---|
2157 | stat->isDownloadingFrom = clientIsDownloadingFrom( peer ); |
---|
2158 | stat->isUploadingTo = clientIsUploadingTo( peer ); |
---|
2159 | stat->isSeed = ( atom->uploadOnly == UPLOAD_ONLY_YES ) || ( peer->progress >= 1.0 ); |
---|
2160 | |
---|
2161 | pch = stat->flagStr; |
---|
2162 | if( t->optimistic == peer ) *pch++ = 'O'; |
---|
2163 | if( stat->isDownloadingFrom ) *pch++ = 'D'; |
---|
2164 | else if( stat->clientIsInterested ) *pch++ = 'd'; |
---|
2165 | if( stat->isUploadingTo ) *pch++ = 'U'; |
---|
2166 | else if( stat->peerIsInterested ) *pch++ = 'u'; |
---|
2167 | if( !stat->clientIsChoked && !stat->clientIsInterested ) *pch++ = 'K'; |
---|
2168 | if( !stat->peerIsChoked && !stat->peerIsInterested ) *pch++ = '?'; |
---|
2169 | if( stat->isEncrypted ) *pch++ = 'E'; |
---|
2170 | if( stat->from == TR_PEER_FROM_DHT ) *pch++ = 'H'; |
---|
2171 | if( stat->from == TR_PEER_FROM_PEX ) *pch++ = 'X'; |
---|
2172 | if( stat->isIncoming ) *pch++ = 'I'; |
---|
2173 | *pch = '\0'; |
---|
2174 | } |
---|
2175 | |
---|
2176 | *setmeCount = size; |
---|
2177 | |
---|
2178 | managerUnlock( t->manager ); |
---|
2179 | return ret; |
---|
2180 | } |
---|
2181 | |
---|
2182 | /** |
---|
2183 | *** |
---|
2184 | **/ |
---|
2185 | |
---|
2186 | struct ChokeData |
---|
2187 | { |
---|
2188 | tr_bool doUnchoke; |
---|
2189 | tr_bool isInterested; |
---|
2190 | tr_bool isChoked; |
---|
2191 | int rate; |
---|
2192 | tr_peer * peer; |
---|
2193 | }; |
---|
2194 | |
---|
2195 | static int |
---|
2196 | compareChoke( const void * va, |
---|
2197 | const void * vb ) |
---|
2198 | { |
---|
2199 | const struct ChokeData * a = va; |
---|
2200 | const struct ChokeData * b = vb; |
---|
2201 | |
---|
2202 | if( a->rate != b->rate ) /* prefer higher overall speeds */ |
---|
2203 | return a->rate > b->rate ? -1 : 1; |
---|
2204 | |
---|
2205 | if( a->isChoked != b->isChoked ) /* prefer unchoked */ |
---|
2206 | return a->isChoked ? 1 : -1; |
---|
2207 | |
---|
2208 | return 0; |
---|
2209 | } |
---|
2210 | |
---|
2211 | static int |
---|
2212 | isNew( const tr_peer * peer ) |
---|
2213 | { |
---|
2214 | return peer && peer->io && tr_peerIoGetAge( peer->io ) < 45; |
---|
2215 | } |
---|
2216 | |
---|
2217 | static int |
---|
2218 | isSame( const tr_peer * peer ) |
---|
2219 | { |
---|
2220 | return peer && peer->client && strstr( peer->client, "Transmission" ); |
---|
2221 | } |
---|
2222 | |
---|
2223 | /** |
---|
2224 | *** |
---|
2225 | **/ |
---|
2226 | |
---|
2227 | static void |
---|
2228 | rechokeTorrent( Torrent * t, const uint64_t now ) |
---|
2229 | { |
---|
2230 | int i, size, unchokedInterested; |
---|
2231 | const int peerCount = tr_ptrArraySize( &t->peers ); |
---|
2232 | tr_peer ** peers = (tr_peer**) tr_ptrArrayBase( &t->peers ); |
---|
2233 | struct ChokeData * choke = tr_new0( struct ChokeData, peerCount ); |
---|
2234 | const tr_session * session = t->manager->session; |
---|
2235 | const int chokeAll = !tr_torrentIsPieceTransferAllowed( t->tor, TR_CLIENT_TO_PEER ); |
---|
2236 | |
---|
2237 | assert( torrentIsLocked( t ) ); |
---|
2238 | |
---|
2239 | /* sort the peers by preference and rate */ |
---|
2240 | for( i = 0, size = 0; i < peerCount; ++i ) |
---|
2241 | { |
---|
2242 | tr_peer * peer = peers[i]; |
---|
2243 | struct peer_atom * atom = peer->atom; |
---|
2244 | |
---|
2245 | if( peer->progress >= 1.0 ) /* choke all seeds */ |
---|
2246 | { |
---|
2247 | tr_peerMsgsSetChoke( peer->msgs, TRUE ); |
---|
2248 | } |
---|
2249 | else if( atom->uploadOnly == UPLOAD_ONLY_YES ) /* choke partial seeds */ |
---|
2250 | { |
---|
2251 | tr_peerMsgsSetChoke( peer->msgs, TRUE ); |
---|
2252 | } |
---|
2253 | else if( chokeAll ) /* choke everyone if we're not uploading */ |
---|
2254 | { |
---|
2255 | tr_peerMsgsSetChoke( peer->msgs, TRUE ); |
---|
2256 | } |
---|
2257 | else |
---|
2258 | { |
---|
2259 | struct ChokeData * n = &choke[size++]; |
---|
2260 | n->peer = peer; |
---|
2261 | n->isInterested = peer->peerIsInterested; |
---|
2262 | n->isChoked = peer->peerIsChoked; |
---|
2263 | n->rate = tr_peerGetPieceSpeed( peer, now, TR_CLIENT_TO_PEER ) * 1024; |
---|
2264 | } |
---|
2265 | } |
---|
2266 | |
---|
2267 | qsort( choke, size, sizeof( struct ChokeData ), compareChoke ); |
---|
2268 | |
---|
2269 | /** |
---|
2270 | * Reciprocation and number of uploads capping is managed by unchoking |
---|
2271 | * the N peers which have the best upload rate and are interested. |
---|
2272 | * This maximizes the client's download rate. These N peers are |
---|
2273 | * referred to as downloaders, because they are interested in downloading |
---|
2274 | * from the client. |
---|
2275 | * |
---|
2276 | * Peers which have a better upload rate (as compared to the downloaders) |
---|
2277 | * but aren't interested get unchoked. If they become interested, the |
---|
2278 | * downloader with the worst upload rate gets choked. If a client has |
---|
2279 | * a complete file, it uses its upload rate rather than its download |
---|
2280 | * rate to decide which peers to unchoke. |
---|
2281 | */ |
---|
2282 | unchokedInterested = 0; |
---|
2283 | for( i=0; i<size && unchokedInterested<session->uploadSlotsPerTorrent; ++i ) { |
---|
2284 | choke[i].doUnchoke = 1; |
---|
2285 | if( choke[i].isInterested ) |
---|
2286 | ++unchokedInterested; |
---|
2287 | } |
---|
2288 | |
---|
2289 | /* optimistic unchoke */ |
---|
2290 | if( i < size ) |
---|
2291 | { |
---|
2292 | int n; |
---|
2293 | struct ChokeData * c; |
---|
2294 | tr_ptrArray randPool = TR_PTR_ARRAY_INIT; |
---|
2295 | |
---|
2296 | for( ; i<size; ++i ) |
---|
2297 | { |
---|
2298 | if( choke[i].isInterested ) |
---|
2299 | { |
---|
2300 | const tr_peer * peer = choke[i].peer; |
---|
2301 | int x = 1, y; |
---|
2302 | if( isNew( peer ) ) x *= 3; |
---|
2303 | if( isSame( peer ) ) x *= 3; |
---|
2304 | for( y=0; y<x; ++y ) |
---|
2305 | tr_ptrArrayAppend( &randPool, &choke[i] ); |
---|
2306 | } |
---|
2307 | } |
---|
2308 | |
---|
2309 | if(( n = tr_ptrArraySize( &randPool ))) |
---|
2310 | { |
---|
2311 | c = tr_ptrArrayNth( &randPool, tr_cryptoWeakRandInt( n )); |
---|
2312 | c->doUnchoke = 1; |
---|
2313 | t->optimistic = c->peer; |
---|
2314 | } |
---|
2315 | |
---|
2316 | tr_ptrArrayDestruct( &randPool, NULL ); |
---|
2317 | } |
---|
2318 | |
---|
2319 | for( i=0; i<size; ++i ) |
---|
2320 | tr_peerMsgsSetChoke( choke[i].peer->msgs, !choke[i].doUnchoke ); |
---|
2321 | |
---|
2322 | /* cleanup */ |
---|
2323 | tr_free( choke ); |
---|
2324 | } |
---|
2325 | |
---|
2326 | static int |
---|
2327 | rechokePulse( void * vmgr ) |
---|
2328 | { |
---|
2329 | uint64_t now; |
---|
2330 | tr_torrent * tor = NULL; |
---|
2331 | tr_peerMgr * mgr = vmgr; |
---|
2332 | managerLock( mgr ); |
---|
2333 | |
---|
2334 | now = tr_date( ); |
---|
2335 | while(( tor = tr_torrentNext( mgr->session, tor ))) |
---|
2336 | if( tor->isRunning ) |
---|
2337 | rechokeTorrent( tor->torrentPeers, now ); |
---|
2338 | |
---|
2339 | managerUnlock( mgr ); |
---|
2340 | return TRUE; |
---|
2341 | } |
---|
2342 | |
---|
2343 | /*** |
---|
2344 | **** |
---|
2345 | **** Life and Death |
---|
2346 | **** |
---|
2347 | ***/ |
---|
2348 | |
---|
2349 | typedef enum |
---|
2350 | { |
---|
2351 | TR_CAN_KEEP, |
---|
2352 | TR_CAN_CLOSE, |
---|
2353 | TR_MUST_CLOSE, |
---|
2354 | } |
---|
2355 | tr_close_type_t; |
---|
2356 | |
---|
2357 | static tr_close_type_t |
---|
2358 | shouldPeerBeClosed( const Torrent * t, |
---|
2359 | const tr_peer * peer, |
---|
2360 | int peerCount, |
---|
2361 | const time_t now ) |
---|
2362 | { |
---|
2363 | const tr_torrent * tor = t->tor; |
---|
2364 | const struct peer_atom * atom = peer->atom; |
---|
2365 | |
---|
2366 | /* if it's marked for purging, close it */ |
---|
2367 | if( peer->doPurge ) |
---|
2368 | { |
---|
2369 | tordbg( t, "purging peer %s because its doPurge flag is set", |
---|
2370 | tr_atomAddrStr( atom ) ); |
---|
2371 | return TR_MUST_CLOSE; |
---|
2372 | } |
---|
2373 | |
---|
2374 | /* if we're seeding and the peer has everything we have, |
---|
2375 | * and enough time has passed for a pex exchange, then disconnect */ |
---|
2376 | if( tr_torrentIsSeed( tor ) ) |
---|
2377 | { |
---|
2378 | int peerHasEverything; |
---|
2379 | if( atom->flags & ADDED_F_SEED_FLAG ) |
---|
2380 | peerHasEverything = TRUE; |
---|
2381 | else if( peer->progress < tr_cpPercentDone( &tor->completion ) ) |
---|
2382 | peerHasEverything = FALSE; |
---|
2383 | else { |
---|
2384 | tr_bitfield * tmp = tr_bitfieldDup( tr_cpPieceBitfield( &tor->completion ) ); |
---|
2385 | tr_bitfieldDifference( tmp, peer->have ); |
---|
2386 | peerHasEverything = tr_bitfieldCountTrueBits( tmp ) == 0; |
---|
2387 | tr_bitfieldFree( tmp ); |
---|
2388 | } |
---|
2389 | |
---|
2390 | if( peerHasEverything && ( !tr_torrentAllowsPex(tor) || (now-atom->time>=30 ))) |
---|
2391 | { |
---|
2392 | tordbg( t, "purging peer %s because we're both seeds", |
---|
2393 | tr_atomAddrStr( atom ) ); |
---|
2394 | return TR_MUST_CLOSE; |
---|
2395 | } |
---|
2396 | } |
---|
2397 | |
---|
2398 | /* disconnect if it's been too long since piece data has been transferred. |
---|
2399 | * this is on a sliding scale based on number of available peers... */ |
---|
2400 | { |
---|
2401 | const int relaxStrictnessIfFewerThanN = (int)( ( getMaxPeerCount( tor ) * 0.9 ) + 0.5 ); |
---|
2402 | /* if we have >= relaxIfFewerThan, strictness is 100%. |
---|
2403 | * if we have zero connections, strictness is 0% */ |
---|
2404 | const float strictness = peerCount >= relaxStrictnessIfFewerThanN |
---|
2405 | ? 1.0 |
---|
2406 | : peerCount / (float)relaxStrictnessIfFewerThanN; |
---|
2407 | const int lo = MIN_UPLOAD_IDLE_SECS; |
---|
2408 | const int hi = MAX_UPLOAD_IDLE_SECS; |
---|
2409 | const int limit = hi - ( ( hi - lo ) * strictness ); |
---|
2410 | const int idleTime = now - MAX( atom->time, atom->piece_data_time ); |
---|
2411 | /*fprintf( stderr, "strictness is %.3f, limit is %d seconds... time since connect is %d, time since piece is %d ... idleTime is %d, doPurge is %d\n", (double)strictness, limit, (int)(now - atom->time), (int)(now - atom->piece_data_time), idleTime, idleTime > limit );*/ |
---|
2412 | if( idleTime > limit ) { |
---|
2413 | tordbg( t, "purging peer %s because it's been %d secs since we shared anything", |
---|
2414 | tr_atomAddrStr( atom ), idleTime ); |
---|
2415 | return TR_CAN_CLOSE; |
---|
2416 | } |
---|
2417 | } |
---|
2418 | |
---|
2419 | return TR_CAN_KEEP; |
---|
2420 | } |
---|
2421 | |
---|
2422 | static void sortPeersByLivelinessReverse( tr_peer ** peers, void ** clientData, int n, uint64_t now ); |
---|
2423 | |
---|
2424 | static tr_peer ** |
---|
2425 | getPeersToClose( Torrent * t, tr_close_type_t closeType, const time_t now, int * setmeSize ) |
---|
2426 | { |
---|
2427 | int i, peerCount, outsize; |
---|
2428 | tr_peer ** peers = (tr_peer**) tr_ptrArrayPeek( &t->peers, &peerCount ); |
---|
2429 | struct tr_peer ** ret = tr_new( tr_peer *, peerCount ); |
---|
2430 | |
---|
2431 | assert( torrentIsLocked( t ) ); |
---|
2432 | |
---|
2433 | for( i = outsize = 0; i < peerCount; ++i ) |
---|
2434 | if( shouldPeerBeClosed( t, peers[i], peerCount, now ) == closeType ) |
---|
2435 | ret[outsize++] = peers[i]; |
---|
2436 | |
---|
2437 | sortPeersByLivelinessReverse ( ret, NULL, outsize, tr_date( ) ); |
---|
2438 | |
---|
2439 | *setmeSize = outsize; |
---|
2440 | return ret; |
---|
2441 | } |
---|
2442 | |
---|
2443 | static int |
---|
2444 | compareCandidates( const void * va, const void * vb ) |
---|
2445 | { |
---|
2446 | const struct peer_atom * a = *(const struct peer_atom**) va; |
---|
2447 | const struct peer_atom * b = *(const struct peer_atom**) vb; |
---|
2448 | |
---|
2449 | /* <Charles> Here we would probably want to try reconnecting to |
---|
2450 | * peers that had most recently given us data. Lots of users have |
---|
2451 | * trouble with resets due to their routers and/or ISPs. This way we |
---|
2452 | * can quickly recover from an unwanted reset. So we sort |
---|
2453 | * piece_data_time in descending order. |
---|
2454 | */ |
---|
2455 | |
---|
2456 | if( a->piece_data_time != b->piece_data_time ) |
---|
2457 | return a->piece_data_time < b->piece_data_time ? 1 : -1; |
---|
2458 | |
---|
2459 | if( a->numFails != b->numFails ) |
---|
2460 | return a->numFails < b->numFails ? -1 : 1; |
---|
2461 | |
---|
2462 | if( a->time != b->time ) |
---|
2463 | return a->time < b->time ? -1 : 1; |
---|
2464 | |
---|
2465 | /* In order to avoid fragmenting the swarm, peers from trackers and |
---|
2466 | * from the DHT should be preferred to peers from PEX. */ |
---|
2467 | if( a->from != b->from ) |
---|
2468 | return a->from < b->from ? -1 : 1; |
---|
2469 | |
---|
2470 | return 0; |
---|
2471 | } |
---|
2472 | |
---|
2473 | static int |
---|
2474 | getReconnectIntervalSecs( const struct peer_atom * atom, const time_t now ) |
---|
2475 | { |
---|
2476 | int sec; |
---|
2477 | |
---|
2478 | /* if we were recently connected to this peer and transferring piece |
---|
2479 | * data, try to reconnect to them sooner rather that later -- we don't |
---|
2480 | * want network troubles to get in the way of a good peer. */ |
---|
2481 | if( ( now - atom->piece_data_time ) <= ( MINIMUM_RECONNECT_INTERVAL_SECS * 2 ) ) |
---|
2482 | sec = MINIMUM_RECONNECT_INTERVAL_SECS; |
---|
2483 | |
---|
2484 | /* don't allow reconnects more often than our minimum */ |
---|
2485 | else if( ( now - atom->time ) < MINIMUM_RECONNECT_INTERVAL_SECS ) |
---|
2486 | sec = MINIMUM_RECONNECT_INTERVAL_SECS; |
---|
2487 | |
---|
2488 | /* otherwise, the interval depends on how many times we've tried |
---|
2489 | * and failed to connect to the peer */ |
---|
2490 | else switch( atom->numFails ) { |
---|
2491 | case 0: sec = 0; break; |
---|
2492 | case 1: sec = 5; break; |
---|
2493 | case 2: sec = 2 * 60; break; |
---|
2494 | case 3: sec = 15 * 60; break; |
---|
2495 | case 4: sec = 30 * 60; break; |
---|
2496 | case 5: sec = 60 * 60; break; |
---|
2497 | default: sec = 120 * 60; break; |
---|
2498 | } |
---|
2499 | |
---|
2500 | return sec; |
---|
2501 | } |
---|
2502 | |
---|
2503 | static struct peer_atom ** |
---|
2504 | getPeerCandidates( Torrent * t, const time_t now, int * setmeSize ) |
---|
2505 | { |
---|
2506 | int i, atomCount, retCount; |
---|
2507 | struct peer_atom ** atoms; |
---|
2508 | struct peer_atom ** ret; |
---|
2509 | const int seed = tr_torrentIsSeed( t->tor ); |
---|
2510 | |
---|
2511 | assert( torrentIsLocked( t ) ); |
---|
2512 | |
---|
2513 | atoms = (struct peer_atom**) tr_ptrArrayPeek( &t->pool, &atomCount ); |
---|
2514 | ret = tr_new( struct peer_atom*, atomCount ); |
---|
2515 | for( i = retCount = 0; i < atomCount; ++i ) |
---|
2516 | { |
---|
2517 | int interval; |
---|
2518 | struct peer_atom * atom = atoms[i]; |
---|
2519 | |
---|
2520 | /* peer fed us too much bad data ... we only keep it around |
---|
2521 | * now to weed it out in case someone sends it to us via pex */ |
---|
2522 | if( atom->myflags & MYFLAG_BANNED ) |
---|
2523 | continue; |
---|
2524 | |
---|
2525 | /* peer was unconnectable before, so we're not going to keep trying. |
---|
2526 | * this is needs a separate flag from `banned', since if they try |
---|
2527 | * to connect to us later, we'll let them in */ |
---|
2528 | if( atom->myflags & MYFLAG_UNREACHABLE ) |
---|
2529 | continue; |
---|
2530 | |
---|
2531 | /* we don't need two connections to the same peer... */ |
---|
2532 | if( peerIsInUse( t, &atom->addr ) ) |
---|
2533 | continue; |
---|
2534 | |
---|
2535 | /* no need to connect if we're both seeds... */ |
---|
2536 | if( seed && ( ( atom->flags & ADDED_F_SEED_FLAG ) || |
---|
2537 | ( atom->uploadOnly == UPLOAD_ONLY_YES ) ) ) |
---|
2538 | continue; |
---|
2539 | |
---|
2540 | /* don't reconnect too often */ |
---|
2541 | interval = getReconnectIntervalSecs( atom, now ); |
---|
2542 | if( ( now - atom->time ) < interval ) |
---|
2543 | { |
---|
2544 | tordbg( t, "RECONNECT peer %d (%s) is in its grace period of %d seconds..", |
---|
2545 | i, tr_atomAddrStr( atom ), interval ); |
---|
2546 | continue; |
---|
2547 | } |
---|
2548 | |
---|
2549 | /* Don't connect to peers in our blocklist */ |
---|
2550 | if( tr_sessionIsAddressBlocked( t->manager->session, &atom->addr ) ) |
---|
2551 | continue; |
---|
2552 | |
---|
2553 | ret[retCount++] = atom; |
---|
2554 | } |
---|
2555 | |
---|
2556 | qsort( ret, retCount, sizeof( struct peer_atom* ), compareCandidates ); |
---|
2557 | *setmeSize = retCount; |
---|
2558 | return ret; |
---|
2559 | } |
---|
2560 | |
---|
2561 | static void |
---|
2562 | closePeer( Torrent * t, tr_peer * peer ) |
---|
2563 | { |
---|
2564 | struct peer_atom * atom; |
---|
2565 | |
---|
2566 | assert( t != NULL ); |
---|
2567 | assert( peer != NULL ); |
---|
2568 | |
---|
2569 | atom = peer->atom; |
---|
2570 | |
---|
2571 | /* if we transferred piece data, then they might be good peers, |
---|
2572 | so reset their `numFails' weight to zero. otherwise we connected |
---|
2573 | to them fruitlessly, so mark it as another fail */ |
---|
2574 | if( atom->piece_data_time ) |
---|
2575 | atom->numFails = 0; |
---|
2576 | else |
---|
2577 | ++atom->numFails; |
---|
2578 | |
---|
2579 | tordbg( t, "removing bad peer %s", tr_peerIoGetAddrStr( peer->io ) ); |
---|
2580 | removePeer( t, peer ); |
---|
2581 | } |
---|
2582 | |
---|
2583 | static void |
---|
2584 | reconnectTorrent( Torrent * t ) |
---|
2585 | { |
---|
2586 | static time_t prevTime = 0; |
---|
2587 | static int newConnectionsThisSecond = 0; |
---|
2588 | const time_t now = time( NULL ); |
---|
2589 | |
---|
2590 | if( prevTime != now ) |
---|
2591 | { |
---|
2592 | prevTime = now; |
---|
2593 | newConnectionsThisSecond = 0; |
---|
2594 | } |
---|
2595 | |
---|
2596 | if( !t->isRunning ) |
---|
2597 | { |
---|
2598 | removeAllPeers( t ); |
---|
2599 | } |
---|
2600 | else |
---|
2601 | { |
---|
2602 | int i; |
---|
2603 | int canCloseCount; |
---|
2604 | int mustCloseCount; |
---|
2605 | int candidateCount; |
---|
2606 | int maxCandidates; |
---|
2607 | struct tr_peer ** canClose = getPeersToClose( t, TR_CAN_CLOSE, now, &canCloseCount ); |
---|
2608 | struct tr_peer ** mustClose = getPeersToClose( t, TR_MUST_CLOSE, now, &mustCloseCount ); |
---|
2609 | struct peer_atom ** candidates = getPeerCandidates( t, now, &candidateCount ); |
---|
2610 | |
---|
2611 | tordbg( t, "reconnect pulse for [%s]: " |
---|
2612 | "%d must-close connections, " |
---|
2613 | "%d can-close connections, " |
---|
2614 | "%d connection candidates, " |
---|
2615 | "%d atoms, " |
---|
2616 | "max per pulse is %d", |
---|
2617 | tr_torrentName( t->tor ), |
---|
2618 | mustCloseCount, |
---|
2619 | canCloseCount, |
---|
2620 | candidateCount, |
---|
2621 | tr_ptrArraySize( &t->pool ), |
---|
2622 | MAX_RECONNECTIONS_PER_PULSE ); |
---|
2623 | |
---|
2624 | /* disconnect the really bad peers */ |
---|
2625 | for( i=0; i<mustCloseCount; ++i ) |
---|
2626 | closePeer( t, mustClose[i] ); |
---|
2627 | |
---|
2628 | /* decide how many peers can we try to add in this pass */ |
---|
2629 | maxCandidates = candidateCount; |
---|
2630 | maxCandidates = MIN( maxCandidates, MAX_RECONNECTIONS_PER_PULSE ); |
---|
2631 | maxCandidates = MIN( maxCandidates, getMaxPeerCount( t->tor ) - getPeerCount( t ) ); |
---|
2632 | maxCandidates = MIN( maxCandidates, MAX_CONNECTIONS_PER_SECOND - newConnectionsThisSecond ); |
---|
2633 | |
---|
2634 | /* maybe disconnect some lesser peers, if we have candidates to replace them with */ |
---|
2635 | for( i=0; ( i<canCloseCount ) && ( i<maxCandidates ); ++i ) |
---|
2636 | closePeer( t, canClose[i] ); |
---|
2637 | |
---|
2638 | tordbg( t, "candidateCount is %d, MAX_RECONNECTIONS_PER_PULSE is %d," |
---|
2639 | " getPeerCount(t) is %d, getMaxPeerCount(t) is %d, " |
---|
2640 | "newConnectionsThisSecond is %d, MAX_CONNECTIONS_PER_SECOND is %d", |
---|
2641 | candidateCount, |
---|
2642 | MAX_RECONNECTIONS_PER_PULSE, |
---|
2643 | getPeerCount( t ), |
---|
2644 | getMaxPeerCount( t->tor ), |
---|
2645 | newConnectionsThisSecond, MAX_CONNECTIONS_PER_SECOND ); |
---|
2646 | |
---|
2647 | /* add some new ones */ |
---|
2648 | for( i=0; i<maxCandidates; ++i ) |
---|
2649 | { |
---|
2650 | tr_peerMgr * mgr = t->manager; |
---|
2651 | struct peer_atom * atom = candidates[i]; |
---|
2652 | tr_peerIo * io; |
---|
2653 | |
---|
2654 | tordbg( t, "Starting an OUTGOING connection with %s", |
---|
2655 | tr_atomAddrStr( atom ) ); |
---|
2656 | |
---|
2657 | io = tr_peerIoNewOutgoing( mgr->session, mgr->session->bandwidth, &atom->addr, atom->port, t->tor->info.hash ); |
---|
2658 | |
---|
2659 | if( io == NULL ) |
---|
2660 | { |
---|
2661 | tordbg( t, "peerIo not created; marking peer %s as unreachable", |
---|
2662 | tr_atomAddrStr( atom ) ); |
---|
2663 | atom->myflags |= MYFLAG_UNREACHABLE; |
---|
2664 | } |
---|
2665 | else |
---|
2666 | { |
---|
2667 | tr_handshake * handshake = tr_handshakeNew( io, |
---|
2668 | mgr->session->encryptionMode, |
---|
2669 | myHandshakeDoneCB, |
---|
2670 | mgr ); |
---|
2671 | |
---|
2672 | assert( tr_peerIoGetTorrentHash( io ) ); |
---|
2673 | |
---|
2674 | tr_peerIoUnref( io ); /* balanced by the implicit ref in tr_peerIoNewOutgoing() */ |
---|
2675 | |
---|
2676 | ++newConnectionsThisSecond; |
---|
2677 | |
---|
2678 | tr_ptrArrayInsertSorted( &t->outgoingHandshakes, handshake, |
---|
2679 | handshakeCompare ); |
---|
2680 | } |
---|
2681 | |
---|
2682 | atom->time = now; |
---|
2683 | } |
---|
2684 | |
---|
2685 | /* cleanup */ |
---|
2686 | tr_free( candidates ); |
---|
2687 | tr_free( mustClose ); |
---|
2688 | tr_free( canClose ); |
---|
2689 | } |
---|
2690 | } |
---|
2691 | |
---|
2692 | struct peer_liveliness |
---|
2693 | { |
---|
2694 | tr_peer * peer; |
---|
2695 | void * clientData; |
---|
2696 | time_t pieceDataTime; |
---|
2697 | time_t time; |
---|
2698 | int speed; |
---|
2699 | tr_bool doPurge; |
---|
2700 | }; |
---|
2701 | |
---|
2702 | static int |
---|
2703 | comparePeerLiveliness( const void * va, const void * vb ) |
---|
2704 | { |
---|
2705 | const struct peer_liveliness * a = va; |
---|
2706 | const struct peer_liveliness * b = vb; |
---|
2707 | |
---|
2708 | if( a->doPurge != b->doPurge ) |
---|
2709 | return a->doPurge ? 1 : -1; |
---|
2710 | |
---|
2711 | if( a->speed != b->speed ) /* faster goes first */ |
---|
2712 | return a->speed > b->speed ? -1 : 1; |
---|
2713 | |
---|
2714 | /* the one to give us data more recently goes first */ |
---|
2715 | if( a->pieceDataTime != b->pieceDataTime ) |
---|
2716 | return a->pieceDataTime > b->pieceDataTime ? -1 : 1; |
---|
2717 | |
---|
2718 | /* the one we connected to most recently goes first */ |
---|
2719 | if( a->time != b->time ) |
---|
2720 | return a->time > b->time ? -1 : 1; |
---|
2721 | |
---|
2722 | return 0; |
---|
2723 | } |
---|
2724 | |
---|
2725 | static int |
---|
2726 | comparePeerLivelinessReverse( const void * va, const void * vb ) |
---|
2727 | { |
---|
2728 | return -comparePeerLiveliness (va, vb); |
---|
2729 | } |
---|
2730 | |
---|
2731 | static void |
---|
2732 | sortPeersByLivelinessImpl( tr_peer ** peers, |
---|
2733 | void ** clientData, |
---|
2734 | int n, |
---|
2735 | uint64_t now, |
---|
2736 | int (*compare) ( const void *va, const void *vb ) ) |
---|
2737 | { |
---|
2738 | int i; |
---|
2739 | struct peer_liveliness *lives, *l; |
---|
2740 | |
---|
2741 | /* build a sortable array of peer + extra info */ |
---|
2742 | lives = l = tr_new0( struct peer_liveliness, n ); |
---|
2743 | for( i=0; i<n; ++i, ++l ) |
---|
2744 | { |
---|
2745 | tr_peer * p = peers[i]; |
---|
2746 | l->peer = p; |
---|
2747 | l->doPurge = p->doPurge; |
---|
2748 | l->pieceDataTime = p->atom->piece_data_time; |
---|
2749 | l->time = p->atom->time; |
---|
2750 | l->speed = 1024.0 * ( tr_peerGetPieceSpeed( p, now, TR_UP ) |
---|
2751 | + tr_peerGetPieceSpeed( p, now, TR_DOWN ) ); |
---|
2752 | if( clientData ) |
---|
2753 | l->clientData = clientData[i]; |
---|
2754 | } |
---|
2755 | |
---|
2756 | /* sort 'em */ |
---|
2757 | assert( n == ( l - lives ) ); |
---|
2758 | qsort( lives, n, sizeof( struct peer_liveliness ), compare ); |
---|
2759 | |
---|
2760 | /* build the peer array */ |
---|
2761 | for( i=0, l=lives; i<n; ++i, ++l ) { |
---|
2762 | peers[i] = l->peer; |
---|
2763 | if( clientData ) |
---|
2764 | clientData[i] = l->clientData; |
---|
2765 | } |
---|
2766 | assert( n == ( l - lives ) ); |
---|
2767 | |
---|
2768 | /* cleanup */ |
---|
2769 | tr_free( lives ); |
---|
2770 | } |
---|
2771 | |
---|
2772 | static void |
---|
2773 | sortPeersByLiveliness( tr_peer ** peers, void ** clientData, int n, uint64_t now ) |
---|
2774 | { |
---|
2775 | sortPeersByLivelinessImpl( peers, clientData, n, now, comparePeerLiveliness ); |
---|
2776 | } |
---|
2777 | |
---|
2778 | static void |
---|
2779 | sortPeersByLivelinessReverse( tr_peer ** peers, void ** clientData, int n, uint64_t now ) |
---|
2780 | { |
---|
2781 | sortPeersByLivelinessImpl( peers, clientData, n, now, comparePeerLivelinessReverse ); |
---|
2782 | } |
---|
2783 | |
---|
2784 | |
---|
2785 | static void |
---|
2786 | enforceTorrentPeerLimit( Torrent * t, uint64_t now ) |
---|
2787 | { |
---|
2788 | int n = tr_ptrArraySize( &t->peers ); |
---|
2789 | const int max = tr_torrentGetPeerLimit( t->tor ); |
---|
2790 | if( n > max ) |
---|
2791 | { |
---|
2792 | void * base = tr_ptrArrayBase( &t->peers ); |
---|
2793 | tr_peer ** peers = tr_memdup( base, n*sizeof( tr_peer* ) ); |
---|
2794 | sortPeersByLiveliness( peers, NULL, n, now ); |
---|
2795 | while( n > max ) |
---|
2796 | closePeer( t, peers[--n] ); |
---|
2797 | tr_free( peers ); |
---|
2798 | } |
---|
2799 | } |
---|
2800 | |
---|
2801 | static void |
---|
2802 | enforceSessionPeerLimit( tr_session * session, uint64_t now ) |
---|
2803 | { |
---|
2804 | int n = 0; |
---|
2805 | tr_torrent * tor = NULL; |
---|
2806 | const int max = tr_sessionGetPeerLimit( session ); |
---|
2807 | |
---|
2808 | /* count the total number of peers */ |
---|
2809 | while(( tor = tr_torrentNext( session, tor ))) |
---|
2810 | n += tr_ptrArraySize( &tor->torrentPeers->peers ); |
---|
2811 | |
---|
2812 | /* if there are too many, prune out the worst */ |
---|
2813 | if( n > max ) |
---|
2814 | { |
---|
2815 | tr_peer ** peers = tr_new( tr_peer*, n ); |
---|
2816 | Torrent ** torrents = tr_new( Torrent*, n ); |
---|
2817 | |
---|
2818 | /* populate the peer array */ |
---|
2819 | n = 0; |
---|
2820 | tor = NULL; |
---|
2821 | while(( tor = tr_torrentNext( session, tor ))) { |
---|
2822 | int i; |
---|
2823 | Torrent * t = tor->torrentPeers; |
---|
2824 | const int tn = tr_ptrArraySize( &t->peers ); |
---|
2825 | for( i=0; i<tn; ++i, ++n ) { |
---|
2826 | peers[n] = tr_ptrArrayNth( &t->peers, i ); |
---|
2827 | torrents[n] = t; |
---|
2828 | } |
---|
2829 | } |
---|
2830 | |
---|
2831 | /* sort 'em */ |
---|
2832 | sortPeersByLiveliness( peers, (void**)torrents, n, now ); |
---|
2833 | |
---|
2834 | /* cull out the crappiest */ |
---|
2835 | while( n-- > max ) |
---|
2836 | closePeer( torrents[n], peers[n] ); |
---|
2837 | |
---|
2838 | /* cleanup */ |
---|
2839 | tr_free( torrents ); |
---|
2840 | tr_free( peers ); |
---|
2841 | } |
---|
2842 | } |
---|
2843 | |
---|
2844 | |
---|
2845 | static int |
---|
2846 | reconnectPulse( void * vmgr ) |
---|
2847 | { |
---|
2848 | tr_torrent * tor; |
---|
2849 | tr_peerMgr * mgr = vmgr; |
---|
2850 | uint64_t now; |
---|
2851 | managerLock( mgr ); |
---|
2852 | |
---|
2853 | now = tr_date( ); |
---|
2854 | |
---|
2855 | /* if we're over the per-torrent peer limits, cull some peers */ |
---|
2856 | tor = NULL; |
---|
2857 | while(( tor = tr_torrentNext( mgr->session, tor ))) |
---|
2858 | if( tor->isRunning ) |
---|
2859 | enforceTorrentPeerLimit( tor->torrentPeers, now ); |
---|
2860 | |
---|
2861 | /* if we're over the per-session peer limits, cull some peers */ |
---|
2862 | enforceSessionPeerLimit( mgr->session, now ); |
---|
2863 | |
---|
2864 | tor = NULL; |
---|
2865 | while(( tor = tr_torrentNext( mgr->session, tor ))) |
---|
2866 | if( tor->isRunning ) |
---|
2867 | reconnectTorrent( tor->torrentPeers ); |
---|
2868 | |
---|
2869 | managerUnlock( mgr ); |
---|
2870 | return TRUE; |
---|
2871 | } |
---|
2872 | |
---|
2873 | /**** |
---|
2874 | ***** |
---|
2875 | ***** BANDWIDTH ALLOCATION |
---|
2876 | ***** |
---|
2877 | ****/ |
---|
2878 | |
---|
2879 | static void |
---|
2880 | pumpAllPeers( tr_peerMgr * mgr ) |
---|
2881 | { |
---|
2882 | tr_torrent * tor = NULL; |
---|
2883 | |
---|
2884 | while(( tor = tr_torrentNext( mgr->session, tor ))) |
---|
2885 | { |
---|
2886 | int j; |
---|
2887 | Torrent * t = tor->torrentPeers; |
---|
2888 | |
---|
2889 | for( j=0; j<tr_ptrArraySize( &t->peers ); ++j ) |
---|
2890 | { |
---|
2891 | tr_peer * peer = tr_ptrArrayNth( &t->peers, j ); |
---|
2892 | tr_peerMsgsPulse( peer->msgs ); |
---|
2893 | } |
---|
2894 | } |
---|
2895 | } |
---|
2896 | |
---|
2897 | static int |
---|
2898 | bandwidthPulse( void * vmgr ) |
---|
2899 | { |
---|
2900 | tr_torrent * tor = NULL; |
---|
2901 | tr_peerMgr * mgr = vmgr; |
---|
2902 | managerLock( mgr ); |
---|
2903 | |
---|
2904 | /* FIXME: this next line probably isn't necessary... */ |
---|
2905 | pumpAllPeers( mgr ); |
---|
2906 | |
---|
2907 | /* allocate bandwidth to the peers */ |
---|
2908 | tr_bandwidthAllocate( mgr->session->bandwidth, TR_UP, BANDWIDTH_PERIOD_MSEC ); |
---|
2909 | tr_bandwidthAllocate( mgr->session->bandwidth, TR_DOWN, BANDWIDTH_PERIOD_MSEC ); |
---|
2910 | |
---|
2911 | /* possibly stop torrents that have seeded enough */ |
---|
2912 | while(( tor = tr_torrentNext( mgr->session, tor ))) { |
---|
2913 | if( tor->needsSeedRatioCheck ) { |
---|
2914 | tor->needsSeedRatioCheck = FALSE; |
---|
2915 | tr_torrentCheckSeedRatio( tor ); |
---|
2916 | } |
---|
2917 | } |
---|
2918 | |
---|
2919 | /* run the completeness check for any torrents that need it */ |
---|
2920 | tor = NULL; |
---|
2921 | while(( tor = tr_torrentNext( mgr->session, tor ))) { |
---|
2922 | if( tor->torrentPeers->needsCompletenessCheck ) { |
---|
2923 | tor->torrentPeers->needsCompletenessCheck = FALSE; |
---|
2924 | tr_torrentRecheckCompleteness( tor ); |
---|
2925 | } |
---|
2926 | } |
---|
2927 | |
---|
2928 | /* possibly stop torrents that have an error */ |
---|
2929 | tor = NULL; |
---|
2930 | while(( tor = tr_torrentNext( mgr->session, tor ))) |
---|
2931 | if( tor->isRunning && ( tor->error == TR_STAT_LOCAL_ERROR )) |
---|
2932 | tr_torrentStop( tor ); |
---|
2933 | |
---|
2934 | managerUnlock( mgr ); |
---|
2935 | return TRUE; |
---|
2936 | } |
---|