source: trunk/libtransmission/torrent.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: 33.9 KB
Line 
1/******************************************************************************
2 * $Id: torrent.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
30#include "transmission.h"
31#include "fastresume.h"
32#include "trcompat.h" /* for strlcpy */
33#include "metainfo.h"
34#include "net.h" /* tr_netNtop */
35#include "shared.h"
36
37/***
38****  LOCKS
39***/
40
41void
42tr_torrentReaderLock( const tr_torrent_t * tor )
43{
44    tr_rwReaderLock ( (tr_rwlock_t*)&tor->lock );
45}
46
47void
48tr_torrentReaderUnlock( const tr_torrent_t * tor )
49{
50    tr_rwReaderUnlock ( (tr_rwlock_t*)&tor->lock );
51}
52
53void
54tr_torrentWriterLock( tr_torrent_t * tor )
55{
56    tr_rwWriterLock ( &tor->lock );
57}
58
59void
60tr_torrentWriterUnlock( tr_torrent_t * tor )
61{
62    tr_rwWriterUnlock ( &tor->lock );
63}
64
65/***
66****  PER-TORRENT UL / DL SPEEDS
67***/
68
69void
70tr_setUseCustomUpload( tr_torrent_t * tor, int limit )
71{
72    tr_torrentWriterLock( tor );
73    tor->customUploadLimit = limit;
74    tr_torrentWriterUnlock( tor );
75}
76
77void
78tr_setUseCustomDownload( tr_torrent_t * tor, int limit )
79{
80    tr_torrentWriterLock( tor );
81    tor->customDownloadLimit = limit;
82    tr_torrentWriterUnlock( tor );
83}
84
85void
86tr_setUploadLimit( tr_torrent_t * tor, int limit )
87{
88    tr_torrentWriterLock( tor );
89    tr_rcSetLimit( tor->upload, limit );
90    tr_torrentWriterUnlock( tor );
91}
92
93void
94tr_setDownloadLimit( tr_torrent_t * tor, int limit )
95{
96    tr_torrentWriterLock( tor );
97    tr_rcSetLimit( tor->download, limit );
98    tr_torrentWriterUnlock( tor );
99}
100
101/***
102****
103****  TORRENT INSTANTIATION
104****
105***/
106
107static int
108getBytePiece( const tr_info_t * info, uint64_t byteOffset )
109{
110    assert( info != NULL );
111    assert( info->pieceSize != 0 );
112
113    return byteOffset / info->pieceSize;
114}
115
116static void
117initFilePieces ( tr_info_t * info, int fileIndex )
118{
119    tr_file_t * file = &info->files[fileIndex];
120    uint64_t firstByte, lastByte;
121
122    assert( info != NULL );
123    assert( 0<=fileIndex && fileIndex<info->fileCount );
124
125    file = &info->files[fileIndex];
126    firstByte = file->offset;
127    lastByte = firstByte + (file->length ? file->length-1 : 0);
128    file->firstPiece = getBytePiece( info, firstByte );
129    file->lastPiece = getBytePiece( info, lastByte );
130    tr_dbg( "file #%d is in pieces [%d...%d] (%s)", fileIndex, file->firstPiece, file->lastPiece, file->name );
131}
132
133static tr_priority_t
134calculatePiecePriority ( const tr_torrent_t * tor,
135                         int                  piece )
136{
137    int i;
138    tr_priority_t priority = TR_PRI_NORMAL;
139
140    for( i=0; i<tor->info.fileCount; ++i )
141    {
142        const tr_file_t * file = &tor->info.files[i];
143        if ( file->firstPiece <= piece
144          && file->lastPiece  >= piece
145          && file->priority   >  priority)
146              priority = file->priority;
147    }
148
149    return priority;
150}
151
152static void
153tr_torrentInitFilePieces( tr_torrent_t * tor )
154{
155    int i;
156    uint64_t offset = 0;
157
158    assert( tor != NULL );
159
160    for( i=0; i<tor->info.fileCount; ++i ) {
161      tor->info.files[i].offset = offset;
162      offset += tor->info.files[i].length;
163      initFilePieces( &tor->info, i );
164    }
165
166    for( i=0; i<tor->info.pieceCount; ++i )
167      tor->info.pieces[i].priority = calculatePiecePriority( tor, i );
168}
169
170static void torrentThreadLoop( void * );
171
172static void
173torrentRealInit( tr_handle_t   * h,
174                 tr_torrent_t  * tor,
175                 const char    * destination,
176                 int             flags )
177{
178    int i;
179    char name[512];
180   
181    tor->info.flags |= flags;
182
183    tr_sharedLock( h->shared );
184
185    tor->destination = tr_strdup( destination );
186
187    tr_torrentInitFilePieces( tor );
188
189    tor->handle   = h;
190    tor->id       = h->id;
191    tor->key      = h->key;
192    tor->azId     = h->azId;
193    tor->hasChangedState = -1;
194   
195    /* Escaped info hash for HTTP queries */
196    for( i = 0; i < SHA_DIGEST_LENGTH; i++ )
197    {
198        snprintf( &tor->escapedHashString[3*i],
199                  sizeof( tor->escapedHashString ) - 3 * i,
200                  "%%%02x", tor->info.hash[i] );
201    }
202
203    tor->pexDisabled = 0;
204
205    /* Block size: usually 16 ko, or less if we have to */
206    tor->blockSize  = MIN( tor->info.pieceSize, 1 << 14 );
207    tor->blockCount = ( tor->info.totalSize + tor->blockSize - 1 ) /
208                        tor->blockSize;
209    tor->completion = tr_cpInit( tor );
210
211    tor->thread = THREAD_EMPTY;
212    tr_rwInit( &tor->lock );
213
214    tor->upload         = tr_rcInit();
215    tor->download       = tr_rcInit();
216    tor->swarmspeed     = tr_rcInit();
217 
218    /* We have a new torrent */
219    tor->publicPort = tr_sharedGetPublicPort( h->shared );
220
221    tr_sharedUnlock( h->shared );
222
223    if( !h->isPortSet )
224        tr_setBindPort( h, TR_DEFAULT_PORT );
225
226    assert( !tor->downloadedCur );
227    assert( !tor->uploadedCur );
228
229    tor->error   = TR_OK;
230    tor->runStatus = flags & TR_FLAG_PAUSED ? TR_RUN_STOPPED : TR_RUN_RUNNING;
231    tor->recheckFlag = tr_ioCheckFiles( tor, TR_RECHECK_FAST );
232    tor->cpStatus = tr_cpGetStatus( tor->completion );
233
234    tr_sharedLock( h->shared );
235    tor->next = h->torrentList;
236    h->torrentList = tor;
237    h->torrentCount++;
238    tr_sharedUnlock( h->shared );
239
240    snprintf( name, sizeof( name ), "torrent %p (%s)", tor, tor->info.name );
241    tr_threadCreate( &tor->thread, torrentThreadLoop, tor, name );
242}
243
244static int
245pathIsInUse ( const tr_handle_t   * h,
246              const char          * destination,
247              const char          * name )
248{
249    const tr_torrent_t * tor;
250   
251    for( tor=h->torrentList; tor; tor=tor->next )
252        if( !strcmp( destination, tor->destination )
253         && !strcmp( name, tor->info.name ) )
254            return TRUE;
255
256    return FALSE;
257}
258
259static int
260hashExists( const tr_handle_t   * h,
261            const uint8_t       * hash )
262{
263    const tr_torrent_t * tor;
264
265    for( tor=h->torrentList; tor; tor=tor->next )
266        if( !memcmp( hash, tor->info.hash, SHA_DIGEST_LENGTH ) )
267            return TRUE;
268
269    return FALSE;
270}
271
272static int
273infoCanAdd( const tr_handle_t   * h,
274            const char          * destination,
275            const tr_info_t     * info )
276{
277    if( hashExists( h, info->hash ) )
278        return TR_EDUPLICATE;
279
280    if( destination && pathIsInUse( h, destination, info->name ) )
281        return TR_EDUPLICATE;
282
283    return TR_OK;
284}
285
286int
287tr_torrentParse( const tr_handle_t  * h,
288                 const char         * path,
289                 const char         * destination,
290                 tr_info_t          * setme_info )
291{
292    int ret;
293    tr_info_t tmp;
294
295    if( setme_info == NULL )
296        setme_info = &tmp;
297
298    memset( setme_info, 0, sizeof( tr_info_t ) );
299    ret = tr_metainfoParseFile( setme_info, h->tag, path, FALSE );
300
301    if( ret == TR_OK )
302        ret = infoCanAdd( h, destination, setme_info );
303
304    if( setme_info == &tmp )
305        tr_metainfoFree( &tmp );
306
307    return ret;
308}
309 
310tr_torrent_t *
311tr_torrentInit( tr_handle_t   * h,
312                const char    * path,
313                const char    * destination,
314                int             flags,
315                int           * error )
316{
317    int val;
318    tr_torrent_t * tor = NULL;
319
320    if(( val = tr_torrentParse( h, path, destination, NULL )))
321        *error = val;
322    else if(!(( tor = tr_new0( tr_torrent_t, 1 ))))
323        *error = TR_EOTHER;
324    else {
325        tr_metainfoParseFile( &tor->info, h->tag, path, TR_FLAG_SAVE & flags );
326        torrentRealInit( h, tor, destination, flags );
327    }
328
329    return tor;
330}
331
332int
333tr_torrentParseHash( const tr_handle_t  * h,
334                     const char         * hashStr,
335                     const char         * destination,
336                     tr_info_t          * setme_info )
337{
338    int ret;
339    tr_info_t tmp;
340
341    if( setme_info == NULL )
342        setme_info = &tmp;
343
344    memset( setme_info, 0, sizeof( tr_info_t ) );
345    ret = tr_metainfoParseHash( setme_info, h->tag, hashStr );
346
347    if( ret == TR_OK )
348        ret = infoCanAdd( h, destination, setme_info );
349
350    if( setme_info == &tmp )
351        tr_metainfoFree( &tmp );
352
353    return ret;
354}
355
356
357tr_torrent_t *
358tr_torrentInitSaved( tr_handle_t    * h,
359                     const char     * hashStr,
360                     const char     * destination,
361                     int              flags,
362                     int            * error )
363{
364    int val;
365    tr_torrent_t * tor = NULL;
366
367    if(( val = tr_torrentParseHash( h, hashStr, destination, NULL )))
368        *error = val;
369    else if(!(( tor = tr_new0( tr_torrent_t, 1 ))))
370        *error = TR_EOTHER;
371    else {
372        tr_metainfoParseHash( &tor->info, h->tag, hashStr );
373        torrentRealInit( h, tor, destination, (TR_FLAG_SAVE|flags) );
374    }
375
376    return tor;
377}
378
379static int
380tr_torrentParseData( const tr_handle_t  * h,
381                     const uint8_t      * data,
382                     size_t               size,
383                     const char         * destination,
384                     tr_info_t          * setme_info )
385{
386    int ret;
387    tr_info_t tmp;
388
389    if( setme_info == NULL )
390        setme_info = &tmp;
391
392    memset( setme_info, 0, sizeof( tr_info_t ) );
393    ret = tr_metainfoParseData( setme_info, h->tag, data, size, FALSE );
394
395    if( ret == TR_OK )
396        ret = infoCanAdd( h, destination, setme_info );
397
398    if( setme_info == &tmp )
399        tr_metainfoFree( &tmp );
400
401    return ret;
402}
403
404tr_torrent_t *
405tr_torrentInitData( tr_handle_t    * h,
406                    const uint8_t  * data,
407                    size_t           size,
408                    const char     * destination,
409                    int              flags,
410                    int            * error )
411{
412    int val;
413    tr_torrent_t * tor = NULL;
414
415    if(( val = tr_torrentParseData( h, data, size, destination, NULL )))
416        *error = val;
417    else if(!(( tor = tr_new0( tr_torrent_t, 1 ))))
418        *error = TR_EOTHER;
419    else {
420        tr_metainfoParseData( &tor->info, h->tag, data, size, TR_FLAG_SAVE & flags );
421        torrentRealInit( h, tor, destination, flags );
422    }
423
424    return tor;
425}
426
427const tr_info_t *
428tr_torrentInfo( const tr_torrent_t * tor )
429{
430    return &tor->info;
431}
432
433/***
434****
435***/
436
437int tr_torrentScrape( tr_torrent_t * tor, int * s, int * l, int * d )
438{
439    return tr_trackerScrape( tor, s, l, d );
440}
441
442void tr_torrentSetFolder( tr_torrent_t * tor, const char * path )
443{
444    tr_free( tor->destination );
445    tor->destination = tr_strdup( path );
446
447    if( !tor->ioLoaded )
448         tor->ioLoaded = tr_ioLoadResume( tor ) == TR_OK;
449}
450
451const char* tr_torrentGetFolder( const tr_torrent_t * tor )
452{
453    return tor->destination;
454}
455
456
457/***********************************************************************
458 * torrentReallyStop
459 ***********************************************************************
460 * Joins the download thread and frees/closes everything related to it.
461 **********************************************************************/
462
463void tr_torrentDisablePex( tr_torrent_t * tor, int disable )
464{
465    tr_torrentWriterLock( tor );
466
467    if( ! ( TR_FLAG_PRIVATE & tor->info.flags ) )
468    {
469        if( tor->pexDisabled != disable )
470        {
471            int i;
472            tor->pexDisabled = disable;
473            for( i=0; i<tor->peerCount; ++i )
474                tr_peerSetPrivate( tor->peers[i], disable );
475        }
476    }
477
478    tr_torrentWriterUnlock( tor );
479}
480
481static int tr_didStateChangeTo ( tr_torrent_t * tor, int status )
482{
483    int ret;
484
485    tr_torrentWriterLock( tor );
486    if (( ret = tor->hasChangedState == status ))
487        tor->hasChangedState = -1;
488    tr_torrentWriterUnlock( tor );
489
490    return ret;
491}
492
493int tr_getIncomplete( tr_torrent_t * tor )
494{
495    return tr_didStateChangeTo( tor, TR_CP_INCOMPLETE );
496}
497int tr_getDone( tr_torrent_t * tor )
498{
499    return tr_didStateChangeTo( tor, TR_CP_DONE );
500}
501int tr_getComplete( tr_torrent_t * tor )
502{
503    return tr_didStateChangeTo( tor, TR_CP_COMPLETE );
504}
505
506void tr_manualUpdate( tr_torrent_t * tor UNUSED )
507{
508#if 0
509    int peerCount, new;
510    uint8_t * peerCompact;
511
512    if( tor->status != TR_RUN_RUNNING )
513        return;
514   
515    tr_torrentWriterLock( tor );
516    tr_trackerAnnouncePulse( tor->tracker, &peerCount, &peerCompact, 1 );
517    new = 0;
518    if( peerCount > 0 )
519    {
520        new = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
521                                    peerCompact, peerCount );
522        free( peerCompact );
523    }
524    tr_dbg( "got %i peers from manual announce, used %i", peerCount, new );
525    tr_torrentWriterUnlock( tor );
526#endif
527}
528
529tr_stat_t * tr_torrentStat( tr_torrent_t * tor )
530{
531    tr_stat_t * s;
532    tr_tracker_t * tc;
533    int i;
534
535    tr_torrentReaderLock( tor );
536
537    tor->statCur = ( tor->statCur + 1 ) % 2;
538    s = &tor->stats[tor->statCur];
539
540    s->error  = tor->error;
541    memcpy( s->errorString, tor->errorString,
542            sizeof( s->errorString ) );
543
544    tc = tor->tracker;
545    s->cannotConnect = tr_trackerCannotConnect( tc );
546    s->tracker = tc
547        ? tr_trackerGet( tc )
548        : &tor->info.trackerList[0].list[0];
549
550    /* peers... */
551    memset( s->peersFrom, 0, sizeof( s->peersFrom ) );
552    s->peersTotal       = 0;
553    s->peersUploading   = 0;
554    s->peersDownloading = 0;
555    for( i=0; i<tor->peerCount; ++i ) {
556        const tr_peer_t * peer = tor->peers[i];
557        ++s->peersTotal;
558        if( tr_peerIsConnected( peer ) ) {
559            ++s->peersFrom[tr_peerIsFrom(peer)];
560            if( tr_peerIsInterested( peer ) && !tr_peerIsChokedByUs( peer ) )
561                ++s->peersUploading;
562            if( tr_peerIsInteresting( peer ) && !tr_peerIsChokingUs( peer ) )
563                ++s->peersDownloading;
564        }
565    }
566
567    s->percentDone = tr_cpPercentDone( tor->completion );
568    s->percentComplete = tr_cpPercentComplete( tor->completion );
569    s->left     = tr_cpLeftUntilDone( tor->completion );
570
571
572    if( tor->recheckFlag )
573        s->status = TR_STATUS_CHECK_WAIT;
574    else switch( tor->runStatus ) {
575        case TR_RUN_STOPPING: /* fallthrough */
576        case TR_RUN_STOPPING_NET_WAIT: s->status = TR_STATUS_STOPPING; break;
577        case TR_RUN_STOPPED: s->status = TR_STATUS_STOPPED; break;
578        case TR_RUN_CHECKING: s->status = TR_STATUS_CHECK; break;
579        case TR_RUN_RUNNING: switch( tor->cpStatus ) {
580            case TR_CP_INCOMPLETE: s->status = TR_STATUS_DOWNLOAD; break;
581            case TR_CP_DONE: s->status = TR_STATUS_DONE; break;
582            case TR_CP_COMPLETE: s->status = TR_STATUS_SEED; break;
583        }
584    }
585
586    s->cpStatus = tor->cpStatus;
587
588    /* tr_rcRate() doesn't make the difference between 'piece'
589       messages and other messages, which causes a non-zero
590       download rate even tough we are not downloading. So we
591       force it to zero not to confuse the user. */
592    s->rateDownload = tor->runStatus==TR_RUN_RUNNING
593        ? tr_rcRate( tor->download )
594        : 0.0;
595    s->rateUpload = tr_rcRate( tor->upload );
596   
597    s->seeders  = tr_trackerSeeders( tc );
598    s->leechers = tr_trackerLeechers( tc );
599    s->completedFromTracker = tr_trackerDownloaded( tc );
600
601    s->swarmspeed = tr_rcRate( tor->swarmspeed );
602   
603    s->startDate = tor->startDate;
604    s->activityDate = tor->activityDate;
605
606    s->eta = s->rateDownload < 0.1
607        ? -1.0f
608        : (s->left / s->rateDownload / 1024.0);
609
610    s->uploaded        = tor->uploadedCur   + tor->uploadedPrev;
611    s->downloaded      = tor->downloadedCur + tor->downloadedPrev;
612    s->downloadedValid = tr_cpDownloadedValid( tor->completion );
613   
614    s->ratio = s->downloaded || s->downloadedValid
615      ? (float)s->uploaded / (float)MAX(s->downloaded, s->downloadedValid)
616      : TR_RATIO_NA; 
617   
618    tr_torrentReaderUnlock( tor );
619
620    return s;
621}
622
623tr_peer_stat_t *
624tr_torrentPeers( const tr_torrent_t * tor, int * peerCount )
625{
626    tr_peer_stat_t * peers;
627
628    tr_torrentReaderLock( tor );
629
630    *peerCount = tor->peerCount;
631   
632    peers = tr_new0( tr_peer_stat_t, tor->peerCount ); 
633    if (peers != NULL)
634    {
635        tr_peer_t * peer;
636        struct in_addr * addr;
637        int i;
638        for( i=0; i<tor->peerCount; ++i )
639        {
640            peer = tor->peers[i];
641           
642            addr = tr_peerAddress( peer );
643            if( NULL != addr )
644            {
645                tr_netNtop( addr, peers[i].addr,
646                           sizeof( peers[i].addr ) );
647            }
648           
649            peers[i].client           =  tr_peerClient( peer );
650            peers[i].isConnected      =  tr_peerIsConnected( peer );
651            peers[i].from             =  tr_peerIsFrom( peer );
652            peers[i].progress         =  tr_peerProgress( peer );
653            peers[i].port             =  tr_peerPort( peer );
654            peers[i].isDownloading    = !tr_peerIsChokingUs( peer );
655            peers[i].uploadToRate     =  tr_peerUploadRate( peer );
656            peers[i].isUploading      = !tr_peerIsChokedByUs( peer );
657            peers[i].downloadFromRate =  tr_peerDownloadRate( peer );
658        }
659    }
660   
661    tr_torrentReaderUnlock( tor );
662   
663    return peers;
664}
665
666void tr_torrentPeersFree( tr_peer_stat_t * peers, int peerCount UNUSED )
667{
668    tr_free( peers );
669}
670
671void tr_torrentAvailability( const tr_torrent_t * tor, int8_t * tab, int size )
672{
673    int i, j, piece;
674    float interval;
675
676    tr_torrentReaderLock( tor );
677
678    interval = (float)tor->info.pieceCount / (float)size;
679    for( i = 0; i < size; i++ )
680    {
681        piece = i * interval;
682
683        if( tr_cpPieceIsComplete( tor->completion, piece ) )
684        {
685            tab[i] = -1;
686            continue;
687        }
688
689        tab[i] = 0;
690        for( j = 0; j < tor->peerCount; j++ )
691        {
692            if( tr_peerHasPiece( tor->peers[j], piece ) )
693            {
694                (tab[i])++;
695            }
696        }
697    }
698
699    tr_torrentReaderUnlock( tor );
700}
701
702uint64_t
703tr_torrentFileBytesCompleted ( const tr_torrent_t * tor, int fileIndex )
704{
705    const tr_file_t * file     =  &tor->info.files[fileIndex];
706    const uint64_t firstBlock       =  file->offset / tor->blockSize;
707    const uint64_t firstBlockOffset =  file->offset % tor->blockSize;
708    const uint64_t lastOffset       =  file->length ? (file->length-1) : 0;
709    const uint64_t lastBlock        = (file->offset + lastOffset) / tor->blockSize;
710    const uint64_t lastBlockOffset  = (file->offset + lastOffset) % tor->blockSize;
711    uint64_t haveBytes = 0;
712
713    assert( tor != NULL );
714    assert( 0<=fileIndex && fileIndex<tor->info.fileCount );
715    assert( file->offset + file->length <= tor->info.totalSize );
716    assert( (int)firstBlock < tor->blockCount );
717    assert( (int)lastBlock < tor->blockCount );
718    assert( firstBlock <= lastBlock );
719    assert( tr_blockPiece( firstBlock ) == file->firstPiece );
720    assert( tr_blockPiece( lastBlock ) == file->lastPiece );
721
722    if( firstBlock == lastBlock )
723    {
724        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
725            haveBytes += lastBlockOffset + 1 - firstBlockOffset;
726    }
727    else
728    {
729        uint64_t i;
730
731        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
732            haveBytes += tor->blockSize - firstBlockOffset;
733
734        for( i=firstBlock+1; i<lastBlock; ++i )
735            if( tr_cpBlockIsComplete( tor->completion, i ) )
736               haveBytes += tor->blockSize;
737
738        if( tr_cpBlockIsComplete( tor->completion, lastBlock ) )
739            haveBytes += lastBlockOffset + 1;
740    }
741
742    return haveBytes;
743}
744
745float
746tr_torrentFileCompletion ( const tr_torrent_t * tor, int fileIndex )
747{
748    const uint64_t c = tr_torrentFileBytesCompleted ( tor, fileIndex );
749    uint64_t length = tor->info.files[fileIndex].length;
750   
751    if( !length )
752        return 1.0;
753    return (double)c / length;
754}
755
756float*
757tr_torrentCompletion( const tr_torrent_t * tor )
758{
759    int i;
760    float * f;
761    tr_torrentReaderLock( tor );
762
763    f = tr_new0( float, tor->info.fileCount );
764    for( i=0; i<tor->info.fileCount; ++i )
765       f[i] = tr_torrentFileCompletion ( tor, i );
766
767    tr_torrentReaderUnlock( tor );
768    return f;
769}
770
771void tr_torrentAmountFinished( const tr_torrent_t * tor, float * tab, int size )
772{
773    int i;
774    float interval;
775    tr_torrentReaderLock( tor );
776
777    interval = (float)tor->info.pieceCount / (float)size;
778    for( i = 0; i < size; i++ )
779    {
780        int piece = i * interval;
781        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
782    }
783
784    tr_torrentReaderUnlock( tor );
785}
786
787void
788tr_torrentResetTransferStats( tr_torrent_t * tor )
789{
790    tr_torrentWriterLock( tor );
791
792    tor->downloadedPrev += tor->downloadedCur;
793    tor->downloadedCur   = 0;
794    tor->uploadedPrev   += tor->uploadedCur;
795    tor->uploadedCur     = 0;
796
797    tr_torrentWriterUnlock( tor );
798}
799
800
801void
802tr_torrentSetHasPiece( tr_torrent_t * tor, int pieceIndex, int has )
803{
804    tr_torrentWriterLock( tor );
805
806    if( has )
807        tr_cpPieceAdd( tor->completion, pieceIndex );
808    else
809        tr_cpPieceRem( tor->completion, pieceIndex );
810
811    tr_torrentWriterUnlock( tor );
812}
813
814void tr_torrentRemoveSaved( tr_torrent_t * tor )
815{
816    tr_metainfoRemoveSaved( tor->info.hashString, tor->handle->tag );
817}
818
819void tr_torrentRecheck( tr_torrent_t * tor )
820{
821    tor->recheckFlag = TRUE;
822}
823
824
825int tr_torrentAttachPeer( tr_torrent_t * tor, tr_peer_t * peer )
826{
827    int i;
828    tr_peer_t * otherPeer;
829
830    assert( tor != NULL );
831    assert( peer != NULL );
832
833    if( tor->peerCount >= TR_MAX_PEER_COUNT )
834    {
835        tr_peerDestroy(  peer );
836        return 0;
837    }
838
839    /* Don't accept two connections from the same IP */
840    for( i = 0; i < tor->peerCount; i++ )
841    {
842        otherPeer = tor->peers[i];
843        if( !memcmp( tr_peerAddress( peer ), tr_peerAddress( otherPeer ), 4 ) )
844        {
845            tr_peerDestroy(  peer );
846            return 0;
847        }
848    }
849
850    tr_peerSetPrivate( peer, tor->info.flags & TR_FLAG_PRIVATE ||
851                       tor->pexDisabled );
852    tr_peerSetTorrent( peer, tor );
853    tor->peers[tor->peerCount++] = peer;
854
855    return 1;
856}
857
858int tr_torrentAddCompact( tr_torrent_t * tor, int from,
859                           uint8_t * buf, int count )
860{
861    struct in_addr addr;
862    in_port_t port;
863    int i, added;
864    tr_peer_t * peer;
865
866    added = 0;
867    for( i = 0; i < count; i++ )
868    {
869        memcpy( &addr, buf, 4 ); buf += 4;
870        memcpy( &port, buf, 2 ); buf += 2;
871
872        peer = tr_peerInit( &addr, port, -1, from );
873        added += tr_torrentAttachPeer( tor, peer );
874    }
875
876    return added;
877}
878
879/***
880****
881***/
882
883static void setRunState( tr_torrent_t * tor, run_status_t run )
884{
885    tr_torrentWriterLock( tor );
886    tor->runStatus = run;
887    tr_torrentWriterUnlock( tor );
888}
889
890void tr_torrentStart( tr_torrent_t * tor )
891{
892    setRunState( tor, TR_RUN_RUNNING );
893}
894
895void tr_torrentStop( tr_torrent_t * tor )
896{
897    setRunState( tor, TR_RUN_STOPPING );
898}
899
900void tr_torrentClose( tr_torrent_t * tor )
901{
902    tr_torrentStop( tor );
903    tor->dieFlag = TRUE;
904}
905
906static void
907tr_torrentFree( tr_torrent_t * tor )
908{
909    tr_torrent_t * t;
910    tr_handle_t * h = tor->handle;
911    tr_info_t * inf = &tor->info;
912
913    tr_sharedLock( h->shared );
914
915    tr_rwClose( &tor->lock );
916    tr_cpClose( tor->completion );
917
918    tr_rcClose( tor->upload );
919    tr_rcClose( tor->download );
920    tr_rcClose( tor->swarmspeed );
921
922    tr_free( tor->destination );
923
924    tr_metainfoFree( inf );
925
926    if( tor == h->torrentList )
927        h->torrentList = tor->next;
928    else for( t=h->torrentList; t!=NULL; t=t->next ) {
929        if( t->next == tor ) {
930            t->next = tor->next;
931            break;
932        }
933    }
934
935    tr_free( tor );
936
937    h->torrentCount--;
938
939    tr_sharedUnlock( h->shared );
940}
941
942static void
943torrentThreadLoop ( void * _tor )
944{
945    static tr_lock_t checkFilesLock;
946    static int checkFilesLockInited = FALSE;
947    tr_torrent_t * tor = _tor;
948
949    /* create the check-files mutex */
950    if( !checkFilesLockInited ) {
951         checkFilesLockInited = TRUE;
952         tr_lockInit( &checkFilesLock );
953    }
954
955    /* loop until the torrent is being deleted */
956    while( ! ( tor->dieFlag && (tor->runStatus == TR_RUN_STOPPED) ) )
957    {
958        cp_status_t cpStatus;
959
960        /* sleep a little while */
961        tr_wait( tor->runStatus == TR_RUN_STOPPED ? 1600 : 600 );
962
963        /* if we're stopping... */
964        if( tor->runStatus == TR_RUN_STOPPING )
965        {
966            int i;
967            int peerCount;
968            uint8_t * peerCompact;
969            tr_torrentWriterLock( tor );
970
971            /* close the IO */
972            tr_ioClose( tor->io );
973            tor->io = NULL;
974
975            /* close the peers */
976            for( i=0; i<tor->peerCount; ++i )
977                tr_peerDestroy( tor->peers[i] );
978            tor->peerCount = 0;
979
980            /* resest the transfer rates */
981            tr_rcReset( tor->download );
982            tr_rcReset( tor->upload );
983            tr_rcReset( tor->swarmspeed );
984
985            /* tell the tracker we're stopping */
986            tr_trackerStopped( tor->tracker );
987            tr_trackerPulse( tor->tracker, &peerCount, &peerCompact );
988            tor->runStatus = TR_RUN_STOPPING_NET_WAIT;
989            tor->stopDate = tr_date();
990            tr_torrentWriterUnlock( tor );
991        }
992
993        if( tor->runStatus == TR_RUN_STOPPING_NET_WAIT )
994        {
995            uint64_t date;
996            int peerCount;
997            uint8_t * peerCompact;
998            tr_trackerPulse( tor->tracker, &peerCount, &peerCompact );
999
1000            /* have we finished telling the tracker that we're stopping? */
1001            date = tr_trackerLastResponseDate( tor->tracker );
1002            if( date > tor->stopDate )
1003            {
1004                tr_torrentWriterLock( tor );
1005                tr_trackerClose( tor->tracker );
1006                tor->tracker = NULL;
1007                tor->runStatus = TR_RUN_STOPPED;
1008                tr_torrentWriterUnlock( tor );
1009            }
1010            continue;
1011        }
1012
1013        /* do we need to check files? */
1014        if( tor->recheckFlag )
1015        {
1016            if( !tr_lockTryLock( &checkFilesLock ) )
1017            {
1018                run_status_t realStatus;
1019
1020                tr_torrentWriterLock( tor );
1021                realStatus = tor->runStatus;
1022                tor->recheckFlag = FALSE;
1023                tor->runStatus = TR_RUN_CHECKING;
1024                tr_torrentWriterUnlock( tor );
1025
1026                tr_ioCheckFiles( tor, TR_RECHECK_FORCE );
1027                setRunState( tor, realStatus );
1028
1029                tr_lockUnlock( &checkFilesLock );
1030            }
1031            continue;
1032        }
1033
1034        /* if we're paused or stopped, not much to do... */
1035        if( tor->runStatus == TR_RUN_STOPPED )
1036            continue;
1037
1038        /* ping our peers if we're running... */
1039        if( tor->runStatus == TR_RUN_RUNNING )
1040        {
1041            int i;
1042            int peerCount;
1043            uint8_t * peerCompact;
1044
1045            /* starting to run... */
1046            if( tor->io == NULL ) {
1047                *tor->errorString = '\0';
1048                tr_torrentResetTransferStats( tor );
1049                tor->io = tr_ioInitFast( tor );
1050                if( tor->io == NULL ) {
1051                    tor->recheckFlag = TRUE;
1052                    continue;
1053                }
1054                tor->tracker = tr_trackerInit( tor );
1055                tor->startDate = tr_date();
1056            }
1057
1058            /* refresh our completion state */
1059            tr_torrentWriterLock( tor );
1060            cpStatus = tr_cpGetStatus( tor->completion );
1061            if( cpStatus != tor->cpStatus ) {
1062                tor->cpStatus = cpStatus;
1063                if( (cpStatus == TR_CP_COMPLETE)        /* if we're complete */
1064                    && tor->tracker!=NULL           /* and we have a tracker */
1065                    && tor->downloadedCur ) {        /* and it just happened */
1066                    tr_trackerCompleted( tor->tracker ); /* tell the tracker */
1067                    tor->hasChangedState = tor->cpStatus;  /* and the client */
1068                }
1069                tr_ioSync( tor->io );
1070            }
1071            tr_torrentWriterUnlock( tor );
1072
1073            /* ping the tracker... */
1074            tr_trackerPulse( tor->tracker, &peerCount, &peerCompact );
1075            if( peerCount > 0 ) {
1076                int used = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
1077                                                 peerCompact, peerCount );
1078                tr_dbg( "got %i peers from announce, used %i", peerCount, used );
1079                free( peerCompact );
1080            }
1081
1082            /* Shuffle peers */
1083            if ( tor->peerCount > 1 ) {
1084                tr_peer_t * tmp = tor->peers[0];
1085                memmove( tor->peers, tor->peers+1,
1086                        (tor->peerCount-1) * sizeof(void*) );
1087                tor->peers[tor->peerCount - 1] = tmp;
1088            }
1089
1090            /* receive/send messages */
1091            tr_torrentWriterLock( tor );
1092            for( i=0; i<tor->peerCount; ) {
1093                tr_peer_t * peer = tor->peers[i];
1094                int ret = tr_peerPulse( peer );
1095                if( ret & TR_ERROR_IO_MASK ) {
1096                    tr_err( "Fatal error, stopping download (%d)", ret );
1097                    tor->runStatus = TR_RUN_STOPPING;
1098                    tor->error = ret;
1099                    strlcpy( tor->errorString,
1100                             tr_errorString(ret),
1101                             sizeof(tor->errorString) );
1102                    break;
1103                }
1104                if( ret ) {
1105                    tr_peerDestroy( peer );
1106                    tor->peerCount--;
1107                    memmove( &tor->peers[i], &tor->peers[i+1],
1108                             (tor->peerCount-i)*sizeof(void*) );
1109                    continue;
1110                }
1111                i++;
1112            }
1113            tr_torrentWriterUnlock( tor );
1114        }
1115    }
1116
1117    tr_ioClose( tor->io );
1118    tr_torrentFree( tor );
1119}
1120
1121
1122/***
1123****
1124****  File prioritization
1125****
1126***/
1127
1128static void
1129tr_torrentSetFilePriorityImpl( tr_torrent_t   * tor,
1130                               int              fileIndex,
1131                               tr_priority_t    priority,
1132                               int              doSave )
1133{
1134    int i;
1135    tr_file_t * file;
1136
1137    tr_torrentWriterLock( tor );
1138
1139    assert( tor != NULL );
1140    assert( 0<=fileIndex && fileIndex<tor->info.fileCount );
1141    assert( priority==TR_PRI_LOW || priority==TR_PRI_NORMAL || priority==TR_PRI_HIGH );
1142
1143    file = &tor->info.files[fileIndex];
1144    file->priority = priority;
1145    for( i=file->firstPiece; i<=file->lastPiece; ++i )
1146      tor->info.pieces[i].priority = calculatePiecePriority( tor, i );
1147
1148    tr_dbg ( "Setting file #%d (pieces %d-%d) priority to %d (%s)",
1149             fileIndex, file->firstPiece, file->lastPiece,
1150             priority, tor->info.files[fileIndex].name );
1151
1152    if( doSave )
1153        fastResumeSave( tor );
1154
1155    tr_torrentWriterUnlock( tor );
1156}
1157
1158void
1159tr_torrentSetFilePriority( tr_torrent_t   * tor,
1160                           int              fileIndex,
1161                           tr_priority_t    priority )
1162{
1163    tr_torrentSetFilePriorityImpl( tor, fileIndex, priority, TRUE );
1164}
1165
1166void
1167tr_torrentSetFilePriorities( tr_torrent_t        * tor,
1168                             int                 * files,
1169                             int                   fileCount,
1170                             tr_priority_t         priority )
1171{
1172    int i;
1173    for( i=0; i<fileCount; ++i ) {
1174        const int fileIndex = files[i];
1175        tr_torrentSetFilePriorityImpl( tor, fileIndex, priority, FALSE );
1176    }
1177    fastResumeSave( tor );
1178}
1179
1180tr_priority_t
1181tr_torrentGetFilePriority( const tr_torrent_t *  tor, int file )
1182{
1183    tr_priority_t ret;
1184
1185    tr_torrentReaderLock( tor );
1186    assert( tor != NULL );
1187    assert( 0<=file && file<tor->info.fileCount );
1188    ret = tor->info.files[file].priority;
1189    tr_torrentReaderUnlock( tor );
1190
1191    return ret;
1192}
1193
1194
1195tr_priority_t*
1196tr_torrentGetFilePriorities( const tr_torrent_t * tor )
1197{
1198    int i;
1199    tr_priority_t * p;
1200
1201    tr_torrentReaderLock( tor );
1202    p = tr_new0( tr_priority_t, tor->info.fileCount );
1203    for( i=0; i<tor->info.fileCount; ++i )
1204        p[i] = tor->info.files[i].priority;
1205    tr_torrentReaderUnlock( tor );
1206
1207    return p;
1208}
1209
1210int
1211tr_torrentGetFileDL( const tr_torrent_t * tor,
1212                     int                  file )
1213{
1214    int do_download;
1215    tr_torrentReaderLock( tor );
1216
1217    assert( 0<=file && file<tor->info.fileCount );
1218    do_download = !tor->info.files[file].dnd;
1219
1220    tr_torrentReaderUnlock( tor );
1221    return do_download != 0;
1222}
1223
1224void
1225tr_torrentSetFileDL( tr_torrent_t  * tor,
1226                     int             fileIndex,
1227                     int             do_download )
1228{
1229    int i;
1230    tr_file_t * file;
1231    const int dnd = !do_download;
1232
1233    tr_torrentWriterLock( tor );
1234
1235    assert( 0<=fileIndex && fileIndex<tor->info.fileCount );
1236    file = &tor->info.files[fileIndex];
1237    file->dnd = dnd;
1238    for( i=file->firstPiece; i<=file->lastPiece; ++i )
1239      tor->info.pieces[i].dnd = dnd;
1240    fastResumeSave( tor );
1241
1242    tr_torrentWriterUnlock( tor );
1243}
1244
1245void
1246tr_torrentSetFileDLs ( tr_torrent_t   * tor,
1247                       int            * files,
1248                       int              fileCount,
1249                       int              do_download )
1250{
1251    int i, j;
1252    const int dnd = !do_download;
1253
1254    tr_torrentWriterLock( tor );
1255
1256    for( i=0; i<fileCount; ++i ) {
1257        const int fileIndex = files[i];
1258        tr_file_t * file = &tor->info.files[fileIndex];
1259        file->dnd = dnd;
1260        for( j=file->firstPiece; j<=file->lastPiece; ++j )
1261            tor->info.pieces[j].dnd = dnd;
1262    }
1263
1264    fastResumeSave( tor );
1265
1266    tr_torrentWriterUnlock( tor );
1267}
Note: See TracBrowser for help on using the repository browser.