source: trunk/libtransmission/transmission.c @ 3787

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

have tr_close() call tr_torrentClose() on all running torrents

  • Property svn:keywords set to Date Rev Author Id
File size: 9.4 KB
Line 
1/******************************************************************************
2 * $Id: transmission.c 3787 2007-11-10 22:29:28Z 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 <assert.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29
30#include <signal.h>
31#include <sys/types.h> /* stat */
32#include <sys/stat.h> /* stat */
33#include <unistd.h> /* stat */
34#include <dirent.h> /* opendir */
35
36#include "transmission.h"
37#include "fdlimit.h"
38#include "list.h"
39#include "net.h"
40#include "peer-mgr.h"
41#include "platform.h"
42#include "ratecontrol.h"
43#include "shared.h"
44#include "trevent.h"
45#include "utils.h"
46
47/* Generate a peer id : "-TRxyzb-" + 12 random alphanumeric
48   characters, where x is the major version number, y is the
49   minor version number, z is the maintenance number, and b
50   designates beta (Azureus-style) */
51void
52tr_peerIdNew ( char * buf, int buflen )
53{
54    int i;
55    assert( buflen == TR_ID_LEN + 1 );
56
57    snprintf( buf, TR_ID_LEN, "%s", PEERID_PREFIX );
58    assert( strlen(buf) == 8 );
59    for( i=8; i<TR_ID_LEN; ++i ) {
60        const int r = tr_rand( 36 );
61        buf[i] = ( r < 26 ) ? ( 'a' + r ) : ( '0' + r - 26 ) ;
62    }
63    buf[TR_ID_LEN] = '\0';
64}
65
66const char*
67getPeerId( void )
68{
69    static char * peerId = NULL;
70    if( !peerId ) {
71        peerId = tr_new0( char, TR_ID_LEN + 1 );
72        tr_peerIdNew( peerId, TR_ID_LEN + 1 );
73    }
74    return peerId;
75}
76
77/***
78****
79***/
80
81tr_encryption_mode
82tr_getEncryptionMode( tr_handle * handle )
83{
84    assert( handle != NULL );
85
86    return handle->encryptionMode;
87}
88
89void
90tr_setEncryptionMode( tr_handle * handle, tr_encryption_mode mode )
91{
92    assert( handle != NULL );
93    assert( mode==TR_ENCRYPTION_PREFERRED
94         || mode==TR_ENCRYPTION_REQUIRED
95         || mode==TR_PLAINTEXT_PREFERRED );
96
97    handle->encryptionMode = mode;
98}
99
100/***
101****
102***/
103
104
105/***********************************************************************
106 * tr_init
107 ***********************************************************************
108 * Allocates a tr_handle structure and initializes a few things
109 **********************************************************************/
110tr_handle * tr_init( const char * tag )
111{
112    tr_handle * h;
113
114#ifndef WIN32
115    /* Don't exit when writing on a broken socket */
116    signal( SIGPIPE, SIG_IGN );
117#endif
118
119    tr_msgInit();
120
121    h = tr_new0( tr_handle, 1 );
122    if( !h )
123        return NULL;
124
125    h->lock = tr_lockNew( );
126
127    h->encryptionMode = TR_ENCRYPTION_PREFERRED;
128
129    tr_netInit(); /* must go before tr_eventInit */
130
131    tr_eventInit( h );
132    while( !h->events )
133        tr_wait( 50 );
134
135    h->tag = strdup( tag );
136    if( !h->tag ) {
137        free( h );
138        return NULL;
139    }
140
141    h->peerMgr = tr_peerMgrNew( h );
142
143    /* Initialize rate and file descripts controls */
144    h->upload   = tr_rcInit();
145    h->download = tr_rcInit();
146
147    tr_fdInit();
148    h->shared = tr_sharedInit( h );
149
150    tr_inf( TR_NAME " " LONG_VERSION_STRING " started" );
151
152    return h;
153}
154
155/***
156****
157***/
158
159void
160tr_globalLock( struct tr_handle * handle )
161{
162    tr_lockLock( handle->lock );
163}
164
165void
166tr_globalUnlock( struct tr_handle * handle )
167{
168    tr_lockUnlock( handle->lock );
169}
170
171int
172tr_globalIsLocked( const struct tr_handle * handle )
173{
174    return tr_lockHave( handle->lock );
175}
176
177/***********************************************************************
178 * tr_setBindPort
179 ***********************************************************************
180 *
181 **********************************************************************/
182void tr_setBindPort( tr_handle * h, int port )
183{
184    h->isPortSet = 1;
185    tr_sharedSetPort( h->shared, port );
186}
187
188int
189tr_getPublicPort( const tr_handle * h )
190{
191    assert( h != NULL );
192    return tr_sharedGetPublicPort( h->shared );
193}
194
195void tr_natTraversalEnable( tr_handle * h, int enable )
196{
197    tr_globalLock( h );
198    tr_sharedTraversalEnable( h->shared, enable );
199    tr_globalUnlock( h );
200}
201
202tr_handle_status * tr_handleStatus( tr_handle * h )
203{
204    tr_handle_status * s;
205
206    h->statCur = ( h->statCur + 1 ) % 2;
207    s = &h->stats[h->statCur];
208
209    tr_globalLock( h );
210
211    s->natTraversalStatus = tr_sharedTraversalStatus( h->shared );
212    s->publicPort = tr_sharedGetPublicPort( h->shared );
213
214    tr_globalUnlock( h );
215
216    return s;
217}
218
219/***
220****
221***/
222
223void
224tr_setUseGlobalSpeedLimit( tr_handle  * h,
225                           int          up_or_down,
226                           int          use_flag )
227{
228    char * ch = up_or_down==TR_UP ? &h->useUploadLimit
229                                  : &h->useDownloadLimit;
230    *ch = use_flag;
231}
232
233void
234tr_setGlobalSpeedLimit( tr_handle  * h,
235                        int          up_or_down,
236                        int          KiB_sec )
237{
238    if( up_or_down == TR_DOWN )
239        tr_rcSetLimit( h->download, KiB_sec );
240    else
241        tr_rcSetLimit( h->upload, KiB_sec );
242}
243
244void
245tr_getGlobalSpeedLimit( tr_handle  * h,
246                        int          up_or_down,
247                        int        * setme_enabled,
248                        int          * setme_KiBsec )
249{
250    if( setme_enabled != NULL )
251       *setme_enabled = up_or_down==TR_UP ? h->useUploadLimit
252                                          : h->useDownloadLimit;
253    if( setme_KiBsec != NULL )
254       *setme_KiBsec = tr_rcGetLimit( up_or_down==TR_UP ? h->upload
255                                                        : h->download );
256}
257
258void
259tr_torrentRates( tr_handle * h, float * toClient, float * toPeer )
260{
261    const tr_torrent * tor;
262    tr_globalLock( h );
263
264    *toClient = *toPeer = 0.0;
265    for( tor = h->torrentList; tor; tor = tor->next )
266    {
267        float c, p;
268        tr_torrentGetRates( tor, &c, &p );
269        *toClient += c;
270        *toPeer += p;
271    }
272
273    tr_globalUnlock( h );
274}
275
276int
277tr_torrentCount( tr_handle * h )
278{
279    return h->torrentCount;
280}
281
282void
283tr_torrentIterate( tr_handle * h, tr_callback_t func, void * d )
284{
285    tr_torrent * tor, * next;
286
287    for( tor = h->torrentList; tor; tor = next )
288    {
289        next = tor->next;
290        func( tor, d );
291    }
292}
293
294static void
295tr_closeImpl( void * vh )
296{
297    tr_handle * h = vh;
298    tr_torrent * t;
299
300    for( t=h->torrentList; t!=NULL; t=t->next )
301        tr_torrentClose( t );
302
303    tr_peerMgrFree( h->peerMgr );
304
305    tr_rcClose( h->upload );
306    tr_rcClose( h->download );
307   
308    tr_natTraversalEnable( h, 0 );
309    while( tr_handleStatus( h )->natTraversalStatus != TR_NAT_TRAVERSAL_DISABLED )
310        tr_wait( 100 );
311
312    tr_sharedClose( h->shared );
313    tr_fdClose();
314
315    h->isClosed = TRUE;
316}
317
318static int
319deadlineReached( const uint64_t deadline )
320{
321    return tr_date( ) >= deadline;
322}
323
324void
325tr_close( tr_handle * h )
326{
327    const int maxwait_msec = 6 * 1000;
328    const uint64_t deadline = tr_date( ) + maxwait_msec;
329
330    tr_runInEventThread( h, tr_closeImpl, h );
331    while( !h->isClosed && !deadlineReached( deadline ) )
332        tr_wait( 100 );
333
334    tr_eventClose( h );
335    while( h->events && !deadlineReached( deadline ) )
336        tr_wait( 100 );
337
338    tr_lockFree( h->lock );
339    free( h->tag );
340    free( h );
341}
342
343tr_torrent **
344tr_loadTorrents ( tr_handle   * h,
345                  const char  * fallbackDestination,
346                  int           isPaused,
347                  int         * setmeCount )
348{
349    int i, n = 0;
350    struct stat sb;
351    DIR * odir = NULL;
352    const char * torrentDir = tr_getTorrentsDirectory( );
353    tr_torrent ** torrents;
354    tr_list *l=NULL, *list=NULL;
355
356    if( !stat( torrentDir, &sb )
357        && S_ISDIR( sb.st_mode )
358        && (( odir = opendir ( torrentDir ) )) )
359    {
360        struct dirent *d;
361        for (d = readdir( odir ); d!=NULL; d=readdir( odir ) )
362        {
363            if( d->d_name && d->d_name[0]!='.' ) /* skip dotfiles, ., and .. */
364            {
365                tr_torrent * tor;
366                char path[MAX_PATH_LENGTH];
367                tr_buildPath( path, sizeof(path), torrentDir, d->d_name, NULL );
368                tor = tr_torrentLoad( h, path, fallbackDestination, isPaused, NULL );
369                if( tor != NULL ) {
370                    tr_list_append( &list, tor );
371                    n++;
372                }
373            }
374        }
375        closedir( odir );
376    }
377
378    torrents = tr_new( tr_torrent*, n );
379    for( i=0, l=list; l!=NULL; l=l->next )
380        torrents[i++] = (tr_torrent*) l->data;
381    assert( i==n );
382
383    tr_list_free( &list, NULL );
384
385    *setmeCount = n;
386    tr_inf( "Loaded %d torrents from disk", *setmeCount );
387    return torrents;
388}
Note: See TracBrowser for help on using the repository browser.