source: trunk/libtransmission/peer.c @ 2343

Last change on this file since 2343 was 2343, checked in by joshe, 15 years ago

Change a couple functions to take an in_addr pointer instead of an in_addr.
Forward declare struct in_addr and include the relevant headers in the .c files where it's used.

  • Property svn:keywords set to Date Rev Author Id
File size: 26.2 KB
Line 
1/******************************************************************************
2 * $Id: peer.c 2343 2007-07-14 16:29:21Z joshe $
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#include "peerext.h"
230#include "peeraz.h"
231#include "peermessages.h"
232#include "peerutils.h"
233#include "peerparse.h"
234
235/***********************************************************************
236 * tr_peerInit
237 ***********************************************************************
238 * Initializes a new peer.
239 **********************************************************************/
240tr_peer_t * tr_peerInit( const struct in_addr * addr, in_port_t port,
241                         int s, int from )
242{
243    tr_peer_t * peer;
244
245    assert( 0 <= from && TR_PEER_FROM__MAX > from );
246
247    peer                   = tr_new0( tr_peer_t, 1 );
248    peer->isChokedByUs     = TRUE;
249    peer->isChokingUs      = TRUE;
250    peer->date             = tr_date();
251    peer->keepAlive        = peer->date;
252    peer->download         = tr_rcInit();
253    peer->upload           = tr_rcInit();
254    peertreeInit( &peer->sentPeers );
255
256    peer->inRequestMax = peer->inRequestAlloc = 2;
257    peer->inRequests = tr_new0( tr_request_t, peer->inRequestAlloc );
258
259    peer->socket = s;
260    peer->addr = *addr;
261    peer->port = port;
262    peer->from = from;
263    peer->credit = SWIFT_INITIAL_CREDIT;
264    if( s >= 0 )
265    {
266        assert( TR_PEER_FROM_INCOMING == from );
267        peer->status = PEER_STATUS_CONNECTING;
268    }
269    else
270    {
271        peer->status = PEER_STATUS_IDLE;
272    }
273
274    return peer;
275}
276
277void tr_peerDestroy( tr_peer_t * peer )
278{
279    tr_torrent_t * tor = peer->tor;
280    tr_request_t * r;
281    int i, block;
282
283    peertreeFree( &peer->sentPeers );
284    for( i = 0; i < peer->inRequestCount; i++ )
285    {
286        r = &peer->inRequests[i];
287        block = tr_block( r->index, r->begin );
288        tr_cpDownloaderRem( tor->completion, block );
289    }
290    tr_bitfieldFree( peer->bitfield );
291    tr_bitfieldFree( peer->blamefield );
292    tr_bitfieldFree( peer->banfield );
293    tr_bitfieldFree( peer->reqfield );
294    tr_list_foreach( peer->outRequests, tr_free );
295    tr_list_free( peer->outRequests );
296    tr_free( peer->inRequests );
297    tr_free( peer->buf );
298    tr_free( peer->outMessages );
299    if( peer->status > PEER_STATUS_IDLE )
300    {
301        tr_netClose( peer->socket );
302    }
303    tr_rcClose( peer->download );
304    tr_rcClose( peer->upload );
305    free( peer->client );
306    free( peer );
307}
308
309const char *
310tr_peerClient( tr_peer_t * peer )
311{
312    if( PEER_STATUS_HANDSHAKE >= peer->status )
313    {
314        return "not connected";
315    }
316
317    if( NULL == peer->client )
318    {
319        peer->client = tr_clientForId( peer->id );
320    }
321
322    return peer->client;
323}
324
325void tr_peerSetPrivate( tr_peer_t * peer, int private )
326{
327    if( peer->private == private )
328    {
329        return;
330    }
331
332    peer->private = private;
333
334    if( !private )
335    {
336        peer->lastPex = 0;
337    }
338
339    if( EXTENDED_HANDSHAKE == peer->extStatus )
340    {
341        sendExtended( peer->tor, peer, EXTENDED_HANDSHAKE_ID );
342    }
343}
344
345void tr_peerSetTorrent( tr_peer_t * peer, tr_torrent_t * tor )
346{
347    peer->tor = tor;
348}
349
350/***********************************************************************
351 * tr_peerRead
352 ***********************************************************************
353 *
354 **********************************************************************/
355int tr_peerRead( tr_peer_t * peer )
356{
357    tr_torrent_t * tor = peer->tor;
358    int ret;
359    uint64_t date;
360
361    /* Try to read */
362    for( ;; )
363    {
364        if( tor )
365        {
366            if( tor->customDownloadLimit
367                ? !tr_rcCanTransfer( tor->download )
368                : !tr_rcCanTransfer( tor->handle->download ) )
369            {
370                break;
371            }
372        }
373
374        if( peer->size < 1 )
375        {
376            peer->size = 1024;
377            peer->buf  = malloc( peer->size );
378        }
379        else if( peer->pos >= peer->size )
380        {
381            peer->size *= 2;
382            peer->buf   = realloc( peer->buf, peer->size );
383        }
384
385        /* Read in smallish chunks, otherwise we might read more
386         * than the download cap is supposed to allow us */
387        ret = tr_netRecv( peer->socket, &peer->buf[peer->pos],
388                          MIN( 1024, peer->size - peer->pos ) ); 
389
390        if( ret & TR_NET_CLOSE )
391        {
392            peer_dbg( "connection closed" );
393            return TR_ERROR;
394        }
395        else if( ret & TR_NET_BLOCK )
396        {
397            break;
398        }
399        date        = tr_date();
400        peer->date  = date;
401        peer->pos  += ret;
402        if( NULL != tor )
403        {
404            if( peer->isInteresting && !peer->isChokingUs )
405            {
406                tor->activityDate = date;
407            }
408           
409            if( ( ret = parseBuf( tor, peer ) ) )
410            {
411                return ret;
412            }
413        }
414        else
415        {
416            if( ( ret = parseBufHeader( peer ) ) )
417            {
418                return ret;
419            }
420        }
421    }
422
423    return TR_OK;
424}
425
426uint64_t tr_peerDate( const tr_peer_t * peer )
427{
428    return peer->date;
429}
430
431/***********************************************************************
432 * tr_peerAddress
433 ***********************************************************************
434 *
435 **********************************************************************/
436struct in_addr * tr_peerAddress( tr_peer_t * peer )
437{
438    return &peer->addr;
439}
440
441/***********************************************************************
442 * tr_peerHash
443 ***********************************************************************
444 *
445 **********************************************************************/
446const uint8_t * tr_peerHash( const tr_peer_t * peer )
447{
448    return parseBufHash( peer );
449}
450
451/***********************************************************************
452 * tr_peerPulse
453 ***********************************************************************
454 *
455 **********************************************************************/
456int tr_peerPulse( tr_peer_t * peer )
457{
458    tr_torrent_t * tor = peer->tor;
459    int ret, size;
460    uint8_t * p;
461    uint64_t date;
462    const int isSeeding = tr_cpGetStatus( tor->completion ) != TR_CP_INCOMPLETE;
463
464    if( ( ret = checkPeer( peer ) ) )
465    {
466        return ret;
467    }
468
469    /* Connect */
470    if( PEER_STATUS_IDLE == peer->status )
471    {
472        peer->socket = tr_netOpenTCP( &peer->addr, peer->port, 0 );
473        if( peer->socket < 0 )
474        {
475            return TR_ERROR;
476        }
477        peer->status = PEER_STATUS_CONNECTING;
478    }
479   
480    /* Disconnect if seeder and torrent is seeding */
481    if(   ( peer->progress >= 1.0 )
482       && ( peer->tor->cpStatus != TR_CP_INCOMPLETE ) )
483    {
484        return TR_ERROR;
485    }
486
487    /* Try to send handshake */
488    if( PEER_STATUS_CONNECTING == peer->status )
489    {
490        uint8_t buf[68];
491        tr_info_t * inf = &tor->info;
492
493        buf[0] = 19;
494        memcpy( &buf[1], "BitTorrent protocol", 19 );
495        memset( &buf[20], 0, 8 );
496        buf[20] = 0x80;         /* azureus protocol */
497        buf[25] = 0x10;         /* extended messages */
498        memcpy( &buf[28], inf->hash, 20 );
499        memcpy( &buf[48], tor->id, 20 );
500
501        switch( tr_netSend( peer->socket, buf, 68 ) )
502        {
503            case 68:
504                peer_dbg( "SEND handshake" );
505                peer->status = PEER_STATUS_HANDSHAKE;
506                break;
507            case TR_NET_BLOCK:
508                break;
509            default:
510                peer_dbg( "connection closed" );
511                return TR_ERROR;
512        }
513    }
514    if( peer->status < PEER_STATUS_HANDSHAKE )
515    {
516        /* Nothing more we can do till we sent the handshake */
517        return TR_OK;
518    }
519
520    /* Read incoming messages */
521    if( ( ret = tr_peerRead( peer ) ) )
522    {
523        return ret;
524    }
525
526    /* Try to send Azureus handshake */
527    if( PEER_STATUS_AZ_GIVER == peer->status )
528    {
529        switch( sendAZHandshake( tor, peer ) )
530        {
531            case TR_NET_BLOCK:
532                break;
533            case TR_NET_CLOSE:
534                peer_dbg( "connection closed" );
535                return TR_ERROR;
536            default:
537                peer->status = PEER_STATUS_AZ_RECEIVER;
538                break;
539        }
540    }
541
542    if( peer->status < PEER_STATUS_CONNECTED )
543    {
544        /* Nothing more we can do till we got the other guy's handshake */
545        return TR_OK;
546    }
547
548    /* Try to write */
549writeBegin:
550
551    /* Send all smaller messages regardless of the upload cap */
552    while( ( p = messagesPending( peer, &size ) ) )
553    {
554        ret = tr_netSend( peer->socket, p, size );
555        if( ret & TR_NET_CLOSE )
556        {
557            return TR_ERROR;
558        }
559        else if( ret & TR_NET_BLOCK )
560        {
561            goto writeEnd;
562        }
563        messagesSent( peer, ret );
564    }
565
566    /* Send pieces if we can */
567    while( ( p = blockPending( tor, peer, &size ) ) )
568    {
569        if( SWIFT_ENABLED && !isSeeding && (peer->credit<0) )
570            break;
571
572        if( tor->customUploadLimit
573            ? !tr_rcCanTransfer( tor->upload )
574            : !tr_rcCanTransfer( tor->handle->upload ) )
575            break;
576
577        ret = tr_netSend( peer->socket, p, size );
578        if( ret & TR_NET_CLOSE )
579            return TR_ERROR;
580
581        if( ret & TR_NET_BLOCK )
582            break;
583
584        blockSent( peer, ret );
585
586        if( ret > 0 )
587            tr_peerGotBlockFromUs( peer, ret );
588
589        date              = tr_date();
590        peer->outDate     = date;
591       
592        if( !tr_peerIsChokedByUs( peer ) )
593            tor->activityDate = date;
594
595        /* In case this block is done, you may have messages
596           pending. Send them before we start the next block */
597        goto writeBegin;
598    }
599writeEnd:
600
601    /* Ask for a block whenever possible */
602    if( !isSeeding
603        && !peer->isInteresting
604        && tor->peerCount > TR_MAX_PEER_COUNT - 2 )
605    {
606        /* This peer is no use to us, and it seems there are
607           more */
608        peer_dbg( "not interesting" );
609        return TR_ERROR;
610    }
611
612    if(     peer->isInteresting
613        && !peer->isChokingUs
614        && !peer->banned
615        &&  peer->inRequestCount < peer->inRequestMax )
616    {
617        int i;
618        int poolSize = 0;
619        int * pool = getPreferredPieces ( tor, peer, &poolSize );
620        const int endgame = !poolSize;
621
622        if( endgame ) /* endgame -- request everything we don't already have */
623        {
624            for( i=0; i<tor->blockCount && peer->inRequestCount<peer->inRequestMax; ++i )
625            {
626                if( !isBlockInteresting( tor, peer, i ) )
627                    continue;
628                if( tr_bitfieldHas( peer->reqfield, i ) ) /* we've already asked them for it */
629                    continue;
630                if( !peer->reqfield )
631                    peer->reqfield = tr_bitfieldNew( tor->blockCount );
632                tr_bitfieldAdd( peer->reqfield, i );
633                sendRequest( tor, peer, i );
634            }
635        }
636        else for( i=0; i<poolSize && peer->inRequestCount<peer->inRequestMax;  )
637        {
638            int unused;
639            const int piece = pool[i];
640            const int block = endgame
641                ? tr_cpMostMissingBlockInPiece( tor->completion, piece, &unused)
642                : tr_cpMissingBlockInPiece ( tor->completion, piece );
643
644            if( block>=0 )
645                sendRequest( tor, peer, block );
646            else ++i;
647        }
648
649        tr_free( pool );
650    }
651
652    return TR_OK;
653}
654
655int tr_peerIsConnected( const tr_peer_t * peer )
656{
657    return peer && (peer->status == PEER_STATUS_CONNECTED);
658}
659
660int tr_peerIsFrom( const tr_peer_t * peer )
661{
662    return peer->from;
663}
664
665int tr_peerIsChokedByUs( const tr_peer_t * peer )
666{
667    return peer->isChokedByUs;
668}
669int tr_peerIsInteresting( const tr_peer_t * peer )
670{
671    return peer->isInteresting;
672}
673int tr_peerIsChokingUs( const tr_peer_t * peer )
674{
675    return peer->isChokingUs;
676}
677int tr_peerIsInterested( const tr_peer_t * peer )
678{
679    return peer->isInterested;
680}
681
682float tr_peerProgress( const tr_peer_t * peer )
683{
684    return peer->progress;
685}
686
687int tr_peerPort( const tr_peer_t * peer )
688{
689    return ntohs( peer->port );
690}
691
692int tr_peerHasPiece( const tr_peer_t * peer, int pieceIndex )
693{
694    return tr_bitfieldHas( peer->bitfield, pieceIndex );
695}
696
697float tr_peerDownloadRate( const tr_peer_t * peer )
698{
699    return tr_rcRate( peer->download );
700}
701
702float tr_peerUploadRate( const tr_peer_t * peer )
703{
704    return tr_rcRate( peer->upload );
705}
706
707int tr_peerTimesChoked( const tr_peer_t * peer )
708{
709    return peer->timesChoked;
710}
711
712void tr_peerChoke( tr_peer_t * peer )
713{
714    sendChoke( peer, 1 );
715    peer->lastChoke = tr_date();
716    ++peer->timesChoked;
717}
718
719void tr_peerUnchoke( tr_peer_t * peer )
720{
721    sendChoke( peer, 0 );
722    peer->lastChoke = tr_date();
723}
724
725uint64_t tr_peerLastChoke( const tr_peer_t * peer )
726{
727    return peer->lastChoke;
728}
729
730void tr_peerSetOptimistic( tr_peer_t * peer, int o )
731{
732    peer->optimistic = o;
733}
734
735int tr_peerIsOptimistic( const tr_peer_t * peer )
736{
737    return peer->optimistic;
738}
739
740static int peerIsBad( const tr_peer_t * peer )
741{
742    return peer->badPcs > 4 + 2 * peer->goodPcs;
743}
744
745static int peerIsGood( const tr_peer_t * peer )
746{
747    return peer->goodPcs > 3 * peer->badPcs;
748}
749
750void tr_peerBlame( tr_peer_t * peer, int piece, int success )
751{
752    tr_torrent_t * tor = peer->tor;
753
754    if( !peer->blamefield || !tr_bitfieldHas( peer->blamefield, piece ) )
755    {
756        return;
757    }
758
759    if( success )
760    {
761        peer->goodPcs++;
762
763        if( peer->banfield && peerIsGood( peer ) )
764        {
765            /* Assume the peer wasn't responsible for the bad pieces
766               we was banned for */
767            tr_bitfieldClear( peer->banfield );
768        }
769    }
770    else
771    {
772        peer->badPcs++;
773
774        /* Ban the peer for this piece */
775        if( !peer->banfield )
776        {
777            peer->banfield = tr_bitfieldNew( tor->info.pieceCount );
778        }
779        tr_bitfieldAdd( peer->banfield, piece );
780
781        if( peerIsBad( peer ) )
782        {
783            /* Full ban */
784            peer_dbg( "banned (%d / %d)", peer->goodPcs, peer->badPcs );
785            peer->banned = TRUE;
786            peer->isInteresting = FALSE;
787            peer->isInterested = FALSE;
788        }
789    }
790    tr_bitfieldRem( peer->blamefield, piece );
791}
792
793int tr_peerGetConnectable( const tr_torrent_t * tor, uint8_t ** _buf )
794{
795    int count = 0;
796    uint8_t * buf;
797    tr_peer_t * peer;
798    int i;
799
800    if( tor->peerCount < 1 )
801    {
802        *_buf = NULL;
803        return 0;
804    }
805
806    buf = malloc( 6 * tor->peerCount );
807    for( i = 0; i < tor->peerCount; i++ )
808    {
809        peer = tor->peers[i];
810
811        /* Skip peers with no known listening port */
812        if( 0 == peer->port )
813            continue;
814
815        memcpy( &buf[count*6], &peer->addr, 4 );
816        memcpy( &buf[count*6+4], &peer->port, 2 );
817        count++;
818    }
819
820    if( count < 1 )
821    {
822        free( buf ); buf = NULL;
823    }
824    *_buf = buf;
825
826    return count * 6;
827}
828
829/***
830****
831***/
832
833void
834tr_peerSentBlockToUs ( tr_peer_t * peer, int byteCount )
835{
836    tr_torrent_t * tor = peer->tor;
837
838    assert( byteCount >= 0 );
839    assert( byteCount <= tor->info.pieceSize );
840
841    tor->downloadedCur += byteCount;
842    tr_rcTransferred( peer->download, byteCount );
843    tr_rcTransferred( tor->download, byteCount );
844    if ( !tor->customUploadLimit )
845        tr_rcTransferred( tor->handle->download, byteCount );
846
847    peer->credit += (int)(byteCount * SWIFT_REPAYMENT_RATIO);
848}
849
850void
851tr_peerGotBlockFromUs ( tr_peer_t * peer, int byteCount )
852{
853    tr_torrent_t * tor = peer->tor;
854
855    assert( byteCount >= 0 );
856    assert( byteCount <= tor->info.pieceSize );
857
858    tor->uploadedCur += byteCount;
859    tr_rcTransferred( peer->upload, byteCount );
860    tr_rcTransferred( tor->upload, byteCount );
861    if ( !tor->customDownloadLimit )
862        tr_rcTransferred( tor->handle->upload, byteCount );
863
864    peer->credit -= byteCount;
865}
866
867static void
868tr_torrentSwiftPulse ( tr_torrent_t * tor )
869{
870    /* Preferred # of seconds for the request queue's turnaround time.
871       This is just an arbitrary number. */
872    const int queueTimeSec = 5;
873    const int blockSizeKiB = tor->blockSize / 1024;
874    const int isSeeding = tr_cpGetStatus( tor->completion ) != TR_CP_INCOMPLETE;
875    int i;
876
877    tr_torrentWriterLock( tor );
878
879    for( i=0; i<tor->peerCount; ++i )
880    {
881        double outboundSpeedKiBs;
882        int size;
883        tr_peer_t * peer = tor->peers[ i ];
884
885        if( !tr_peerIsConnected( peer ) )
886            continue;
887
888        /* decide how many blocks we'll concurrently ask this peer for */
889        outboundSpeedKiBs = tr_rcRate(peer->upload);
890        size = queueTimeSec * outboundSpeedKiBs / blockSizeKiB;
891        if( size < 4 ) /* don't let it get TOO small */
892            size = 4;
893        size += 4; /* and always leave room to grow */
894        peer->inRequestMax = size;
895        if( peer->inRequestAlloc < peer->inRequestMax ) {
896            peer->inRequestAlloc = peer->inRequestMax;
897            peer->inRequests = tr_renew( tr_request_t, peer->inRequests, peer->inRequestAlloc );
898        }
899    }
900
901    /* if we're not seeding, decide on how much
902       bandwidth to allocate for leechers */
903    if( !isSeeding )
904    {
905        tr_peer_t ** deadbeats = tr_new( tr_peer_t*, tor->peerCount );
906        int deadbeatCount = 0;
907
908        for( i=0; i<tor->peerCount; ++i ) {
909            tr_peer_t * peer = tor->peers[ i ];
910            if( tr_peerIsConnected( peer ) && ( peer->credit < 0 ) )
911                deadbeats[deadbeatCount++] = peer;
912        }
913
914        if( deadbeatCount )
915        {
916            const double ul_KiBsec = tr_rcRate( tor->download );
917            const double ul_KiB = ul_KiBsec * SWIFT_REFRESH_INTERVAL_SEC;
918            const double ul_bytes = ul_KiB * 1024;
919            const double freeCreditTotal = ul_bytes * SWIFT_LARGESSE;
920            const int freeCreditPerPeer = (int)( freeCreditTotal / deadbeatCount );
921            for( i=0; i<deadbeatCount; ++i )
922                deadbeats[i]->credit = freeCreditPerPeer;
923            tr_dbg( "torrent %s has %d deadbeats, "
924                    "who are each being granted %d bytes' credit "
925                    "for a total of %.1f KiB, "
926                    "%d%% of the torrent's ul speed %.1f\n", 
927                tor->info.name, deadbeatCount, freeCreditPerPeer,
928                ul_KiBsec*SWIFT_LARGESSE, (int)(SWIFT_LARGESSE*100), ul_KiBsec );
929        }
930
931        tr_free( deadbeats );
932    }
933
934    tr_torrentWriterUnlock( tor );
935}
936void
937tr_swiftPulse( tr_handle_t * h )
938{
939    static time_t lastPulseTime = 0;
940
941    if( lastPulseTime + SWIFT_REFRESH_INTERVAL_SEC <= time( NULL ) )
942    {
943        tr_torrent_t * tor;
944        for( tor=h->torrentList; tor; tor=tor->next )
945            tr_torrentSwiftPulse( tor );
946
947        lastPulseTime = time( NULL );
948    }
949}
Note: See TracBrowser for help on using the repository browser.