source: trunk/libtransmission/peer.c @ 2428

Last change on this file since 2428 was 2428, checked in by charles, 15 years ago

remove the TR_HTONL macro

  • Property svn:keywords set to Date Rev Author Id
File size: 26.5 KB
Line 
1/******************************************************************************
2 * $Id: peer.c 2428 2007-07-19 10:49:44Z charles $
3 *
4 * Copyright (c) 2005-2007 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#include <sys/types.h>
26#include <sys/socket.h>
27#include <netinet/in.h>
28#include <arpa/inet.h>
29#include <stdarg.h>
30
31#include "transmission.h"
32#include "bencode.h"
33#include "clients.h" /* for tr_clientForId() */
34#include "peertree.h"
35#include "list.h"
36#include "net.h"
37
38/*****
39******
40*****/
41
42/**
43*** The "SWIFT" system is described by Karthik Tamilmani,
44*** Vinay Pai, and Alexander Mohr of Stony Brook University
45*** in their paper "SWIFT: A System With Incentives For Trading"
46*** http://citeseer.ist.psu.edu/tamilmani04swift.html
47**/
48
49/**
50 * Use SWIFT?
51 */
52static const int SWIFT_ENABLED = 1;
53
54/**
55 * For every byte the peer uploads to us,
56 * allow them to download this many bytes from us
57 */
58static const double SWIFT_REPAYMENT_RATIO = 1.33;
59
60/**
61 * Allow new peers to download this many bytes from
62 * us when getting started.  This can prevent gridlock
63 * with other peers using tit-for-tat algorithms
64 */
65static const int SWIFT_INITIAL_CREDIT = 64 * 1024; /* 64 KiB */
66
67/**
68 * We expend a fraction of our torrent's total upload speed
69 * on largesse by uniformly distributing free credit to
70 * all of our peers.  This too helps prevent gridlock.
71 */
72static const double SWIFT_LARGESSE = 0.10; /* 10% of our UL */
73
74/**
75 * How frequently to extend largesse-based credit
76 */
77static const int SWIFT_REFRESH_INTERVAL_SEC = 5;
78
79/*****
80******
81*****/
82
83#define PERCENT_PEER_WANTED     25      /* Percent before we start relax peers min activeness */
84#define MIN_UPLOAD_IDLE         60000   /* In high peer situations we wait only 1 min
85                                            until dropping peers for idling */
86#define MAX_UPLOAD_IDLE         240000  /* In low peer situations we wait the
87                                            4 mins until dropping peers for idling */
88#define MIN_KEEP_ALIVE          180000  /* In high peer situations we wait only 3 min
89                                            without a keep-alive */
90#define MAX_KEEP_ALIVE          360000  /* In low peer situations we wait the
91                                            6 mins without a keep-alive */
92#define MIN_CON_TIMEOUT         8000    /* Time to timeout connecting to peer,
93                                            during low peer situations */
94#define MAX_CON_TIMEOUT         30000   /* Time to timeout connecting to peer,
95                                            during high peer situations */
96#define PEX_PEER_CUTOFF         50 /* only try to add new peers from pex if
97                                      we have fewer existing peers than this */
98#define PEX_INTERVAL            60 /* don't send pex messages more frequently
99                                      than PEX_INTERVAL +
100                                      rand( PEX_INTERVAL / 10 ) seconds */
101#define PEER_SUPPORTS_EXTENDED_MESSAGES( bits ) ( (bits)[5] & 0x10 )
102#define PEER_SUPPORTS_AZUREUS_PROTOCOL( bits )  ( (bits)[0] & 0x80 )
103
104#define PEER_MSG_CHOKE          0
105#define PEER_MSG_UNCHOKE        1
106#define PEER_MSG_INTERESTED     2
107#define PEER_MSG_UNINTERESTED   3
108#define PEER_MSG_HAVE           4
109#define PEER_MSG_BITFIELD       5
110#define PEER_MSG_REQUEST        6
111#define PEER_MSG_PIECE          7
112#define PEER_MSG_CANCEL         8
113#define PEER_MSG_PORT           9
114#define PEER_MSG_EXTENDED       20
115
116typedef struct tr_request_s
117{
118    int index;
119    int begin;
120    int length;
121
122} tr_request_t;
123
124struct tr_peer_s
125{
126    tr_torrent_t      * tor;
127
128    struct in_addr      addr;
129    in_port_t           port;  /* peer's listening port, 0 if not known */
130
131#define PEER_STATUS_IDLE        1 /* Need to connect */
132#define PEER_STATUS_CONNECTING  2 /* Trying to send handshake */
133#define PEER_STATUS_HANDSHAKE   3 /* Waiting for peer's handshake */
134#define PEER_STATUS_AZ_GIVER    4 /* Sending Azureus handshake */
135#define PEER_STATUS_AZ_RECEIVER 5 /* Receiving Azureus handshake */
136#define PEER_STATUS_CONNECTED   6 /* Got peer's handshake */
137    int                 status;
138    int                 socket;
139    char                from;
140    char                private;
141    char                azproto;  /* azureus peer protocol is being used */
142    uint64_t            date;
143    uint64_t            keepAlive;
144
145#define EXTENDED_NOT_SUPPORTED   0 /* extended messages not supported */
146#define EXTENDED_SUPPORTED       1 /* waiting to send extended handshake */
147#define EXTENDED_HANDSHAKE       2 /* sent extended handshake */
148    uint8_t             extStatus;
149    uint8_t             pexStatus;   /* peer's ut_pex id, 0 if not supported */
150    uint64_t            lastPex;     /* time when last pex packet was sent */
151    int                 advertisedPort; /* listening port we last told peer */
152    tr_peertree_t       sentPeers;
153
154    char                isChokedByUs;
155    char                isChokingUs;
156    char                isInteresting;
157    char                isInterested;
158
159    int                 optimistic;
160    int                 timesChoked;
161    uint64_t            lastChoke;
162
163    uint8_t             id[TR_ID_LEN];
164
165    /* The pieces that the peer has */
166    tr_bitfield_t     * bitfield;
167
168    /* blocks we've requested from this peer */
169    tr_bitfield_t     * reqfield;
170    int                 pieceCount;
171    float               progress;
172
173    int                 goodPcs;
174    int                 badPcs;
175    int                 banned;
176    /* The pieces that the peer is contributing to */
177    tr_bitfield_t     * blamefield;
178    /* The bad pieces that the peer has contributed to */
179    tr_bitfield_t     * banfield;
180
181    uint8_t           * buf;
182    int                 size;
183    int                 pos;
184
185    uint8_t           * outMessages;
186    int                 outMessagesSize;
187    int                 outMessagesPos;
188    uint8_t             outBlock[25+16384];
189    int                 outBlockSize;
190    int                 outBlockLoaded;
191    int                 outBlockSending;
192
193    int                 inRequestCount;
194    int                 inRequestMax;
195    int                 inRequestAlloc;
196    tr_request_t      * inRequests;
197    int                 inIndex;
198    int                 inBegin;
199    int                 inLength;
200
201    tr_list_t         * outRequests;
202    uint64_t            outDate;
203
204    tr_ratecontrol_t  * download;
205    tr_ratecontrol_t  * upload;
206
207    char              * client;
208
209    int64_t             credit;
210};
211
212#define peer_dbg( a... ) __peer_dbg( peer, ## a )
213static void __peer_dbg( tr_peer_t * peer, char * msg, ... ) PRINTF( 2, 3 );
214
215static void __peer_dbg( tr_peer_t * peer, char * msg, ... )
216{
217    char    string[256];
218    va_list args;
219
220    va_start( args, msg );
221    snprintf( string, sizeof string, "%08x:%04x ",
222             (uint32_t) peer->addr.s_addr, peer->port );
223    vsnprintf( &string[14], sizeof( string ) - 14, msg, args );
224    va_end( args ); 
225
226    tr_dbg( "%s", string );
227}
228
229/* utilities for endian conversions with char pointers */
230
231static uint32_t tr_ntohl( const void * p )
232{
233    uint32_t u;
234    memcpy( &u, p, sizeof( uint32_t ) );
235    return ntohl( u );
236}
237static void tr_htonl( uint32_t a, void * p )
238{
239    const uint32_t u = htonl( a );
240    memcpy ( p, &u, sizeof( uint32_t ) );
241}
242
243#include "peerext.h"
244#include "peeraz.h"
245#include "peermessages.h"
246#include "peerutils.h"
247#include "peerparse.h"
248
249/***********************************************************************
250 * tr_peerInit
251 ***********************************************************************
252 * Initializes a new peer.
253 **********************************************************************/
254tr_peer_t * tr_peerInit( const struct in_addr * addr, in_port_t port,
255                         int s, int from )
256{
257    tr_peer_t * peer;
258
259    assert( 0 <= from && TR_PEER_FROM__MAX > from );
260
261    peer                   = tr_new0( tr_peer_t, 1 );
262    peer->isChokedByUs     = TRUE;
263    peer->isChokingUs      = TRUE;
264    peer->date             = tr_date();
265    peer->keepAlive        = peer->date;
266    peer->download         = tr_rcInit();
267    peer->upload           = tr_rcInit();
268    peertreeInit( &peer->sentPeers );
269
270    peer->inRequestMax = peer->inRequestAlloc = 2;
271    peer->inRequests = tr_new0( tr_request_t, peer->inRequestAlloc );
272
273    peer->socket = s;
274    peer->addr = *addr;
275    peer->port = port;
276    peer->from = from;
277    peer->credit = SWIFT_INITIAL_CREDIT;
278    if( s >= 0 )
279    {
280        assert( TR_PEER_FROM_INCOMING == from );
281        peer->status = PEER_STATUS_CONNECTING;
282    }
283    else
284    {
285        peer->status = PEER_STATUS_IDLE;
286    }
287
288    return peer;
289}
290
291void tr_peerDestroy( tr_peer_t * peer )
292{
293    tr_torrent_t * tor = peer->tor;
294    tr_request_t * r;
295    int i, block;
296
297    peertreeFree( &peer->sentPeers );
298    for( i = 0; i < peer->inRequestCount; i++ )
299    {
300        r = &peer->inRequests[i];
301        block = tr_block( r->index, r->begin );
302        tr_cpDownloaderRem( tor->completion, block );
303    }
304    tr_bitfieldFree( peer->bitfield );
305    tr_bitfieldFree( peer->blamefield );
306    tr_bitfieldFree( peer->banfield );
307    tr_bitfieldFree( peer->reqfield );
308    tr_list_foreach( peer->outRequests, tr_free );
309    tr_list_free( peer->outRequests );
310    tr_free( peer->inRequests );
311    tr_free( peer->buf );
312    tr_free( peer->outMessages );
313    if( peer->status > PEER_STATUS_IDLE )
314    {
315        tr_netClose( peer->socket );
316    }
317    tr_rcClose( peer->download );
318    tr_rcClose( peer->upload );
319    free( peer->client );
320    free( peer );
321}
322
323const char *
324tr_peerClient( tr_peer_t * peer )
325{
326    if( PEER_STATUS_HANDSHAKE >= peer->status )
327    {
328        return "not connected";
329    }
330
331    if( NULL == peer->client )
332    {
333        peer->client = tr_clientForId( peer->id );
334    }
335
336    return peer->client;
337}
338
339void tr_peerSetPrivate( tr_peer_t * peer, int private )
340{
341    if( peer->private == private )
342    {
343        return;
344    }
345
346    peer->private = private;
347
348    if( !private )
349    {
350        peer->lastPex = 0;
351    }
352
353    if( EXTENDED_HANDSHAKE == peer->extStatus )
354    {
355        sendExtended( peer->tor, peer, EXTENDED_HANDSHAKE_ID );
356    }
357}
358
359void tr_peerSetTorrent( tr_peer_t * peer, tr_torrent_t * tor )
360{
361    peer->tor = tor;
362}
363
364/***********************************************************************
365 * tr_peerRead
366 ***********************************************************************
367 *
368 **********************************************************************/
369int tr_peerRead( tr_peer_t * peer )
370{
371    tr_torrent_t * tor = peer->tor;
372    int ret;
373    uint64_t date;
374
375    /* Try to read */
376    for( ;; )
377    {
378        if( tor )
379        {
380            if( tor->customDownloadLimit
381                ? !tr_rcCanTransfer( tor->download )
382                : !tr_rcCanTransfer( tor->handle->download ) )
383            {
384                break;
385            }
386        }
387
388        if( peer->size < 1 )
389        {
390            peer->size = 1024;
391            peer->buf  = malloc( peer->size );
392        }
393        else if( peer->pos >= peer->size )
394        {
395            peer->size *= 2;
396            peer->buf   = realloc( peer->buf, peer->size );
397        }
398
399        /* Read in smallish chunks, otherwise we might read more
400         * than the download cap is supposed to allow us */
401        ret = tr_netRecv( peer->socket, &peer->buf[peer->pos],
402                          MIN( 1024, peer->size - peer->pos ) ); 
403
404        if( ret & TR_NET_CLOSE )
405        {
406            peer_dbg( "connection closed" );
407            return TR_ERROR;
408        }
409        else if( ret & TR_NET_BLOCK )
410        {
411            break;
412        }
413        date        = tr_date();
414        peer->date  = date;
415        peer->pos  += ret;
416        if( NULL != tor )
417        {
418            if( peer->isInteresting && !peer->isChokingUs )
419            {
420                tor->activityDate = date;
421            }
422           
423            if( ( ret = parseBuf( tor, peer ) ) )
424            {
425                return ret;
426            }
427        }
428        else
429        {
430            if( ( ret = parseBufHeader( peer ) ) )
431            {
432                return ret;
433            }
434        }
435    }
436
437    return TR_OK;
438}
439
440uint64_t tr_peerDate( const tr_peer_t * peer )
441{
442    return peer->date;
443}
444
445/***********************************************************************
446 * tr_peerAddress
447 ***********************************************************************
448 *
449 **********************************************************************/
450struct in_addr * tr_peerAddress( tr_peer_t * peer )
451{
452    return &peer->addr;
453}
454
455/***********************************************************************
456 * tr_peerHash
457 ***********************************************************************
458 *
459 **********************************************************************/
460const uint8_t * tr_peerHash( const tr_peer_t * peer )
461{
462    return parseBufHash( peer );
463}
464
465/***********************************************************************
466 * tr_peerPulse
467 ***********************************************************************
468 *
469 **********************************************************************/
470int tr_peerPulse( tr_peer_t * peer )
471{
472    tr_torrent_t * tor = peer->tor;
473    int ret, size;
474    uint8_t * p;
475    uint64_t date;
476    const int isSeeding = tr_cpGetStatus( tor->completion ) != TR_CP_INCOMPLETE;
477
478    if( ( ret = checkPeer( peer ) ) )
479    {
480        return ret;
481    }
482
483    /* Connect */
484    if( PEER_STATUS_IDLE == peer->status )
485    {
486        peer->socket = tr_netOpenTCP( &peer->addr, peer->port, 0 );
487        if( peer->socket < 0 )
488        {
489            return TR_ERROR;
490        }
491        peer->status = PEER_STATUS_CONNECTING;
492    }
493   
494    /* Disconnect if seeder and torrent is seeding */
495    if(   ( peer->progress >= 1.0 )
496       && ( peer->tor->cpStatus != TR_CP_INCOMPLETE ) )
497    {
498        return TR_ERROR;
499    }
500
501    /* Try to send handshake */
502    if( PEER_STATUS_CONNECTING == peer->status )
503    {
504        uint8_t buf[68];
505        tr_info_t * inf = &tor->info;
506
507        buf[0] = 19;
508        memcpy( &buf[1], "BitTorrent protocol", 19 );
509        memset( &buf[20], 0, 8 );
510        buf[20] = 0x80;         /* azureus protocol */
511        buf[25] = 0x10;         /* extended messages */
512        memcpy( &buf[28], inf->hash, 20 );
513        memcpy( &buf[48], tor->peer_id, 20 );
514
515        switch( tr_netSend( peer->socket, buf, 68 ) )
516        {
517            case 68:
518                peer_dbg( "SEND handshake" );
519                peer->status = PEER_STATUS_HANDSHAKE;
520                break;
521            case TR_NET_BLOCK:
522                break;
523            default:
524                peer_dbg( "connection closed" );
525                return TR_ERROR;
526        }
527    }
528    if( peer->status < PEER_STATUS_HANDSHAKE )
529    {
530        /* Nothing more we can do till we sent the handshake */
531        return TR_OK;
532    }
533
534    /* Read incoming messages */
535    if( ( ret = tr_peerRead( peer ) ) )
536    {
537        return ret;
538    }
539
540    /* Try to send Azureus handshake */
541    if( PEER_STATUS_AZ_GIVER == peer->status )
542    {
543        switch( sendAZHandshake( tor, peer ) )
544        {
545            case TR_NET_BLOCK:
546                break;
547            case TR_NET_CLOSE:
548                peer_dbg( "connection closed" );
549                return TR_ERROR;
550            default:
551                peer->status = PEER_STATUS_AZ_RECEIVER;
552                break;
553        }
554    }
555
556    if( peer->status < PEER_STATUS_CONNECTED )
557    {
558        /* Nothing more we can do till we got the other guy's handshake */
559        return TR_OK;
560    }
561
562    /* Try to write */
563writeBegin:
564
565    /* Send all smaller messages regardless of the upload cap */
566    while( ( p = messagesPending( peer, &size ) ) )
567    {
568        ret = tr_netSend( peer->socket, p, size );
569        if( ret & TR_NET_CLOSE )
570        {
571            return TR_ERROR;
572        }
573        else if( ret & TR_NET_BLOCK )
574        {
575            goto writeEnd;
576        }
577        messagesSent( peer, ret );
578    }
579
580    /* Send pieces if we can */
581    while( ( p = blockPending( tor, peer, &size ) ) )
582    {
583        if( SWIFT_ENABLED && !isSeeding && (peer->credit<0) )
584            break;
585
586        if( tor->customUploadLimit
587            ? !tr_rcCanTransfer( tor->upload )
588            : !tr_rcCanTransfer( tor->handle->upload ) )
589            break;
590
591        ret = tr_netSend( peer->socket, p, size );
592        if( ret & TR_NET_CLOSE )
593            return TR_ERROR;
594
595        if( ret & TR_NET_BLOCK )
596            break;
597
598        blockSent( peer, ret );
599
600        if( ret > 0 )
601            tr_peerGotBlockFromUs( peer, ret );
602
603        date              = tr_date();
604        peer->outDate     = date;
605       
606        if( !tr_peerIsChokedByUs( peer ) )
607            tor->activityDate = date;
608
609        /* In case this block is done, you may have messages
610           pending. Send them before we start the next block */
611        goto writeBegin;
612    }
613writeEnd:
614
615    /* Ask for a block whenever possible */
616    if( !isSeeding
617        && !peer->isInteresting
618        && tor->peerCount > TR_MAX_PEER_COUNT - 2 )
619    {
620        /* This peer is no use to us, and it seems there are
621           more */
622        peer_dbg( "not interesting" );
623        return TR_ERROR;
624    }
625
626    if(     peer->isInteresting
627        && !peer->isChokingUs
628        && !peer->banned
629        &&  peer->inRequestCount < peer->inRequestMax )
630    {
631        int i;
632        int poolSize = 0;
633        int * pool = getPreferredPieces ( tor, peer, &poolSize );
634        const int endgame = !poolSize;
635
636        if( endgame ) /* endgame -- request everything we don't already have */
637        {
638            for( i=0; i<tor->blockCount && peer->inRequestCount<peer->inRequestMax; ++i )
639            {
640                if( !isBlockInteresting( tor, peer, i ) )
641                    continue;
642                if( tr_bitfieldHas( peer->reqfield, i ) ) /* we've already asked them for it */
643                    continue;
644                if( !peer->reqfield )
645                    peer->reqfield = tr_bitfieldNew( tor->blockCount );
646                tr_bitfieldAdd( peer->reqfield, i );
647                sendRequest( tor, peer, i );
648            }
649        }
650        else for( i=0; i<poolSize && peer->inRequestCount<peer->inRequestMax;  )
651        {
652            int unused;
653            const int piece = pool[i];
654            const int block = endgame
655                ? tr_cpMostMissingBlockInPiece( tor->completion, piece, &unused)
656                : tr_cpMissingBlockInPiece ( tor->completion, piece );
657
658            if( block>=0 )
659                sendRequest( tor, peer, block );
660            else ++i;
661        }
662
663        tr_free( pool );
664    }
665
666    return TR_OK;
667}
668
669int tr_peerIsConnected( const tr_peer_t * peer )
670{
671    return peer && (peer->status == PEER_STATUS_CONNECTED);
672}
673
674int tr_peerIsFrom( const tr_peer_t * peer )
675{
676    return peer->from;
677}
678
679int tr_peerIsChokedByUs( const tr_peer_t * peer )
680{
681    return peer->isChokedByUs;
682}
683int tr_peerIsInteresting( const tr_peer_t * peer )
684{
685    return peer->isInteresting;
686}
687int tr_peerIsChokingUs( const tr_peer_t * peer )
688{
689    return peer->isChokingUs;
690}
691int tr_peerIsInterested( const tr_peer_t * peer )
692{
693    return peer->isInterested;
694}
695
696float tr_peerProgress( const tr_peer_t * peer )
697{
698    return peer->progress;
699}
700
701int tr_peerPort( const tr_peer_t * peer )
702{
703    return ntohs( peer->port );
704}
705
706int tr_peerHasPiece( const tr_peer_t * peer, int pieceIndex )
707{
708    return tr_bitfieldHas( peer->bitfield, pieceIndex );
709}
710
711float tr_peerDownloadRate( const tr_peer_t * peer )
712{
713    return tr_rcRate( peer->download );
714}
715
716float tr_peerUploadRate( const tr_peer_t * peer )
717{
718    return tr_rcRate( peer->upload );
719}
720
721int tr_peerTimesChoked( const tr_peer_t * peer )
722{
723    return peer->timesChoked;
724}
725
726void tr_peerChoke( tr_peer_t * peer )
727{
728    sendChoke( peer, 1 );
729    peer->lastChoke = tr_date();
730    ++peer->timesChoked;
731}
732
733void tr_peerUnchoke( tr_peer_t * peer )
734{
735    sendChoke( peer, 0 );
736    peer->lastChoke = tr_date();
737}
738
739uint64_t tr_peerLastChoke( const tr_peer_t * peer )
740{
741    return peer->lastChoke;
742}
743
744void tr_peerSetOptimistic( tr_peer_t * peer, int o )
745{
746    peer->optimistic = o;
747}
748
749int tr_peerIsOptimistic( const tr_peer_t * peer )
750{
751    return peer->optimistic;
752}
753
754static int peerIsBad( const tr_peer_t * peer )
755{
756    return peer->badPcs > 4 + 2 * peer->goodPcs;
757}
758
759static int peerIsGood( const tr_peer_t * peer )
760{
761    return peer->goodPcs > 3 * peer->badPcs;
762}
763
764void tr_peerBlame( tr_peer_t * peer, int piece, int success )
765{
766    tr_torrent_t * tor = peer->tor;
767
768    if( !peer->blamefield || !tr_bitfieldHas( peer->blamefield, piece ) )
769    {
770        return;
771    }
772
773    if( success )
774    {
775        peer->goodPcs++;
776
777        if( peer->banfield && peerIsGood( peer ) )
778        {
779            /* Assume the peer wasn't responsible for the bad pieces
780               we was banned for */
781            tr_bitfieldClear( peer->banfield );
782        }
783    }
784    else
785    {
786        peer->badPcs++;
787
788        /* Ban the peer for this piece */
789        if( !peer->banfield )
790        {
791            peer->banfield = tr_bitfieldNew( tor->info.pieceCount );
792        }
793        tr_bitfieldAdd( peer->banfield, piece );
794
795        if( peerIsBad( peer ) )
796        {
797            /* Full ban */
798            peer_dbg( "banned (%d / %d)", peer->goodPcs, peer->badPcs );
799            peer->banned = TRUE;
800            peer->isInteresting = FALSE;
801            peer->isInterested = FALSE;
802        }
803    }
804    tr_bitfieldRem( peer->blamefield, piece );
805}
806
807int tr_peerGetConnectable( const tr_torrent_t * tor, uint8_t ** _buf )
808{
809    int count = 0;
810    uint8_t * buf;
811    tr_peer_t * peer;
812    int i;
813
814    if( tor->peerCount < 1 )
815    {
816        *_buf = NULL;
817        return 0;
818    }
819
820    buf = malloc( 6 * tor->peerCount );
821    for( i = 0; i < tor->peerCount; i++ )
822    {
823        peer = tor->peers[i];
824
825        /* Skip peers with no known listening port */
826        if( 0 == peer->port )
827            continue;
828
829        memcpy( &buf[count*6], &peer->addr, 4 );
830        memcpy( &buf[count*6+4], &peer->port, 2 );
831        count++;
832    }
833
834    if( count < 1 )
835    {
836        free( buf ); buf = NULL;
837    }
838    *_buf = buf;
839
840    return count * 6;
841}
842
843/***
844****
845***/
846
847void
848tr_peerSentBlockToUs ( tr_peer_t * peer, int byteCount )
849{
850    tr_torrent_t * tor = peer->tor;
851
852    assert( byteCount >= 0 );
853    assert( byteCount <= tor->info.pieceSize );
854
855    tor->downloadedCur += byteCount;
856    tr_rcTransferred( peer->download, byteCount );
857    tr_rcTransferred( tor->download, byteCount );
858    if ( !tor->customUploadLimit )
859        tr_rcTransferred( tor->handle->download, byteCount );
860
861    peer->credit += (int)(byteCount * SWIFT_REPAYMENT_RATIO);
862}
863
864void
865tr_peerGotBlockFromUs ( tr_peer_t * peer, int byteCount )
866{
867    tr_torrent_t * tor = peer->tor;
868
869    assert( byteCount >= 0 );
870    assert( byteCount <= tor->info.pieceSize );
871
872    tor->uploadedCur += byteCount;
873    tr_rcTransferred( peer->upload, byteCount );
874    tr_rcTransferred( tor->upload, byteCount );
875    if ( !tor->customDownloadLimit )
876        tr_rcTransferred( tor->handle->upload, byteCount );
877
878    peer->credit -= byteCount;
879}
880
881static void
882tr_torrentSwiftPulse ( tr_torrent_t * tor )
883{
884    /* Preferred # of seconds for the request queue's turnaround time.
885       This is just an arbitrary number. */
886    const int queueTimeSec = 5;
887    const int blockSizeKiB = tor->blockSize / 1024;
888    const int isSeeding = tr_cpGetStatus( tor->completion ) != TR_CP_INCOMPLETE;
889    int i;
890
891    tr_torrentWriterLock( tor );
892
893    for( i=0; i<tor->peerCount; ++i )
894    {
895        double outboundSpeedKiBs;
896        int size;
897        tr_peer_t * peer = tor->peers[ i ];
898
899        if( !tr_peerIsConnected( peer ) )
900            continue;
901
902        /* decide how many blocks we'll concurrently ask this peer for */
903        outboundSpeedKiBs = tr_rcRate(peer->upload);
904        size = queueTimeSec * outboundSpeedKiBs / blockSizeKiB;
905        if( size < 4 ) /* don't let it get TOO small */
906            size = 4;
907        size += 4; /* and always leave room to grow */
908        peer->inRequestMax = size;
909        if( peer->inRequestAlloc < peer->inRequestMax ) {
910            peer->inRequestAlloc = peer->inRequestMax;
911            peer->inRequests = tr_renew( tr_request_t, peer->inRequests, peer->inRequestAlloc );
912        }
913    }
914
915    /* if we're not seeding, decide on how much
916       bandwidth to allocate for leechers */
917    if( !isSeeding )
918    {
919        tr_peer_t ** deadbeats = tr_new( tr_peer_t*, tor->peerCount );
920        int deadbeatCount = 0;
921
922        for( i=0; i<tor->peerCount; ++i ) {
923            tr_peer_t * peer = tor->peers[ i ];
924            if( tr_peerIsConnected( peer ) && ( peer->credit < 0 ) )
925                deadbeats[deadbeatCount++] = peer;
926        }
927
928        if( deadbeatCount )
929        {
930            const double ul_KiBsec = tr_rcRate( tor->download );
931            const double ul_KiB = ul_KiBsec * SWIFT_REFRESH_INTERVAL_SEC;
932            const double ul_bytes = ul_KiB * 1024;
933            const double freeCreditTotal = ul_bytes * SWIFT_LARGESSE;
934            const int freeCreditPerPeer = (int)( freeCreditTotal / deadbeatCount );
935            for( i=0; i<deadbeatCount; ++i )
936                deadbeats[i]->credit = freeCreditPerPeer;
937            tr_dbg( "torrent %s has %d deadbeats, "
938                    "who are each being granted %d bytes' credit "
939                    "for a total of %.1f KiB, "
940                    "%d%% of the torrent's ul speed %.1f\n", 
941                tor->info.name, deadbeatCount, freeCreditPerPeer,
942                ul_KiBsec*SWIFT_LARGESSE, (int)(SWIFT_LARGESSE*100), ul_KiBsec );
943        }
944
945        tr_free( deadbeats );
946    }
947
948    tr_torrentWriterUnlock( tor );
949}
950void
951tr_swiftPulse( tr_handle_t * h )
952{
953    static time_t lastPulseTime = 0;
954
955    if( lastPulseTime + SWIFT_REFRESH_INTERVAL_SEC <= time( NULL ) )
956    {
957        tr_torrent_t * tor;
958        for( tor=h->torrentList; tor; tor=tor->next )
959            tr_torrentSwiftPulse( tor );
960
961        lastPulseTime = time( NULL );
962    }
963}
Note: See TracBrowser for help on using the repository browser.