source: trunk/libtransmission/transmission.h @ 9334

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

(trunk libT) make tr_torrentFindFile() a public API

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