source: trunk/libtransmission/transmission.c @ 4306

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

replace the per-torrent PEX setting with a global one, as per discussion with SoftwareElves? and BentMyWookie?

  • Property svn:keywords set to Date Rev Author Id
File size: 10.4 KB
Line 
1/******************************************************************************
2 * $Id: transmission.c 4306 2007-12-24 05:03:40Z 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    h->isPexEnabled = 1;
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
285
286void
287tr_setGlobalPeerLimit( tr_handle * handle UNUSED,
288                       uint16_t    maxGlobalPeers )
289{
290    tr_fdSetPeerLimit( maxGlobalPeers );
291}
292
293uint16_t
294tr_getGlobalPeerLimit( const tr_handle * handle UNUSED )
295{
296    return tr_fdGetPeerLimit( );
297}
298
299void
300tr_torrentRates( tr_handle * h, float * toClient, float * toPeer )
301{
302    const tr_torrent * tor;
303    tr_globalLock( h );
304
305    *toClient = *toPeer = 0.0;
306    for( tor = h->torrentList; tor; tor = tor->next )
307    {
308        float c, p;
309        tr_torrentGetRates( tor, &c, &p );
310        *toClient += c;
311        *toPeer += p;
312    }
313
314    tr_globalUnlock( h );
315}
316
317int
318tr_torrentCount( tr_handle * h )
319{
320    return h->torrentCount;
321}
322
323void
324tr_torrentIterate( tr_handle * h, tr_callback_t func, void * d )
325{
326    tr_torrent * tor, * next;
327
328    for( tor = h->torrentList; tor; tor = next )
329    {
330        next = tor->next;
331        func( tor, d );
332    }
333}
334
335static void
336tr_closeImpl( void * vh )
337{
338    tr_handle * h = vh;
339    tr_torrent * t;
340
341    tr_sharedShuttingDown( h->shared );
342    tr_trackerShuttingDown( h );
343
344    for( t=h->torrentList; t!=NULL; t=t->next )
345        tr_torrentClose( t );
346
347    tr_peerMgrFree( h->peerMgr );
348
349    tr_rcClose( h->upload );
350    tr_rcClose( h->download );
351   
352    h->isClosed = TRUE;
353}
354
355static int
356deadlineReached( const uint64_t deadline )
357{
358    return tr_date( ) >= deadline;
359}
360
361#define SHUTDOWN_MAX_SECONDS 30
362
363void
364tr_close( tr_handle * h )
365{
366    const int maxwait_msec = SHUTDOWN_MAX_SECONDS * 1000;
367    const uint64_t deadline = tr_date( ) + maxwait_msec;
368
369    tr_runInEventThread( h, tr_closeImpl, h );
370    while( !h->isClosed && !deadlineReached( deadline ) )
371        tr_wait( 100 );
372
373    tr_eventClose( h );
374    while( h->events && !deadlineReached( deadline ) )
375        tr_wait( 100 );
376
377    tr_fdClose( );
378    tr_statsClose( h );
379    tr_lockFree( h->lock );
380    free( h->tag );
381    free( h );
382}
383
384tr_torrent **
385tr_loadTorrents ( tr_handle   * h,
386                  tr_ctor     * ctor,
387                  int         * setmeCount )
388{
389    int i, n = 0;
390    struct stat sb;
391    DIR * odir = NULL;
392    const char * dirname = tr_getTorrentsDirectory( );
393    tr_torrent ** torrents;
394    tr_list *l=NULL, *list=NULL;
395
396    tr_ctorSetSave( ctor, FALSE ); /* since we already have them */
397
398    if( !stat( dirname, &sb )
399        && S_ISDIR( sb.st_mode )
400        && (( odir = opendir ( dirname ) )) )
401    {
402        struct dirent *d;
403        for (d = readdir( odir ); d!=NULL; d=readdir( odir ) )
404        {
405            if( d->d_name && d->d_name[0]!='.' ) /* skip dotfiles, ., and .. */
406            {
407                tr_torrent * tor;
408                char filename[MAX_PATH_LENGTH];
409                tr_buildPath( filename, sizeof(filename), dirname, d->d_name, NULL );
410                tr_ctorSetMetainfoFromFile( ctor, filename );
411                tor = tr_torrentNew( h, ctor, NULL );
412                if( tor != NULL ) {
413                    tr_list_append( &list, tor );
414                    n++;
415                }
416            }
417        }
418        closedir( odir );
419    }
420
421    torrents = tr_new( tr_torrent*, n );
422    for( i=0, l=list; l!=NULL; l=l->next )
423        torrents[i++] = (tr_torrent*) l->data;
424    assert( i==n );
425
426    tr_list_free( &list, NULL );
427
428    *setmeCount = n;
429    tr_inf( "Loaded %d torrents from disk", *setmeCount );
430    return torrents;
431}
432
433/***
434****
435***/
436
437void
438tr_setPexEnabled( tr_handle * handle, int isPexEnabled )
439{
440    handle->isPexEnabled = isPexEnabled ? 1 : 0;
441}
442
443int
444tr_isPexEnabled( const tr_handle * handle )
445{
446    return handle->isPexEnabled;
447}
Note: See TracBrowser for help on using the repository browser.