source: trunk/libtransmission/session.c @ 10554

Last change on this file since 10554 was 10554, checked in by charles, 11 years ago

(trunk libT) #3117 "Tracker queries to not honor bind-address-ipv4" -- fix a crash-on-shutdown reported by Waldorf in #3181. The crash was introduced by r10535 for #3117

  • Property svn:keywords set to Date Rev Author Id
File size: 65.9 KB
Line 
1/*
2 * This file Copyright (C) 2008-2010 Mnemosyne LLC
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: session.c 10554 2010-04-30 17:38:40Z charles $
11 */
12
13#include <assert.h>
14#include <errno.h> /* ENOENT */
15#include <stdlib.h>
16#include <string.h> /* memcpy */
17
18#include <signal.h>
19#include <sys/types.h> /* stat(), umask() */
20#include <sys/stat.h> /* stat(), umask() */
21#include <unistd.h> /* stat */
22#include <dirent.h> /* opendir */
23
24#include <event.h>
25
26#include "transmission.h"
27#include "announcer.h"
28#include "bandwidth.h"
29#include "bencode.h"
30#include "blocklist.h"
31#include "crypto.h"
32#include "fdlimit.h"
33#include "list.h"
34#include "metainfo.h" /* tr_metainfoFree */
35#include "net.h"
36#include "peer-io.h"
37#include "peer-mgr.h"
38#include "platform.h" /* tr_lock */
39#include "port-forwarding.h"
40#include "rpc-server.h"
41#include "session.h"
42#include "stats.h"
43#include "torrent.h"
44#include "tr-dht.h"
45#include "trevent.h"
46#include "utils.h"
47#include "verify.h"
48#include "version.h"
49#include "web.h"
50
51enum
52{
53    SAVE_INTERVAL_SECS = 120
54};
55
56
57#define dbgmsg( ... ) \
58    do { \
59        if( tr_deepLoggingIsActive( ) ) \
60            tr_deepLog( __FILE__, __LINE__, NULL, __VA_ARGS__ ); \
61    } while( 0 )
62
63static tr_port
64getRandomPort( tr_session * s )
65{
66    return tr_cryptoWeakRandInt( s->randomPortHigh - s->randomPortLow + 1) + s->randomPortLow;
67}
68
69/* Generate a peer id : "-TRxyzb-" + 12 random alphanumeric
70   characters, where x is the major version number, y is the
71   minor version number, z is the maintenance number, and b
72   designates beta (Azureus-style) */
73uint8_t*
74tr_peerIdNew( void )
75{
76    int          i;
77    int          val;
78    int          total = 0;
79    uint8_t *    buf = tr_new( uint8_t, 21 );
80    const char * pool = "0123456789abcdefghijklmnopqrstuvwxyz";
81    const int    base = 36;
82
83    memcpy( buf, PEERID_PREFIX, 8 );
84
85    for( i = 8; i < 19; ++i )
86    {
87        val = tr_cryptoRandInt( base );
88        total += val;
89        buf[i] = pool[val];
90    }
91
92    val = total % base ? base - ( total % base ) : 0;
93    buf[19] = pool[val];
94    buf[20] = '\0';
95
96    return buf;
97}
98
99const uint8_t*
100tr_getPeerId( void )
101{
102    static uint8_t * id = NULL;
103
104    if( id == NULL )
105        id = tr_peerIdNew( );
106    return id;
107}
108
109/***
110****
111***/
112
113tr_encryption_mode
114tr_sessionGetEncryption( tr_session * session )
115{
116    assert( session );
117
118    return session->encryptionMode;
119}
120
121void
122tr_sessionSetEncryption( tr_session *       session,
123                         tr_encryption_mode mode )
124{
125    assert( session );
126    assert( mode == TR_ENCRYPTION_PREFERRED
127          || mode == TR_ENCRYPTION_REQUIRED
128          || mode == TR_CLEAR_PREFERRED );
129
130    session->encryptionMode = mode;
131}
132
133/***
134****
135***/
136
137struct tr_bindinfo
138{
139    int socket;
140    tr_address addr;
141    struct event ev;
142};
143
144
145static void
146close_bindinfo( struct tr_bindinfo * b )
147{
148    if( ( b != NULL ) && ( b->socket >=0 ) )
149    {
150        event_del( &b->ev );
151        tr_netCloseSocket( b->socket );
152    }
153}
154
155static void
156close_incoming_peer_port( tr_session * session )
157{
158    close_bindinfo( session->public_ipv4 );
159    close_bindinfo( session->public_ipv6 );
160}
161
162static void
163free_incoming_peer_port( tr_session * session )
164{
165    close_bindinfo( session->public_ipv4 );
166    tr_free( session->public_ipv4 );
167    session->public_ipv4 = NULL;
168
169    close_bindinfo( session->public_ipv6 );
170    tr_free( session->public_ipv6 );
171    session->public_ipv6 = NULL;
172}
173
174static void
175accept_incoming_peer( int fd, short what UNUSED, void * vsession )
176{
177    int clientSocket;
178    tr_port clientPort;
179    tr_address clientAddr;
180    tr_session * session = vsession;
181
182    clientSocket = tr_netAccept( session, fd, &clientAddr, &clientPort );
183    if( clientSocket > 0 ) {
184        tr_deepLog( __FILE__, __LINE__, NULL, "new incoming connection %d (%s)",
185                   clientSocket, tr_peerIoAddrStr( &clientAddr, clientPort ) );
186        tr_peerMgrAddIncoming( session->peerMgr, &clientAddr, clientPort, clientSocket );
187    }
188}
189
190static void
191open_incoming_peer_port( tr_session * session )
192{
193    struct tr_bindinfo * b;
194
195    /* bind an ipv4 port to listen for incoming peers... */
196    b = session->public_ipv4;
197    b->socket = tr_netBindTCP( &b->addr, session->peerPort, FALSE );
198    if( b->socket >= 0 ) {
199        event_set( &b->ev, b->socket, EV_READ | EV_PERSIST, accept_incoming_peer, session );
200        event_add( &b->ev, NULL );
201    }
202
203    /* and do the exact same thing for ipv6, if it's supported... */
204    if( tr_net_hasIPv6( session->peerPort ) ) {
205        b = session->public_ipv6;
206        b->socket = tr_netBindTCP( &b->addr, session->peerPort, FALSE );
207        if( b->socket >= 0 ) {
208            event_set( &b->ev, b->socket, EV_READ | EV_PERSIST, accept_incoming_peer, session );
209            event_add( &b->ev, NULL );
210        }
211    }
212}
213
214const tr_address*
215tr_sessionGetPublicAddress( const tr_session * session, int tr_af_type )
216{
217    const struct tr_bindinfo * bindinfo;
218
219    switch( tr_af_type )
220    {
221        case TR_AF_INET:  bindinfo = session->public_ipv4; break;
222        case TR_AF_INET6: bindinfo = session->public_ipv6; break;
223        default:          bindinfo = NULL;                 break;
224    }
225
226    return bindinfo ? &bindinfo->addr : NULL;
227}
228
229/***
230****
231***/
232
233#ifdef TR_EMBEDDED
234 #define TR_DEFAULT_ENCRYPTION   TR_CLEAR_PREFERRED
235#else
236 #define TR_DEFAULT_ENCRYPTION   TR_ENCRYPTION_PREFERRED
237#endif
238
239void
240tr_sessionGetDefaultSettings( const char * configDir UNUSED, tr_benc * d )
241{
242    assert( tr_bencIsDict( d ) );
243
244    tr_bencDictReserve( d, 35 );
245    tr_bencDictAddBool( d, TR_PREFS_KEY_BLOCKLIST_ENABLED,        FALSE );
246    tr_bencDictAddBool( d, TR_PREFS_KEY_DHT_ENABLED,              TRUE );
247    tr_bencDictAddStr ( d, TR_PREFS_KEY_DOWNLOAD_DIR,             tr_getDefaultDownloadDir( ) );
248    tr_bencDictAddInt ( d, TR_PREFS_KEY_DSPEED,                   100 );
249    tr_bencDictAddBool( d, TR_PREFS_KEY_DSPEED_ENABLED,           FALSE );
250    tr_bencDictAddInt ( d, TR_PREFS_KEY_ENCRYPTION,               TR_DEFAULT_ENCRYPTION );
251    tr_bencDictAddStr ( d, TR_PREFS_KEY_INCOMPLETE_DIR,           tr_getDefaultDownloadDir( ) );
252    tr_bencDictAddBool( d, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED,   FALSE );
253    tr_bencDictAddBool( d, TR_PREFS_KEY_LAZY_BITFIELD,            TRUE );
254    tr_bencDictAddInt ( d, TR_PREFS_KEY_MSGLEVEL,                 TR_MSG_INF );
255    tr_bencDictAddInt ( d, TR_PREFS_KEY_OPEN_FILE_LIMIT,          atoi( TR_DEFAULT_OPEN_FILE_LIMIT_STR ) );
256    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_LIMIT_GLOBAL,        atoi( TR_DEFAULT_PEER_LIMIT_GLOBAL_STR ) );
257    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_LIMIT_TORRENT,       atoi( TR_DEFAULT_PEER_LIMIT_TORRENT_STR ) );
258    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_PORT,                atoi( TR_DEFAULT_PEER_PORT_STR ) );
259    tr_bencDictAddBool( d, TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START, FALSE );
260    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_PORT_RANDOM_LOW,     49152 );
261    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_PORT_RANDOM_HIGH,    65535 );
262    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_SOCKET_TOS,          atoi( TR_DEFAULT_PEER_SOCKET_TOS_STR ) );
263    tr_bencDictAddBool( d, TR_PREFS_KEY_PEX_ENABLED,              TRUE );
264    tr_bencDictAddBool( d, TR_PREFS_KEY_PORT_FORWARDING,          TRUE );
265    tr_bencDictAddInt ( d, TR_PREFS_KEY_PREALLOCATION,            TR_PREALLOCATE_SPARSE );
266    tr_bencDictAddStr ( d, TR_PREFS_KEY_PROXY,                    "" );
267    tr_bencDictAddBool( d, TR_PREFS_KEY_PROXY_AUTH_ENABLED,       FALSE );
268    tr_bencDictAddBool( d, TR_PREFS_KEY_PROXY_ENABLED,            FALSE );
269    tr_bencDictAddStr ( d, TR_PREFS_KEY_PROXY_PASSWORD,           "" );
270    tr_bencDictAddInt ( d, TR_PREFS_KEY_PROXY_PORT,               80 );
271    tr_bencDictAddInt ( d, TR_PREFS_KEY_PROXY_TYPE,               TR_PROXY_HTTP );
272    tr_bencDictAddStr ( d, TR_PREFS_KEY_PROXY_USERNAME,           "" );
273    tr_bencDictAddReal( d, TR_PREFS_KEY_RATIO,                    2.0 );
274    tr_bencDictAddBool( d, TR_PREFS_KEY_RATIO_ENABLED,            FALSE );
275    tr_bencDictAddBool( d, TR_PREFS_KEY_RENAME_PARTIAL_FILES,     TRUE );
276    tr_bencDictAddBool( d, TR_PREFS_KEY_RPC_AUTH_REQUIRED,        FALSE );
277    tr_bencDictAddStr ( d, TR_PREFS_KEY_RPC_BIND_ADDRESS,         "0.0.0.0" );
278    tr_bencDictAddBool( d, TR_PREFS_KEY_RPC_ENABLED,              FALSE );
279    tr_bencDictAddStr ( d, TR_PREFS_KEY_RPC_PASSWORD,             "" );
280    tr_bencDictAddStr ( d, TR_PREFS_KEY_RPC_USERNAME,             "" );
281    tr_bencDictAddStr ( d, TR_PREFS_KEY_RPC_WHITELIST,            TR_DEFAULT_RPC_WHITELIST );
282    tr_bencDictAddBool( d, TR_PREFS_KEY_RPC_WHITELIST_ENABLED,    TRUE );
283    tr_bencDictAddInt ( d, TR_PREFS_KEY_RPC_PORT,                 atoi( TR_DEFAULT_RPC_PORT_STR ) );
284    tr_bencDictAddBool( d, TR_PREFS_KEY_ALT_SPEED_ENABLED,        FALSE );
285    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_UP,             50 ); /* half the regular */
286    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_DOWN,           50 ); /* half the regular */
287    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN,     540 ); /* 9am */
288    tr_bencDictAddBool( d, TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED,   FALSE );
289    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_END,       1020 ); /* 5pm */
290    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_DAY,       TR_SCHED_ALL );
291    tr_bencDictAddInt ( d, TR_PREFS_KEY_USPEED,                   100 );
292    tr_bencDictAddBool( d, TR_PREFS_KEY_USPEED_ENABLED,           FALSE );
293    tr_bencDictAddInt ( d, TR_PREFS_KEY_UMASK,                    022 );
294    tr_bencDictAddInt ( d, TR_PREFS_KEY_UPLOAD_SLOTS_PER_TORRENT, 14 );
295    tr_bencDictAddStr ( d, TR_PREFS_KEY_BIND_ADDRESS_IPV4,        TR_DEFAULT_BIND_ADDRESS_IPV4 );
296    tr_bencDictAddStr ( d, TR_PREFS_KEY_BIND_ADDRESS_IPV6,        TR_DEFAULT_BIND_ADDRESS_IPV6 );
297    tr_bencDictAddBool( d, TR_PREFS_KEY_START,                    TRUE );
298    tr_bencDictAddBool( d, TR_PREFS_KEY_TRASH_ORIGINAL,           FALSE );
299}
300
301void
302tr_sessionGetSettings( tr_session * s, struct tr_benc * d )
303{
304    assert( tr_bencIsDict( d ) );
305
306    tr_bencDictReserve( d, 30 );
307    tr_bencDictAddBool( d, TR_PREFS_KEY_BLOCKLIST_ENABLED,        tr_blocklistIsEnabled( s ) );
308    tr_bencDictAddBool( d, TR_PREFS_KEY_DHT_ENABLED,              s->isDHTEnabled );
309    tr_bencDictAddStr ( d, TR_PREFS_KEY_DOWNLOAD_DIR,             s->downloadDir );
310    tr_bencDictAddInt ( d, TR_PREFS_KEY_DSPEED,                   tr_sessionGetSpeedLimit( s, TR_DOWN ) );
311    tr_bencDictAddBool( d, TR_PREFS_KEY_DSPEED_ENABLED,           tr_sessionIsSpeedLimited( s, TR_DOWN ) );
312    tr_bencDictAddInt ( d, TR_PREFS_KEY_ENCRYPTION,               s->encryptionMode );
313    tr_bencDictAddStr ( d, TR_PREFS_KEY_INCOMPLETE_DIR,           tr_sessionGetIncompleteDir( s ) );
314    tr_bencDictAddBool( d, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED,   tr_sessionIsIncompleteDirEnabled( s ) );
315    tr_bencDictAddBool( d, TR_PREFS_KEY_LAZY_BITFIELD,            s->useLazyBitfield );
316    tr_bencDictAddInt ( d, TR_PREFS_KEY_MSGLEVEL,                 tr_getMessageLevel( ) );
317    tr_bencDictAddInt ( d, TR_PREFS_KEY_OPEN_FILE_LIMIT,          tr_fdGetFileLimit( s ) );
318    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_LIMIT_GLOBAL,        tr_sessionGetPeerLimit( s ) );
319    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_LIMIT_TORRENT,       s->peerLimitPerTorrent );
320    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_PORT,                tr_sessionGetPeerPort( s ) );
321    tr_bencDictAddBool( d, TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START, s->isPortRandom );
322    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_PORT_RANDOM_LOW,     s->randomPortLow );
323    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_PORT_RANDOM_HIGH,    s->randomPortHigh );
324    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_SOCKET_TOS,          s->peerSocketTOS );
325    if(s->peer_congestion_algorithm && s->peer_congestion_algorithm[0])
326        tr_bencDictAddStr ( d, TR_PREFS_KEY_PEER_CONGESTION_ALGORITHM, s->peer_congestion_algorithm );
327    tr_bencDictAddBool( d, TR_PREFS_KEY_PEX_ENABLED,              s->isPexEnabled );
328    tr_bencDictAddBool( d, TR_PREFS_KEY_PORT_FORWARDING,          tr_sessionIsPortForwardingEnabled( s ) );
329    tr_bencDictAddInt ( d, TR_PREFS_KEY_PREALLOCATION,            s->preallocationMode );
330    tr_bencDictAddStr ( d, TR_PREFS_KEY_PROXY,                    s->proxy );
331    tr_bencDictAddBool( d, TR_PREFS_KEY_PROXY_AUTH_ENABLED,       s->isProxyAuthEnabled );
332    tr_bencDictAddBool( d, TR_PREFS_KEY_PROXY_ENABLED,            s->isProxyEnabled );
333    tr_bencDictAddStr ( d, TR_PREFS_KEY_PROXY_PASSWORD,           s->proxyPassword );
334    tr_bencDictAddInt ( d, TR_PREFS_KEY_PROXY_PORT,               s->proxyPort );
335    tr_bencDictAddInt ( d, TR_PREFS_KEY_PROXY_TYPE,               s->proxyType );
336    tr_bencDictAddStr ( d, TR_PREFS_KEY_PROXY_USERNAME,           s->proxyUsername );
337    tr_bencDictAddReal( d, TR_PREFS_KEY_RATIO,                    s->desiredRatio );
338    tr_bencDictAddBool( d, TR_PREFS_KEY_RATIO_ENABLED,            s->isRatioLimited );
339    tr_bencDictAddBool( d, TR_PREFS_KEY_RENAME_PARTIAL_FILES,     tr_sessionIsIncompleteFileNamingEnabled( s ) );
340    tr_bencDictAddBool( d, TR_PREFS_KEY_RPC_AUTH_REQUIRED,        tr_sessionIsRPCPasswordEnabled( s ) );
341    tr_bencDictAddStr ( d, TR_PREFS_KEY_RPC_BIND_ADDRESS,         tr_sessionGetRPCBindAddress( s ) );
342    tr_bencDictAddBool( d, TR_PREFS_KEY_RPC_ENABLED,              tr_sessionIsRPCEnabled( s ) );
343    tr_bencDictAddStr ( d, TR_PREFS_KEY_RPC_PASSWORD,             tr_sessionGetRPCPassword( s ) );
344    tr_bencDictAddInt ( d, TR_PREFS_KEY_RPC_PORT,                 tr_sessionGetRPCPort( s ) );
345    tr_bencDictAddStr ( d, TR_PREFS_KEY_RPC_USERNAME,             tr_sessionGetRPCUsername( s ) );
346    tr_bencDictAddStr ( d, TR_PREFS_KEY_RPC_WHITELIST,            tr_sessionGetRPCWhitelist( s ) );
347    tr_bencDictAddBool( d, TR_PREFS_KEY_RPC_WHITELIST_ENABLED,    tr_sessionGetRPCWhitelistEnabled( s ) );
348    tr_bencDictAddBool( d, TR_PREFS_KEY_ALT_SPEED_ENABLED,        tr_sessionUsesAltSpeed( s ) );
349    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_UP,             tr_sessionGetAltSpeed( s, TR_UP ) );
350    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_DOWN,           tr_sessionGetAltSpeed( s, TR_DOWN ) );
351    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN,     tr_sessionGetAltSpeedBegin( s ) );
352    tr_bencDictAddBool( d, TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED,   tr_sessionUsesAltSpeedTime( s ) );
353    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_END,       tr_sessionGetAltSpeedEnd( s ) );
354    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_DAY,       tr_sessionGetAltSpeedDay( s ) );
355    tr_bencDictAddInt ( d, TR_PREFS_KEY_USPEED,                   tr_sessionGetSpeedLimit( s, TR_UP ) );
356    tr_bencDictAddBool( d, TR_PREFS_KEY_USPEED_ENABLED,           tr_sessionIsSpeedLimited( s, TR_UP ) );
357    tr_bencDictAddInt ( d, TR_PREFS_KEY_UMASK,                    s->umask );
358    tr_bencDictAddInt ( d, TR_PREFS_KEY_UPLOAD_SLOTS_PER_TORRENT, s->uploadSlotsPerTorrent );
359    tr_bencDictAddStr ( d, TR_PREFS_KEY_BIND_ADDRESS_IPV4,        tr_ntop_non_ts( &s->public_ipv4->addr ) );
360    tr_bencDictAddStr ( d, TR_PREFS_KEY_BIND_ADDRESS_IPV6,        tr_ntop_non_ts( &s->public_ipv6->addr ) );
361    tr_bencDictAddBool( d, TR_PREFS_KEY_START,                    !tr_sessionGetPaused( s ) );
362    tr_bencDictAddBool( d, TR_PREFS_KEY_TRASH_ORIGINAL,           tr_sessionGetDeleteSource( s ) );
363}
364
365tr_bool
366tr_sessionLoadSettings( tr_benc * d, const char * configDir, const char * appName )
367{
368    int err = 0;
369    char * filename;
370    tr_benc fileSettings;
371    tr_benc sessionDefaults;
372    tr_benc tmp;
373    tr_bool success = FALSE;
374
375    assert( tr_bencIsDict( d ) );
376
377    /* initializing the defaults: caller may have passed in some app-level defaults.
378     * preserve those and use the session defaults to fill in any missing gaps. */
379    tr_bencInitDict( &sessionDefaults, 0 );
380    tr_sessionGetDefaultSettings( configDir, &sessionDefaults );
381    tr_bencMergeDicts( &sessionDefaults, d );
382    tmp = *d; *d = sessionDefaults; sessionDefaults = tmp;
383
384    /* if caller didn't specify a config dir, use the default */
385    if( !configDir || !*configDir )
386        configDir = tr_getDefaultConfigDir( appName );
387
388    /* file settings override the defaults */
389    filename = tr_buildPath( configDir, "settings.json", NULL );
390    err = tr_bencLoadFile( &fileSettings, TR_FMT_JSON, filename );
391    if( !err ) {
392        tr_bencMergeDicts( d, &fileSettings );
393        tr_bencFree( &fileSettings );
394    }
395
396    /* cleanup */
397    tr_bencFree( &sessionDefaults );
398    tr_free( filename );
399    success = (err==0) || (err==ENOENT);
400    return success;
401}
402
403void
404tr_sessionSaveSettings( tr_session    * session,
405                        const char    * configDir,
406                        const tr_benc * clientSettings )
407{
408    tr_benc settings;
409    char * filename = tr_buildPath( configDir, "settings.json", NULL );
410
411    assert( tr_bencIsDict( clientSettings ) );
412
413    tr_bencInitDict( &settings, 0 );
414
415    /* the existing file settings are the fallback values */
416    {
417        tr_benc fileSettings;
418        const int err = tr_bencLoadFile( &fileSettings, TR_FMT_JSON, filename );
419        if( !err )
420        {
421            tr_bencMergeDicts( &settings, &fileSettings );
422            tr_bencFree( &fileSettings );
423        }
424    }
425
426    /* the client's settings override the file settings */
427    tr_bencMergeDicts( &settings, clientSettings );
428
429    /* the session's true values override the file & client settings */
430    {
431        tr_benc sessionSettings;
432        tr_bencInitDict( &sessionSettings, 0 );
433        tr_sessionGetSettings( session, &sessionSettings );
434        tr_bencMergeDicts( &settings, &sessionSettings );
435        tr_bencFree( &sessionSettings );
436    }
437
438    /* save the result */
439    tr_bencToFile( &settings, TR_FMT_JSON, filename );
440
441    /* cleanup */
442    tr_free( filename );
443    tr_bencFree( &settings );
444}
445
446/***
447****
448***/
449
450/**
451 * Periodically save the .resume files of any torrents whose
452 * status has recently changed.  This prevents loss of metadata
453 * in the case of a crash, unclean shutdown, clumsy user, etc.
454 */
455static void
456onSaveTimer( int foo UNUSED, short bar UNUSED, void * vsession )
457{
458    tr_torrent * tor = NULL;
459    tr_session * session = vsession;
460
461    while(( tor = tr_torrentNext( session, tor )))
462        tr_torrentSave( tor );
463
464    tr_statsSaveDirty( session );
465
466    tr_timerAdd( session->saveTimer, SAVE_INTERVAL_SECS, 0 );
467}
468
469/***
470****
471***/
472
473static void tr_sessionInitImpl( void * );
474
475struct init_data
476{
477    tr_session  * session;
478    const char  * configDir;
479    tr_bool       done;
480    tr_bool       messageQueuingEnabled;
481    tr_benc     * clientSettings;
482};
483
484tr_session *
485tr_sessionInit( const char  * tag,
486                const char  * configDir,
487                tr_bool       messageQueuingEnabled,
488                tr_benc     * clientSettings )
489{
490    int64_t i;
491    tr_session * session;
492    struct init_data data;
493
494    tr_msgInit( );
495
496    assert( tr_bencIsDict( clientSettings ) );
497
498    /* initialize the bare skeleton of the session object */
499    session = tr_new0( tr_session, 1 );
500    session->bandwidth = tr_bandwidthNew( session, NULL );
501    session->lock = tr_lockNew( );
502    session->tag = tr_strdup( tag );
503    session->magicNumber = SESSION_MAGIC_NUMBER;
504    session->buffer = tr_valloc( SESSION_BUFFER_SIZE );
505    tr_bencInitList( &session->removedTorrents, 0 );
506
507    /* nice to start logging at the very beginning */
508    if( tr_bencDictFindInt( clientSettings, TR_PREFS_KEY_MSGLEVEL, &i ) )
509        tr_setMessageLevel( i );
510
511    /* start the libtransmission thread */
512    tr_netInit( ); /* must go before tr_eventInit */
513    tr_eventInit( session );
514    assert( session->events != NULL );
515
516    /* run the rest in the libtransmission thread */
517    data.done = FALSE;
518    data.session = session;
519    data.configDir = configDir;
520    data.messageQueuingEnabled = messageQueuingEnabled;
521    data.clientSettings = clientSettings;
522    tr_runInEventThread( session, tr_sessionInitImpl, &data );
523    while( !data.done )
524        tr_wait_msec( 100 );
525
526    return session;
527}
528
529static void turtleCheckClock( tr_session * s, struct tr_turtle_info * t );
530
531static void
532onNowTimer( int foo UNUSED, short bar UNUSED, void * vsession )
533{
534    int usec;
535    const int min = 100;
536    const int max = 999999;
537    struct timeval tv;
538    tr_session * session = vsession;
539
540    assert( tr_isSession( session ) );
541    assert( session->nowTimer != NULL );
542
543    /* schedule the next timer for right after the next second begins */
544    gettimeofday( &tv, NULL );
545    usec = 1000000 - tv.tv_usec;
546    if( usec > max ) usec = max;
547    if( usec < min ) usec = min;
548    tr_timerAdd( session->nowTimer, 0, usec );
549    /* fprintf( stderr, "time %zu sec, %zu microsec\n", (size_t)tr_time(), (size_t)tv.tv_usec ); */
550
551    /* tr_session things to do once per second */
552    tr_timeUpdate( tv.tv_sec );
553    if( session->turtle.isClockEnabled )
554        turtleCheckClock( session, &session->turtle );
555}
556
557static void loadBlocklists( tr_session * session );
558
559static void
560tr_sessionInitImpl( void * vdata )
561{
562    tr_benc settings;
563    struct init_data * data = vdata;
564    tr_benc * clientSettings = data->clientSettings;
565    tr_session * session = data->session;
566
567    assert( tr_amInEventThread( session ) );
568    assert( tr_bencIsDict( clientSettings ) );
569
570    dbgmsg( "tr_sessionInit: the session's top-level bandwidth object is %p",
571            session->bandwidth );
572
573    tr_bencInitDict( &settings, 0 );
574    tr_sessionGetDefaultSettings( data->configDir, &settings );
575    tr_bencMergeDicts( &settings, clientSettings );
576
577    session->nowTimer = tr_new0( struct event, 1 );
578    evtimer_set( session->nowTimer, onNowTimer, session );
579    onNowTimer( 0, 0, session );
580
581#ifndef WIN32
582    /* Don't exit when writing on a broken socket */
583    signal( SIGPIPE, SIG_IGN );
584#endif
585
586    tr_setMessageQueuing( data->messageQueuingEnabled );
587
588    tr_setConfigDir( session, data->configDir );
589
590    session->peerMgr = tr_peerMgrNew( session );
591
592    session->shared = tr_sharedInit( session );
593
594    /**
595    ***  Blocklist
596    **/
597
598    {
599        char * filename = tr_buildPath( session->configDir, "blocklists", NULL );
600        tr_mkdirp( filename, 0777 );
601        tr_free( filename );
602        loadBlocklists( session );
603    }
604
605    assert( tr_isSession( session ) );
606
607    session->saveTimer = tr_new0( struct event, 1 );
608    evtimer_set( session->saveTimer, onSaveTimer, session );
609    tr_timerAdd( session->saveTimer, SAVE_INTERVAL_SECS, 0 );
610
611    tr_announcerInit( session );
612
613    /* first %s is the application name
614       second %s is the version number */
615    tr_inf( _( "%s %s started" ), TR_NAME, LONG_VERSION_STRING );
616
617    tr_statsInit( session );
618
619    tr_webInit( session );
620
621    tr_sessionSet( session, &settings );
622
623    if( session->isDHTEnabled )
624    {
625        tr_dhtInit( session, &session->public_ipv4->addr );
626    }
627
628    /* cleanup */
629    tr_bencFree( &settings );
630    data->done = TRUE;
631}
632
633static void turtleBootstrap( tr_session *, struct tr_turtle_info * );
634static void setPeerPort( tr_session * session, tr_port port );
635
636static void
637sessionSetImpl( void * vdata )
638{
639    int64_t i;
640    double  d;
641    tr_bool boolVal;
642    const char * str;
643    struct tr_bindinfo b;
644    struct init_data * data = vdata;
645    tr_session * session = data->session;
646    tr_benc * settings = data->clientSettings;
647    struct tr_turtle_info * turtle = &session->turtle;
648
649    assert( tr_isSession( session ) );
650    assert( tr_bencIsDict( settings ) );
651    assert( tr_amInEventThread( session ) );
652
653    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_MSGLEVEL, &i ) )
654        tr_setMessageLevel( i );
655
656    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_UMASK, &i ) ) {
657        session->umask = (mode_t)i;
658        umask( session->umask );
659    }
660
661    /* misc features */
662    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_LAZY_BITFIELD, &boolVal ) )
663        tr_sessionSetLazyBitfieldEnabled( session, boolVal );
664    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_PEER_LIMIT_TORRENT, &i ) )
665        tr_sessionSetPeerLimitPerTorrent( session, i );
666    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_PEX_ENABLED, &boolVal ) )
667        tr_sessionSetPexEnabled( session, boolVal );
668    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_DHT_ENABLED, &boolVal ) )
669        tr_sessionSetDHTEnabled( session, boolVal );
670    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_ENCRYPTION, &i ) )
671        tr_sessionSetEncryption( session, i );
672    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_PEER_SOCKET_TOS, &i ) )
673        session->peerSocketTOS = i;
674    if( tr_bencDictFindStr( settings, TR_PREFS_KEY_PEER_CONGESTION_ALGORITHM, &str ) )
675        session->peer_congestion_algorithm = tr_strdup(str);
676    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_BLOCKLIST_ENABLED, &boolVal ) )
677        tr_blocklistSetEnabled( session, boolVal );
678    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_START, &boolVal ) )
679        tr_sessionSetPaused( session, !boolVal );
680    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_TRASH_ORIGINAL, &boolVal) )
681        tr_sessionSetDeleteSource( session, boolVal );
682
683    /* files and directories */
684    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_PREALLOCATION, &i ) )
685        session->preallocationMode = i;
686    if( tr_bencDictFindStr( settings, TR_PREFS_KEY_DOWNLOAD_DIR, &str ) )
687        tr_sessionSetDownloadDir( session, str );
688    if( tr_bencDictFindStr( settings, TR_PREFS_KEY_INCOMPLETE_DIR, &str ) )
689        tr_sessionSetIncompleteDir( session, str );
690    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED, &boolVal ) )
691        tr_sessionSetIncompleteDirEnabled( session, boolVal );
692    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_RENAME_PARTIAL_FILES, &boolVal ) )
693        tr_sessionSetIncompleteFileNamingEnabled( session, boolVal );
694
695    /* proxies */
696    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_PROXY_ENABLED, &boolVal ) )
697        tr_sessionSetProxyEnabled( session, boolVal );
698    if( tr_bencDictFindStr( settings, TR_PREFS_KEY_PROXY, &str ) )
699        tr_sessionSetProxy( session, str );
700    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_PROXY_PORT, &i ) )
701        tr_sessionSetProxyPort( session, i );
702    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_PROXY_TYPE, &i ) )
703        tr_sessionSetProxyType( session, i );
704    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_PROXY_AUTH_ENABLED, &boolVal ) )
705        tr_sessionSetProxyAuthEnabled( session, boolVal );
706    if( tr_bencDictFindStr( settings, TR_PREFS_KEY_PROXY_USERNAME, &str ) )
707        tr_sessionSetProxyUsername( session, str );
708    if( tr_bencDictFindStr( settings, TR_PREFS_KEY_PROXY_PASSWORD, &str ) )
709        tr_sessionSetProxyPassword( session, str );
710
711    /* rpc server */
712    if( session->rpcServer != NULL ) /* close the old one */
713        tr_rpcClose( &session->rpcServer );
714    session->rpcServer = tr_rpcInit( session, settings );
715
716    /* public addresses */
717
718    free_incoming_peer_port( session );
719
720    str = TR_PREFS_KEY_BIND_ADDRESS_IPV4;
721    tr_bencDictFindStr( settings, TR_PREFS_KEY_BIND_ADDRESS_IPV4, &str );
722    if( !tr_pton( str, &b.addr ) || ( b.addr.type != TR_AF_INET ) )
723        b.addr = tr_inaddr_any;
724    b.socket = -1;
725    session->public_ipv4 = tr_memdup( &b, sizeof( struct tr_bindinfo ) );
726
727    str = TR_PREFS_KEY_BIND_ADDRESS_IPV6;
728    tr_bencDictFindStr( settings, TR_PREFS_KEY_BIND_ADDRESS_IPV6, &str );
729    if( !tr_pton( str, &b.addr ) || ( b.addr.type != TR_AF_INET6 ) )
730        b.addr = tr_in6addr_any;
731    b.socket = -1;
732    session->public_ipv6 = tr_memdup( &b, sizeof( struct tr_bindinfo ) );
733
734    /* incoming peer port */
735    if( tr_bencDictFindInt ( settings, TR_PREFS_KEY_PEER_PORT_RANDOM_LOW, &i ) )
736        session->randomPortLow = i;
737    if( tr_bencDictFindInt ( settings, TR_PREFS_KEY_PEER_PORT_RANDOM_HIGH, &i ) )
738        session->randomPortHigh = i;
739    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START, &boolVal ) )
740        tr_sessionSetPeerPortRandomOnStart( session, boolVal );
741    if( !tr_bencDictFindInt( settings, TR_PREFS_KEY_PEER_PORT, &i ) )
742        i = session->peerPort;
743    setPeerPort( session, boolVal ? getRandomPort( session ) : i );
744    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_PORT_FORWARDING, &boolVal ) )
745        tr_sessionSetPortForwardingEnabled( session, boolVal );
746
747    /* file and peer socket limits */
748    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, &i ) )
749        tr_fdSetPeerLimit( session, i );
750    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_OPEN_FILE_LIMIT, &i ) )
751        tr_fdSetFileLimit( session, i );
752
753    /**
754    **/
755
756    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_UPLOAD_SLOTS_PER_TORRENT, &i ) )
757        session->uploadSlotsPerTorrent = i;
758
759    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_USPEED, &i ) )
760        tr_sessionSetSpeedLimit( session, TR_UP, i );
761    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_USPEED_ENABLED, &boolVal ) )
762        tr_sessionLimitSpeed( session, TR_UP, boolVal );
763
764    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_DSPEED, &i ) )
765        tr_sessionSetSpeedLimit( session, TR_DOWN, i );
766    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_DSPEED_ENABLED, &boolVal ) )
767        tr_sessionLimitSpeed( session, TR_DOWN, boolVal );
768
769    if( tr_bencDictFindReal( settings, TR_PREFS_KEY_RATIO, &d ) )
770        tr_sessionSetRatioLimit( session, d );
771    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_RATIO_ENABLED, &boolVal ) )
772        tr_sessionSetRatioLimited( session, boolVal );
773
774    /**
775    ***  Turtle Mode
776    **/
777
778    /* update the turtle mode's fields */
779    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_ALT_SPEED_UP, &i ) )
780        turtle->speedLimit[TR_UP] = i;
781    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_ALT_SPEED_DOWN, &i ) )
782        turtle->speedLimit[TR_DOWN] = i;
783    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN, &i ) )
784        turtle->beginMinute = i;
785    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_ALT_SPEED_TIME_END, &i ) )
786        turtle->endMinute = i;
787    if( tr_bencDictFindInt( settings, TR_PREFS_KEY_ALT_SPEED_TIME_DAY, &i ) )
788        turtle->days = i;
789    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED, &boolVal ) )
790        turtle->isClockEnabled = boolVal;
791    if( tr_bencDictFindBool( settings, TR_PREFS_KEY_ALT_SPEED_ENABLED, &boolVal ) )
792        turtle->isEnabled = boolVal;
793    turtleBootstrap( session, turtle );
794
795    data->done = TRUE;
796}
797
798void
799tr_sessionSet( tr_session * session, struct tr_benc  * settings )
800{
801    struct init_data data;
802    data.done = FALSE;
803    data.session = session;
804    data.clientSettings = settings;
805
806    /* run the rest in the libtransmission thread */
807    tr_runInEventThread( session, sessionSetImpl, &data );
808    while( !data.done )
809        tr_wait_msec( 100 );
810}
811
812/***
813****
814***/
815
816void
817tr_sessionSetDownloadDir( tr_session * session, const char * dir )
818{
819    assert( tr_isSession( session ) );
820
821    if( session->downloadDir != dir )
822    {
823        tr_free( session->downloadDir );
824        session->downloadDir = tr_strdup( dir );
825    }
826}
827
828const char *
829tr_sessionGetDownloadDir( const tr_session * session )
830{
831    assert( tr_isSession( session ) );
832
833    return session->downloadDir;
834}
835
836/***
837****
838***/
839
840void
841tr_sessionSetIncompleteFileNamingEnabled( tr_session * session, tr_bool b )
842{
843    assert( tr_isSession( session ) );
844    assert( tr_isBool( b ) );
845
846    session->isIncompleteFileNamingEnabled = b;
847}
848
849tr_bool
850tr_sessionIsIncompleteFileNamingEnabled( const tr_session * session )
851{
852    assert( tr_isSession( session ) );
853
854    return session->isIncompleteFileNamingEnabled;
855}
856
857/***
858****
859***/
860
861
862void
863tr_sessionSetIncompleteDir( tr_session * session, const char * dir )
864{
865    assert( tr_isSession( session ) );
866
867    if( session->incompleteDir != dir )
868    {
869        tr_free( session->incompleteDir );
870
871        session->incompleteDir = tr_strdup( dir );
872    }
873}
874
875const char*
876tr_sessionGetIncompleteDir( const tr_session * session )
877{
878    assert( tr_isSession( session ) );
879
880    return session->incompleteDir;
881}
882
883void
884tr_sessionSetIncompleteDirEnabled( tr_session * session, tr_bool b )
885{
886    assert( tr_isSession( session ) );
887    assert( tr_isBool( b ) );
888
889    session->isIncompleteDirEnabled = b;
890}
891
892tr_bool
893tr_sessionIsIncompleteDirEnabled( const tr_session * session )
894{
895    assert( tr_isSession( session ) );
896
897    return session->isIncompleteDirEnabled;
898}
899
900/***
901****
902***/
903
904void*
905tr_sessionGetBuffer( tr_session * session )
906{
907    assert( tr_isSession( session ) );
908    assert( !session->bufferInUse );
909    assert( tr_amInEventThread( session ) );
910
911    session->bufferInUse = TRUE;
912    return session->buffer;
913}
914
915void
916tr_sessionReleaseBuffer( tr_session * session )
917{
918    assert( tr_isSession( session ) );
919    assert( session->bufferInUse );
920    assert( tr_amInEventThread( session ) );
921
922    session->bufferInUse = FALSE;
923}
924
925void
926tr_sessionLock( tr_session * session )
927{
928    assert( tr_isSession( session ) );
929
930    tr_lockLock( session->lock );
931}
932
933void
934tr_sessionUnlock( tr_session * session )
935{
936    assert( tr_isSession( session ) );
937
938    tr_lockUnlock( session->lock );
939}
940
941tr_bool
942tr_sessionIsLocked( const tr_session * session )
943{
944    return tr_isSession( session ) && tr_lockHave( session->lock );
945}
946
947/***********************************************************************
948 * tr_setBindPort
949 ***********************************************************************
950 *
951 **********************************************************************/
952
953static void
954peerPortChanged( void * session )
955{
956    tr_torrent * tor = NULL;
957
958    assert( tr_isSession( session ) );
959
960    close_incoming_peer_port( session );
961    open_incoming_peer_port( session );
962    tr_sharedPortChanged( session );
963
964    while(( tor = tr_torrentNext( session, tor )))
965        tr_torrentChangeMyPort( tor );
966}
967
968static void
969setPeerPort( tr_session * session, tr_port port )
970{
971    session->peerPort = port;
972
973    tr_runInEventThread( session, peerPortChanged, session );
974}
975
976void
977tr_sessionSetPeerPort( tr_session * session, tr_port port )
978{
979    assert( tr_isSession( session ) );
980
981    if( session->peerPort != port )
982    {
983        setPeerPort( session, port );
984    }
985}
986
987tr_port
988tr_sessionGetPeerPort( const tr_session * session )
989{
990    assert( tr_isSession( session ) );
991
992    return session->peerPort;
993}
994
995tr_port
996tr_sessionSetPeerPortRandom( tr_session * session )
997{
998    assert( tr_isSession( session ) );
999
1000    tr_sessionSetPeerPort( session, getRandomPort( session ) );
1001    return session->peerPort;
1002}
1003
1004void
1005tr_sessionSetPeerPortRandomOnStart( tr_session * session,
1006                                    tr_bool random )
1007{
1008    assert( tr_isSession( session ) );
1009
1010    session->isPortRandom = random;
1011}
1012
1013tr_bool
1014tr_sessionGetPeerPortRandomOnStart( tr_session * session )
1015{
1016    assert( tr_isSession( session ) );
1017
1018    return session->isPortRandom;
1019}
1020
1021tr_port_forwarding
1022tr_sessionGetPortForwarding( const tr_session * session )
1023{
1024    assert( tr_isSession( session ) );
1025
1026    return tr_sharedTraversalStatus( session->shared );
1027}
1028
1029/***
1030****
1031***/
1032
1033void
1034tr_sessionSetRatioLimited( tr_session * session, tr_bool isLimited )
1035{
1036    assert( tr_isSession( session ) );
1037
1038    session->isRatioLimited = isLimited;
1039}
1040
1041void
1042tr_sessionSetRatioLimit( tr_session * session, double desiredRatio )
1043{
1044    assert( tr_isSession( session ) );
1045
1046    session->desiredRatio = desiredRatio;
1047}
1048
1049tr_bool
1050tr_sessionIsRatioLimited( const tr_session  * session )
1051{
1052    assert( tr_isSession( session ) );
1053
1054    return session->isRatioLimited;
1055}
1056
1057double
1058tr_sessionGetRatioLimit( const tr_session * session )
1059{
1060    assert( tr_isSession( session ) );
1061
1062    return session->desiredRatio;
1063}
1064
1065/***
1066****
1067****  SPEED LIMITS
1068****
1069***/
1070
1071tr_bool
1072tr_sessionGetActiveSpeedLimit( const tr_session * session, tr_direction dir, int * setme )
1073{
1074    int isLimited = TRUE;
1075
1076    if( !tr_isSession( session ) )
1077        return FALSE;
1078
1079    if( tr_sessionUsesAltSpeed( session ) )
1080        *setme = tr_sessionGetAltSpeed( session, dir );
1081    else if( tr_sessionIsSpeedLimited( session, dir ) )
1082        *setme = tr_sessionGetSpeedLimit( session, dir );
1083    else
1084        isLimited = FALSE;
1085
1086    return isLimited;
1087}
1088
1089static void
1090updateBandwidth( tr_session * session, tr_direction dir )
1091{
1092    int limit = 0;
1093    const tr_bool isLimited = tr_sessionGetActiveSpeedLimit( session, dir, &limit );
1094    const tr_bool zeroCase = isLimited && !limit;
1095
1096    tr_bandwidthSetLimited( session->bandwidth, dir, isLimited && !zeroCase );
1097
1098    tr_bandwidthSetDesiredSpeed( session->bandwidth, dir, limit );
1099}
1100
1101enum
1102{
1103    MINUTES_PER_HOUR = 60,
1104    MINUTES_PER_DAY = MINUTES_PER_HOUR * 24,
1105    MINUTES_PER_WEEK = MINUTES_PER_DAY * 7
1106};
1107
1108static void
1109turtleUpdateTable( struct tr_turtle_info * t )
1110{
1111    int day;
1112    tr_bitfield * b = &t->minutes;
1113
1114    tr_bitfieldClear( b );
1115
1116    for( day=0; day<7; ++day )
1117    {
1118        if( t->days & (1<<day) )
1119        {
1120            int i;
1121            const time_t begin = t->beginMinute;
1122            time_t end = t->endMinute;
1123
1124            if( end <= begin )
1125                end += MINUTES_PER_DAY;
1126
1127            for( i=begin; i<end; ++i )
1128                tr_bitfieldAdd( b, (i+day*MINUTES_PER_DAY) % MINUTES_PER_WEEK );
1129        }
1130    }
1131}
1132
1133static void
1134altSpeedToggled( void * vsession )
1135{
1136    tr_session * session = vsession;
1137    struct tr_turtle_info * t = &session->turtle;
1138
1139    assert( tr_isSession( session ) );
1140
1141    updateBandwidth( session, TR_UP );
1142    updateBandwidth( session, TR_DOWN );
1143
1144    if( t->callback != NULL )
1145        (*t->callback)( session, t->isEnabled, t->changedByUser, t->callbackUserData );
1146}
1147
1148static void
1149useAltSpeed( tr_session * s, struct tr_turtle_info * t,
1150             tr_bool enabled, tr_bool byUser )
1151{
1152    assert( tr_isSession( s ) );
1153    assert( t != NULL );
1154    assert( tr_isBool( enabled ) );
1155    assert( tr_isBool( byUser ) );
1156
1157    if( t->isEnabled != enabled )
1158    {
1159        t->isEnabled = enabled;
1160        t->changedByUser = byUser;
1161        tr_runInEventThread( s, altSpeedToggled, s );
1162    }
1163}
1164
1165/**
1166 * @param enabled whether turtle should be on/off according to the scheduler
1167 * @param changed whether that's different from the previous minute
1168 */
1169static void
1170testTurtleTime( const struct tr_turtle_info * t,
1171                tr_bool * enabled,
1172                tr_bool * changed )
1173{
1174    tr_bool e;
1175    struct tm tm;
1176    size_t minute_of_the_week;
1177    const time_t now = tr_time( );
1178
1179    tr_localtime_r( &now, &tm );
1180
1181    minute_of_the_week = tm.tm_wday * MINUTES_PER_DAY
1182                       + tm.tm_hour * MINUTES_PER_HOUR
1183                       + tm.tm_min;
1184    if( minute_of_the_week >= MINUTES_PER_WEEK ) /* leap minutes? */
1185        minute_of_the_week = MINUTES_PER_WEEK - 1;
1186
1187    e = tr_bitfieldHasFast( &t->minutes, minute_of_the_week );
1188    if( enabled != NULL )
1189        *enabled = e;
1190
1191    if( changed != NULL )
1192    {
1193        const size_t prev = minute_of_the_week > 0 ? minute_of_the_week - 1
1194                                                   : MINUTES_PER_WEEK - 1;
1195        *changed = e != tr_bitfieldHasFast( &t->minutes, prev );
1196    }
1197}
1198
1199static void
1200turtleCheckClock( tr_session * s, struct tr_turtle_info * t )
1201{
1202    tr_bool enabled;
1203    tr_bool changed;
1204
1205    assert( t->isClockEnabled );
1206
1207    testTurtleTime( t, &enabled, &changed );
1208
1209    if( changed )
1210    {
1211        tr_inf( "Time to turn %s turtle mode!", (enabled?"on":"off") );
1212        useAltSpeed( s, t, enabled, FALSE );
1213    }
1214}
1215
1216/* Called after the turtle's fields are loaded from an outside source.
1217 * It initializes the implementation fields
1218 * and turns on turtle mode if the clock settings say to. */
1219static void
1220turtleBootstrap( tr_session * session, struct tr_turtle_info * turtle )
1221{
1222    turtle->changedByUser = FALSE;
1223
1224    tr_bitfieldConstruct( &turtle->minutes, MINUTES_PER_WEEK );
1225
1226    turtleUpdateTable( turtle );
1227
1228    if( turtle->isClockEnabled )
1229        testTurtleTime( turtle, &turtle->isEnabled, NULL );
1230
1231    altSpeedToggled( session );
1232}
1233
1234/***
1235****  Primary session speed limits
1236***/
1237
1238void
1239tr_sessionSetSpeedLimit( tr_session * s, tr_direction d, int KB_s )
1240{
1241    assert( tr_isSession( s ) );
1242    assert( tr_isDirection( d ) );
1243    assert( KB_s >= 0 );
1244
1245    s->speedLimit[d] = KB_s;
1246
1247    updateBandwidth( s, d );
1248}
1249
1250int
1251tr_sessionGetSpeedLimit( const tr_session * s, tr_direction d )
1252{
1253    assert( tr_isSession( s ) );
1254    assert( tr_isDirection( d ) );
1255
1256    return s->speedLimit[d];
1257}
1258
1259void
1260tr_sessionLimitSpeed( tr_session * s, tr_direction d, tr_bool b )
1261{
1262    assert( tr_isSession( s ) );
1263    assert( tr_isDirection( d ) );
1264    assert( tr_isBool( b ) );
1265
1266    s->speedLimitEnabled[d] = b;
1267
1268    updateBandwidth( s, d );
1269}
1270
1271tr_bool
1272tr_sessionIsSpeedLimited( const tr_session * s, tr_direction d )
1273{
1274    assert( tr_isSession( s ) );
1275    assert( tr_isDirection( d ) );
1276
1277    return s->speedLimitEnabled[d];
1278}
1279
1280/***
1281****  Alternative speed limits that are used during scheduled times
1282***/
1283
1284void
1285tr_sessionSetAltSpeed( tr_session * s, tr_direction d, int KB_s )
1286{
1287    assert( tr_isSession( s ) );
1288    assert( tr_isDirection( d ) );
1289    assert( KB_s >= 0 );
1290
1291    s->turtle.speedLimit[d] = KB_s;
1292
1293    updateBandwidth( s, d );
1294}
1295
1296int
1297tr_sessionGetAltSpeed( const tr_session * s, tr_direction d )
1298{
1299    assert( tr_isSession( s ) );
1300    assert( tr_isDirection( d ) );
1301
1302    return s->turtle.speedLimit[d];
1303}
1304
1305static void
1306userPokedTheClock( tr_session * s, struct tr_turtle_info * t )
1307{
1308    tr_dbg( "Refreshing the turtle mode clock due to user changes" );
1309
1310    turtleUpdateTable( t );
1311
1312    if( t->isClockEnabled )
1313    {
1314        tr_bool enabled, changed;
1315        testTurtleTime( t, &enabled, &changed );
1316        useAltSpeed( s, t, enabled, TRUE );
1317    }
1318}
1319
1320void
1321tr_sessionUseAltSpeedTime( tr_session * s, tr_bool b )
1322{
1323    struct tr_turtle_info * t = &s->turtle;
1324
1325    assert( tr_isSession( s ) );
1326    assert( tr_isBool ( b ) );
1327
1328    if( t->isClockEnabled != b ) {
1329        t->isClockEnabled = b;
1330        userPokedTheClock( s, t );
1331    }
1332}
1333
1334tr_bool
1335tr_sessionUsesAltSpeedTime( const tr_session * s )
1336{
1337    assert( tr_isSession( s ) );
1338
1339    return s->turtle.isClockEnabled;
1340}
1341
1342void
1343tr_sessionSetAltSpeedBegin( tr_session * s, int minute )
1344{
1345    assert( tr_isSession( s ) );
1346    assert( 0<=minute && minute<(60*24) );
1347
1348    if( s->turtle.beginMinute != minute ) {
1349        s->turtle.beginMinute = minute;
1350        userPokedTheClock( s, &s->turtle );
1351    }
1352}
1353
1354int
1355tr_sessionGetAltSpeedBegin( const tr_session * s )
1356{
1357    assert( tr_isSession( s ) );
1358
1359    return s->turtle.beginMinute;
1360}
1361
1362void
1363tr_sessionSetAltSpeedEnd( tr_session * s, int minute )
1364{
1365    assert( tr_isSession( s ) );
1366    assert( 0<=minute && minute<(60*24) );
1367
1368    if( s->turtle.endMinute != minute ) {
1369        s->turtle.endMinute = minute;
1370        userPokedTheClock( s, &s->turtle );
1371    }
1372}
1373
1374int
1375tr_sessionGetAltSpeedEnd( const tr_session * s )
1376{
1377    assert( tr_isSession( s ) );
1378
1379    return s->turtle.endMinute;
1380}
1381
1382void
1383tr_sessionSetAltSpeedDay( tr_session * s, tr_sched_day days )
1384{
1385    assert( tr_isSession( s ) );
1386
1387    if( s->turtle.days != days ) {
1388        s->turtle.days = days;
1389        userPokedTheClock( s, &s->turtle );
1390    }
1391}
1392
1393tr_sched_day
1394tr_sessionGetAltSpeedDay( const tr_session * s )
1395{
1396    assert( tr_isSession( s ) );
1397
1398    return s->turtle.days;
1399}
1400
1401void
1402tr_sessionUseAltSpeed( tr_session * session, tr_bool enabled )
1403{
1404    useAltSpeed( session, &session->turtle, enabled, TRUE );
1405}
1406
1407tr_bool
1408tr_sessionUsesAltSpeed( const tr_session * s )
1409{
1410    assert( tr_isSession( s ) );
1411
1412    return s->turtle.isEnabled;
1413}
1414
1415void
1416tr_sessionSetAltSpeedFunc( tr_session       * session,
1417                           tr_altSpeedFunc    func,
1418                           void             * userData )
1419{
1420    assert( tr_isSession( session ) );
1421
1422    session->turtle.callback = func;
1423    session->turtle.callbackUserData = userData;
1424}
1425
1426void
1427tr_sessionClearAltSpeedFunc( tr_session * session )
1428{
1429    tr_sessionSetAltSpeedFunc( session, NULL, NULL );
1430}
1431
1432/***
1433****
1434***/
1435
1436void
1437tr_sessionSetPeerLimit( tr_session * session, uint16_t maxGlobalPeers )
1438{
1439    assert( tr_isSession( session ) );
1440
1441    tr_fdSetPeerLimit( session, maxGlobalPeers );
1442}
1443
1444uint16_t
1445tr_sessionGetPeerLimit( const tr_session * session )
1446{
1447    assert( tr_isSession( session ) );
1448
1449    return tr_fdGetPeerLimit( session );
1450}
1451
1452void
1453tr_sessionSetPeerLimitPerTorrent( tr_session  * session, uint16_t n )
1454{
1455    assert( tr_isSession( session ) );
1456
1457    session->peerLimitPerTorrent = n;
1458}
1459
1460uint16_t
1461tr_sessionGetPeerLimitPerTorrent( const tr_session * session )
1462{
1463    assert( tr_isSession( session ) );
1464
1465    return session->peerLimitPerTorrent;
1466}
1467
1468/***
1469****
1470***/
1471
1472void
1473tr_sessionSetPaused( tr_session * session, tr_bool isPaused )
1474{
1475    assert( tr_isSession( session ) );
1476
1477    session->pauseAddedTorrent = isPaused;
1478}
1479
1480tr_bool
1481tr_sessionGetPaused( const tr_session * session )
1482{
1483    assert( tr_isSession( session ) );
1484
1485    return session->pauseAddedTorrent;
1486}
1487
1488void
1489tr_sessionSetDeleteSource( tr_session * session, tr_bool deleteSource )
1490{
1491    assert( tr_isSession( session ) );
1492
1493    session->deleteSourceTorrent = deleteSource;
1494}
1495
1496tr_bool
1497tr_sessionGetDeleteSource( const tr_session * session )
1498{
1499    assert( tr_isSession( session ) );
1500
1501    return session->deleteSourceTorrent;
1502}
1503
1504/***
1505****
1506***/
1507
1508double
1509tr_sessionGetPieceSpeed( const tr_session * session, tr_direction dir )
1510{
1511    return tr_isSession( session ) ? tr_bandwidthGetPieceSpeed( session->bandwidth, 0, dir ) : 0.0;
1512}
1513
1514double
1515tr_sessionGetRawSpeed( const tr_session * session, tr_direction dir )
1516{
1517    return tr_isSession( session ) ? tr_bandwidthGetRawSpeed( session->bandwidth, 0, dir ) : 0.0;
1518}
1519
1520int
1521tr_sessionCountTorrents( const tr_session * session )
1522{
1523    return tr_isSession( session ) ? session->torrentCount : 0;
1524}
1525
1526static int
1527compareTorrentByCur( const void * va, const void * vb )
1528{
1529    const tr_torrent * a = *(const tr_torrent**)va;
1530    const tr_torrent * b = *(const tr_torrent**)vb;
1531    const uint64_t     aCur = a->downloadedCur + a->uploadedCur;
1532    const uint64_t     bCur = b->downloadedCur + b->uploadedCur;
1533
1534    if( aCur != bCur )
1535        return aCur > bCur ? -1 : 1; /* close the biggest torrents first */
1536
1537    return 0;
1538}
1539
1540static void closeBlocklists( tr_session * );
1541
1542static void
1543sessionCloseImpl( void * vsession )
1544{
1545    tr_session *  session = vsession;
1546    tr_torrent *  tor;
1547    int           i, n;
1548    tr_torrent ** torrents;
1549
1550    assert( tr_isSession( session ) );
1551
1552    free_incoming_peer_port( session );
1553
1554    if( session->isDHTEnabled )
1555        tr_dhtUninit( session );
1556
1557    evtimer_del( session->saveTimer );
1558    tr_free( session->saveTimer );
1559    session->saveTimer = NULL;
1560
1561    evtimer_del( session->nowTimer );
1562    tr_free( session->nowTimer );
1563    session->nowTimer = NULL;
1564
1565    tr_verifyClose( session );
1566    tr_sharedClose( session );
1567    tr_rpcClose( &session->rpcServer );
1568
1569    /* close the torrents.  get the most active ones first so that
1570     * if we can't get them all closed in a reasonable amount of time,
1571     * at least we get the most important ones first. */
1572    tor = NULL;
1573    n = session->torrentCount;
1574    torrents = tr_new( tr_torrent *, session->torrentCount );
1575    for( i = 0; i < n; ++i )
1576        torrents[i] = tor = tr_torrentNext( session, tor );
1577    qsort( torrents, n, sizeof( tr_torrent* ), compareTorrentByCur );
1578    for( i = 0; i < n; ++i )
1579        tr_torrentFree( torrents[i] );
1580    tr_free( torrents );
1581
1582    tr_announcerClose( session );
1583    tr_statsClose( session );
1584    tr_peerMgrFree( session->peerMgr );
1585    tr_webClose( session, TR_WEB_CLOSE_WHEN_IDLE );
1586
1587    closeBlocklists( session );
1588
1589    tr_fdClose( session );
1590
1591    session->isClosed = TRUE;
1592}
1593
1594static int
1595deadlineReached( const time_t deadline )
1596{
1597    return time( NULL ) >= deadline;
1598}
1599
1600#define SHUTDOWN_MAX_SECONDS 20
1601
1602void
1603tr_sessionClose( tr_session * session )
1604{
1605    const time_t deadline = time( NULL ) + SHUTDOWN_MAX_SECONDS;
1606
1607    assert( tr_isSession( session ) );
1608
1609    dbgmsg( "shutting down transmission session %p", session );
1610
1611    /* close the session */
1612    tr_runInEventThread( session, sessionCloseImpl, session );
1613    while( !session->isClosed && !deadlineReached( deadline ) )
1614    {
1615        dbgmsg( "waiting for the libtransmission thread to finish" );
1616        tr_wait_msec( 100 );
1617    }
1618
1619    /* "shared" and "tracker" have live sockets,
1620     * so we need to keep the transmission thread alive
1621     * for a bit while they tell the router & tracker
1622     * that we're closing now */
1623    while( ( session->shared || session->web || session->announcer )
1624           && !deadlineReached( deadline ) )
1625    {
1626        dbgmsg( "waiting on port unmap (%p) or announcer (%p)",
1627                session->shared, session->announcer );
1628        tr_wait_msec( 100 );
1629    }
1630
1631    tr_webClose( session, TR_WEB_CLOSE_NOW );
1632
1633    /* close the libtransmission thread */
1634    tr_eventClose( session );
1635    while( session->events != NULL )
1636    {
1637        static tr_bool forced = FALSE;
1638        dbgmsg( "waiting for libtransmission thread to finish" );
1639        tr_wait_msec( 500 );
1640        if( deadlineReached( deadline ) && !forced )
1641        {
1642            event_loopbreak( );
1643            forced = TRUE;
1644
1645            if( time( NULL ) >= deadline + 3 )
1646                break;
1647        }
1648    }
1649
1650    /* free the session memory */
1651    tr_bencFree( &session->removedTorrents );
1652    tr_bandwidthFree( session->bandwidth );
1653    tr_bitfieldDestruct( &session->turtle.minutes );
1654    tr_lockFree( session->lock );
1655    if( session->metainfoLookup ) {
1656        tr_bencFree( session->metainfoLookup );
1657        tr_free( session->metainfoLookup );
1658    }
1659    tr_free( session->buffer );
1660    tr_free( session->tag );
1661    tr_free( session->configDir );
1662    tr_free( session->resumeDir );
1663    tr_free( session->torrentDir );
1664    tr_free( session->downloadDir );
1665    tr_free( session->incompleteDir );
1666    tr_free( session->proxy );
1667    tr_free( session->proxyUsername );
1668    tr_free( session->proxyPassword );
1669    tr_free( session->peer_congestion_algorithm );
1670    tr_free( session );
1671}
1672
1673tr_torrent **
1674tr_sessionLoadTorrents( tr_session * session,
1675                        tr_ctor    * ctor,
1676                        int        * setmeCount )
1677{
1678    int           i, n = 0;
1679    struct stat   sb;
1680    DIR *         odir = NULL;
1681    const char *  dirname = tr_getTorrentDir( session );
1682    tr_torrent ** torrents;
1683    tr_list *     l = NULL, *list = NULL;
1684
1685    assert( tr_isSession( session ) );
1686
1687    tr_ctorSetSave( ctor, FALSE ); /* since we already have them */
1688
1689    if( !stat( dirname, &sb )
1690      && S_ISDIR( sb.st_mode )
1691      && ( ( odir = opendir ( dirname ) ) ) )
1692    {
1693        struct dirent *d;
1694        for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
1695        {
1696            if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles, ., and ..
1697                                                     */
1698            {
1699                tr_torrent * tor;
1700                char * path = tr_buildPath( dirname, d->d_name, NULL );
1701                tr_ctorSetMetainfoFromFile( ctor, path );
1702                if(( tor = tr_torrentNew( ctor, NULL )))
1703                {
1704                    tr_list_append( &list, tor );
1705                    ++n;
1706                }
1707                tr_free( path );
1708            }
1709        }
1710        closedir( odir );
1711    }
1712
1713    torrents = tr_new( tr_torrent *, n );
1714    for( i = 0, l = list; l != NULL; l = l->next )
1715        torrents[i++] = (tr_torrent*) l->data;
1716    assert( i == n );
1717
1718    tr_list_free( &list, NULL );
1719
1720    if( n )
1721        tr_inf( _( "Loaded %d torrents" ), n );
1722
1723    if( setmeCount )
1724        *setmeCount = n;
1725    return torrents;
1726}
1727
1728/***
1729****
1730***/
1731
1732void
1733tr_sessionSetPexEnabled( tr_session * session,
1734                         tr_bool      enabled )
1735{
1736    assert( tr_isSession( session ) );
1737
1738    session->isPexEnabled = enabled != 0;
1739}
1740
1741tr_bool
1742tr_sessionIsPexEnabled( const tr_session * session )
1743{
1744    assert( tr_isSession( session ) );
1745
1746    return session->isPexEnabled;
1747}
1748
1749tr_bool
1750tr_sessionAllowsDHT( const tr_session * session UNUSED )
1751{
1752    return tr_sessionIsDHTEnabled( session );
1753}
1754
1755tr_bool
1756tr_sessionIsDHTEnabled( const tr_session * session )
1757{
1758    assert( tr_isSession( session ) );
1759
1760    return session->isDHTEnabled;
1761}
1762
1763static void
1764toggleDHTImpl(  void * data )
1765{
1766    tr_session * session = data;
1767    assert( tr_isSession( session ) );
1768
1769    if( session->isDHTEnabled )
1770        tr_dhtUninit( session );
1771
1772    session->isDHTEnabled = !session->isDHTEnabled;
1773
1774    if( session->isDHTEnabled )
1775        tr_dhtInit( session, &session->public_ipv4->addr );
1776}
1777
1778void
1779tr_sessionSetDHTEnabled( tr_session * session, tr_bool enabled )
1780{
1781    assert( tr_isSession( session ) );
1782    assert( tr_isBool( enabled ) );
1783
1784    if( ( enabled != 0 ) != ( session->isDHTEnabled != 0 ) )
1785        tr_runInEventThread( session, toggleDHTImpl, session );
1786}
1787
1788/***
1789****
1790***/
1791
1792void
1793tr_sessionSetLazyBitfieldEnabled( tr_session * session,
1794                                  tr_bool      enabled )
1795{
1796    assert( tr_isSession( session ) );
1797
1798    session->useLazyBitfield = enabled != 0;
1799}
1800
1801tr_bool
1802tr_sessionIsLazyBitfieldEnabled( const tr_session * session )
1803{
1804    assert( tr_isSession( session ) );
1805
1806    return session->useLazyBitfield;
1807}
1808
1809/***
1810****
1811***/
1812
1813struct port_forwarding_data
1814{
1815    tr_bool enabled;
1816    struct tr_shared * shared;
1817};
1818
1819static void
1820setPortForwardingEnabled( void * vdata )
1821{
1822    struct port_forwarding_data * data = vdata;
1823    tr_sharedTraversalEnable( data->shared, data->enabled );
1824    tr_free( data );
1825}
1826
1827void
1828tr_sessionSetPortForwardingEnabled( tr_session  * session, tr_bool enabled )
1829{
1830    struct port_forwarding_data * d;
1831    d = tr_new0( struct port_forwarding_data, 1 );
1832    d->shared = session->shared;
1833    d->enabled = enabled;
1834    tr_runInEventThread( session, setPortForwardingEnabled, d );
1835}
1836
1837tr_bool
1838tr_sessionIsPortForwardingEnabled( const tr_session * session )
1839{
1840    assert( tr_isSession( session ) );
1841
1842    return tr_sharedTraversalIsEnabled( session->shared );
1843}
1844
1845/***
1846****
1847***/
1848
1849static int
1850tr_stringEndsWith( const char * str, const char * end )
1851{
1852    const size_t slen = strlen( str );
1853    const size_t elen = strlen( end );
1854
1855    return slen >= elen && !memcmp( &str[slen - elen], end, elen );
1856}
1857
1858static void
1859loadBlocklists( tr_session * session )
1860{
1861    int         binCount = 0;
1862    int         newCount = 0;
1863    struct stat sb;
1864    char      * dirname;
1865    DIR *       odir = NULL;
1866    tr_list *   list = NULL;
1867    const tr_bool   isEnabled = session->isBlocklistEnabled;
1868
1869    /* walk through the directory and find blocklists */
1870    dirname = tr_buildPath( session->configDir, "blocklists", NULL );
1871    if( !stat( dirname,
1872               &sb ) && S_ISDIR( sb.st_mode )
1873      && ( ( odir = opendir( dirname ) ) ) )
1874    {
1875        struct dirent *d;
1876        for( d = readdir( odir ); d; d = readdir( odir ) )
1877        {
1878            char * filename;
1879
1880            if( !d->d_name || d->d_name[0] == '.' ) /* skip dotfiles, ., and ..
1881                                                      */
1882                continue;
1883
1884            filename = tr_buildPath( dirname, d->d_name, NULL );
1885
1886            if( tr_stringEndsWith( filename, ".bin" ) )
1887            {
1888                /* if we don't already have this blocklist, add it */
1889                if( !tr_list_find( list, filename,
1890                                   (TrListCompareFunc)strcmp ) )
1891                {
1892                    tr_list_append( &list,
1893                                   _tr_blocklistNew( filename, isEnabled ) );
1894                    ++binCount;
1895                }
1896            }
1897            else
1898            {
1899                /* strip out the file suffix, if there is one, and add ".bin"
1900                  instead */
1901                tr_blocklist * b;
1902                const char *   dot = strrchr( d->d_name, '.' );
1903                const int      len = dot ? dot - d->d_name
1904                                         : (int)strlen( d->d_name );
1905                char         * tmp = tr_strdup_printf(
1906                                        "%s" TR_PATH_DELIMITER_STR "%*.*s.bin",
1907                                        dirname, len, len, d->d_name );
1908                b = _tr_blocklistNew( tmp, isEnabled );
1909                _tr_blocklistSetContent( b, filename );
1910                tr_list_append( &list, b );
1911                ++newCount;
1912                tr_free( tmp );
1913            }
1914
1915            tr_free( filename );
1916        }
1917
1918        closedir( odir );
1919    }
1920
1921    session->blocklists = list;
1922
1923    if( binCount )
1924        tr_dbg( "Found %d blocklists in \"%s\"", binCount, dirname );
1925    if( newCount )
1926        tr_dbg( "Found %d new blocklists in \"%s\"", newCount, dirname );
1927
1928    tr_free( dirname );
1929}
1930
1931static void
1932closeBlocklists( tr_session * session )
1933{
1934    tr_list_free( &session->blocklists,
1935                  (TrListForeachFunc)_tr_blocklistFree );
1936}
1937
1938void
1939tr_sessionReloadBlocklists( tr_session * session )
1940{
1941    closeBlocklists( session );
1942    loadBlocklists( session );
1943}
1944
1945int
1946tr_blocklistGetRuleCount( const tr_session * session )
1947{
1948    int       n = 0;
1949    tr_list * l;
1950
1951    assert( tr_isSession( session ) );
1952
1953    for( l = session->blocklists; l; l = l->next )
1954        n += _tr_blocklistGetRuleCount( l->data );
1955    return n;
1956}
1957
1958tr_bool
1959tr_blocklistIsEnabled( const tr_session * session )
1960{
1961    assert( tr_isSession( session ) );
1962
1963    return session->isBlocklistEnabled;
1964}
1965
1966void
1967tr_blocklistSetEnabled( tr_session * session,
1968                        tr_bool      isEnabled )
1969{
1970    tr_list * l;
1971
1972    assert( tr_isSession( session ) );
1973
1974    session->isBlocklistEnabled = isEnabled != 0;
1975
1976    for( l=session->blocklists; l!=NULL; l=l->next )
1977        _tr_blocklistSetEnabled( l->data, isEnabled );
1978}
1979
1980tr_bool
1981tr_blocklistExists( const tr_session * session )
1982{
1983    assert( tr_isSession( session ) );
1984
1985    return session->blocklists != NULL;
1986}
1987
1988int
1989tr_blocklistSetContent( tr_session * session,
1990                        const char * contentFilename )
1991{
1992    tr_list * l;
1993    int ruleCount;
1994    tr_blocklist * b;
1995    const char * defaultName = "level1.bin";
1996    tr_sessionLock( session );
1997
1998    for( b = NULL, l = session->blocklists; !b && l; l = l->next )
1999        if( tr_stringEndsWith( _tr_blocklistGetFilename( l->data ),
2000                               defaultName ) )
2001            b = l->data;
2002
2003    if( !b )
2004    {
2005        char * path = tr_buildPath( session->configDir, "blocklists", defaultName, NULL );
2006        b = _tr_blocklistNew( path, session->isBlocklistEnabled );
2007        tr_list_append( &session->blocklists, b );
2008        tr_free( path );
2009    }
2010
2011    ruleCount = _tr_blocklistSetContent( b, contentFilename );
2012    tr_sessionUnlock( session );
2013    return ruleCount;
2014}
2015
2016tr_bool
2017tr_sessionIsAddressBlocked( const tr_session * session,
2018                            const tr_address * addr )
2019{
2020    tr_list * l;
2021
2022    assert( tr_isSession( session ) );
2023
2024    for( l = session->blocklists; l; l = l->next )
2025        if( _tr_blocklistHasAddress( l->data, addr ) )
2026            return TRUE;
2027    return FALSE;
2028}
2029
2030/***
2031****
2032***/
2033
2034static void
2035metainfoLookupInit( tr_session * session )
2036{
2037    struct stat  sb;
2038    const char * dirname = tr_getTorrentDir( session );
2039    DIR *        odir = NULL;
2040    tr_ctor *    ctor = NULL;
2041    tr_benc * lookup;
2042    int n = 0;
2043
2044    assert( tr_isSession( session ) );
2045
2046    /* walk through the directory and find the mappings */
2047    lookup = tr_new0( tr_benc, 1 );
2048    tr_bencInitDict( lookup, 0 );
2049    ctor = tr_ctorNew( session );
2050    tr_ctorSetSave( ctor, FALSE ); /* since we already have them */
2051    if( !stat( dirname, &sb ) && S_ISDIR( sb.st_mode ) && ( ( odir = opendir( dirname ) ) ) )
2052    {
2053        struct dirent *d;
2054        while(( d = readdir( odir )))
2055        {
2056            if( d->d_name && d->d_name[0] != '.' )
2057            {
2058                tr_info inf;
2059                char * path = tr_buildPath( dirname, d->d_name, NULL );
2060                tr_ctorSetMetainfoFromFile( ctor, path );
2061                if( !tr_torrentParse( ctor, &inf ) )
2062                {
2063                    ++n;
2064                    tr_bencDictAddStr( lookup, inf.hashString, path );
2065                }
2066                tr_free( path );
2067            }
2068        }
2069        closedir( odir );
2070    }
2071    tr_ctorFree( ctor );
2072
2073    session->metainfoLookup = lookup;
2074    tr_dbg( "Found %d torrents in \"%s\"", n, dirname );
2075}
2076
2077const char*
2078tr_sessionFindTorrentFile( const tr_session * session,
2079                           const char       * hashString )
2080{
2081    const char * filename = NULL;
2082    if( !session->metainfoLookup )
2083        metainfoLookupInit( (tr_session*)session );
2084    tr_bencDictFindStr( session->metainfoLookup, hashString, &filename );
2085    return filename;
2086}
2087
2088void
2089tr_sessionSetTorrentFile( tr_session * session,
2090                          const char * hashString,
2091                          const char * filename )
2092{
2093    /* since we walk session->configDir/torrents/ to build the lookup table,
2094     * and tr_sessionSetTorrentFile() is just to tell us there's a new file
2095     * in that same directory, we don't need to do anything here if the
2096     * lookup table hasn't been built yet */
2097    if( session->metainfoLookup )
2098        tr_bencDictAddStr( session->metainfoLookup, hashString, filename );
2099}
2100
2101tr_torrent*
2102tr_torrentNext( tr_session * session,
2103                tr_torrent * tor )
2104{
2105    tr_torrent * ret;
2106
2107    assert( !session || tr_isSession( session ) );
2108
2109    if( !session )
2110        ret = NULL;
2111    else if( !tor )
2112        ret = session->torrentList;
2113    else
2114        ret = tor->next;
2115
2116    return ret;
2117}
2118
2119/***
2120****
2121***/
2122
2123void
2124tr_sessionSetRPCEnabled( tr_session * session,
2125                         tr_bool      isEnabled )
2126{
2127    assert( tr_isSession( session ) );
2128
2129    tr_rpcSetEnabled( session->rpcServer, isEnabled );
2130}
2131
2132tr_bool
2133tr_sessionIsRPCEnabled( const tr_session * session )
2134{
2135    assert( tr_isSession( session ) );
2136
2137    return tr_rpcIsEnabled( session->rpcServer );
2138}
2139
2140void
2141tr_sessionSetRPCPort( tr_session * session,
2142                      tr_port      port )
2143{
2144    assert( tr_isSession( session ) );
2145
2146    tr_rpcSetPort( session->rpcServer, port );
2147}
2148
2149tr_port
2150tr_sessionGetRPCPort( const tr_session * session )
2151{
2152    assert( tr_isSession( session ) );
2153
2154    return tr_rpcGetPort( session->rpcServer );
2155}
2156
2157void
2158tr_sessionSetRPCCallback( tr_session * session,
2159                          tr_rpc_func  func,
2160                          void *       user_data )
2161{
2162    assert( tr_isSession( session ) );
2163
2164    session->rpc_func = func;
2165    session->rpc_func_user_data = user_data;
2166}
2167
2168void
2169tr_sessionSetRPCWhitelist( tr_session * session,
2170                           const char * whitelist )
2171{
2172    assert( tr_isSession( session ) );
2173
2174    tr_rpcSetWhitelist( session->rpcServer, whitelist );
2175}
2176
2177const char*
2178tr_sessionGetRPCWhitelist( const tr_session * session )
2179{
2180    assert( tr_isSession( session ) );
2181
2182    return tr_rpcGetWhitelist( session->rpcServer );
2183}
2184
2185void
2186tr_sessionSetRPCWhitelistEnabled( tr_session * session,
2187                                  tr_bool      isEnabled )
2188{
2189    assert( tr_isSession( session ) );
2190
2191    tr_rpcSetWhitelistEnabled( session->rpcServer, isEnabled );
2192}
2193
2194tr_bool
2195tr_sessionGetRPCWhitelistEnabled( const tr_session * session )
2196{
2197    assert( tr_isSession( session ) );
2198
2199    return tr_rpcGetWhitelistEnabled( session->rpcServer );
2200}
2201
2202
2203void
2204tr_sessionSetRPCPassword( tr_session * session,
2205                          const char * password )
2206{
2207    assert( tr_isSession( session ) );
2208
2209    tr_rpcSetPassword( session->rpcServer, password );
2210}
2211
2212const char*
2213tr_sessionGetRPCPassword( const tr_session * session )
2214{
2215    assert( tr_isSession( session ) );
2216
2217    return tr_rpcGetPassword( session->rpcServer );
2218}
2219
2220void
2221tr_sessionSetRPCUsername( tr_session * session,
2222                          const char * username )
2223{
2224    assert( tr_isSession( session ) );
2225
2226    tr_rpcSetUsername( session->rpcServer, username );
2227}
2228
2229const char*
2230tr_sessionGetRPCUsername( const tr_session * session )
2231{
2232    assert( tr_isSession( session ) );
2233
2234    return tr_rpcGetUsername( session->rpcServer );
2235}
2236
2237void
2238tr_sessionSetRPCPasswordEnabled( tr_session * session,
2239                                 tr_bool      isEnabled )
2240{
2241    assert( tr_isSession( session ) );
2242
2243    tr_rpcSetPasswordEnabled( session->rpcServer, isEnabled );
2244}
2245
2246tr_bool
2247tr_sessionIsRPCPasswordEnabled( const tr_session * session )
2248{
2249    assert( tr_isSession( session ) );
2250
2251    return tr_rpcIsPasswordEnabled( session->rpcServer );
2252}
2253
2254const char *
2255tr_sessionGetRPCBindAddress( const tr_session * session )
2256{
2257    assert( tr_isSession( session ) );
2258
2259    return tr_rpcGetBindAddress( session->rpcServer );
2260}
2261
2262/***
2263****
2264***/
2265
2266tr_bool
2267tr_sessionIsProxyEnabled( const tr_session * session )
2268{
2269    assert( tr_isSession( session ) );
2270
2271    return session->isProxyEnabled;
2272}
2273
2274void
2275tr_sessionSetProxyEnabled( tr_session * session,
2276                           tr_bool      isEnabled )
2277{
2278    assert( tr_isSession( session ) );
2279    assert( tr_isBool( isEnabled ) );
2280
2281    session->isProxyEnabled = isEnabled != 0;
2282}
2283
2284tr_proxy_type
2285tr_sessionGetProxyType( const tr_session * session )
2286{
2287    assert( tr_isSession( session ) );
2288
2289    return session->proxyType;
2290}
2291
2292void
2293tr_sessionSetProxyType( tr_session *  session,
2294                        tr_proxy_type type )
2295{
2296    assert( tr_isSession( session ) );
2297
2298    session->proxyType = type;
2299}
2300
2301const char*
2302tr_sessionGetProxy( const tr_session * session )
2303{
2304    assert( tr_isSession( session ) );
2305
2306    return session->proxy;
2307}
2308
2309tr_port
2310tr_sessionGetProxyPort( const tr_session * session )
2311{
2312    assert( tr_isSession( session ) );
2313
2314    return session->proxyPort;
2315}
2316
2317void
2318tr_sessionSetProxy( tr_session * session,
2319                    const char * proxy )
2320{
2321    assert( tr_isSession( session ) );
2322
2323    if( proxy != session->proxy )
2324    {
2325        tr_free( session->proxy );
2326        session->proxy = tr_strdup( proxy );
2327    }
2328}
2329
2330void
2331tr_sessionSetProxyPort( tr_session * session,
2332                        tr_port      port )
2333{
2334    assert( tr_isSession( session ) );
2335
2336    session->proxyPort = port;
2337}
2338
2339tr_bool
2340tr_sessionIsProxyAuthEnabled( const tr_session * session )
2341{
2342    assert( tr_isSession( session ) );
2343
2344    return session->isProxyAuthEnabled;
2345}
2346
2347void
2348tr_sessionSetProxyAuthEnabled( tr_session * session,
2349                               tr_bool      isEnabled )
2350{
2351    assert( tr_isSession( session ) );
2352    assert( tr_isBool( isEnabled ) );
2353
2354    session->isProxyAuthEnabled = isEnabled != 0;
2355}
2356
2357const char*
2358tr_sessionGetProxyUsername( const tr_session * session )
2359{
2360    assert( tr_isSession( session ) );
2361
2362    return session->proxyUsername;
2363}
2364
2365void
2366tr_sessionSetProxyUsername( tr_session * session,
2367                            const char * username )
2368{
2369    assert( tr_isSession( session ) );
2370
2371    if( username != session->proxyUsername )
2372    {
2373        tr_free( session->proxyUsername );
2374        session->proxyUsername = tr_strdup( username );
2375    }
2376}
2377
2378const char*
2379tr_sessionGetProxyPassword( const tr_session * session )
2380{
2381    assert( tr_isSession( session ) );
2382
2383    return session->proxyPassword;
2384}
2385
2386void
2387tr_sessionSetProxyPassword( tr_session * session,
2388                            const char * password )
2389{
2390    assert( tr_isSession( session ) );
2391
2392    if( password != session->proxyPassword )
2393    {
2394        tr_free( session->proxyPassword );
2395        session->proxyPassword = tr_strdup( password );
2396    }
2397}
Note: See TracBrowser for help on using the repository browser.