source: branches/new_api/libtransmission/transmission.c @ 138

Last change on this file since 138 was 138, checked in by titer, 16 years ago

Adds an error feedback for tr_torrentInit.
Adds tr_torrentInfo along with tr_torrentStat.
Removed now unused tr_setFinished.

File size: 19.2 KB
Line 
1/******************************************************************************
2 * Copyright (c) 2005 Eric Petit
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
21 *****************************************************************************/
22
23#include "transmission.h"
24
25/***********************************************************************
26 * Local prototypes
27 **********************************************************************/
28static void torrentReallyStop( tr_torrent_t * );
29static void  downloadLoop( void * );
30static void  acceptLoop( void * );
31static void acceptStop( tr_handle_t * h );
32
33/***********************************************************************
34 * tr_init
35 ***********************************************************************
36 * Allocates a tr_handle_t structure and initializes a few things
37 **********************************************************************/
38tr_handle_t * tr_init()
39{
40    tr_handle_t * h;
41    int           i, r;
42
43    h = calloc( sizeof( tr_handle_t ), 1 );
44
45    /* Generate a peer id : "-TRxxyy-" + 12 random alphanumeric
46       characters, where xx is the major version number and yy the
47       minor version number (Azureus-style) */
48    sprintf( h->id, "-TR%02d%02d-", VERSION_MAJOR, VERSION_MINOR );
49    for( i = 8; i < 20; i++ )
50    {
51        r        = tr_rand( 36 );
52        h->id[i] = ( r < 26 ) ? ( 'a' + r ) : ( '0' + r - 26 ) ;
53    }
54
55    /* Random key */
56    for( i = 0; i < 20; i++ )
57    {
58        r         = tr_rand( 36 );
59        h->key[i] = ( r < 26 ) ? ( 'a' + r ) : ( '0' + r - 26 ) ;
60    }
61
62    /* Don't exit when writing on a broken socket */
63    signal( SIGPIPE, SIG_IGN );
64
65    /* Initialize rate and file descripts controls */
66    h->upload   = tr_rcInit();
67    h->download = tr_rcInit();
68    h->fdlimit  = tr_fdInit();
69    h->choking  = tr_chokingInit( h );
70
71    h->bindPort = -1;
72    h->bindSocket = -1;
73
74    h->acceptDie = 0;
75    tr_lockInit( &h->acceptLock );
76    tr_threadCreate( &h->acceptThread, acceptLoop, h );
77
78    return h;
79}
80
81/***********************************************************************
82 * tr_setBindPort
83 ***********************************************************************
84 *
85 **********************************************************************/
86void tr_setBindPort( tr_handle_t * h, int port )
87{
88    int sock;
89    tr_torrent_t * tor;
90
91    if( h->bindPort == port )
92      return;
93
94#ifndef BEOS_NETSERVER
95    /* BeOS net_server seems to be unable to set incoming connections to
96       non-blocking. Too bad. */
97    if( !tr_fdSocketWillCreate( h->fdlimit, 0 ) )
98    {
99        /* XXX should handle failure here in a better way */
100        sock = tr_netBind( port );
101    }
102#else
103    return;
104#endif
105
106    tr_lockLock( &h->acceptLock );
107
108    h->bindPort = port;
109
110    for( tor = h->torrentList; tor; tor = tor->next )
111    {
112        tr_lockLock( &tor->lock );
113        if( NULL != tor->tracker )
114        {
115            tr_trackerChangePort( tor->tracker, port );
116        }
117        tr_lockUnlock( &tor->lock );
118    }
119
120    if( h->bindSocket > -1 )
121    {
122        tr_netClose( h->bindSocket );
123        tr_fdSocketClosed( h->fdlimit, 0 );
124    }
125
126    h->bindSocket = sock;
127
128    tr_lockUnlock( &h->acceptLock );
129}
130
131/***********************************************************************
132 * tr_setUploadLimit
133 ***********************************************************************
134 *
135 **********************************************************************/
136void tr_setUploadLimit( tr_handle_t * h, int limit )
137{
138    tr_rcSetLimit( h->upload, limit );
139    tr_chokingSetLimit( h->choking, limit );
140}
141
142/***********************************************************************
143 * tr_torrentRates
144 ***********************************************************************
145 *
146 **********************************************************************/
147void tr_torrentRates( tr_handle_t * h, float * dl, float * ul )
148{
149    tr_torrent_t * tor;
150
151    *dl = 0.0;
152    *ul = 0.0;
153    for( tor = h->torrentList; tor; tor = tor->next )
154    {
155        tr_lockLock( &tor->lock );
156        if( tor->status & TR_STATUS_DOWNLOAD )
157            *dl += tr_rcRate( tor->download );
158        *ul += tr_rcRate( tor->upload );
159        tr_lockUnlock( &tor->lock );
160    }
161}
162
163/***********************************************************************
164 * tr_torrentInit
165 ***********************************************************************
166 * Allocates a tr_torrent_t structure, then relies on tr_metainfoParse
167 * to fill it.
168 **********************************************************************/
169tr_torrent_t * tr_torrentInit( tr_handle_t * h, const char * path,
170                               int * error )
171{
172    tr_torrent_t  * tor, * tor_tmp;
173    tr_info_t     * inf;
174    int             i;
175    char          * s1, * s2;
176
177    tor = calloc( sizeof( tr_torrent_t ), 1 );
178    inf = &tor->info;
179
180    /* Parse torrent file */
181    if( tr_metainfoParse( inf, path ) )
182    {
183        *error = TR_EINVALID;
184        free( tor );
185        return NULL;
186    }
187
188    /* Make sure this torrent is not already open */
189    for( tor_tmp = h->torrentList; tor_tmp; tor_tmp = tor_tmp->next )
190    {
191        if( !memcmp( tor->info.hash, tor_tmp->info.hash,
192                     SHA_DIGEST_LENGTH ) )
193        {
194            *error = TR_EDUPLICATE;
195            free( tor );
196            return NULL;
197        }
198    }
199
200    tor->status = TR_STATUS_PAUSE;
201    tor->id     = h->id;
202    tor->key    = h->key;
203        tor->finished = 0;
204
205
206    /* Guess scrape URL */
207    s1 = strchr( inf->trackerAnnounce, '/' );
208    while( ( s2 = strchr( s1 + 1, '/' ) ) )
209    {
210        s1 = s2;
211    }
212    s1++;
213    if( !strncmp( s1, "announce", 8 ) )
214    {
215        int pre  = (long) s1 - (long) inf->trackerAnnounce;
216        int post = strlen( inf->trackerAnnounce ) - pre - 8;
217        memcpy( tor->scrape, inf->trackerAnnounce, pre );
218        sprintf( &tor->scrape[pre], "scrape" );
219        memcpy( &tor->scrape[pre+6], &inf->trackerAnnounce[pre+8], post );
220    }
221
222    /* Escaped info hash for HTTP queries */
223    for( i = 0; i < SHA_DIGEST_LENGTH; i++ )
224    {
225        sprintf( &tor->hashString[3*i], "%%%02x", inf->hash[i] );
226    }
227
228    /* Block size: usually 16 ko, or less if we have to */
229    tor->blockSize  = MIN( inf->pieceSize, 1 << 14 );
230    tor->blockCount = ( inf->totalSize + tor->blockSize - 1 ) /
231                        tor->blockSize;
232    tor->completion = tr_cpInit( tor );
233
234    tr_lockInit( &tor->lock );
235
236    tor->globalUpload   = h->upload;
237    tor->globalDownload = h->download;
238    tor->fdlimit        = h->fdlimit;
239    tor->upload         = tr_rcInit();
240    tor->download       = tr_rcInit();
241 
242    /* We have a new torrent */
243    tr_lockLock( &h->acceptLock );
244    tor->prev = NULL;
245    tor->next = h->torrentList;
246    if( tor->next )
247    {
248        tor->next->prev = tor;
249    }
250    h->torrentList = tor;
251    (h->torrentCount)++;
252    tr_lockUnlock( &h->acceptLock );
253
254    return tor;
255}
256
257tr_info_t * tr_torrentInfo( tr_torrent_t * tor )
258{
259    return &tor->info;
260}
261
262/***********************************************************************
263 * tr_torrentScrape
264 **********************************************************************/
265int tr_torrentScrape( tr_torrent_t * tor, int * s, int * l )
266{
267    return tr_trackerScrape( tor, s, l );
268}
269
270void tr_torrentSetFolder( tr_torrent_t * tor, const char * path )
271{
272    tor->destination = strdup( path );
273}
274
275char * tr_torrentGetFolder( tr_torrent_t * tor )
276{
277    return tor->destination;
278}
279
280void tr_torrentStart( tr_torrent_t * tor )
281{
282    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
283    {
284        /* Join the thread first */
285        torrentReallyStop( tor );
286    }
287
288    tor->status  = TR_STATUS_CHECK;
289    tor->tracker = tr_trackerInit( tor );
290
291    tor->date = tr_date();
292    tor->die = 0;
293    tr_threadCreate( &tor->thread, downloadLoop, tor );
294}
295
296void tr_torrentStop( tr_torrent_t * tor )
297{
298    tr_lockLock( &tor->lock );
299    tr_trackerStopped( tor->tracker );
300    tr_rcReset( tor->download );
301    tr_rcReset( tor->upload );
302    tor->status = TR_STATUS_STOPPING;
303    tor->stopDate = tr_date();
304    tr_lockUnlock( &tor->lock );
305}
306
307/***********************************************************************
308 * torrentReallyStop
309 ***********************************************************************
310 * Joins the download thread and frees/closes everything related to it.
311 **********************************************************************/
312static void torrentReallyStop( tr_torrent_t * tor )
313{
314    tor->die = 1;
315    tr_threadJoin( &tor->thread );
316    tr_dbg( "Thread joined" );
317
318    tr_trackerClose( tor->tracker );
319
320    while( tor->peerCount > 0 )
321    {
322        tr_peerRem( tor, 0 );
323    }
324}
325
326/***********************************************************************
327 * tr_torrentCount
328 ***********************************************************************
329 *
330 **********************************************************************/
331int tr_torrentCount( tr_handle_t * h )
332{
333    return h->torrentCount;
334}
335
336int tr_getFinished( tr_torrent_t * tor )
337{
338    if( tor->finished )
339    {
340        tor->finished = 0;
341        return 1;
342    }
343    return 0;
344}
345
346tr_stat_t * tr_torrentStat( tr_torrent_t * tor )
347{
348    tr_stat_t * s;
349    tr_info_t * inf = &tor->info;
350    int i, j, piece;
351
352    tor->statCur = ( tor->statCur + 1 ) % 2;
353    s = &tor->stats[tor->statCur];
354
355    if( ( tor->status & TR_STATUS_STOPPED ) ||
356        ( ( tor->status & TR_STATUS_STOPPING ) &&
357          tr_date() > tor->stopDate + 60000 ) )
358    {
359        torrentReallyStop( tor );
360        tor->status = TR_STATUS_PAUSE;
361    }
362
363    tr_lockLock( &tor->lock );
364
365    s->status = tor->status;
366    memcpy( s->error, tor->error, sizeof( s->error ) );
367
368    s->peersTotal       = 0;
369    s->peersUploading   = 0;
370    s->peersDownloading = 0;
371
372    for( i = 0; i < tor->peerCount; i++ )
373    {
374        if( tr_peerIsConnected( tor->peers[i] ) )
375        {
376            (s->peersTotal)++;
377            if( tr_peerIsUploading( tor->peers[i] ) )
378            {
379                (s->peersUploading)++;
380            }
381            if( tr_peerIsDownloading( tor->peers[i] ) )
382            {
383                (s->peersDownloading)++;
384            }
385        }
386    }
387
388    s->progress = tr_cpCompletionAsFloat( tor->completion );
389    if( tor->status & TR_STATUS_DOWNLOAD )
390        s->rateDownload = tr_rcRate( tor->download );
391    else
392        /* tr_rcRate() doesn't make the difference between 'piece'
393           messages and other messages, which causes a non-zero
394           download rate even tough we are not downloading. So we
395           force it to zero not to confuse the user. */
396        s->rateDownload = 0.0;
397    s->rateUpload = tr_rcRate( tor->upload );
398   
399    s->seeders    = tr_trackerSeeders(tor);
400        s->leechers       = tr_trackerLeechers(tor);
401
402    if( s->rateDownload < 0.1 )
403    {
404        s->eta = -1;
405    }
406    else
407    {
408        s->eta = (float) ( 1.0 - s->progress ) *
409            (float) inf->totalSize / s->rateDownload / 1024.0;
410        if( s->eta > 99 * 3600 + 59 * 60 + 59 )
411        {
412            s->eta = -1;
413        }
414    }
415
416    for( i = 0; i < 120; i++ )
417    {
418        piece = i * inf->pieceCount / 120;
419
420        if( tr_cpPieceIsComplete( tor->completion, piece ) )
421        {
422            s->pieces[i] = -1;
423            continue;
424        }
425
426        s->pieces[i] = 0;
427       
428        for( j = 0; j < tor->peerCount; j++ )
429        {
430            if( tr_peerBitfield( tor->peers[j] ) &&
431                tr_bitfieldHas( tr_peerBitfield( tor->peers[j] ), piece ) )
432            {
433                (s->pieces[i])++;
434            }
435        }
436    }
437
438    s->downloaded = tor->downloaded;
439    s->uploaded   = tor->uploaded;
440
441    s->folder = tor->destination;
442
443    tr_lockUnlock( &tor->lock );
444
445    return s;
446}
447
448/***********************************************************************
449 * tr_torrentClose
450 ***********************************************************************
451 * Frees memory allocated by tr_torrentInit.
452 **********************************************************************/
453void tr_torrentClose( tr_handle_t * h, tr_torrent_t * tor )
454{
455    tr_info_t * inf = &tor->info;
456
457    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
458    {
459        /* Join the thread first */
460        torrentReallyStop( tor );
461    }
462
463    tr_lockLock( &h->acceptLock );
464
465    h->torrentCount--;
466
467    tr_lockClose( &tor->lock );
468    tr_cpClose( tor->completion );
469
470    tr_rcClose( tor->upload );
471    tr_rcClose( tor->download );
472
473    if( tor->destination )
474    {
475        free( tor->destination );
476    }
477    free( inf->pieces );
478    free( inf->files );
479
480    if( tor->prev )
481    {
482        tor->prev->next = tor->next;
483    }
484    if( tor->next )
485    {
486        tor->next->prev = tor->prev;
487    }
488    free( tor );
489
490    tr_lockUnlock( &h->acceptLock );
491}
492
493void tr_close( tr_handle_t * h )
494{
495    acceptStop( h );
496    tr_chokingClose( h->choking );
497    tr_fdClose( h->fdlimit );
498    tr_rcClose( h->upload );
499    tr_rcClose( h->download );
500    free( h );
501}
502
503/***********************************************************************
504 * downloadLoop
505 **********************************************************************/
506static void downloadLoop( void * _tor )
507{
508    tr_torrent_t * tor = _tor;
509    uint64_t       date1, date2;
510
511    tr_dbg( "Thread started" );
512
513#ifdef SYS_BEOS
514    /* This is required because on BeOS, SIGINT is sent to each thread,
515       which kills them not nicely */
516    signal( SIGINT, SIG_IGN );
517#endif
518
519    tr_lockLock( &tor->lock );
520
521    tr_cpReset( tor->completion );
522    tor->io     = tr_ioInit( tor );
523    tor->status = tr_cpIsSeeding( tor->completion ) ?
524                      TR_STATUS_SEED : TR_STATUS_DOWNLOAD;
525
526    while( !tor->die )
527    {
528        date1 = tr_date();
529
530        /* Are we finished ? */
531        if( ( tor->status & TR_STATUS_DOWNLOAD ) &&
532            tr_cpIsSeeding( tor->completion ) )
533        {
534            /* Done */
535            tor->status = TR_STATUS_SEED;
536                        tor->finished = 1;
537            tr_trackerCompleted( tor->tracker );
538            tr_ioSaveResume( tor->io );
539        }
540
541        /* Receive/send messages */
542        tr_peerPulse( tor );
543
544        /* Try to get new peers or to send a message to the tracker */
545        tr_trackerPulse( tor->tracker );
546
547        if( tor->status & TR_STATUS_STOPPED )
548        {
549            break;
550        }
551
552        /* Wait up to 20 ms */
553        date2 = tr_date();
554        if( date2 < date1 + 20 )
555        {
556            tr_lockUnlock( &tor->lock );
557            tr_wait( date1 + 20 - date2 );
558            tr_lockLock( &tor->lock );
559        }
560    }
561
562    tr_lockUnlock( &tor->lock );
563
564    tr_ioClose( tor->io );
565
566    tor->status = TR_STATUS_STOPPED;
567
568    tr_dbg( "Thread exited" );
569}
570
571/***********************************************************************
572 * acceptLoop
573 **********************************************************************/
574static void acceptLoop( void * _h )
575{
576    tr_handle_t * h = _h;
577    uint64_t      date1, date2, lastchoke = 0;
578    int           ii;
579    uint8_t     * hash;
580    tr_torrent_t * tor;
581
582    tr_dbg( "Accept thread started" );
583
584#ifdef SYS_BEOS
585    /* This is required because on BeOS, SIGINT is sent to each thread,
586       which kills them not nicely */
587    signal( SIGINT, SIG_IGN );
588#endif
589
590    tr_lockLock( &h->acceptLock );
591
592    while( !h->acceptDie )
593    {
594        date1 = tr_date();
595
596        /* Check for incoming connections */
597        if( h->bindSocket > -1 &&
598            h->acceptPeerCount < TR_MAX_PEER_COUNT &&
599            !tr_fdSocketWillCreate( h->fdlimit, 0 ) )
600        {
601            int            s;
602            struct in_addr addr;
603            in_port_t      port;
604            s = tr_netAccept( h->bindSocket, &addr, &port );
605            if( s > -1 )
606            {
607                h->acceptPeers[h->acceptPeerCount++] = tr_peerInit( addr, port, s );
608            }
609            else
610            {
611                tr_fdSocketClosed( h->fdlimit, 0 );
612            }
613        }
614
615        for( ii = 0; ii < h->acceptPeerCount; )
616        {
617            if( tr_peerRead( NULL, h->acceptPeers[ii] ) )
618            {
619                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
620                goto removePeer;
621            }
622            if( NULL != ( hash = tr_peerHash( h->acceptPeers[ii] ) ) )
623            {
624                for( tor = h->torrentList; tor; tor = tor->next )
625                {
626                    tr_lockLock( &tor->lock );
627                    if( 0 == memcmp( tor->info.hash, hash,
628                                     SHA_DIGEST_LENGTH ) )
629                    {
630                      tr_peerAttach( tor, h->acceptPeers[ii] );
631                      tr_lockUnlock( &tor->lock );
632                      goto removePeer;
633                    }
634                    tr_lockUnlock( &tor->lock );
635                }
636                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
637                goto removePeer;
638            }
639            if( date1 > tr_peerDate( h->acceptPeers[ii] ) + 10000 )
640            {
641                /* Give them 10 seconds to send the handshake */
642                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
643                goto removePeer;
644            }
645            ii++;
646            continue;
647           removePeer:
648            h->acceptPeerCount--;
649            memmove( &h->acceptPeers[ii], &h->acceptPeers[ii+1],
650                     ( h->acceptPeerCount - ii ) * sizeof( tr_peer_t * ) );
651        }
652
653        if( date1 > lastchoke + 2000 )
654        {
655            tr_chokingPulse( h->choking );
656            lastchoke = date1;
657        }
658
659        /* Wait up to 20 ms */
660        date2 = tr_date();
661        if( date2 < date1 + 20 )
662        {
663            tr_lockUnlock( &h->acceptLock );
664            tr_wait( date1 + 20 - date2 );
665            tr_lockLock( &h->acceptLock );
666        }
667    }
668
669    tr_lockUnlock( &h->acceptLock );
670
671    tr_dbg( "Accept thread exited" );
672}
673
674/***********************************************************************
675 * acceptStop
676 ***********************************************************************
677 * Joins the accept thread and frees/closes everything related to it.
678 **********************************************************************/
679static void acceptStop( tr_handle_t * h )
680{
681    int ii;
682
683    h->acceptDie = 1;
684    tr_threadJoin( &h->acceptThread );
685    tr_lockClose( &h->acceptLock );
686    tr_dbg( "Accept thread joined" );
687
688    for( ii = 0; ii < h->acceptPeerCount; ii++ )
689    {
690        tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
691    }
692
693    if( h->bindSocket > -1 )
694    {
695        tr_netClose( h->bindSocket );
696        tr_fdSocketClosed( h->fdlimit, 0 );
697    }
698}
Note: See TracBrowser for help on using the repository browser.