source: trunk/libtransmission/transmission.c @ 4008

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

throw away all pending `scrape' requests on shutdown... we don't need them then, so they just slow us down

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