source: trunk/libtransmission/transmission.c @ 3989

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

fix crash-on-exit introduced by stats code

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