source: trunk/libtransmission/transmission.c @ 61

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

Removed now unused tables and some now unused code

File size: 19.3 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_handle_t * h, int 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
70    h->bindPort = TR_DEFAULT_PORT;
71    h->bindSocket = -1;
72
73#ifndef BEOS_NETSERVER
74    /* BeOS net_server seems to be unable to set incoming connections to
75       non-blocking. Too bad. */
76    if( !tr_fdSocketWillCreate( h->fdlimit, 0 ) )
77    {
78        /* XXX should handle failure here in a better way */
79        h->bindSocket = tr_netBind( h->bindPort );
80    }
81#endif
82
83
84    h->acceptDie = 0;
85    tr_lockInit( &h->acceptLock );
86    tr_threadCreate( &h->acceptThread, acceptLoop, h );
87
88    return h;
89}
90
91/***********************************************************************
92 * tr_setBindPort
93 ***********************************************************************
94 *
95 **********************************************************************/
96void tr_setBindPort( tr_handle_t * h, int port )
97{
98    int ii, sock;
99
100    if( h->bindPort == port )
101      return;
102
103#ifndef BEOS_NETSERVER
104    /* BeOS net_server seems to be unable to set incoming connections to
105       non-blocking. Too bad. */
106    if( !tr_fdSocketWillCreate( h->fdlimit, 0 ) )
107    {
108        /* XXX should handle failure here in a better way */
109        sock = tr_netBind( port );
110    }
111#else
112    return;
113#endif
114
115    tr_lockLock( &h->acceptLock );
116
117    h->bindPort = port;
118
119    for( ii = 0; ii < h->torrentCount; ii++ )
120    {
121        tr_lockLock( &h->torrents[ii]->lock );
122        if( NULL != h->torrents[ii]->tracker )
123        {
124            tr_trackerChangePort( h->torrents[ii]->tracker, port );
125        }
126        tr_lockUnlock( &h->torrents[ii]->lock );
127    }
128
129    if( h->bindSocket > -1 )
130    {
131        tr_netClose( h->bindSocket );
132        tr_fdSocketClosed( h->fdlimit, 0 );
133    }
134
135    h->bindSocket = sock;
136
137    tr_lockUnlock( &h->acceptLock );
138}
139
140/***********************************************************************
141 * tr_setUploadLimit
142 ***********************************************************************
143 *
144 **********************************************************************/
145void tr_setUploadLimit( tr_handle_t * h, int limit )
146{
147    tr_rcSetLimit( h->upload, limit );
148}
149
150/***********************************************************************
151 * tr_torrentRates
152 ***********************************************************************
153 *
154 **********************************************************************/
155void tr_torrentRates( tr_handle_t * h, float * dl, float * ul )
156{
157    *dl = tr_rcRate( h->download );
158    *ul = tr_rcRate( h->upload );
159}
160
161/***********************************************************************
162 * tr_torrentInit
163 ***********************************************************************
164 * Allocates a tr_torrent_t structure, then relies on tr_metainfoParse
165 * to fill it.
166 **********************************************************************/
167int tr_torrentInit( tr_handle_t * h, const char * path )
168{
169    tr_torrent_t  * tor;
170    tr_info_t     * inf;
171    int             i;
172    char          * s1, * s2;
173
174    if( h->torrentCount >= TR_MAX_TORRENT_COUNT )
175    {
176        tr_err( "Maximum number of torrents reached" );
177        return 1;
178    }
179
180    tor = calloc( sizeof( tr_torrent_t ), 1 );
181    inf = &tor->info;
182
183    /* Parse torrent file */
184    if( tr_metainfoParse( inf, path ) )
185    {
186        free( tor );
187        return 1;
188    }
189
190    /* Make sure this torrent is not already open */
191    for( i = 0; i < h->torrentCount; i++ )
192    {
193        if( !memcmp( tor->info.hash, h->torrents[i]->info.hash,
194                     SHA_DIGEST_LENGTH ) )
195        {
196            tr_err( "Torrent already open" );
197            free( tor );
198            return 1;
199        }
200    }
201
202    tor->status = TR_STATUS_PAUSE;
203    tor->id     = h->id;
204    tor->key    = h->key;
205        tor->finished = 0;
206
207
208    /* Guess scrape URL */
209    s1 = strchr( inf->trackerAnnounce, '/' );
210    while( ( s2 = strchr( s1 + 1, '/' ) ) )
211    {
212        s1 = s2;
213    }
214    s1++;
215    if( !strncmp( s1, "announce", 8 ) )
216    {
217        int pre  = (long) s1 - (long) inf->trackerAnnounce;
218        int post = strlen( inf->trackerAnnounce ) - pre - 8;
219        memcpy( tor->scrape, inf->trackerAnnounce, pre );
220        sprintf( &tor->scrape[pre], "scrape" );
221        memcpy( &tor->scrape[pre+6], &inf->trackerAnnounce[pre+8], post );
222    }
223
224    /* Escaped info hash for HTTP queries */
225    for( i = 0; i < SHA_DIGEST_LENGTH; i++ )
226    {
227        sprintf( &tor->hashString[3*i], "%%%02x", inf->hash[i] );
228    }
229
230    /* Block size: usually 16 ko, or less if we have to */
231    tor->blockSize  = MIN( inf->pieceSize, 1 << 14 );
232    tor->blockCount = ( inf->totalSize + tor->blockSize - 1 ) /
233                        tor->blockSize;
234    tor->completion = tr_cpInit( tor );
235
236    tr_lockInit( &tor->lock );
237
238    tor->globalUpload   = h->upload;
239    tor->globalDownload = h->download;
240    tor->fdlimit        = h->fdlimit;
241    tor->upload         = tr_rcInit();
242    tor->download       = tr_rcInit();
243 
244    /* We have a new torrent */
245    tr_lockLock( &h->acceptLock );
246    h->torrents[h->torrentCount] = tor;
247    (h->torrentCount)++;
248    tr_lockUnlock( &h->acceptLock );
249
250    return 0;
251}
252
253/***********************************************************************
254 * tr_torrentScrape
255 ***********************************************************************
256 * Allocates a tr_torrent_t structure, then relies on tr_metainfoParse
257 * to fill it.
258 **********************************************************************/
259int tr_torrentScrape( tr_handle_t * h, int t, int * s, int * l )
260{
261    return tr_trackerScrape( h->torrents[t], s, l );
262}
263
264void tr_torrentSetFolder( tr_handle_t * h, int t, const char * path )
265{
266    tr_torrent_t * tor = h->torrents[t];
267
268    tor->destination = strdup( path );
269}
270
271char * tr_torrentGetFolder( tr_handle_t * h, int t )
272{
273    tr_torrent_t * tor = h->torrents[t];
274
275    return tor->destination;
276}
277
278void tr_torrentStart( tr_handle_t * h, int t )
279{
280    tr_torrent_t * tor = h->torrents[t];
281
282    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
283    {
284        /* Join the thread first */
285        torrentReallyStop( h, t );
286    }
287
288    tor->status   = TR_STATUS_CHECK;
289    tor->tracker  = tr_trackerInit( h, tor );
290
291    tor->date = tr_date();
292    tor->die = 0;
293    tr_threadCreate( &tor->thread, downloadLoop, tor );
294}
295
296void tr_torrentStop( tr_handle_t * h, int t )
297{
298    tr_torrent_t * tor = h->torrents[t];
299
300    tr_lockLock( &tor->lock );
301    tr_trackerStopped( tor->tracker );
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_handle_t * h, int t )
313{
314    tr_torrent_t * tor = h->torrents[t];
315
316    tor->die = 1;
317    tr_threadJoin( &tor->thread );
318    tr_dbg( "Thread joined" );
319
320    tr_trackerClose( tor->tracker );
321
322    while( tor->peerCount > 0 )
323    {
324        tr_peerRem( tor, 0 );
325    }
326
327    tor->downloaded = 0;
328    tor->uploaded   = 0;
329}
330
331/***********************************************************************
332 * tr_torrentCount
333 ***********************************************************************
334 *
335 **********************************************************************/
336int tr_torrentCount( tr_handle_t * h )
337{
338    return h->torrentCount;
339}
340
341int tr_getFinished( tr_handle_t * h, int i)
342{
343        return h->torrents[i]->finished;
344}
345void tr_setFinished( tr_handle_t * h, int i, int val)
346{
347        h->torrents[i]->finished = val;
348}
349
350int tr_torrentStat( tr_handle_t * h, tr_stat_t ** stat )
351{
352    tr_stat_t * s;
353    tr_torrent_t * tor;
354    tr_info_t * inf;
355    int i, j, k, piece;
356
357    if( h->torrentCount < 1 )
358    {
359        *stat = NULL;
360        return 0;
361    }
362
363    s = malloc( h->torrentCount * sizeof( tr_stat_t ) );
364
365    for( i = 0; i < h->torrentCount; i++ )
366    {
367        tor = h->torrents[i];
368        inf = &tor->info;
369
370        if( ( tor->status & TR_STATUS_STOPPED ) ||
371            ( ( tor->status & TR_STATUS_STOPPING ) &&
372              tr_date() > tor->stopDate + 60000 ) )
373        {
374            torrentReallyStop( h, i );
375            tor->status = TR_STATUS_PAUSE;
376        }
377
378        tr_lockLock( &tor->lock );
379
380        memcpy( &s[i].info, &tor->info, sizeof( tr_info_t ) );
381        s[i].status = tor->status;
382        memcpy( s[i].error, tor->error, sizeof( s[i].error ) );
383
384        s[i].peersTotal       = 0;
385        s[i].peersUploading   = 0;
386        s[i].peersDownloading = 0;
387
388        for( j = 0; j < tor->peerCount; j++ )
389        {
390            if( tr_peerIsConnected( tor->peers[j] ) )
391            {
392                (s[i].peersTotal)++;
393                if( tr_peerIsUploading( tor->peers[j] ) )
394                {
395                    (s[i].peersUploading)++;
396                }
397                if( tr_peerIsDownloading( tor->peers[j] ) )
398                {
399                    (s[i].peersDownloading)++;
400                }
401            }
402        }
403
404        s[i].progress     = tr_cpCompletionAsFloat( tor->completion );
405        s[i].rateDownload = tr_rcRate( tor->download );
406        s[i].rateUpload   = tr_rcRate( tor->upload );
407       
408        s[i].seeders      = tr_trackerSeeders(tor);
409                s[i].leechers     = tr_trackerLeechers(tor);
410
411        if( s[i].rateDownload < 0.1 )
412        {
413            s[i].eta = -1;
414        }
415        else
416        {
417            s[i].eta = (float) ( 1.0 - s[i].progress ) *
418                (float) inf->totalSize / s[i].rateDownload / 1024.0;
419            if( s[i].eta > 99 * 3600 + 59 * 60 + 59 )
420            {
421                s[i].eta = -1;
422            }
423        }
424
425        for( j = 0; j < 120; j++ )
426        {
427            piece = j * inf->pieceCount / 120;
428
429            if( tr_cpPieceIsComplete( tor->completion, piece ) )
430            {
431                s[i].pieces[j] = -1;
432                continue;
433            }
434
435            s[i].pieces[j] = 0;
436           
437            for( k = 0; k < tor->peerCount; k++ )
438            {
439                if( tr_peerBitfield( tor->peers[k] ) &&
440                    tr_bitfieldHas( tr_peerBitfield( tor->peers[k] ), piece ) )
441                {
442                    (s[i].pieces[j])++;
443                }
444            }
445        }
446
447        s[i].downloaded = tor->downloaded;
448        s[i].uploaded   = tor->uploaded;
449
450        s[i].folder = tor->destination;
451
452        tr_lockUnlock( &tor->lock );
453    }
454
455    *stat = s;
456    return h->torrentCount;
457}
458
459/***********************************************************************
460 * tr_torrentClose
461 ***********************************************************************
462 * Frees memory allocated by tr_torrentInit.
463 **********************************************************************/
464void tr_torrentClose( tr_handle_t * h, int t )
465{
466    tr_torrent_t * tor = h->torrents[t];
467    tr_info_t    * inf = &tor->info;
468
469    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
470    {
471        /* Join the thread first */
472        torrentReallyStop( h, t );
473    }
474
475    tr_lockLock( &h->acceptLock );
476
477    h->torrentCount--;
478
479    tr_lockClose( &tor->lock );
480    tr_cpClose( tor->completion );
481
482    tr_rcClose( tor->upload );
483    tr_rcClose( tor->download );
484
485    if( tor->destination )
486    {
487        free( tor->destination );
488    }
489    free( inf->pieces );
490    free( inf->files );
491    free( tor );
492
493    memmove( &h->torrents[t], &h->torrents[t+1],
494             ( h->torrentCount - t ) * sizeof( void * ) );
495
496    tr_lockUnlock( &h->acceptLock );
497}
498
499void tr_close( tr_handle_t * h )
500{
501    acceptStop( h );
502    tr_fdClose( h->fdlimit );
503    tr_rcClose( h->upload );
504    free( h );
505}
506
507/***********************************************************************
508 * downloadLoop
509 **********************************************************************/
510static void downloadLoop( void * _tor )
511{
512    tr_torrent_t * tor = _tor;
513    uint64_t       date1, date2;
514
515    tr_dbg( "Thread started" );
516
517#ifdef SYS_BEOS
518    /* This is required because on BeOS, SIGINT is sent to each thread,
519       which kills them not nicely */
520    signal( SIGINT, SIG_IGN );
521#endif
522
523    tr_lockLock( &tor->lock );
524
525    tr_cpReset( tor->completion );
526    tor->io     = tr_ioInit( tor );
527    tor->status = tr_cpIsSeeding( tor->completion ) ?
528                      TR_STATUS_SEED : TR_STATUS_DOWNLOAD;
529
530    while( !tor->die )
531    {
532        date1 = tr_date();
533
534        /* Are we finished ? */
535        if( ( tor->status & TR_STATUS_DOWNLOAD ) &&
536            tr_cpIsSeeding( tor->completion ) )
537        {
538            /* Done */
539            tor->status = TR_STATUS_SEED;
540                        tor->finished = 1;
541            tr_trackerCompleted( tor->tracker );
542        }
543
544        /* Receive/send messages */
545        tr_peerPulse( tor );
546
547        /* Try to get new peers or to send a message to the tracker */
548        tr_trackerPulse( tor->tracker );
549
550        if( tor->status & TR_STATUS_STOPPED )
551        {
552            break;
553        }
554
555        /* Wait up to 20 ms */
556        date2 = tr_date();
557        if( date2 < date1 + 20 )
558        {
559            tr_lockUnlock( &tor->lock );
560            tr_wait( date1 + 20 - date2 );
561            tr_lockLock( &tor->lock );
562        }
563    }
564
565    tr_lockUnlock( &tor->lock );
566
567    tr_ioClose( tor->io );
568
569    tor->status = TR_STATUS_STOPPED;
570
571    tr_dbg( "Thread exited" );
572}
573
574/***********************************************************************
575 * acceptLoop
576 **********************************************************************/
577static void acceptLoop( void * _h )
578{
579    tr_handle_t * h = _h;
580    uint64_t      date1, date2;
581    int           ii, jj;
582    uint8_t     * hash;
583
584    tr_dbg( "Accept thread started" );
585
586#ifdef SYS_BEOS
587    /* This is required because on BeOS, SIGINT is sent to each thread,
588       which kills them not nicely */
589    signal( SIGINT, SIG_IGN );
590#endif
591
592    tr_lockLock( &h->acceptLock );
593
594    while( !h->acceptDie )
595    {
596        date1 = tr_date();
597
598        /* Check for incoming connections */
599        if( h->bindSocket > -1 &&
600            h->acceptPeerCount < TR_MAX_PEER_COUNT &&
601            !tr_fdSocketWillCreate( h->fdlimit, 0 ) )
602        {
603            int            s;
604            struct in_addr addr;
605            in_port_t      port;
606            s = tr_netAccept( h->bindSocket, &addr, &port );
607            if( s > -1 )
608            {
609                h->acceptPeers[h->acceptPeerCount++] = tr_peerInit( addr, port, s );
610            }
611            else
612            {
613                tr_fdSocketClosed( h->fdlimit, 0 );
614            }
615        }
616
617        for( ii = 0; ii < h->acceptPeerCount; )
618        {
619            if( tr_peerRead( NULL, h->acceptPeers[ii] ) )
620            {
621                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
622                goto removePeer;
623            }
624            if( NULL != ( hash = tr_peerHash( h->acceptPeers[ii] ) ) )
625            {
626                for( jj = 0; jj < h->torrentCount; jj++ )
627                {
628                    tr_lockLock( &h->torrents[jj]->lock );
629                    if( 0 == memcmp( h->torrents[jj]->info.hash, hash,
630                                     SHA_DIGEST_LENGTH ) )
631                    {
632                      tr_peerAttach( h->torrents[jj], h->acceptPeers[ii] );
633                      tr_lockUnlock( &h->torrents[jj]->lock );
634                      goto removePeer;
635                    }
636                    tr_lockUnlock( &h->torrents[jj]->lock );
637                }
638                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
639                goto removePeer;
640            }
641            ii++;
642            continue;
643           removePeer:
644            h->acceptPeerCount--;
645            memmove( &h->acceptPeers[ii], &h->acceptPeers[ii+1],
646                     ( h->acceptPeerCount - ii ) * sizeof( tr_peer_t * ) );
647        }
648
649        /* Wait up to 20 ms */
650        date2 = tr_date();
651        if( date2 < date1 + 20 )
652        {
653            tr_lockUnlock( &h->acceptLock );
654            tr_wait( date1 + 20 - date2 );
655            tr_lockLock( &h->acceptLock );
656        }
657    }
658
659    tr_lockUnlock( &h->acceptLock );
660
661    tr_dbg( "Accept thread exited" );
662}
663
664/***********************************************************************
665 * acceptStop
666 ***********************************************************************
667 * Joins the accept thread and frees/closes everything related to it.
668 **********************************************************************/
669static void acceptStop( tr_handle_t * h )
670{
671    int ii;
672
673    h->acceptDie = 1;
674    tr_threadJoin( &h->acceptThread );
675    tr_lockClose( &h->acceptLock );
676    tr_dbg( "Accept thread joined" );
677
678    for( ii = 0; ii < h->acceptPeerCount; ii++ )
679    {
680        tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
681    }
682
683    if( h->bindSocket > -1 )
684    {
685        tr_netClose( h->bindSocket );
686        tr_fdSocketClosed( h->fdlimit, 0 );
687    }
688}
Note: See TracBrowser for help on using the repository browser.