source: trunk/libtransmission/peer.c @ 1869

Last change on this file since 1869 was 1869, checked in by livings124, 15 years ago

determine upload/download rates the old way, which is not the most accurate way at a few points, but should have a positive overall impact

  • Property svn:keywords set to Date Rev Author Id
File size: 19.7 KB
Line 
1/******************************************************************************
2 * $Id: peer.c 1869 2007-05-16 02:03:18Z livings124 $
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 "transmission.h"
26#include "peertree.h"
27
28#define MAX_REQUEST_COUNT       32
29#define OUR_REQUEST_COUNT       8  /* TODO: we should detect if we are on a
30                                      high-speed network and adapt */
31#define PEX_PEER_CUTOFF         50 /* only try to add new peers from pex if
32                                      we have fewer existing peers than this */
33#define PEX_INTERVAL            60 /* don't send pex messages more frequently
34                                      than PEX_INTERVAL +
35                                      rand( PEX_INTERVAL / 10 ) seconds */
36#define PEER_SUPPORTS_EXTENDED_MESSAGES( bits ) ( (bits)[5] & 0x10 )
37#define PEER_SUPPORTS_AZUREUS_PROTOCOL( bits )  ( (bits)[0] & 0x80 )
38
39#define PEER_MSG_CHOKE          0
40#define PEER_MSG_UNCHOKE        1
41#define PEER_MSG_INTERESTED     2
42#define PEER_MSG_UNINTERESTED   3
43#define PEER_MSG_HAVE           4
44#define PEER_MSG_BITFIELD       5
45#define PEER_MSG_REQUEST        6
46#define PEER_MSG_PIECE          7
47#define PEER_MSG_CANCEL         8
48#define PEER_MSG_PORT           9
49#define PEER_MSG_EXTENDED       20
50
51typedef struct tr_request_s
52{
53    int index;
54    int begin;
55    int length;
56
57} tr_request_t;
58
59struct tr_peer_s
60{
61    tr_torrent_t      * tor;
62
63    struct in_addr      addr;
64    in_port_t           port;  /* peer's listening port, 0 if not known */
65
66#define PEER_STATUS_IDLE        1 /* Need to connect */
67#define PEER_STATUS_CONNECTING  2 /* Trying to send handshake */
68#define PEER_STATUS_HANDSHAKE   3 /* Waiting for peer's handshake */
69#define PEER_STATUS_AZ_GIVER    4 /* Sending Azureus handshake */
70#define PEER_STATUS_AZ_RECEIVER 5 /* Receiving Azureus handshake */
71#define PEER_STATUS_CONNECTED   6 /* Got peer's handshake */
72    int                 status;
73    int                 socket;
74    char                from;
75    char                private;
76    char                azproto;  /* azureus peer protocol is being used */
77    uint64_t            date;
78    uint64_t            keepAlive;
79
80#define EXTENDED_NOT_SUPPORTED   0 /* extended messages not supported */
81#define EXTENDED_SUPPORTED       1 /* waiting to send extended handshake */
82#define EXTENDED_HANDSHAKE       2 /* sent extended handshake */
83    uint8_t             extStatus;
84    uint8_t             pexStatus;   /* peer's ut_pex id, 0 if not supported */
85    uint64_t            lastPex;     /* time when last pex packet was sent */
86    int                 advertisedPort; /* listening port we last told peer */
87    tr_peertree_t       sentPeers;
88
89    char                amChoking;
90    char                amInterested;
91    char                peerChoking;
92    char                peerInterested;
93
94    int                 optimistic;
95    uint64_t            lastChoke;
96
97    uint8_t             id[TR_ID_LEN];
98
99    /* The pieces that the peer has */
100    tr_bitfield_t     * bitfield;
101    int                 pieceCount;
102    float               progress;
103
104    int                 goodPcs;
105    int                 badPcs;
106    int                 banned;
107    /* The pieces that the peer is contributing to */
108    tr_bitfield_t     * blamefield;
109    /* The bad pieces that the peer has contributed to */
110    tr_bitfield_t     * banfield;
111
112    uint8_t           * buf;
113    int                 size;
114    int                 pos;
115
116    uint8_t           * outMessages;
117    int                 outMessagesSize;
118    int                 outMessagesPos;
119    uint8_t             outBlock[25+16384];
120    int                 outBlockSize;
121    int                 outBlockLoaded;
122    int                 outBlockSending;
123
124    int                 inRequestCount;
125    tr_request_t        inRequests[OUR_REQUEST_COUNT];
126    int                 inIndex;
127    int                 inBegin;
128    int                 inLength;
129    uint64_t            inTotal;
130
131    int                 outRequestCount;
132    tr_request_t        outRequests[MAX_REQUEST_COUNT];
133    uint64_t            outTotal;
134    uint64_t            outDate;
135
136    tr_ratecontrol_t  * download;
137    tr_ratecontrol_t  * upload;
138
139    char              * client;
140};
141
142#define peer_dbg( a... ) __peer_dbg( peer, ## a )
143static void __peer_dbg( tr_peer_t * peer, char * msg, ... ) PRINTF( 2, 3 );
144
145static void __peer_dbg( tr_peer_t * peer, char * msg, ... )
146{
147    char    string[256];
148    va_list args;
149
150    va_start( args, msg );
151    snprintf( string, sizeof string, "%08x:%04x ",
152             (uint32_t) peer->addr.s_addr, peer->port );
153    vsnprintf( &string[14], sizeof( string ) - 14, msg, args );
154    va_end( args ); 
155
156    tr_dbg( "%s", string );
157}
158
159#include "peerext.h"
160#include "peeraz.h"
161#include "peermessages.h"
162#include "peerutils.h"
163#include "peerparse.h"
164
165/***********************************************************************
166 * tr_peerInit
167 ***********************************************************************
168 * Initializes a new peer.
169 **********************************************************************/
170tr_peer_t * tr_peerInit( struct in_addr addr, in_port_t port, int s, int from )
171{
172    tr_peer_t * peer = peerInit();
173
174    assert( 0 <= from && TR_PEER_FROM__MAX > from );
175
176    peer->socket = s;
177    peer->addr = addr;
178    peer->port = port;
179    peer->from = from;
180    if( s >= 0 )
181    {
182        assert( TR_PEER_FROM_INCOMING == from );
183        peer->status = PEER_STATUS_CONNECTING;
184    }
185    else
186    {
187        peer->status = PEER_STATUS_IDLE;
188    }
189
190    return peer;
191}
192
193void tr_peerDestroy( tr_peer_t * peer )
194{
195    tr_torrent_t * tor = peer->tor;
196    tr_request_t * r;
197    int i, block;
198
199    peertreeFree( &peer->sentPeers );
200    for( i = 0; i < peer->inRequestCount; i++ )
201    {
202        r = &peer->inRequests[i];
203        block = tr_block( r->index, r->begin );
204        tr_cpDownloaderRem( tor->completion, block );
205    }
206    tr_bitfieldFree( peer->bitfield );
207    tr_bitfieldFree( peer->blamefield );
208    tr_bitfieldFree( peer->banfield );
209    if( peer->buf )
210    {
211        free( peer->buf );
212    }
213    if( peer->outMessages )
214    {
215        free( peer->outMessages );
216    }
217    if( peer->status > PEER_STATUS_IDLE )
218    {
219        tr_netClose( peer->socket );
220    }
221    tr_rcClose( peer->download );
222    tr_rcClose( peer->upload );
223    free( peer->client );
224    free( peer );
225}
226
227const char *
228tr_peerClient( tr_peer_t * peer )
229{
230    if( PEER_STATUS_HANDSHAKE >= peer->status )
231    {
232        return "not connected";
233    }
234
235    if( NULL == peer->client )
236    {
237        peer->client = tr_clientForId( peer->id );
238    }
239
240    return peer->client;
241}
242
243void tr_peerSetPrivate( tr_peer_t * peer, int private )
244{
245    if( peer->private == private )
246    {
247        return;
248    }
249
250    peer->private = private;
251
252    if( !private )
253    {
254        peer->lastPex = 0;
255    }
256
257    if( EXTENDED_HANDSHAKE == peer->extStatus )
258    {
259        sendExtended( peer->tor, peer, EXTENDED_HANDSHAKE_ID );
260    }
261}
262
263void tr_peerSetTorrent( tr_peer_t * peer, tr_torrent_t * tor )
264{
265    peer->tor = tor;
266}
267
268/***********************************************************************
269 * tr_peerRead
270 ***********************************************************************
271 *
272 **********************************************************************/
273int tr_peerRead( tr_peer_t * peer )
274{
275    tr_torrent_t * tor = peer->tor;
276    int ret;
277
278    /* Try to read */
279    for( ;; )
280    {
281        if( tor )
282        {
283            if( tor->customDownloadLimit
284                ? !tr_rcCanTransfer( tor->download )
285                : !tr_rcCanTransfer( tor->handle->download ) )
286            {
287                break;
288            }
289        }
290
291        if( peer->size < 1 )
292        {
293            peer->size = 1024;
294            peer->buf  = malloc( peer->size );
295        }
296        else if( peer->pos >= peer->size )
297        {
298            peer->size *= 2;
299            peer->buf   = realloc( peer->buf, peer->size );
300        }
301        /* Never read more than 1K each time, otherwise the rate
302           control is no use */
303        ret = tr_netRecv( peer->socket, &peer->buf[peer->pos],
304                          MIN( 1024, peer->size - peer->pos ) );
305        if( ret & TR_NET_CLOSE )
306        {
307            peer_dbg( "connection closed" );
308            return TR_ERROR;
309        }
310        else if( ret & TR_NET_BLOCK )
311        {
312            break;
313        }
314        peer->date  = tr_date();
315        peer->pos  += ret;
316        if( NULL != tor )
317        {
318            tr_rcTransferred( peer->download, ret );
319            tr_rcTransferred( tor->download, ret );
320            if ( !tor->customDownloadLimit )
321            {
322                tr_rcTransferred( tor->handle->download, ret );
323            }
324           
325            if( ( ret = parseBuf( tor, peer ) ) )
326            {
327                return ret;
328            }
329        }
330        else
331        {
332            if( ( ret = parseBufHeader( peer ) ) )
333            {
334                return ret;
335            }
336        }
337    }
338
339    return TR_OK;
340}
341
342uint64_t tr_peerDate( tr_peer_t * peer )
343{
344    return peer->date;
345}
346
347/***********************************************************************
348 * tr_peerId
349 ***********************************************************************
350 *
351 **********************************************************************/
352uint8_t * tr_peerId( tr_peer_t * peer )
353{
354    return & peer->id[0];
355}
356
357/***********************************************************************
358 * tr_peerAddress
359 ***********************************************************************
360 *
361 **********************************************************************/
362struct in_addr * tr_peerAddress( tr_peer_t * peer )
363{
364    return &peer->addr;
365}
366
367/***********************************************************************
368 * tr_peerHash
369 ***********************************************************************
370 *
371 **********************************************************************/
372uint8_t * tr_peerHash( tr_peer_t * peer )
373{
374    return parseBufHash( peer );
375}
376
377/***********************************************************************
378 * tr_peerPulse
379 ***********************************************************************
380 *
381 **********************************************************************/
382int tr_peerPulse( tr_peer_t * peer )
383{
384    tr_torrent_t * tor = peer->tor;
385    int ret, size;
386    uint8_t * p;
387
388    if( ( ret = checkPeer( peer ) ) )
389    {
390        return ret;
391    }
392
393    /* Connect */
394    if( PEER_STATUS_IDLE == peer->status )
395    {
396        peer->socket = tr_netOpenTCP( peer->addr, peer->port, 0 );
397        if( peer->socket < 0 )
398        {
399            return TR_ERROR;
400        }
401        peer->status = PEER_STATUS_CONNECTING;
402    }
403
404    /* Try to send handshake */
405    if( PEER_STATUS_CONNECTING == peer->status )
406    {
407        uint8_t buf[68];
408        tr_info_t * inf = &tor->info;
409
410        buf[0] = 19;
411        memcpy( &buf[1], "BitTorrent protocol", 19 );
412        memset( &buf[20], 0, 8 );
413        buf[20] = 0x80;         /* azureus protocol */
414        buf[25] = 0x10;         /* extended messages */
415        memcpy( &buf[28], inf->hash, 20 );
416        memcpy( &buf[48], tor->id, 20 );
417
418        switch( tr_netSend( peer->socket, buf, 68 ) )
419        {
420            case 68:
421                peer_dbg( "SEND handshake" );
422                peer->status = PEER_STATUS_HANDSHAKE;
423                break;
424            case TR_NET_BLOCK:
425                break;
426            default:
427                peer_dbg( "connection closed" );
428                return TR_ERROR;
429        }
430    }
431    if( peer->status < PEER_STATUS_HANDSHAKE )
432    {
433        /* Nothing more we can do till we sent the handshake */
434        return TR_OK;
435    }
436
437    /* Read incoming messages */
438    if( ( ret = tr_peerRead( peer ) ) )
439    {
440        return ret;
441    }
442
443    /* Try to send Azureus handshake */
444    if( PEER_STATUS_AZ_GIVER == peer->status )
445    {
446        switch( sendAZHandshake( tor, peer ) )
447        {
448            case TR_NET_BLOCK:
449                break;
450            case TR_NET_CLOSE:
451                peer_dbg( "connection closed" );
452                return TR_ERROR;
453            default:
454                peer->status = PEER_STATUS_AZ_RECEIVER;
455                break;
456        }
457    }
458
459    if( peer->status < PEER_STATUS_CONNECTED )
460    {
461        /* Nothing more we can do till we got the other guy's handshake */
462        return TR_OK;
463    }
464
465    /* Try to write */
466writeBegin:
467
468    /* Send all smaller messages regardless of the upload cap */
469    while( ( p = messagesPending( peer, &size ) ) )
470    {
471        ret = tr_netSend( peer->socket, p, size );
472        if( ret & TR_NET_CLOSE )
473        {
474            return TR_ERROR;
475        }
476        else if( ret & TR_NET_BLOCK )
477        {
478            goto writeEnd;
479        }
480        messagesSent( peer, ret );
481    }
482
483    /* Send pieces if we can */
484    while( ( p = blockPending( tor, peer, &size ) ) )
485    {
486        if( tor->customUploadLimit
487            ? !tr_rcCanTransfer( tor->upload )
488            : !tr_rcCanTransfer( tor->handle->upload ) )
489        {
490            break;
491        }
492
493        ret = tr_netSend( peer->socket, p, size );
494        if( ret & TR_NET_CLOSE )
495        {
496            return TR_ERROR;
497        }
498        else if( ret & TR_NET_BLOCK )
499        {
500            break;
501        }
502
503        blockSent( peer, ret );
504        tr_rcTransferred( peer->upload, ret );
505        tr_rcTransferred( tor->upload, ret );
506        if ( !tor->customUploadLimit )
507        {
508            tr_rcTransferred( tor->handle->upload, ret );
509        }
510
511        tor->uploadedCur += ret;
512        peer->outTotal   += ret;
513        peer->outDate     = tr_date();
514
515        /* In case this block is done, you may have messages
516           pending. Send them before we start the next block */
517        goto writeBegin;
518    }
519writeEnd:
520
521    /* Ask for a block whenever possible */
522    if( !tr_cpIsSeeding( tor->completion ) &&
523        !peer->amInterested && tor->peerCount > TR_MAX_PEER_COUNT - 2 )
524    {
525        /* This peer is no use to us, and it seems there are
526           more */
527        peer_dbg( "not interesting" );
528        return TR_ERROR;
529    }
530
531    if( peer->amInterested && !peer->peerChoking && !peer->banned )
532    {
533        int block;
534        while( peer->inRequestCount < OUR_REQUEST_COUNT )
535        {
536            block = chooseBlock( tor, peer );
537            if( block < 0 )
538            {
539                break;
540            }
541            sendRequest( tor, peer, block );
542        }
543    }
544
545    return TR_OK;
546}
547
548/***********************************************************************
549 * tr_peerIsConnected
550 ***********************************************************************
551 *
552 **********************************************************************/
553int tr_peerIsConnected( tr_peer_t * peer )
554{
555    return PEER_STATUS_CONNECTED == peer->status;
556}
557
558/***********************************************************************
559 * tr_peerIsIncoming
560 ***********************************************************************
561 *
562 **********************************************************************/
563int tr_peerIsFrom( tr_peer_t * peer )
564{
565    return peer->from;
566}
567
568int tr_peerAmChoking( tr_peer_t * peer )
569{
570    return peer->amChoking;
571}
572int tr_peerAmInterested( tr_peer_t * peer )
573{
574    return peer->amInterested;
575}
576int tr_peerIsChoking( tr_peer_t * peer )
577{
578    return peer->peerChoking;
579}
580int tr_peerIsInterested( tr_peer_t * peer )
581{
582    return peer->peerInterested;
583}
584
585/***********************************************************************
586 * tr_peerProgress
587 ***********************************************************************
588 *
589 **********************************************************************/
590float tr_peerProgress( tr_peer_t * peer )
591{
592    return peer->progress;
593}
594
595/***********************************************************************
596 * tr_peerPort
597 ***********************************************************************
598 * Returns peer's listening port in host byte order
599 **********************************************************************/
600int tr_peerPort( tr_peer_t * peer )
601{
602    return ntohs( peer->port );
603}
604
605/***********************************************************************
606 * tr_peerBitfield
607 ***********************************************************************
608 *
609 **********************************************************************/
610tr_bitfield_t * tr_peerBitfield( tr_peer_t * peer )
611{
612    return peer->bitfield;
613}
614
615float tr_peerDownloadRate( tr_peer_t * peer )
616{
617    return tr_rcRate( peer->download );
618}
619
620float tr_peerUploadRate( tr_peer_t * peer )
621{
622    return tr_rcRate( peer->upload );
623}
624
625void tr_peerChoke( tr_peer_t * peer )
626{
627    sendChoke( peer, 1 );
628    peer->lastChoke = tr_date();
629}
630
631void tr_peerUnchoke( tr_peer_t * peer )
632{
633    sendChoke( peer, 0 );
634    peer->lastChoke = tr_date();
635}
636
637uint64_t tr_peerLastChoke( tr_peer_t * peer )
638{
639    return peer->lastChoke;
640}
641
642void tr_peerSetOptimistic( tr_peer_t * peer, int o )
643{
644    peer->optimistic = o;
645}
646
647int tr_peerIsOptimistic( tr_peer_t * peer )
648{
649    return peer->optimistic;
650}
651
652static inline int peerIsBad( tr_peer_t * peer )
653{
654    return ( peer->badPcs > 4 + 2 * peer->goodPcs );
655}
656
657static inline int peerIsGood( tr_peer_t * peer )
658{
659    return ( peer->goodPcs > 3 * peer->badPcs );
660}
661
662void tr_peerBlame( tr_peer_t * peer, int piece, int success )
663{
664    tr_torrent_t * tor = peer->tor;
665
666    if( !peer->blamefield || !tr_bitfieldHas( peer->blamefield, piece ) )
667    {
668        return;
669    }
670
671    if( success )
672    {
673        peer->goodPcs++;
674
675        if( peer->banfield && peerIsGood( peer ) )
676        {
677            /* Assume the peer wasn't responsible for the bad pieces
678               we was banned for */
679            tr_bitfieldClear( peer->banfield );
680        }
681    }
682    else
683    {
684        peer->badPcs++;
685
686        /* Ban the peer for this piece */
687        if( !peer->banfield )
688        {
689            peer->banfield = tr_bitfieldNew( tor->info.pieceCount );
690        }
691        tr_bitfieldAdd( peer->banfield, piece );
692
693        if( peerIsBad( peer ) )
694        {
695            /* Full ban */
696            peer_dbg( "banned (%d / %d)", peer->goodPcs, peer->badPcs );
697            peer->banned = 1;
698            peer->peerInterested = 0;
699        }
700    }
701    tr_bitfieldRem( peer->blamefield, piece );
702}
703
704int tr_peerGetConnectable( tr_torrent_t * tor, uint8_t ** _buf )
705{
706    int count = 0;
707    uint8_t * buf;
708    tr_peer_t * peer;
709    int i;
710
711    if( tor->peerCount < 1 )
712    {
713        *_buf = NULL;
714        return 0;
715    }
716
717    buf = malloc( 6 * tor->peerCount );
718    for( i = 0; i < tor->peerCount; i++ )
719    {
720        peer = tor->peers[i];
721
722        /* Skip peers with no known listening port */
723        if( 0 == peer->port )
724            continue;
725
726        memcpy( &buf[count*6], &peer->addr, 4 );
727        memcpy( &buf[count*6+4], &peer->port, 2 );
728        count++;
729    }
730
731    if( count < 1 )
732    {
733        free( buf ); buf = NULL;
734    }
735    *_buf = buf;
736
737    return count * 6;
738}
Note: See TracBrowser for help on using the repository browser.