source: trunk/libtransmission/torrent.c @ 2241

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

fix crash reported by persept

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