source: branches/pex/libtransmission/peerutils.h @ 1540

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

Implement Azureus peer protocol, including PEX message.
Implement extended messages, including uTorrent PEX.

  • Property svn:keywords set to Date Rev Author Id
File size: 9.7 KB
Line 
1/******************************************************************************
2 * $Id: peerutils.h 1540 2007-03-08 04:06:58Z 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
25static void updateInterest( tr_torrent_t * tor, tr_peer_t * peer );
26
27/***********************************************************************
28 * peerInit
29 ***********************************************************************
30 * Allocates a new tr_peer_t and returns a pointer to it.
31 **********************************************************************/
32static tr_peer_t * peerInit()
33{
34    tr_peer_t * peer;
35
36    peer              = calloc( sizeof( tr_peer_t ), 1 );
37    peertreeInit( &peer->sentPeers );
38    peer->amChoking   = 1;
39    peer->peerChoking = 1;
40    peer->date        = tr_date();
41    peer->keepAlive   = peer->date;
42    peer->download    = tr_rcInit();
43    peer->upload      = tr_rcInit();
44
45    return peer;
46}
47
48static int peerCmp( tr_peer_t * peer1, tr_peer_t * peer2 )
49{
50    /* Wait until we got the peers' ids */
51    if( peer1->status <= PEER_STATUS_HANDSHAKE ||
52        peer2->status <= PEER_STATUS_HANDSHAKE )
53    {
54        return 1;
55    }
56
57    return memcmp( peer1->id, peer2->id, 20 );
58}
59
60static int checkPeer( tr_peer_t * peer )
61{
62    tr_torrent_t * tor = peer->tor;
63    uint64_t       now;
64
65    now = tr_date();
66
67    if( peer->status < PEER_STATUS_CONNECTED &&
68        now > peer->date + 8000 )
69    {
70        /* If it has been too long, don't wait for the socket
71           to timeout - forget about it now */
72        peer_dbg( "connection timeout" );
73        return TR_ERROR;
74    }
75
76    /* Drop peers who haven't even sent a keep-alive within the
77       last 3 minutes */
78    if( now > peer->date + 180000 )
79    {
80        peer_dbg( "read timeout" );
81        return TR_ERROR;
82    }
83
84    /* Drop peers which are supposed to upload but actually
85       haven't sent anything within the last minute */
86    if( peer->inRequestCount && now > peer->date + 60000 )
87    {
88        peer_dbg( "bad uploader" );
89        return TR_ERROR;
90    }
91
92    if( PEER_STATUS_CONNECTED == peer->status )
93    {
94        /* Send keep-alive every 2 minutes */
95        if( now > peer->keepAlive + 120000 )
96        {
97            sendKeepAlive( peer );
98            peer->keepAlive = now;
99        }
100
101        /* Resend extended handshake if our public port changed */
102        if( EXTENDED_HANDSHAKE == peer->extStatus && 
103            tor->publicPort != peer->advertisedPort )
104        {
105            sendExtended( tor, peer, EXTENDED_HANDSHAKE_ID );
106        }
107
108        /* Send peer list */
109        if( !peer->private && 0 < peer->pexStatus )
110        {
111            if( 0 == peer->lastPex )
112            {
113                /* randomize time when first pex message is sent */
114                peer->lastPex = now - 1000 * tr_rand( PEX_INTERVAL );
115            }
116            if( now > peer->lastPex + 1000 * PEX_INTERVAL )
117            {
118                if( ( EXTENDED_HANDSHAKE == peer->extStatus &&
119                      !sendExtended( tor, peer, EXTENDED_PEX_ID ) ) ||
120                    ( peer->azproto && !sendAZPex( tor, peer ) ) )
121                {
122                    peer->lastPex = now + 1000 * tr_rand( PEX_INTERVAL / 10 );
123                }
124            }
125        }
126    }
127
128    return TR_OK;
129}
130
131/***********************************************************************
132 * isInteresting
133 ***********************************************************************
134 * Returns 1 if 'peer' has at least one piece that we haven't completed,
135 * or 0 otherwise.
136 **********************************************************************/
137static int isInteresting( tr_torrent_t * tor, tr_peer_t * peer )
138{
139    int ii;
140    tr_bitfield_t * bitfield = tr_cpPieceBitfield( tor->completion );
141
142    if( !peer->bitfield )
143    {
144        /* We don't know what this peer has */
145        return 0;
146    }
147
148    assert( bitfield->len == peer->bitfield->len );
149    for( ii = 0; ii < bitfield->len; ii++ )
150    {
151        if( ( peer->bitfield->bits[ii] & ~(bitfield->bits[ii]) ) & 0xFF )
152        {
153            return 1;
154        }
155    }
156
157    return 0;
158}
159static void updateInterest( tr_torrent_t * tor, tr_peer_t * peer )
160{
161    int interested = isInteresting( tor, peer );
162
163    if( interested && !peer->amInterested )
164    {
165        sendInterest( peer, 1 );
166    }
167    if( !interested && peer->amInterested )
168    {
169        sendInterest( peer, 0 );
170    }
171}
172
173/***********************************************************************
174 * chooseBlock
175 ***********************************************************************
176 * At this point, we know the peer has at least one block we have an
177 * interest in. If he has more than one, we choose which one we are
178 * going to ask first.
179 * Our main goal is to complete pieces, so we look the pieces which are
180 * missing less blocks.
181 **********************************************************************/
182static inline int chooseBlock( tr_torrent_t * tor, tr_peer_t * peer )
183{
184    tr_info_t * inf = &tor->info;
185
186    int i;
187    int missingBlocks, minMissing;
188    int poolSize, * pool;
189    int block, minDownloading;
190
191    /* Choose a piece */
192    pool       = malloc( inf->pieceCount * sizeof( int ) );
193    poolSize   = 0;
194    minMissing = tor->blockCount + 1;
195    for( i = 0; i < inf->pieceCount; i++ )
196    {
197        missingBlocks = tr_cpMissingBlocksForPiece( tor->completion, i );
198        if( missingBlocks < 1 )
199        {
200            /* We already have or are downloading all blocks */
201            continue;
202        }
203        if( !tr_bitfieldHas( peer->bitfield, i ) )
204        {
205            /* The peer doesn't have this piece */
206            continue;
207        }
208        if( peer->banfield && tr_bitfieldHas( peer->banfield, i ) )
209        {
210            /* The peer is banned for this piece */
211            continue;
212        }
213
214        /* We are interested in this piece, remember it */
215        if( missingBlocks < minMissing )
216        {
217            minMissing = missingBlocks;
218            poolSize   = 0;
219        }
220        if( missingBlocks <= minMissing )
221        {
222            pool[poolSize++] = i;
223        }
224    }
225
226    if( poolSize )
227    {
228        /* All pieces in 'pool' have 'minMissing' missing blocks. Find
229           the rarest ones. */
230        tr_bitfield_t * bitfield;
231        int piece;
232        int min, foo, j;
233        int * pool2;
234        int   pool2Size;
235
236        pool2     = malloc( poolSize * sizeof( int ) );
237        pool2Size = 0;
238        min       = TR_MAX_PEER_COUNT + 1;
239        for( i = 0; i < poolSize; i++ )
240        {
241            foo = 0;
242            for( j = 0; j < tor->peerCount; j++ )
243            {
244                bitfield = tor->peers[j]->bitfield;
245                if( bitfield && tr_bitfieldHas( bitfield, pool[i] ) )
246                {
247                    foo++;
248                }
249            }
250            if( foo < min )
251            {
252                min       = foo;
253                pool2Size = 0;
254            }
255            if( foo <= min )
256            {
257                pool2[pool2Size++] = pool[i];
258            }
259        }
260        free( pool );
261
262        if( pool2Size < 1 )
263        {
264            /* Shouldn't happen */
265            free( pool2 );
266            return -1;
267        }
268
269        /* All pieces in pool2 have the same number of missing blocks,
270           and are availabme from the same number of peers. Pick a
271           random one */
272        piece = pool2[tr_rand(pool2Size)];
273        free( pool2 );
274
275        /* Pick a block in this piece */
276        block = tr_cpMissingBlockInPiece( tor->completion, piece );
277        goto check;
278    }
279
280    free( pool );
281
282    /* "End game" mode */
283    minDownloading = 255;
284    block = -1;
285    for( i = 0; i < inf->pieceCount; i++ )
286    {
287        int downloaders, block2;
288        if( !tr_bitfieldHas( peer->bitfield, i ) )
289        {
290            /* The peer doesn't have this piece */
291            continue;
292        }
293        if( peer->banfield && tr_bitfieldHas( peer->banfield, i ) )
294        {
295            /* The peer is banned for this piece */
296            continue;
297        }
298        if( tr_cpPieceIsComplete( tor->completion, i ) )
299        {
300            /* We already have it */
301            continue;
302        }
303        block2 = tr_cpMostMissingBlockInPiece( tor->completion, i, &downloaders );
304        if( block2 > -1 && downloaders < minDownloading )
305        {
306            block = block2;
307            minDownloading = downloaders;
308        }
309    }
310
311check:
312    if( block < 0 )
313    {
314        /* Shouldn't happen */
315        return -1;
316    }
317
318    for( i = 0; i < peer->inRequestCount; i++ )
319    {
320        tr_request_t * r;
321        r = &peer->inRequests[i];
322        if( tr_block( r->index, r->begin ) == block )
323        {
324            /* We are already asking this peer for this block */
325            return -1;
326        }
327    }
328
329    return block;
330}
Note: See TracBrowser for help on using the repository browser.