source: trunk/libtransmission/transmission.c @ 4311

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

(gtk) fix startup port issue by hitting it with a damn big hammer

  • Property svn:keywords set to Date Rev Author Id
File size: 11.2 KB
Line 
1/******************************************************************************
2 * $Id: transmission.c 4311 2007-12-24 07:02: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
106tr_handle *
107tr_initFull( const char * tag,
108             int          isPexEnabled,
109             int          isNatEnabled,
110             int          publicPort,
111             int          encryptionMode,
112             int          isUploadLimitEnabled,
113             int          uploadLimit,
114             int          isDownloadLimitEnabled,
115             int          downloadLimit,
116             int          globalPeerLimit )
117{
118    tr_handle * h;
119
120#ifndef WIN32
121    /* Don't exit when writing on a broken socket */
122    signal( SIGPIPE, SIG_IGN );
123#endif
124
125    tr_msgInit( );
126
127    h = tr_new0( tr_handle, 1 );
128    h->lock = tr_lockNew( );
129    h->isPexEnabled = isPexEnabled ? 1 : 0;
130    h->encryptionMode = encryptionMode;
131
132    tr_netInit(); /* must go before tr_eventInit */
133
134    tr_eventInit( h );
135    while( !h->events )
136        tr_wait( 50 );
137
138    h->tag = strdup( tag );
139    if( !h->tag ) {
140        free( h );
141        return NULL;
142    }
143
144    h->peerMgr = tr_peerMgrNew( h );
145
146    /* Initialize rate and file descripts controls */
147
148    h->upload = tr_rcInit();
149    tr_rcSetLimit( h->upload, uploadLimit );
150    h->useUploadLimit = isUploadLimitEnabled;
151
152    h->download = tr_rcInit();
153    tr_rcSetLimit( h->download, downloadLimit );
154    h->useDownloadLimit = isDownloadLimitEnabled;
155
156    tr_fdInit( globalPeerLimit );
157    h->shared = tr_sharedInit( h, isNatEnabled, publicPort );
158    h->isPortSet = publicPort >= 0;
159
160    tr_inf( TR_NAME " " LONG_VERSION_STRING " started" );
161
162    tr_statsInit( h );
163
164    return h;
165}
166
167tr_handle * tr_init( const char * tag )
168{
169    return tr_initFull( tag,
170                        TRUE, /* pex enabled */
171                        FALSE, /* nat enabled */
172                        -1, /* public port */
173                        TR_ENCRYPTION_PREFERRED, /* encryption mode */
174                        FALSE, /* use upload speed limit? */ 
175                        -1, /* upload speed limit */
176                        FALSE, /* use download speed limit? */
177                        -1, /* download speed limit */
178                        512 ); /* globalPeerLimit */
179}
180
181/***
182****
183***/
184
185void
186tr_globalLock( struct tr_handle * handle )
187{
188    tr_lockLock( handle->lock );
189}
190
191void
192tr_globalUnlock( struct tr_handle * handle )
193{
194    tr_lockUnlock( handle->lock );
195}
196
197int
198tr_globalIsLocked( const struct tr_handle * handle )
199{
200    return tr_lockHave( handle->lock );
201}
202
203/***********************************************************************
204 * tr_setBindPort
205 ***********************************************************************
206 *
207 **********************************************************************/
208
209struct bind_port_data
210{
211    tr_handle * handle;
212    int port;
213};
214
215static void
216tr_setBindPortImpl( void * vdata )
217{
218    struct bind_port_data * data = vdata;
219    tr_handle * handle = data->handle;
220    const int port = data->port;
221
222    handle->isPortSet = 1;
223    tr_sharedSetPort( handle->shared, port );
224
225    tr_free( data );
226}
227
228void
229tr_setBindPort( tr_handle * handle, int port )
230{
231    struct bind_port_data * data = tr_new( struct bind_port_data, 1 );
232    data->handle = handle;
233    data->port = port;
234    tr_runInEventThread( handle, tr_setBindPortImpl, data );
235}
236
237int
238tr_getPublicPort( const tr_handle * h )
239{
240    assert( h != NULL );
241    return tr_sharedGetPublicPort( h->shared );
242}
243
244void tr_natTraversalEnable( tr_handle * h, int enable )
245{
246    tr_globalLock( h );
247    tr_sharedTraversalEnable( h->shared, enable );
248    tr_globalUnlock( h );
249}
250
251tr_handle_status * tr_handleStatus( tr_handle * h )
252{
253    tr_handle_status * s;
254
255    h->statCur = ( h->statCur + 1 ) % 2;
256    s = &h->stats[h->statCur];
257
258    tr_globalLock( h );
259
260    s->natTraversalStatus = tr_sharedTraversalStatus( h->shared );
261    s->publicPort = tr_sharedGetPublicPort( h->shared );
262
263    tr_globalUnlock( h );
264
265    return s;
266}
267
268/***
269****
270***/
271
272void
273tr_setUseGlobalSpeedLimit( tr_handle  * h,
274                           int          up_or_down,
275                           int          use_flag )
276{
277    char * ch = up_or_down==TR_UP ? &h->useUploadLimit
278                                  : &h->useDownloadLimit;
279    *ch = use_flag;
280}
281
282void
283tr_setGlobalSpeedLimit( tr_handle  * h,
284                        int          up_or_down,
285                        int          KiB_sec )
286{
287    if( up_or_down == TR_DOWN )
288        tr_rcSetLimit( h->download, KiB_sec );
289    else
290        tr_rcSetLimit( h->upload, KiB_sec );
291}
292
293void
294tr_getGlobalSpeedLimit( tr_handle  * h,
295                        int          up_or_down,
296                        int        * setme_enabled,
297                        int          * setme_KiBsec )
298{
299    if( setme_enabled != NULL )
300       *setme_enabled = up_or_down==TR_UP ? h->useUploadLimit
301                                          : h->useDownloadLimit;
302    if( setme_KiBsec != NULL )
303       *setme_KiBsec = tr_rcGetLimit( up_or_down==TR_UP ? h->upload
304                                                        : h->download );
305}
306
307
308void
309tr_setGlobalPeerLimit( tr_handle * handle UNUSED,
310                       uint16_t    maxGlobalPeers )
311{
312    tr_fdSetPeerLimit( maxGlobalPeers );
313}
314
315uint16_t
316tr_getGlobalPeerLimit( const tr_handle * handle UNUSED )
317{
318    return tr_fdGetPeerLimit( );
319}
320
321void
322tr_torrentRates( tr_handle * h, float * toClient, float * toPeer )
323{
324    const tr_torrent * tor;
325    tr_globalLock( h );
326
327    *toClient = *toPeer = 0.0;
328    for( tor = h->torrentList; tor; tor = tor->next )
329    {
330        float c, p;
331        tr_torrentGetRates( tor, &c, &p );
332        *toClient += c;
333        *toPeer += p;
334    }
335
336    tr_globalUnlock( h );
337}
338
339int
340tr_torrentCount( tr_handle * h )
341{
342    return h->torrentCount;
343}
344
345void
346tr_torrentIterate( tr_handle * h, tr_callback_t func, void * d )
347{
348    tr_torrent * tor, * next;
349
350    for( tor = h->torrentList; tor; tor = next )
351    {
352        next = tor->next;
353        func( tor, d );
354    }
355}
356
357static void
358tr_closeImpl( void * vh )
359{
360    tr_handle * h = vh;
361    tr_torrent * t;
362
363    tr_sharedShuttingDown( h->shared );
364    tr_trackerShuttingDown( h );
365
366    for( t=h->torrentList; t!=NULL; t=t->next )
367        tr_torrentClose( t );
368
369    tr_peerMgrFree( h->peerMgr );
370
371    tr_rcClose( h->upload );
372    tr_rcClose( h->download );
373   
374    h->isClosed = TRUE;
375}
376
377static int
378deadlineReached( const uint64_t deadline )
379{
380    return tr_date( ) >= deadline;
381}
382
383#define SHUTDOWN_MAX_SECONDS 30
384
385void
386tr_close( tr_handle * h )
387{
388    const int maxwait_msec = SHUTDOWN_MAX_SECONDS * 1000;
389    const uint64_t deadline = tr_date( ) + maxwait_msec;
390
391    tr_runInEventThread( h, tr_closeImpl, h );
392    while( !h->isClosed && !deadlineReached( deadline ) )
393        tr_wait( 100 );
394
395    tr_eventClose( h );
396    while( h->events && !deadlineReached( deadline ) )
397        tr_wait( 100 );
398
399    tr_fdClose( );
400    tr_statsClose( h );
401    tr_lockFree( h->lock );
402    free( h->tag );
403    free( h );
404}
405
406tr_torrent **
407tr_loadTorrents ( tr_handle   * h,
408                  tr_ctor     * ctor,
409                  int         * setmeCount )
410{
411    int i, n = 0;
412    struct stat sb;
413    DIR * odir = NULL;
414    const char * dirname = tr_getTorrentsDirectory( );
415    tr_torrent ** torrents;
416    tr_list *l=NULL, *list=NULL;
417
418    tr_ctorSetSave( ctor, FALSE ); /* since we already have them */
419
420    if( !stat( dirname, &sb )
421        && S_ISDIR( sb.st_mode )
422        && (( odir = opendir ( dirname ) )) )
423    {
424        struct dirent *d;
425        for (d = readdir( odir ); d!=NULL; d=readdir( odir ) )
426        {
427            if( d->d_name && d->d_name[0]!='.' ) /* skip dotfiles, ., and .. */
428            {
429                tr_torrent * tor;
430                char filename[MAX_PATH_LENGTH];
431                tr_buildPath( filename, sizeof(filename), dirname, d->d_name, NULL );
432                tr_ctorSetMetainfoFromFile( ctor, filename );
433                tor = tr_torrentNew( h, ctor, NULL );
434                if( tor != NULL ) {
435                    tr_list_append( &list, tor );
436                    n++;
437                }
438            }
439        }
440        closedir( odir );
441    }
442
443    torrents = tr_new( tr_torrent*, n );
444    for( i=0, l=list; l!=NULL; l=l->next )
445        torrents[i++] = (tr_torrent*) l->data;
446    assert( i==n );
447
448    tr_list_free( &list, NULL );
449
450    *setmeCount = n;
451    tr_inf( "Loaded %d torrents from disk", *setmeCount );
452    return torrents;
453}
454
455/***
456****
457***/
458
459void
460tr_setPexEnabled( tr_handle * handle, int isPexEnabled )
461{
462    handle->isPexEnabled = isPexEnabled ? 1 : 0;
463}
464
465int
466tr_isPexEnabled( const tr_handle * handle )
467{
468    return handle->isPexEnabled;
469}
Note: See TracBrowser for help on using the repository browser.