source: trunk/libtransmission/transmission.h @ 8460

Last change on this file since 8460 was 8460, checked in by charles, 13 years ago

(trunk) add hooks for disabling/enabling DHT in gtk client, qt client, and transmission-remote

  • Property svn:keywords set to Date Rev Author Id
File size: 54.5 KB
Line 
1/******************************************************************************
2 * $Id: transmission.h 8460 2009-05-21 00:15:54Z charles $
3 *
4 * Copyright (c) 2005-2008 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/*
26 * This file defines the public API for the libtransmission library.
27 *
28 * Other headers suitable for public consumption are bencode.h
29 * and utils.h.  Most of the remaining headers in libtransmission
30 * should be considered private to libtransmission.
31 */
32#ifndef TR_TRANSMISSION_H
33#define TR_TRANSMISSION_H 1
34
35#ifdef __cplusplus
36extern "C" {
37#endif
38
39#include <inttypes.h> /* uintN_t */
40#ifndef PRId64
41 #define PRId64 "lld"
42#endif
43#ifndef PRIu64
44 #define PRIu64 "llu"
45#endif
46#ifndef PRIu32
47 #define PRIu32 "lu"
48#endif
49#include <time.h> /* time_t */
50
51#if defined( WIN32 ) && defined(_MSC_VER)
52 #define TR_INLINE __inline
53#else
54 #define TR_INLINE inline
55#endif
56
57#define SHA_DIGEST_LENGTH 20
58#define TR_INET6_ADDRSTRLEN 46
59
60#define TR_RPC_SESSION_ID_HEADER "X-Transmission-Session-Id"
61
62typedef uint32_t tr_file_index_t;
63typedef uint32_t tr_piece_index_t;
64typedef uint64_t tr_block_index_t;
65typedef uint16_t tr_port;
66typedef uint8_t tr_bool;
67
68enum
69{
70    TR_PRI_LOW    = -1,
71    TR_PRI_NORMAL =  0, /* since NORMAL is 0, memset initializes nicely */
72    TR_PRI_HIGH   =  1
73};
74
75typedef int8_t tr_priority_t;
76
77static TR_INLINE tr_bool tr_isPriority( tr_priority_t p )
78{
79    return ( p == TR_PRI_LOW )
80        || ( p == TR_PRI_NORMAL )
81        || ( p == TR_PRI_HIGH );
82}
83
84/**
85 * @brief returns Transmission's default configuration file directory.
86 *
87 * The default configuration directory is determined this way:
88 * 1. If the TRANSMISSION_HOME environmental variable is set, its value is used.
89 * 2. On Darwin, "${HOME}/Library/Application Support/${appname}" is used.
90 * 3. On Windows, "${CSIDL_APPDATA}/${appname}" is used.
91 * 4. If XDG_CONFIG_HOME is set, "${XDG_CONFIG_HOME}/${appname}" is used.
92 * 5. ${HOME}/.config/${appname}" is used as a last resort.
93 */
94const char* tr_getDefaultConfigDir( const char * appname );
95
96/**
97 * @brief returns Transmisson's default download directory.
98 *
99 * The default download directory is determined this way:
100 * 1. If the HOME environmental variable is set, "${HOME}/Downloads" is used.
101 * 2. On Windows, "${CSIDL_MYDOCUMENTS}/Downloads" is used.
102 * 3. Otherwise, getpwuid(getuid())->pw_dir + "/Downloads" is used.
103 */
104const char* tr_getDefaultDownloadDir( void );
105
106typedef struct tr_ctor tr_ctor;
107typedef struct tr_info tr_info;
108typedef struct tr_torrent tr_torrent;
109typedef struct tr_session tr_session;
110
111
112/**
113 * @addtogroup tr_session Session
114 *
115 * A libtransmission session is created by calling tr_sessionInit().
116 * libtransmission creates a thread for itself so that it can operate
117 * independently of the caller's event loop.  The session will continue
118 * until tr_sessionClose() is called.
119 *
120 * @{
121 */
122
123typedef enum
124{
125    TR_PREALLOCATE_NONE   = 0,
126    TR_PREALLOCATE_SPARSE = 1,
127    TR_PREALLOCATE_FULL   = 2
128}
129tr_preallocation_mode;
130
131static TR_INLINE tr_bool tr_isPreallocationMode( tr_preallocation_mode m  )
132{
133    return ( m == TR_PREALLOCATE_NONE )
134        || ( m == TR_PREALLOCATE_SPARSE )
135        || ( m == TR_PREALLOCATE_FULL );
136}
137
138typedef enum
139{
140    TR_PROXY_HTTP,
141    TR_PROXY_SOCKS4,
142    TR_PROXY_SOCKS5
143}
144tr_proxy_type;
145
146typedef enum
147{
148    TR_CLEAR_PREFERRED,
149    TR_ENCRYPTION_PREFERRED,
150    TR_ENCRYPTION_REQUIRED
151}
152tr_encryption_mode;
153
154static TR_INLINE tr_bool tr_isEncryptionMode( tr_encryption_mode m )
155{
156    return ( m == TR_CLEAR_PREFERRED )
157        || ( m == TR_ENCRYPTION_PREFERRED )
158        || ( m == TR_ENCRYPTION_REQUIRED );
159}
160
161
162#define TR_DEFAULT_BIND_ADDRESS_IPV4 "0.0.0.0"
163#define TR_DEFAULT_BIND_ADDRESS_IPV6 "::"
164#define TR_DEFAULT_OPEN_FILE_LIMIT_STR "32"
165#define TR_DEFAULT_RPC_WHITELIST "127.0.0.1"
166#define TR_DEFAULT_RPC_PORT_STR "9091"
167#define TR_DEFAULT_PEER_PORT_STR "51413"
168#define TR_DEFAULT_PEER_SOCKET_TOS_STR "0"
169#define TR_DEFAULT_PEER_LIMIT_GLOBAL_STR "240"
170#define TR_DEFAULT_PEER_LIMIT_TORRENT_STR "60"
171
172#define TR_PREFS_KEY_ALT_SPEED_ENABLED          "alt-speed-enabled"
173#define TR_PREFS_KEY_ALT_SPEED_UP               "alt-speed-up"
174#define TR_PREFS_KEY_ALT_SPEED_DOWN             "alt-speed-down"
175#define TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN       "alt-speed-time-begin"
176#define TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED     "alt-speed-time-enabled"
177#define TR_PREFS_KEY_ALT_SPEED_TIME_END         "alt-speed-time-end"
178#define TR_PREFS_KEY_ALT_SPEED_TIME_DAY         "alt-speed-time-day"
179#define TR_PREFS_KEY_BIND_ADDRESS_IPV4          "bind-address-ipv4"
180#define TR_PREFS_KEY_BIND_ADDRESS_IPV6          "bind-address-ipv6"
181#define TR_PREFS_KEY_BLOCKLIST_ENABLED          "blocklist-enabled"
182#define TR_PREFS_KEY_DHT_ENABLED                "dht-enabled"
183#define TR_PREFS_KEY_DOWNLOAD_DIR               "download-dir"
184#define TR_PREFS_KEY_ENCRYPTION                 "encryption"
185#define TR_PREFS_KEY_LAZY_BITFIELD              "lazy-bitfield-enabled"
186#define TR_PREFS_KEY_MSGLEVEL                   "message-level"
187#define TR_PREFS_KEY_OPEN_FILE_LIMIT            "open-file-limit"
188#define TR_PREFS_KEY_PEER_LIMIT_GLOBAL          "peer-limit-global"
189#define TR_PREFS_KEY_PEER_LIMIT_TORRENT         "peer-limit-per-torrent"
190#define TR_PREFS_KEY_PEER_PORT                  "peer-port"
191#define TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START  "peer-port-random-on-start"
192#define TR_PREFS_KEY_PEER_PORT_RANDOM_LOW       "peer-port-random-low"
193#define TR_PREFS_KEY_PEER_PORT_RANDOM_HIGH      "peer-port-random-high"
194#define TR_PREFS_KEY_PEER_SOCKET_TOS            "peer-socket-tos"
195#define TR_PREFS_KEY_PEX_ENABLED                "pex-enabled"
196#define TR_PREFS_KEY_PORT_FORWARDING            "port-forwarding-enabled"
197#define TR_PREFS_KEY_PROXY_AUTH_ENABLED         "proxy-auth-enabled"
198#define TR_PREFS_KEY_PREALLOCATION              "preallocation"
199#define TR_PREFS_KEY_PROXY_ENABLED              "proxy-enabled"
200#define TR_PREFS_KEY_PROXY_PASSWORD             "proxy-auth-password"
201#define TR_PREFS_KEY_PROXY_PORT                 "proxy-port"
202#define TR_PREFS_KEY_PROXY                      "proxy"
203#define TR_PREFS_KEY_PROXY_TYPE                 "proxy-type"
204#define TR_PREFS_KEY_PROXY_USERNAME             "proxy-auth-username"
205#define TR_PREFS_KEY_RATIO                      "ratio-limit"
206#define TR_PREFS_KEY_RATIO_ENABLED              "ratio-limit-enabled"
207#define TR_PREFS_KEY_RPC_AUTH_REQUIRED          "rpc-authentication-required"
208#define TR_PREFS_KEY_RPC_BIND_ADDRESS           "rpc-bind-address"
209#define TR_PREFS_KEY_RPC_ENABLED                "rpc-enabled"
210#define TR_PREFS_KEY_RPC_PASSWORD               "rpc-password"
211#define TR_PREFS_KEY_RPC_PORT                   "rpc-port"
212#define TR_PREFS_KEY_RPC_USERNAME               "rpc-username"
213#define TR_PREFS_KEY_RPC_WHITELIST_ENABLED      "rpc-whitelist-enabled"
214#define TR_PREFS_KEY_RPC_WHITELIST              "rpc-whitelist"
215#define TR_PREFS_KEY_DSPEED                     "speed-limit-down"
216#define TR_PREFS_KEY_DSPEED_ENABLED             "speed-limit-down-enabled"
217#define TR_PREFS_KEY_USPEED_ENABLED             "speed-limit-up-enabled"
218#define TR_PREFS_KEY_USPEED                     "speed-limit-up"
219#define TR_PREFS_KEY_UPLOAD_SLOTS_PER_TORRENT   "upload-slots-per-torrent"
220
221struct tr_benc;
222
223/**
224 * Add libtransmission's default settings to the benc dictionary.
225 *
226 * Example:
227 * @code
228 *     tr_benc settings;
229 *     int64_t i;
230 *
231 *     tr_bencInitDict( &settings, 0 );
232 *     tr_sessionGetDefaultSettings( &settings );
233 *     if( tr_bencDictFindInt( &settings, TR_PREFS_KEY_PEER_PORT, &i ) )
234 *         fprintf( stderr, "the default peer port is %d\n", (int)i );
235 *     tr_bencFree( &settings );
236 * @endcode
237 *
238 * @param initme pointer to a tr_benc dictionary
239 * @see tr_sessionLoadSettings()
240 * @see tr_sessionInit()
241 * @see tr_getDefaultConfigDir()
242 */
243void tr_sessionGetDefaultSettings( struct tr_benc * dictionary );
244
245/**
246 * Add the session's configuration settings to the benc dictionary.
247 *
248 * FIXME: this probably belongs in libtransmissionapp
249 *
250 * @param session
251 * @param dictionary
252 * @see tr_sessionGetDefaultSettings()
253 */
254void tr_sessionGetSettings( tr_session *, struct tr_benc * dictionary );
255
256/**
257 * Load settings from the configuration directory's settings.json file,
258 * using libtransmission's default settings as fallbacks for missing keys.
259 *
260 * FIXME: this belongs in libtransmissionapp
261 *
262 * @param dictionary pointer to an uninitialized tr_benc
263 * @param configDir the configuration directory to find settings.json
264 * @param appName if configDir is empty, appName is used to get the default config dir.
265 * @see tr_sessionGetDefaultSettings()
266 * @see tr_sessionInit()
267 * @see tr_sessionSaveSettings()
268 */
269void tr_sessionLoadSettings( struct tr_benc  * dictionary,
270                             const char      * configDir,
271                             const char      * appName );
272
273/**
274 * Add the session's configuration settings to the benc dictionary
275 * and save it to the configuration directory's settings.json file.
276 *
277 * FIXME: this belongs in libtransmissionapp
278 *
279 * @param session
280 * @param dictionary
281 * @see tr_sessionLoadSettings()
282 */
283void tr_sessionSaveSettings( tr_session           * session,
284                             const char           * configDir,
285                             const struct tr_benc * dictonary );
286
287/**
288 * Initialize a libtransmission session.
289 *
290 * For example, this will instantiate a session with all the default values:
291 * @code
292 *     tr_benc settings;
293 *     tr_session * session;
294 *     const char * configDir;
295 *
296 *     tr_bencInitDict( &settings, 0 );
297 *     tr_sessionGetDefaultSettings( &settings );
298 *     configDir = tr_getDefaultConfigDir( "Transmission" );
299 *     session = tr_sessionInit( "mac", configDir, true, &settings );
300 *
301 *     tr_bencFree( &settings );
302 * @encode
303 *
304 * @param tag "gtk", "macosx", "daemon", etc... this is only for pre-1.30 resume files
305 * @param configDir where Transmission will look for resume files, blocklists, etc.
306 * @param messageQueueingEnabled if false, messages will be dumped to stderr
307 * @param settings libtransmission settings
308 * @see tr_sessionGetDefaultSettings()
309 * @see tr_sessionLoadSettings()
310 * @see tr_getDefaultConfigDir()
311 */
312tr_session * tr_sessionInit( const char     * tag,
313                             const char     * configDir,
314                             tr_bool          messageQueueingEnabled,
315                             struct tr_benc * settings );
316
317/** @brief End a libtransmission session
318    @see tr_sessionInit() */
319void tr_sessionClose( tr_session * );
320
321/**
322 * @brief Return the session's configuration directory
323 *
324 * This is where transmission stores its .torrent files, .resume files,
325 * blocklists, etc.
326 */
327const char * tr_sessionGetConfigDir( const tr_session * );
328
329/**
330 * @brief Set the per-session default download folder for new torrents.
331 * @see tr_sessionInit()
332 * @see tr_sessionGetDownloadDir()
333 * @see tr_ctorSetDownloadDir()
334 */
335void tr_sessionSetDownloadDir( tr_session  * session,
336                               const char  * downloadDir );
337
338/**
339 * @brief Get the default download folder for new torrents.
340 *
341 * This is set by tr_sessionInit() or tr_sessionSetDownloadDir(),
342 * and can be overridden on a per-torrent basis by tr_ctorSetDownloadDir().
343 */
344const char * tr_sessionGetDownloadDir( const tr_session * session );
345
346/**
347 * @brief Set whether or not RPC calls are allowed in this session.
348 *
349 * @details If true, libtransmission will open a server socket to listen
350 * for incoming http RPC requests as described in docs/rpc-spec.txt.
351 *
352 * This is intially set by tr_sessionInit() and can be
353 * queried by tr_sessionIsRPCEnabled().
354 */
355void tr_sessionSetRPCEnabled( tr_session  * session,
356                              tr_bool       isEnabled );
357
358/** @brief Get whether or not RPC calls are allowed in this session.
359    @see tr_sessionInit()
360    @see tr_sessionSetRPCEnabled() */
361tr_bool tr_sessionIsRPCEnabled( const tr_session * session );
362
363/** @brief Specify which port to listen for RPC requests on.
364    @see tr_sessionInit()
365    @see tr_sessionGetRPCPort */
366void tr_sessionSetRPCPort( tr_session  * session,
367                           tr_port       port );
368
369/** @brief Get which port to listen for RPC requests on.
370    @see tr_sessionInit()
371    @see tr_sessionSetRPCPort */
372tr_port tr_sessionGetRPCPort( const tr_session * session );
373
374/**
375 * @brief Specify a whitelist for remote RPC access
376 *
377 * The whitelist is a comma-separated list of dotted-quad IP addresses
378 * to be allowed.  Wildmat notation is supported, meaning that
379 * '?' is interpreted as a single-character wildcard and
380 * '*' is interprted as a multi-character wildcard.
381 */
382void   tr_sessionSetRPCWhitelist( tr_session * session,
383                                  const char * whitelist );
384
385/** @brief get the Access Control List for allowing/denying RPC requests.
386    @return a comma-separated string of whitelist domains.
387    @see tr_sessionInit
388    @see tr_sessionSetRPCWhitelist */
389const char* tr_sessionGetRPCWhitelist( const tr_session * );
390
391void  tr_sessionSetRPCWhitelistEnabled( tr_session * session,
392                                        tr_bool      isEnabled );
393
394tr_bool tr_sessionGetRPCWhitelistEnabled( const tr_session * session );
395
396void  tr_sessionSetRPCPassword( tr_session * session,
397                                const char * password );
398
399void  tr_sessionSetRPCUsername( tr_session * session,
400                                const char * username );
401
402/** @brief get the password used to restrict RPC requests.
403    @return the password string.
404    @see tr_sessionInit()
405    @see tr_sessionSetRPCPassword() */
406const char* tr_sessionGetRPCPassword( const tr_session * session );
407
408const char* tr_sessionGetRPCUsername( const tr_session * session  );
409
410void  tr_sessionSetRPCPasswordEnabled( tr_session * session,
411                                       tr_bool      isEnabled );
412
413tr_bool tr_sessionIsRPCPasswordEnabled( const tr_session * session );
414
415const char* tr_sessionGetRPCBindAddress( const tr_session * session );
416
417
418typedef enum
419{
420    TR_RPC_TORRENT_ADDED,
421    TR_RPC_TORRENT_STARTED,
422    TR_RPC_TORRENT_STOPPED,
423    TR_RPC_TORRENT_REMOVING,
424    TR_RPC_TORRENT_CHANGED, /* catch-all for the "torrent-set" rpc method */
425    TR_RPC_SESSION_CHANGED
426}
427tr_rpc_callback_type;
428
429typedef enum
430{
431    /* no special handling is needed by the caller */
432    TR_RPC_OK            = 0,
433
434    /* indicates to the caller that the client will take care of
435     * removing the torrent itself.  For example the client may
436     * need to keep the torrent alive long enough to cleanly close
437     * some resources in another thread. */
438    TR_RPC_NOREMOVE   = ( 1 << 1 )
439}
440tr_rpc_callback_status;
441
442typedef tr_rpc_callback_status (*tr_rpc_func)(tr_session          * session,
443                                              tr_rpc_callback_type  type,
444                                              struct tr_torrent   * tor_or_null,
445                                              void                * user_data );
446
447/**
448 * Register to be notified whenever something is changed via RPC,
449 * such as a torrent being added, removed, started, stopped, etc.
450 *
451 * func is invoked FROM LIBTRANSMISSION'S THREAD!
452 * This means func must be fast (to avoid blocking peers),
453 * shouldn't call libtransmission functions (to avoid deadlock),
454 * and shouldn't modify client-level memory without using a mutex!
455 */
456void tr_sessionSetRPCCallback( tr_session   * session,
457                               tr_rpc_func    func,
458                               void         * user_data );
459
460/**
461***
462**/
463
464tr_bool       tr_sessionIsProxyEnabled( const tr_session * );
465
466tr_bool       tr_sessionIsProxyAuthEnabled( const tr_session * );
467
468const char*   tr_sessionGetProxy( const tr_session * );
469
470tr_port       tr_sessionGetProxyPort( const tr_session * );
471
472tr_proxy_type tr_sessionGetProxyType( const tr_session * );
473
474const char*   tr_sessionGetProxyUsername( const tr_session * );
475
476const char*   tr_sessionGetProxyPassword( const tr_session * );
477
478void          tr_sessionSetProxyEnabled( tr_session * session,
479                                         tr_bool      isEnabled );
480
481void          tr_sessionSetProxyAuthEnabled( tr_session * session,
482                                             tr_bool      isEnabled );
483
484void          tr_sessionSetProxy( tr_session * session,
485                                  const char * proxy );
486
487void          tr_sessionSetProxyPort( tr_session * session,
488                                      tr_port      port );
489
490void          tr_sessionSetProxyType( tr_session    * session,
491                                      tr_proxy_type   proxy_type );
492
493void          tr_sessionSetProxyUsername( tr_session * session,
494                                          const char * username );
495
496void          tr_sessionSetProxyPassword( tr_session * session,
497                                          const char * password );
498
499/**
500***
501**/
502
503typedef struct tr_session_stats
504{
505    float       ratio;        /* TR_RATIO_INF, TR_RATIO_NA, or total up/down */
506    uint64_t    uploadedBytes; /* total up */
507    uint64_t    downloadedBytes; /* total down */
508    uint64_t    filesAdded;   /* number of files added */
509    uint64_t    sessionCount; /* program started N times */
510    uint64_t    secondsActive; /* how long Transmisson's been running */
511}
512tr_session_stats;
513
514/* stats from the current session. */
515void               tr_sessionGetStats( const tr_session * session,
516                                       tr_session_stats * setme );
517
518/* stats from the current and past sessions. */
519void               tr_sessionGetCumulativeStats( const tr_session * session,
520                                                 tr_session_stats * setme );
521
522void               tr_sessionClearStats( tr_session * session );
523
524/**
525 * Set whether or not torrents are allowed to do peer exchanges.
526 * PEX is always disabled in private torrents regardless of this.
527 * In public torrents, PEX is enabled by default.
528 */
529void               tr_sessionSetPexEnabled( tr_session  * session,
530                                            tr_bool       isEnabled );
531
532tr_bool            tr_sessionIsPexEnabled( const tr_session * session );
533
534tr_bool            tr_sessionIsDHTEnabled( const tr_session * session );
535
536void               tr_sessionSetDHTEnabled( tr_session * session, tr_bool );
537
538void               tr_sessionSetLazyBitfieldEnabled( tr_session * session,
539                                                     tr_bool       enabled );
540
541tr_bool            tr_sessionIsLazyBitfieldEnabled( const tr_session * session );
542
543tr_encryption_mode tr_sessionGetEncryption( tr_session * session );
544
545void               tr_sessionSetEncryption( tr_session          * session,
546                                            tr_encryption_mode    mode );
547
548
549/***********************************************************************
550** Incoming Peer Connections Port
551*/
552
553void  tr_sessionSetPortForwardingEnabled( tr_session  * session,
554                                          tr_bool       enabled );
555
556tr_bool tr_sessionIsPortForwardingEnabled( const tr_session  * session );
557
558void  tr_sessionSetPeerPort( tr_session  * session,
559                             tr_port       port);
560
561tr_port tr_sessionGetPeerPort( const tr_session * session );
562
563tr_port tr_sessionSetPeerPortRandom( tr_session  * session );
564
565void  tr_sessionSetPeerPortRandomOnStart( tr_session * session,
566                                          tr_bool random );
567
568tr_bool  tr_sessionGetPeerPortRandomOnStart( tr_session * session );
569
570typedef enum
571{
572    TR_PORT_ERROR,
573    TR_PORT_UNMAPPED,
574    TR_PORT_UNMAPPING,
575    TR_PORT_MAPPING,
576    TR_PORT_MAPPED
577}
578tr_port_forwarding;
579
580tr_port_forwarding tr_sessionGetPortForwarding( const tr_session * session );
581
582int tr_sessionCountTorrents( const tr_session * session );
583
584typedef enum
585{
586    TR_CLIENT_TO_PEER = 0, TR_UP = 0,
587    TR_PEER_TO_CLIENT = 1, TR_DOWN = 1
588}
589tr_direction;
590
591/***
592****
593***/
594
595/***
596****  Primary session speed limits
597***/
598
599void     tr_sessionSetSpeedLimit      ( tr_session *, tr_direction, int KB_s );
600int      tr_sessionGetSpeedLimit      ( const tr_session *, tr_direction );
601
602void     tr_sessionLimitSpeed         ( tr_session *, tr_direction, tr_bool );
603tr_bool  tr_sessionIsSpeedLimited     ( const tr_session *, tr_direction );
604
605
606/***
607****  Alternative speed limits that are used during scheduled times
608***/
609
610void     tr_sessionSetAltSpeed        ( tr_session *, tr_direction, int KB_s );
611int      tr_sessionGetAltSpeed        ( const tr_session *, tr_direction );
612
613void     tr_sessionUseAltSpeed        ( tr_session *, tr_bool );
614tr_bool  tr_sessionUsesAltSpeed       ( const tr_session * );
615
616void     tr_sessionUseAltSpeedTime    ( tr_session *, tr_bool );
617tr_bool  tr_sessionUsesAltSpeedTime   ( const tr_session * );
618
619void     tr_sessionSetAltSpeedBegin   ( tr_session *, int minsSinceMidnight );
620int      tr_sessionGetAltSpeedBegin   ( const tr_session * );
621
622void     tr_sessionSetAltSpeedEnd     ( tr_session *, int minsSinceMidnight );
623int      tr_sessionGetAltSpeedEnd     ( const tr_session * );
624
625typedef enum
626{
627    TR_SCHED_SUN      = (1<<0),
628    TR_SCHED_MON      = (1<<1),
629    TR_SCHED_TUES     = (1<<2),
630    TR_SCHED_WED      = (1<<3),
631    TR_SCHED_THURS    = (1<<4),
632    TR_SCHED_FRI      = (1<<5),
633    TR_SCHED_SAT      = (1<<6),
634    TR_SCHED_WEEKDAY  = (TR_SCHED_MON|TR_SCHED_TUES|TR_SCHED_WED|TR_SCHED_THURS|TR_SCHED_FRI),
635    TR_SCHED_WEEKEND  = (TR_SCHED_SUN|TR_SCHED_SAT),
636    TR_SCHED_ALL      = (TR_SCHED_WEEKDAY|TR_SCHED_WEEKEND)
637}
638tr_sched_day;
639
640void     tr_sessionSetAltSpeedDay     ( tr_session *, tr_sched_day day );
641tr_sched_day tr_sessionGetAltSpeedDay ( const tr_session * );
642
643typedef void ( tr_altSpeedFunc )      ( tr_session *, tr_bool active, tr_bool userDriven, void * );
644void     tr_sessionClearAltSpeedFunc  ( tr_session * );
645void     tr_sessionSetAltSpeedFunc    ( tr_session *, tr_altSpeedFunc *, void * );
646
647/***
648****
649***/
650
651double     tr_sessionGetRawSpeed      ( const tr_session *, tr_direction );
652double     tr_sessionGetPieceSpeed    ( const tr_session *, tr_direction );
653
654
655void       tr_sessionSetRatioLimited  ( tr_session *, tr_bool isLimited );
656tr_bool    tr_sessionIsRatioLimited   ( const tr_session * );
657
658void       tr_sessionSetRatioLimit    ( tr_session *, double desiredRatio );
659double     tr_sessionGetRatioLimit    ( const tr_session * );
660
661void       tr_sessionSetPeerLimit( tr_session *, uint16_t maxGlobalPeers );
662uint16_t   tr_sessionGetPeerLimit( const tr_session * );
663
664void       tr_sessionSetPeerLimitPerTorrent( tr_session *, uint16_t maxGlobalPeers );
665uint16_t   tr_sessionGetPeerLimitPerTorrent( const tr_session * );
666
667tr_priority_t   tr_torrentGetPriority( const tr_torrent * );
668void            tr_torrentSetPriority( tr_torrent *, tr_priority_t );
669
670
671/**
672 *  Load all the torrents in tr_getTorrentDir().
673 *  This can be used at startup to kickstart all the torrents
674 *  from the previous session.
675 */
676tr_torrent ** tr_sessionLoadTorrents( tr_session  * session,
677                                      tr_ctor     * ctor,
678                                      int         * setmeCount );
679
680int tr_sessionGetActiveTorrentCount( tr_session * session );
681
682/** @} */
683
684/**
685***
686**/
687
688
689/***********************************************************************
690** Message Logging
691*/
692
693enum
694{
695    TR_MSG_ERR = 1,
696    TR_MSG_INF = 2,
697    TR_MSG_DBG = 3
698};
699void tr_setMessageLevel( int );
700
701int  tr_getMessageLevel( void );
702
703typedef struct tr_msg_list
704{
705    /* TR_MSG_ERR, TR_MSG_INF, or TR_MSG_DBG */
706    uint8_t level;
707
708    /* The line number in the source file where this message originated */
709    int line;
710
711    /* Time the message was generated */
712    time_t when;
713
714    /* The torrent associated with this message,
715     * or a module name such as "Port Forwarding" for non-torrent messages,
716     * or NULL. */
717    char *  name;
718
719    /* The message */
720    char *  message;
721
722    /* The source file where this message originated */
723    const char * file;
724
725    /* linked list of messages */
726    struct tr_msg_list * next;
727}
728tr_msg_list;
729
730void          tr_setMessageQueuing( tr_bool isEnabled );
731
732tr_bool       tr_getMessageQueuing( void );
733
734tr_msg_list * tr_getQueuedMessages( void );
735
736void          tr_freeMessageList( tr_msg_list * freeme );
737
738/** @addtogroup Blocklists
739    @{ */
740
741/**
742 * Specify a range of IPs for Transmission to block.
743 *
744 * filename must be an uncompressed ascii file,
745 * using the same format as the bluetack level1 file.
746 *
747 * libtransmission does not keep a handle to `filename'
748 * after this call returns, so the caller is free to
749 * keep or delete `filename' as it wishes.
750 * libtransmission makes its own copy of the file
751 * massaged into a format easier to search.
752 *
753 * The caller only needs to invoke this when the blocklist
754 * has changed.
755 *
756 * Passing NULL for a filename will clear the blocklist.
757 */
758int     tr_blocklistSetContent   ( tr_session       * session,
759                                   const char       * filename );
760
761int     tr_blocklistGetRuleCount ( const tr_session * session );
762
763tr_bool tr_blocklistExists       ( const tr_session * session );
764
765tr_bool tr_blocklistIsEnabled    ( const tr_session * session );
766
767void    tr_blocklistSetEnabled   ( tr_session       * session,
768                                   tr_bool            isEnabled );
769
770
771/** @} */
772
773
774/** @addtogroup tr_ctor Torrent Instantiation
775    @{
776
777    Instantiating a tr_torrent had gotten more complicated as features were
778    added.  At one point there were four functions to check metainfo and five
779    to create tr_torrent.
780
781    To remedy this, a Torrent Constructor (struct tr_ctor) has been introduced:
782    - Simplifies the API to two functions: tr_torrentParse() and tr_torrentNew()
783    - You can set the fields you want; the system sets defaults for the rest.
784    - You can specify whether or not your fields should supercede resume's.
785    - We can add new features to tr_ctor without breaking tr_torrentNew()'s API.
786
787    All the tr_ctor{Get,Set}*() functions with a return value return
788    an error number, or zero if no error occurred.
789
790    You must call one of the SetMetainfo() functions before creating
791    a torrent with a tr_ctor.  The other functions are optional.
792
793    You can reuse a single tr_ctor to create a batch of torrents --
794    just call one of the SetMetainfo() functions between each
795    tr_torrentNew() call.
796
797    Every call to tr_ctorSetMetainfo*() frees the previous metainfo.
798 */
799
800typedef enum
801{
802    TR_FALLBACK, /* indicates the ctor value should be used only
803                    in case of missing resume settings */
804
805    TR_FORCE, /* indicates the ctor value should be used
806                 regardless of what's in the resume settings */
807}
808tr_ctorMode;
809
810struct tr_benc;
811
812/* it's okay to use NULL here if you're only parsing the torrent.
813 * @see tr_torrentParse() */
814tr_ctor*    tr_ctorNew( const tr_session * session_or_NULL );
815
816void        tr_ctorFree( tr_ctor * ctor );
817
818void        tr_ctorSetDeleteSource( tr_ctor * ctor,
819                                    tr_bool   doDelete );
820
821int         tr_ctorSetMetainfo( tr_ctor *       ctor,
822                                const uint8_t * metainfo,
823                                size_t          len );
824
825int         tr_ctorSetMetainfoFromFile( tr_ctor *    ctor,
826                                        const char * filename );
827
828int         tr_ctorSetMetainfoFromHash( tr_ctor *    ctor,
829                                        const char * hashString );
830
831/** Set the maximum number of peers this torrent can connect to.
832    (Default: 50) */
833void        tr_ctorSetPeerLimit( tr_ctor *   ctor,
834                                 tr_ctorMode mode,
835                                 uint16_t    peerLimit  );
836
837/** Set the download folder for the torrent being added with this ctor.
838    @see tr_ctorSetDownloadDir()
839    @see tr_sessionInit() */
840void        tr_ctorSetDownloadDir( tr_ctor *    ctor,
841                                   tr_ctorMode  mode,
842                                   const char * directory );
843
844/** Set whether or not the torrent begins downloading/seeding when created.
845    (Default: not paused) */
846void        tr_ctorSetPaused( tr_ctor      * ctor,
847                              tr_ctorMode    mode,
848                              tr_bool        isPaused );
849
850void        tr_ctorSetFilePriorities( tr_ctor                * ctor,
851                                      const tr_file_index_t  * files,
852                                      tr_file_index_t          fileCount,
853                                      tr_priority_t            priority );
854
855void        tr_ctorSetFilesWanted( tr_ctor                * ctor,
856                                   const tr_file_index_t  * fileIndices,
857                                   tr_file_index_t          fileCount,
858                                   tr_bool                  wanted );
859
860
861int         tr_ctorGetPeerLimit( const tr_ctor * ctor,
862                                 tr_ctorMode     mode,
863                                 uint16_t *      setmeCount );
864
865int         tr_ctorGetPaused( const tr_ctor * ctor,
866                              tr_ctorMode     mode,
867                              tr_bool       * setmeIsPaused );
868
869int         tr_ctorGetDownloadDir( const tr_ctor  * ctor,
870                                   tr_ctorMode      mode,
871                                   const char    ** setmeDownloadDir );
872
873int         tr_ctorGetMetainfo( const tr_ctor         * ctor,
874                                const struct tr_benc ** setme );
875
876int         tr_ctorGetDeleteSource( const tr_ctor  * ctor,
877                                    tr_bool        * setmeDoDelete );
878
879tr_session* tr_ctorGetSession( const tr_ctor * ctor );
880
881/* returns NULL if tr_ctorSetMetainfoFromFile() wasn't used */
882const char* tr_ctorGetSourceFile( const tr_ctor * ctor );
883
884#define TR_EINVALID     1
885#define TR_EDUPLICATE   2
886
887/**
888 * Parses the specified metainfo.
889 * Returns 0 if it parsed successfully and can be added to Transmission.
890 * Returns TR_EINVALID if it couldn't be parsed.
891 * Returns TR_EDUPLICATE if it parsed but can't be added.
892 *     "download-dir" must be set to test for TR_EDUPLICATE.
893 *
894 * If setme_info is non-NULL and parsing is successful
895 * (that is, if TR_EINVALID is not returned), then the parsed
896 * metainfo is stored in setme_info and should be freed by the
897 * caller via tr_metainfoFree().
898 *
899 * If the constructor's session variable is NULL,
900 * info.torrent will be NULL and the duplicate check will not be performed.
901 */
902int tr_torrentParse( const tr_ctor * ctor,
903                     tr_info       * setme_info_or_NULL );
904
905/** @brief free a metainfo
906    @see tr_torrentParse */
907void tr_metainfoFree( tr_info * inf );
908
909
910/** Instantiate a single torrent.
911    @return 0 on success,
912            TR_EINVALID if the torrent couldn't be parsed, or
913            TR_EDUPLICATE if there's already a matching torrent object. */
914tr_torrent * tr_torrentNew( const tr_ctor   * ctor,
915                            int             * setmeError );
916
917/** @} */
918
919/***********************************************************************
920 ***
921 ***  TORRENTS
922 **/
923
924/** @addtogroup tr_torrent Torrents
925    @{ */
926
927/** @brief Frees memory allocated by tr_torrentNew().
928           Running torrents are stopped first.  */
929void tr_torrentFree( tr_torrent * torrent );
930
931/** @brief Removes our .torrent and .resume files for
932           this torrent, then calls tr_torrentFree(). */
933void tr_torrentRemove( tr_torrent * torrent );
934
935/** @brief Start a torrent */
936void tr_torrentStart( tr_torrent * torrent );
937
938/** @brief Stop (pause) a torrent */
939void tr_torrentStop( tr_torrent * torrent );
940
941typedef int tr_fileFunc( const char * filename );
942
943enum
944{
945    TR_LOC_MOVING,
946    TR_LOC_DONE,
947    TR_LOC_ERROR
948};
949
950/** @brief Tell transmsision where to find this torrent's local data */
951void tr_torrentSetLocation( tr_torrent  * torrent,
952                            const char  * location,
953                            tr_bool       move_from_previous_location,
954                            double      * setme_progress,
955                            int         * setme_state );
956
957/**
958 * @brief Deletes the torrent's local data.
959 * @param torrent
960 * @param fileFunc Pass in "unlink" to destroy the files or, on platforms with
961 *                 recycle bins, pass in a function that uses it instead.
962 *                 tr_torrentDeleteLocalData() ignores fileFunc's return value.
963 */
964void tr_torrentDeleteLocalData( tr_torrent * torrent,  tr_fileFunc fileFunc );
965
966uint64_t tr_torrentGetBytesLeftToAllocate( const tr_torrent * torrent );
967
968/**
969 * @brief Returns this torrent's unique ID.
970 *
971 * IDs are good as simple lookup keys, but are not persistent
972 * between sessions.  If you need that, use tr_info.hash or
973 * tr_info.hashString.
974 */
975int tr_torrentId( const tr_torrent * torrent );
976
977tr_torrent* tr_torrentFindFromId( tr_session * session, int id );
978
979
980/***
981****  Torrent speed limits
982****
983***/
984
985void     tr_torrentSetSpeedLimit      ( tr_torrent *, tr_direction, int KB_s );
986int      tr_torrentGetSpeedLimit      ( const tr_torrent *, tr_direction );
987
988void     tr_torrentUseSpeedLimit      ( tr_torrent *, tr_direction, tr_bool );
989tr_bool  tr_torrentUsesSpeedLimit     ( const tr_torrent *, tr_direction );
990
991void     tr_torrentUseSessionLimits   ( tr_torrent *, tr_bool );
992tr_bool  tr_torrentUsesSessionLimits  ( const tr_torrent * );
993
994
995/****
996*****  Ratio Limits
997****/
998
999typedef enum
1000{
1001    TR_RATIOLIMIT_GLOBAL    = 0, /* follow the global settings */
1002    TR_RATIOLIMIT_SINGLE    = 1, /* override the global settings, seeding until a certain ratio */
1003    TR_RATIOLIMIT_UNLIMITED = 2  /* override the global settings, seeding regardless of ratio */
1004}
1005tr_ratiolimit;
1006
1007void          tr_torrentSetRatioMode( tr_torrent         * tor,
1008                                      tr_ratiolimit        mode );
1009
1010tr_ratiolimit tr_torrentGetRatioMode( const tr_torrent   * tor );
1011
1012void          tr_torrentSetRatioLimit( tr_torrent        * tor,
1013                                       double              ratio );
1014
1015double        tr_torrentGetRatioLimit( const tr_torrent  * tor );
1016
1017
1018tr_bool       tr_torrentGetSeedRatio( const tr_torrent *, double * ratio );
1019
1020/****
1021*****  Peer Limits
1022****/
1023
1024void          tr_torrentSetPeerLimit( tr_torrent * tor,
1025                                      uint16_t     peerLimit );
1026
1027uint16_t      tr_torrentGetPeerLimit( const tr_torrent * tor );
1028
1029/****
1030*****  File Priorities
1031****/
1032
1033
1034/**
1035 * @brief Set a batch of files to a particular priority.
1036 *
1037 * @param priority must be one of TR_PRI_NORMAL, _HIGH, or _LOW
1038 */
1039void tr_torrentSetFilePriorities( tr_torrent       * torrent,
1040                                  tr_file_index_t  * files,
1041                                  tr_file_index_t    fileCount,
1042                                  tr_priority_t      priority );
1043
1044/**
1045 * @brief Get this torrent's file priorities.
1046 *
1047 * @return A malloc()ed array of tor->info.fileCount items,
1048 *         each holding a TR_PRI_NORMAL, TR_PRI_HIGH, or TR_PRI_LOW.
1049 *         It's the caller's responsibility to free() this.
1050 */
1051tr_priority_t*  tr_torrentGetFilePriorities( const tr_torrent * torrent );
1052
1053/**
1054 * @brief Single-file form of tr_torrentGetFilePriorities.
1055 * @return TR_PRI_NORMAL, TR_PRI_HIGH, or TR_PRI_LOW.
1056 */
1057tr_priority_t   tr_torrentGetFilePriority( const tr_torrent  * torrent,
1058                                           tr_file_index_t     file );
1059
1060/**
1061 * @brief See if a file's `download' flag is set.
1062 * @return true if the file's `download' flag is set.
1063 */
1064int tr_torrentGetFileDL( const tr_torrent  * torrent,
1065                         tr_file_index_t     file );
1066
1067/** @brief Set a batch of files to be downloaded or not. */
1068void            tr_torrentSetFileDLs( tr_torrent       * torrent,
1069                                      tr_file_index_t  * files,
1070                                      tr_file_index_t    fileCount,
1071                                      tr_bool            do_download );
1072
1073
1074const tr_info * tr_torrentInfo( const tr_torrent * torrent );
1075
1076/* Raw function to change the torrent's downloadDir field.
1077   This should only be used by libtransmission or to bootstrap
1078   a newly-instantiated tr_torrent object. */
1079void tr_torrentSetDownloadDir( tr_torrent  * torrent, const char * path );
1080
1081const char * tr_torrentGetDownloadDir( const tr_torrent * torrent );
1082
1083/**
1084***
1085**/
1086
1087typedef struct tr_tracker_info
1088{
1089    int     tier;
1090    char *  announce;
1091    char *  scrape;
1092}
1093tr_tracker_info;
1094
1095/**
1096 * @brief Modify a torrent's tracker list.
1097 *
1098 * This updates both the `torrent' object's tracker list
1099 * and the metainfo file in tr_sessionGetConfigDir()'s torrent subdirectory.
1100 *
1101 * @param torrent The torrent whose tracker list is to be modified
1102 * @param trackers An array of trackers, sorted by tier from first to last.
1103 *                 NOTE: only the `tier' and `announce' fields are used.
1104 *                 libtransmission derives `scrape' from `announce'.
1105 * @param trackerCount size of the `trackers' array
1106 */
1107void tr_torrentSetAnnounceList( tr_torrent *            torrent,
1108                                const tr_tracker_info * trackers,
1109                                int                     trackerCount );
1110
1111
1112/**
1113***
1114**/
1115
1116typedef enum
1117{
1118    TR_LEECH,           /* doesn't have all the desired pieces */
1119    TR_SEED,            /* has the entire torrent */
1120    TR_PARTIAL_SEED     /* has the desired pieces, but not the entire torrent */
1121}
1122tr_completeness;
1123
1124typedef void ( tr_torrent_completeness_func )( tr_torrent       * torrent,
1125                                               tr_completeness    completeness,
1126                                               void             * user_data );
1127
1128typedef void ( tr_torrent_ratio_limit_hit_func )( tr_torrent   * torrent,
1129                                                  void         * user_data );
1130
1131/**
1132 * Register to be notified whenever a torrent's "completeness"
1133 * changes.  This will be called, for example, when a torrent
1134 * finishes downloading and changes from TR_LEECH to
1135 * either TR_SEED or TR_PARTIAL_SEED.
1136 *
1137 * func is invoked FROM LIBTRANSMISSION'S THREAD!
1138 * This means func must be fast (to avoid blocking peers),
1139 * shouldn't call libtransmission functions (to avoid deadlock),
1140 * and shouldn't modify client-level memory without using a mutex!
1141 *
1142 * @see tr_completeness
1143 */
1144void tr_torrentSetCompletenessCallback(
1145         tr_torrent                    * torrent,
1146         tr_torrent_completeness_func    func,
1147         void                          * user_data );
1148
1149void tr_torrentClearCompletenessCallback( tr_torrent * torrent );
1150
1151
1152/**
1153 * Register to be notified whenever a torrent's ratio limit
1154 * has been hit. This will be called when the torrent's
1155 * ul/dl ratio has met or exceeded the designated ratio limit.
1156 *
1157 * Has the same restrictions as tr_torrentSetCompletenessCallback
1158 */
1159void tr_torrentSetRatioLimitHitCallback(
1160     tr_torrent                     * torrent,
1161     tr_torrent_ratio_limit_hit_func  func,
1162     void                           * user_data );
1163
1164void tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent );
1165
1166
1167/**
1168 * MANUAL ANNOUNCE
1169 *
1170 * Trackers usually set an announce interval of 15 or 30 minutes.
1171 * Users can send one-time announce requests that override this
1172 * interval by calling tr_torrentManualUpdate().
1173 *
1174 * The wait interval for tr_torrentManualUpdate() is much smaller.
1175 * You can test whether or not a manual update is possible
1176 * (for example, to desensitize the button) by calling
1177 * tr_torrentCanManualUpdate().
1178 */
1179
1180void tr_torrentManualUpdate( tr_torrent * torrent );
1181
1182tr_bool tr_torrentCanManualUpdate( const tr_torrent * torrent );
1183
1184/***********************************************************************
1185* tr_torrentPeers
1186***********************************************************************/
1187
1188typedef struct tr_peer_stat
1189{
1190    tr_bool      isEncrypted;
1191    tr_bool      isDownloadingFrom;
1192    tr_bool      isUploadingTo;
1193    tr_bool      isSeed;
1194
1195    tr_bool      peerIsChoked;
1196    tr_bool      peerIsInterested;
1197    tr_bool      clientIsChoked;
1198    tr_bool      clientIsInterested;
1199    tr_bool      isIncoming;
1200
1201    uint8_t      from;
1202    tr_port      port;
1203
1204    char         addr[TR_INET6_ADDRSTRLEN];
1205    char         client[80];
1206    char         flagStr[32];
1207
1208    float        progress;
1209    float        rateToPeer;
1210    float        rateToClient;
1211}
1212tr_peer_stat;
1213
1214tr_peer_stat * tr_torrentPeers( const tr_torrent * torrent,
1215                                int *              peerCount );
1216
1217void           tr_torrentPeersFree( tr_peer_stat * peerStats,
1218                                    int            peerCount );
1219
1220/**
1221 * @brief get the download speeds for each of this torrent's webseed sources.
1222 *
1223 * @return an array of tor->info.webseedCount floats giving download speeds.
1224 *         Each speed in the array corresponds to the webseed at the same
1225 *         array index in tor->info.webseeds.
1226 *         To differentiate "idle" and "stalled" status, idle webseeds will
1227 *         return -1 instead of 0 KiB/s.
1228 *         NOTE: always free this array with tr_free() when you're done with it.
1229 */
1230float*         tr_torrentWebSpeeds( const tr_torrent * torrent );
1231
1232typedef struct tr_file_stat
1233{
1234    uint64_t    bytesCompleted;
1235    float       progress;
1236}
1237tr_file_stat;
1238
1239tr_file_stat * tr_torrentFiles( const tr_torrent  * torrent,
1240                                tr_file_index_t   * fileCount );
1241
1242void tr_torrentFilesFree( tr_file_stat     * files,
1243                          tr_file_index_t    fileCount );
1244
1245
1246/***********************************************************************
1247 * tr_torrentAvailability
1248 ***********************************************************************
1249 * Use this to draw an advanced progress bar which is 'size' pixels
1250 * wide. Fills 'tab' which you must have allocated: each byte is set
1251 * to either -1 if we have the piece, otherwise it is set to the number
1252 * of connected peers who have the piece.
1253 **********************************************************************/
1254void tr_torrentAvailability( const tr_torrent  * torrent,
1255                             int8_t            * tab,
1256                             int                  size );
1257
1258void tr_torrentAmountFinished( const tr_torrent  * torrent,
1259                               float *             tab,
1260                               int                 size );
1261
1262void tr_torrentVerify( tr_torrent * torrent );
1263
1264/***********************************************************************
1265 * tr_info
1266 **********************************************************************/
1267
1268typedef struct tr_file
1269{
1270    uint64_t            length;    /* Length of the file, in bytes */
1271    char *              name;      /* Path to the file */
1272    int8_t              priority;  /* TR_PRI_HIGH, _NORMAL, or _LOW */
1273    int8_t              dnd;       /* nonzero if the file shouldn't be
1274                                     downloaded */
1275    tr_piece_index_t    firstPiece; /* We need pieces [firstPiece... */
1276    tr_piece_index_t    lastPiece; /* ...lastPiece] to dl this file */
1277    uint64_t            offset;    /* file begins at the torrent's nth byte */
1278}
1279tr_file;
1280
1281typedef struct tr_piece
1282{
1283    uint8_t    hash[SHA_DIGEST_LENGTH]; /* pieces hash */
1284    int8_t     priority;               /* TR_PRI_HIGH, _NORMAL, or _LOW */
1285    int8_t     dnd;                    /* nonzero if the piece shouldn't be
1286                                         downloaded */
1287}
1288tr_piece;
1289
1290struct tr_info
1291{
1292    /* Flags */
1293    tr_bool            isPrivate;
1294    tr_bool            isMultifile;
1295
1296    /* General info */
1297    uint8_t            hash[SHA_DIGEST_LENGTH];
1298    char               hashString[2 * SHA_DIGEST_LENGTH + 1];
1299    char            *  name;
1300
1301    /* Path to torrent Transmission's internal copy of the .torrent file.
1302       This field exists for compatability reasons in the Mac OS X client
1303       and should not be used in new code. */
1304    char            *  torrent;
1305
1306    /* these trackers are sorted by tier */
1307    tr_tracker_info *  trackers;
1308    int                trackerCount;
1309
1310    char           **  webseeds;
1311    int                webseedCount;
1312
1313    /* Torrent info */
1314    char             * comment;
1315    char             * creator;
1316    time_t             dateCreated;
1317
1318    /* Pieces info */
1319    uint32_t           pieceSize;
1320    tr_piece_index_t   pieceCount;
1321    uint64_t           totalSize;
1322    tr_piece *         pieces;
1323
1324    /* Files info */
1325    tr_file_index_t    fileCount;
1326    tr_file *          files;
1327};
1328
1329/**
1330 * What the torrent is doing right now.
1331 *
1332 * Note: these values will become a straight enum at some point in the future.
1333 * Do not rely on their current `bitfield' implementation
1334 */
1335typedef enum
1336{
1337    TR_STATUS_CHECK_WAIT   = ( 1 << 0 ), /* Waiting in queue to check files */
1338    TR_STATUS_CHECK        = ( 1 << 1 ), /* Checking files */
1339    TR_STATUS_DOWNLOAD     = ( 1 << 2 ), /* Downloading */
1340    TR_STATUS_SEED         = ( 1 << 3 ), /* Seeding */
1341    TR_STATUS_STOPPED      = ( 1 << 4 )  /* Torrent is stopped */
1342}
1343tr_torrent_activity;
1344
1345tr_torrent_activity tr_torrentGetActivity( tr_torrent * );
1346
1347typedef enum
1348{
1349    TR_LOCKFILE_SUCCESS = 0,
1350    TR_LOCKFILE_EOPEN,
1351    TR_LOCKFILE_ELOCK
1352}
1353tr_lockfile_state_t;
1354
1355enum
1356{
1357    TR_PEER_FROM_INCOMING  = 0,  /* connections made to the listening port */
1358    TR_PEER_FROM_TRACKER   = 1,  /* peers received from a tracker */
1359    TR_PEER_FROM_DHT       = 2,  /* peers learnt from the DHT */
1360    TR_PEER_FROM_CACHE     = 3,  /* peers read from the peer cache */
1361    TR_PEER_FROM_PEX       = 4,  /* peers discovered via PEX */
1362    TR_PEER_FROM__MAX
1363};
1364
1365/** Can be used as a mnemonic for "no error" errno */
1366#define TR_OK 0
1367
1368/**
1369 * The current status of a torrent.
1370 * @see tr_torrentStat()
1371 */
1372typedef struct tr_stat
1373{
1374    /** The torrent's unique Id.
1375        @see tr_torrentId() */
1376    int    id;
1377
1378    /** What is this torrent doing right now? */
1379    tr_torrent_activity activity;
1380
1381    /** Our current announce URL, or NULL if none.
1382        This URL may change during the session if the torrent's
1383        metainfo has multiple trackers and the current one
1384        becomes unreachable. */
1385    char *  announceURL;
1386
1387    /** Our current scrape URL, or NULL if none.
1388        This URL may change during the session if the torrent's
1389        metainfo has multiple trackers and the current one
1390        becomes unreachable. */
1391    char *  scrapeURL;
1392
1393    /** The errno status for this torrent.  0 means everything's fine. */
1394    int     error;
1395
1396    /** Typically an error string returned from the tracker. */
1397    char    errorString[128];
1398
1399    /** When tr_stat.status is TR_STATUS_CHECK or TR_STATUS_CHECK_WAIT,
1400        this is the percentage of how much of the files has been
1401        verified.  When it gets to 1, the verify process is done.
1402        Range is [0..1]
1403        @see tr_stat.status */
1404    float    recheckProgress;
1405
1406    /** How much has been downloaded of the entire torrent.
1407        Range is [0..1] */
1408    float    percentComplete;
1409
1410    /** How much has been downloaded of the files the user wants.  This differs
1411        from percentComplete if the user wants only some of the torrent's files.
1412        Range is [0..1]
1413        @see tr_stat.leftUntilDone */
1414    float    percentDone;
1415   
1416    /** The percentage of the actual ratio to the seed ratio.  This will be
1417        equal to 1 if the ratio is reached or the torrent is set to seed forever.
1418        Range is [0..1] */
1419    float    percentRatio;
1420
1421    /** Speed all data being sent for this torrent. (KiB/s)
1422        This includes piece data, protocol messages, and TCP overhead */
1423    double rawUploadSpeed;
1424
1425    /** Speed all data being received for this torrent. (KiB/s)
1426        This includes piece data, protocol messages, and TCP overhead */
1427    double rawDownloadSpeed;
1428
1429    /** Speed all piece being sent for this torrent. (KiB/s)
1430        This ONLY counts piece data. */
1431    double pieceUploadSpeed;
1432
1433    /** Speed all piece being received for this torrent. (KiB/s)
1434        This ONLY counts piece data. */
1435    double pieceDownloadSpeed;
1436
1437#define TR_ETA_NOT_AVAIL -1
1438#define TR_ETA_UNKNOWN -2
1439    /** If downloading, estimated number of seconds left until the torrent is done.
1440        If seeding, estimated number of seconds left until seed ratio is reached. */
1441    int    eta;
1442
1443    /** Number of peers that the tracker says this torrent has */
1444    int    peersKnown;
1445
1446    /** Number of peers that we're connected to */
1447    int    peersConnected;
1448
1449    /** How many peers we found out about from the tracker, or from pex,
1450        or from incoming connections, or from our resume file. */
1451    int    peersFrom[TR_PEER_FROM__MAX];
1452
1453    /** Number of peers that are sending data to us. */
1454    int    peersSendingToUs;
1455
1456    /** Number of peers that we're sending data to */
1457    int    peersGettingFromUs;
1458
1459    /** Number of webseeds that are sending data to us. */
1460    int    webseedsSendingToUs;
1461
1462    /** Number of seeders that the tracker says this torrent has */
1463    int    seeders;
1464
1465    /** Number of leechers that the tracker says this torrent has */
1466    int    leechers;
1467
1468    /** Number of downloaders that the tracker says this torrent has.
1469        This is a new key introduced in BEP 21 and may not be supported by some trackers.
1470        If the tracker doesn't support this key, the value here will be -1. */
1471    int    downloaders;
1472
1473    /** Number of finished downloads that the tracker says torrent has */
1474    int    timesCompleted;
1475
1476    /** Byte count of all the piece data we'll have downloaded when we're done,
1477        whether or not we have it yet.  This may be less than tr_info.totalSize
1478        if only some of the torrent's files are wanted.
1479        [0...tr_info.totalSize] */
1480    uint64_t    sizeWhenDone;
1481
1482    /** Byte count of how much data is left to be downloaded until we've got
1483        all the pieces that we want.  [0...tr_info.sizeWhenDone] */
1484    uint64_t    leftUntilDone;
1485
1486    /** Byte count of all the piece data we want and don't have yet,
1487        but that a connected peer does have. [0...leftUntilDone] */
1488    uint64_t    desiredAvailable;
1489
1490    /** Byte count of all the corrupt data you've ever downloaded for
1491        this torrent.  If you're on a poisoned torrent, this number can
1492        grow very large. */
1493    uint64_t    corruptEver;
1494
1495    /** Byte count of all data you've ever uploaded for this torrent. */
1496    uint64_t    uploadedEver;
1497
1498    /** Byte count of all the non-corrupt data you've ever downloaded
1499        for this torrent.  If you deleted the files and downloaded a second
1500        time, this will be 2*totalSize.. */
1501    uint64_t    downloadedEver;
1502
1503    /** Byte count of all the checksum-verified data we have for this torrent.
1504      */
1505    uint64_t    haveValid;
1506
1507    /** Byte count of all the partial piece data we have for this torrent.
1508        As pieces become complete, this value may decrease as portions of it
1509        are moved to `corrupt' or `haveValid'. */
1510    uint64_t    haveUnchecked;
1511
1512    /** This is the unmodified string returned by the tracker in response
1513        to the torrent's most recent scrape request.  If no request was
1514        sent or there was no response, this string is empty. */
1515    char    scrapeResponse[64];
1516
1517    /** The unmodified string returned by the tracker in response
1518        to the torrent's most recent scrape request.  If no request was
1519        sent or there was no response, this string is empty. */
1520    char    announceResponse[64];
1521
1522    /** Time the most recent scrape request was sent,
1523        or zero if one hasn't been sent yet. */
1524    time_t    lastScrapeTime;
1525
1526    /** Time when the next scrape request will be sent,
1527        or 0 if an error has occured that stops scraping,
1528        or 1 if a scrape is currently in progress s.t.
1529        we haven't set a timer for the next one yet. */
1530    time_t    nextScrapeTime;
1531
1532    /** Time the most recent announce request was sent,
1533        or zero if one hasn't been sent yet. */
1534    time_t    lastAnnounceTime;
1535
1536    /** Time when the next reannounce request will be sent,
1537        or 0 if the torrent is stopped,
1538        or 1 if an announce is currently in progress s.t.
1539        we haven't set a timer for the next one yet */
1540    time_t    nextAnnounceTime;
1541
1542    /** If the torrent is running, this is the time at which
1543        the client can manually ask the torrent's tracker
1544        for more peers,
1545        or 0 if the torrent is stopped or doesn't allow manual,
1546        or 1 if an announce is currently in progress s.t.
1547        we haven't set a timer for the next one yet */
1548    time_t    manualAnnounceTime;
1549
1550    /** A very rough estimate in KiB/s of how quickly data is being
1551        passed around between all the peers we're connected to.
1552        Don't put too much weight in this number. */
1553    float    swarmSpeed;
1554
1555#define TR_RATIO_NA  -1
1556#define TR_RATIO_INF -2
1557    /** TR_RATIO_INF, TR_RATIO_NA, or a regular ratio */
1558    float    ratio;
1559
1560    /** When the torrent was first added. */
1561    time_t    addedDate;
1562
1563    /** When the torrent finished downloading. */
1564    time_t    doneDate;
1565
1566    /** When the torrent was last started. */
1567    time_t    startDate;
1568
1569    /** The last time we uploaded or downloaded piece data on this torrent. */
1570    time_t    activityDate;
1571}
1572tr_stat;
1573
1574/** Return a pointer to an tr_stat structure with updated information
1575    on the torrent.  This is typically called by the GUI clients every
1576    second or so to get a new snapshot of the torrent's status. */
1577const tr_stat * tr_torrentStat( tr_torrent * torrent );
1578
1579/** Like tr_torrentStat(), but only recalculates the statistics if it's
1580    been longer than a second since they were last calculated.  This can
1581    reduce the CPU load if you're calling tr_torrentStat() frequently. */
1582const tr_stat * tr_torrentStatCached( tr_torrent * torrent );
1583
1584/** @deprecated this method will be removed in 1.40 */
1585void tr_torrentSetAddedDate( tr_torrent * torrent,
1586                             time_t       addedDate );
1587
1588/** @deprecated this method will be removed in 1.40 */
1589void tr_torrentSetActivityDate( tr_torrent * torrent,
1590                                time_t       activityDate );
1591
1592/** @deprecated this method will be removed in 1.40 */
1593void tr_torrentSetDoneDate( tr_torrent  * torrent,
1594                            time_t        doneDate );
1595
1596/** @brief Sanity checker to test that the direction is TR_UP or TR_DOWN */
1597static TR_INLINE tr_bool tr_isDirection( tr_direction d ) { return d==TR_UP || d==TR_DOWN; }
1598
1599/** @brief Sanity checker to test that a bool is TRUE or FALSE */
1600static TR_INLINE tr_bool tr_isBool( tr_bool b ) { return b==1 || b==0; }
1601
1602/** @} */
1603
1604#ifdef __cplusplus
1605}
1606#endif
1607
1608#endif
Note: See TracBrowser for help on using the repository browser.