source: trunk/libtransmission/transmission.h @ 12615

Last change on this file since 12615 was 12615, checked in by jordan, 10 years ago

Add a callback to be invoked when the queue starts a torrent.

  • Property svn:keywords set to Date Rev Author Id
File size: 70.5 KB
Line 
1/******************************************************************************
2 * $Id: transmission.h 12615 2011-08-03 03:14:57Z jordan $
3 *
4 * Copyright (c) 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#if !defined(__cplusplus)
48 #ifdef HAVE_STDBOOL_H
49  #include <stdbool.h>
50 #elif !defined(__bool_true_false_are_defined)
51  #define bool uint8_t
52  #define true 1
53  #define false 0
54 #endif
55#endif
56
57#ifndef PRId64
58 #define PRId64 "lld"
59#endif
60#ifndef PRIu64
61 #define PRIu64 "llu"
62#endif
63#ifndef PRIu32
64 #define PRIu32 "lu"
65#endif
66
67#if defined(WIN32) && defined(_MSC_VER)
68 #define inline __inline
69#endif
70
71#define SHA_DIGEST_LENGTH 20
72#define TR_INET6_ADDRSTRLEN 46
73
74typedef uint32_t tr_file_index_t;
75typedef uint32_t tr_piece_index_t;
76/* assuming a 16 KiB block, a 32-bit block index gives us a maximum torrent size of 63 TiB.
77 * if we ever need to grow past that, change this to uint64_t ;) */
78typedef uint32_t tr_block_index_t;
79typedef uint16_t tr_port;
80
81typedef struct tr_ctor tr_ctor;
82typedef struct tr_info tr_info;
83typedef struct tr_torrent tr_torrent;
84typedef struct tr_session tr_session;
85
86struct tr_benc;
87
88typedef int8_t tr_priority_t;
89
90#define TR_RPC_SESSION_ID_HEADER "X-Transmission-Session-Id"
91
92typedef enum
93{
94    TR_PREALLOCATE_NONE   = 0,
95    TR_PREALLOCATE_SPARSE = 1,
96    TR_PREALLOCATE_FULL   = 2
97}
98tr_preallocation_mode;
99
100typedef enum
101{
102    TR_CLEAR_PREFERRED,
103    TR_ENCRYPTION_PREFERRED,
104    TR_ENCRYPTION_REQUIRED
105}
106tr_encryption_mode;
107
108
109/***
110****
111****  Startup & Shutdown
112****
113***/
114
115/**
116 * @addtogroup tr_session Session
117 *
118 * A libtransmission session is created by calling tr_sessionInit().
119 * libtransmission creates a thread for itself so that it can operate
120 * independently of the caller's event loop. The session will continue
121 * until tr_sessionClose() is called.
122 *
123 * @{
124 */
125
126/**
127 * @brief returns Transmission's default configuration file directory.
128 *
129 * The default configuration directory is determined this way:
130 * -# If the TRANSMISSION_HOME environment variable is set, its value is used.
131 * -# On Darwin, "${HOME}/Library/Application Support/${appname}" is used.
132 * -# On Windows, "${CSIDL_APPDATA}/${appname}" is used.
133 * -# If XDG_CONFIG_HOME is set, "${XDG_CONFIG_HOME}/${appname}" is used.
134 * -# ${HOME}/.config/${appname}" is used as a last resort.
135 */
136const char* tr_getDefaultConfigDir( const char * appname );
137
138/**
139 * @brief returns Transmisson's default download directory.
140 *
141 * The default download directory is determined this way:
142 * -# If the HOME environment variable is set, "${HOME}/Downloads" is used.
143 * -# On Windows, "${CSIDL_MYDOCUMENTS}/Downloads" is used.
144 * -# Otherwise, getpwuid(getuid())->pw_dir + "/Downloads" is used.
145 */
146const char* tr_getDefaultDownloadDir( void );
147
148
149#define TR_DEFAULT_BIND_ADDRESS_IPV4        "0.0.0.0"
150#define TR_DEFAULT_BIND_ADDRESS_IPV6             "::"
151#define TR_DEFAULT_RPC_WHITELIST          "127.0.0.1"
152#define TR_DEFAULT_RPC_PORT_STR                "9091"
153#define TR_DEFAULT_RPC_URL_STR       "/transmission/"
154#define TR_DEFAULT_PEER_PORT_STR              "51413"
155#define TR_DEFAULT_PEER_SOCKET_TOS_STR      "default"
156#define TR_DEFAULT_PEER_LIMIT_GLOBAL_STR        "240"
157#define TR_DEFAULT_PEER_LIMIT_TORRENT_STR        "60"
158
159#define TR_PREFS_KEY_ALT_SPEED_ENABLED                  "alt-speed-enabled"
160#define TR_PREFS_KEY_ALT_SPEED_UP_KBps                  "alt-speed-up"
161#define TR_PREFS_KEY_ALT_SPEED_DOWN_KBps                "alt-speed-down"
162#define TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN               "alt-speed-time-begin"
163#define TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED             "alt-speed-time-enabled"
164#define TR_PREFS_KEY_ALT_SPEED_TIME_END                 "alt-speed-time-end"
165#define TR_PREFS_KEY_ALT_SPEED_TIME_DAY                 "alt-speed-time-day"
166#define TR_PREFS_KEY_BIND_ADDRESS_IPV4                  "bind-address-ipv4"
167#define TR_PREFS_KEY_BIND_ADDRESS_IPV6                  "bind-address-ipv6"
168#define TR_PREFS_KEY_BLOCKLIST_ENABLED                  "blocklist-enabled"
169#define TR_PREFS_KEY_BLOCKLIST_URL                      "blocklist-url"
170#define TR_PREFS_KEY_MAX_CACHE_SIZE_MB                  "cache-size-mb"
171#define TR_PREFS_KEY_DHT_ENABLED                        "dht-enabled"
172#define TR_PREFS_KEY_UTP_ENABLED                        "utp-enabled"
173#define TR_PREFS_KEY_LPD_ENABLED                        "lpd-enabled"
174#define TR_PREFS_KEY_DOWNLOAD_QUEUE_SIZE                "download-queue-size"
175#define TR_PREFS_KEY_DOWNLOAD_QUEUE_ENABLED             "download-queue-enabled"
176#define TR_PREFS_KEY_PREFETCH_ENABLED                   "prefetch-enabled"
177#define TR_PREFS_KEY_DOWNLOAD_DIR                       "download-dir"
178#define TR_PREFS_KEY_ENCRYPTION                         "encryption"
179#define TR_PREFS_KEY_IDLE_LIMIT                         "idle-seeding-limit"
180#define TR_PREFS_KEY_IDLE_LIMIT_ENABLED                 "idle-seeding-limit-enabled"
181#define TR_PREFS_KEY_INCOMPLETE_DIR                     "incomplete-dir"
182#define TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED             "incomplete-dir-enabled"
183#define TR_PREFS_KEY_MSGLEVEL                           "message-level"
184#define TR_PREFS_KEY_PEER_LIMIT_GLOBAL                  "peer-limit-global"
185#define TR_PREFS_KEY_PEER_LIMIT_TORRENT                 "peer-limit-per-torrent"
186#define TR_PREFS_KEY_PEER_PORT                          "peer-port"
187#define TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START          "peer-port-random-on-start"
188#define TR_PREFS_KEY_PEER_PORT_RANDOM_LOW               "peer-port-random-low"
189#define TR_PREFS_KEY_PEER_PORT_RANDOM_HIGH              "peer-port-random-high"
190#define TR_PREFS_KEY_PEER_SOCKET_TOS                    "peer-socket-tos"
191#define TR_PREFS_KEY_PEER_CONGESTION_ALGORITHM          "peer-congestion-algorithm"
192#define TR_PREFS_KEY_PEX_ENABLED                        "pex-enabled"
193#define TR_PREFS_KEY_PORT_FORWARDING                    "port-forwarding-enabled"
194#define TR_PREFS_KEY_PREALLOCATION                      "preallocation"
195#define TR_PREFS_KEY_RATIO                              "ratio-limit"
196#define TR_PREFS_KEY_RATIO_ENABLED                      "ratio-limit-enabled"
197#define TR_PREFS_KEY_RENAME_PARTIAL_FILES               "rename-partial-files"
198#define TR_PREFS_KEY_RPC_AUTH_REQUIRED                  "rpc-authentication-required"
199#define TR_PREFS_KEY_RPC_BIND_ADDRESS                   "rpc-bind-address"
200#define TR_PREFS_KEY_RPC_ENABLED                        "rpc-enabled"
201#define TR_PREFS_KEY_RPC_PASSWORD                       "rpc-password"
202#define TR_PREFS_KEY_RPC_PORT                           "rpc-port"
203#define TR_PREFS_KEY_RPC_USERNAME                       "rpc-username"
204#define TR_PREFS_KEY_RPC_URL                            "rpc-url"
205#define TR_PREFS_KEY_RPC_WHITELIST_ENABLED              "rpc-whitelist-enabled"
206#define TR_PREFS_KEY_SCRAPE_PAUSED_TORRENTS             "scrape-paused-torrents-enabled"
207#define TR_PREFS_KEY_SCRIPT_TORRENT_DONE_FILENAME       "script-torrent-done-filename"
208#define TR_PREFS_KEY_SCRIPT_TORRENT_DONE_ENABLED        "script-torrent-done-enabled"
209#define TR_PREFS_KEY_SEED_QUEUE_SIZE                    "seed-queue-size"
210#define TR_PREFS_KEY_SEED_QUEUE_ENABLED                 "seed-queue-enabled"
211#define TR_PREFS_KEY_RPC_WHITELIST                      "rpc-whitelist"
212#define TR_PREFS_KEY_QUEUE_STALLED_MINUTES              "queue-stalled-minutes"
213#define TR_PREFS_KEY_DSPEED_KBps                        "speed-limit-down"
214#define TR_PREFS_KEY_DSPEED_ENABLED                     "speed-limit-down-enabled"
215#define TR_PREFS_KEY_USPEED_KBps                        "speed-limit-up"
216#define TR_PREFS_KEY_USPEED_ENABLED                     "speed-limit-up-enabled"
217#define TR_PREFS_KEY_UMASK                              "umask"
218#define TR_PREFS_KEY_UPLOAD_SLOTS_PER_TORRENT           "upload-slots-per-torrent"
219#define TR_PREFS_KEY_START                              "start-added-torrents"
220#define TR_PREFS_KEY_TRASH_ORIGINAL                     "trash-original-torrent-files"
221
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 current 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 find the default dir.
265 * @return success true if the settings were loaded, false otherwise
266 * @see tr_sessionGetDefaultSettings()
267 * @see tr_sessionInit()
268 * @see tr_sessionSaveSettings()
269 */
270bool tr_sessionLoadSettings( struct tr_benc  * dictionary,
271                             const char      * configDir,
272                             const char      * appName );
273
274/**
275 * Add the session's configuration settings to the benc dictionary
276 * and save it to the configuration directory's settings.json file.
277 *
278 * FIXME: this belongs in libtransmissionapp
279 *
280 * @param session
281 * @param dictionary
282 * @see tr_sessionLoadSettings()
283 */
284void tr_sessionSaveSettings( tr_session           * session,
285                             const char           * configDir,
286                             const struct tr_benc * dictonary );
287
288/**
289 * @brief Initialize a libtransmission session.
290 *
291 * For example, this will instantiate a session with all the default values:
292 * @code
293 *     tr_benc settings;
294 *     tr_session * session;
295 *     const char * configDir;
296 *
297 *     tr_bencInitDict( &settings, 0 );
298 *     tr_sessionGetDefaultSettings( &settings );
299 *     configDir = tr_getDefaultConfigDir( "Transmission" );
300 *     session = tr_sessionInit( "mac", configDir, true, &settings );
301 *
302 *     tr_bencFree( &settings );
303 * @endcode
304 *
305 * @param tag "gtk", "macosx", "daemon", etc... this is only for pre-1.30 resume files
306 * @param configDir where Transmission will look for resume files, blocklists, etc.
307 * @param messageQueueingEnabled if false, messages will be dumped to stderr
308 * @param settings libtransmission settings
309 * @see tr_sessionGetDefaultSettings()
310 * @see tr_sessionLoadSettings()
311 * @see tr_getDefaultConfigDir()
312 */
313tr_session * tr_sessionInit( const char     * tag,
314                             const char     * configDir,
315                             bool             messageQueueingEnabled,
316                             struct tr_benc * settings );
317
318/** @brief Update a session's settings from a benc dictionary
319           like to the one used in tr_sessionInit() */
320void tr_sessionSet( tr_session      * session,
321                    struct tr_benc  * settings );
322
323/** @brief Rescan the blocklists directory and
324           reload whatever blocklist files are found there */
325void tr_sessionReloadBlocklists( tr_session * session );
326
327
328/** @brief End a libtransmission session
329    @see tr_sessionInit() */
330void tr_sessionClose( tr_session * );
331
332/**
333 * @brief Return the session's configuration directory.
334 *
335 * This is where transmission stores its .torrent files, .resume files,
336 * blocklists, etc. It's set in tr_transmissionInit() and is immutable
337 * during the session.
338 */
339const char * tr_sessionGetConfigDir( const tr_session * );
340
341/**
342 * @brief Set the per-session default download folder for new torrents.
343 * @see tr_sessionInit()
344 * @see tr_sessionGetDownloadDir()
345 * @see tr_ctorSetDownloadDir()
346 */
347void tr_sessionSetDownloadDir( tr_session * session, const char * downloadDir );
348
349/**
350 * @brief Get the default download folder for new torrents.
351 *
352 * This is set by tr_sessionInit() or tr_sessionSetDownloadDir(),
353 * and can be overridden on a per-torrent basis by tr_ctorSetDownloadDir().
354 */
355const char * tr_sessionGetDownloadDir( const tr_session * session );
356
357/**
358 * @brief Get available disk space (in bytes) for the default download folder.
359 * @return zero or positive integer on success, -1 in case of error.
360 */
361int64_t tr_sessionGetDownloadDirFreeSpace( const tr_session * session );
362
363/**
364 * @brief Set the torrent's bandwidth priority.
365 */
366void tr_ctorSetBandwidthPriority( tr_ctor * ctor, tr_priority_t priority );
367
368/**
369 * @brief Get the torrent's bandwidth priority.
370 */
371tr_priority_t tr_ctorGetBandwidthPriority( const tr_ctor * ctor );
372
373
374/**
375 * @brief set the per-session incomplete download folder.
376 *
377 * When you add a new torrent and the session's incomplete directory is enabled,
378 * the new torrent will start downloading into that directory, and then be moved
379 * to tr_torrent.downloadDir when the torrent is finished downloading.
380 *
381 * Torrents aren't moved as a result of changing the session's incomplete dir --
382 * it's applied to new torrents, not existing ones.
383 *
384 * tr_torrentSetLocation() overrules the incomplete dir: when a user specifies
385 * a new location, that becomes the torrent's new downloadDir and the torrent
386 * is moved there immediately regardless of whether or not it's complete.
387 *
388 * @see tr_sessionInit()
389 * @see tr_sessionGetIncompleteDir()
390 * @see tr_sessionSetIncompleteDirEnabled()
391 * @see tr_sessionGetIncompleteDirEnabled()
392 */
393void tr_sessionSetIncompleteDir( tr_session * session, const char * dir );
394
395/** @brief get the per-session incomplete download folder */
396const char* tr_sessionGetIncompleteDir( const tr_session * session );
397
398/** @brief enable or disable use of the incomplete download folder */
399void tr_sessionSetIncompleteDirEnabled( tr_session * session, bool );
400
401/** @brief get whether or not the incomplete download folder is enabled */
402bool tr_sessionIsIncompleteDirEnabled( const tr_session * session );
403
404
405/**
406 * @brief When enabled, newly-created files will have ".part" appended
407 *        to their filename until the file is fully downloaded
408 *
409 * This is not retroactive -- toggling this will not rename existing files.
410 * It only applies to new files created by Transmission after this API call.
411 *
412 * @see tr_sessionIsIncompleteFileNamingEnabled()
413 */
414void tr_sessionSetIncompleteFileNamingEnabled( tr_session * session, bool );
415
416/** @brief return true if files will end in ".part" until they're complete */
417bool tr_sessionIsIncompleteFileNamingEnabled( const tr_session * session );
418
419/**
420 * @brief Set whether or not RPC calls are allowed in this session.
421 *
422 * @details If true, libtransmission will open a server socket to listen
423 * for incoming http RPC requests as described in docs/rpc-spec.txt.
424 *
425 * This is intially set by tr_sessionInit() and can be
426 * queried by tr_sessionIsRPCEnabled().
427 */
428void tr_sessionSetRPCEnabled( tr_session  * session,
429                              bool          isEnabled );
430
431/** @brief Get whether or not RPC calls are allowed in this session.
432    @see tr_sessionInit()
433    @see tr_sessionSetRPCEnabled() */
434bool tr_sessionIsRPCEnabled( const tr_session * session );
435
436/** @brief Specify which port to listen for RPC requests on.
437    @see tr_sessionInit()
438    @see tr_sessionGetRPCPort */
439void tr_sessionSetRPCPort( tr_session  * session,
440                           tr_port       port );
441
442/** @brief Get which port to listen for RPC requests on.
443    @see tr_sessionInit()
444    @see tr_sessionSetRPCPort */
445tr_port tr_sessionGetRPCPort( const tr_session * session );
446
447/**
448 * @brief Specify which base URL to use.
449 *
450 * @detail The RPC API is accessible under <url>/rpc, the web interface under
451 * <url>/web.
452 *
453 *  @see tr_sessionGetRPCUrl
454 */
455void tr_sessionSetRPCUrl( tr_session  * session,
456                          const char * url );
457
458/**
459 * @brief Get the base URL.
460 * @see tr_sessionInit()
461 * @see tr_sessionSetRPCUrl
462 */
463const char* tr_sessionGetRPCUrl( const tr_session * session );
464
465/**
466 * @brief Specify a whitelist for remote RPC access
467 *
468 * The whitelist is a comma-separated list of dotted-quad IP addresses
469 * to be allowed. Wildmat notation is supported, meaning that
470 * '?' is interpreted as a single-character wildcard and
471 * '*' is interprted as a multi-character wildcard.
472 */
473void   tr_sessionSetRPCWhitelist( tr_session * session,
474                                  const char * whitelist );
475
476/** @brief get the Access Control List for allowing/denying RPC requests.
477    @return a comma-separated string of whitelist domains.
478    @see tr_sessionInit
479    @see tr_sessionSetRPCWhitelist */
480const char* tr_sessionGetRPCWhitelist( const tr_session * );
481
482void  tr_sessionSetRPCWhitelistEnabled( tr_session * session,
483                                        bool         isEnabled );
484
485bool tr_sessionGetRPCWhitelistEnabled( const tr_session * session );
486
487void  tr_sessionSetRPCPassword( tr_session * session,
488                                const char * password );
489
490void  tr_sessionSetRPCUsername( tr_session * session,
491                                const char * username );
492
493/** @brief get the password used to restrict RPC requests.
494    @return the password string.
495    @see tr_sessionInit()
496    @see tr_sessionSetRPCPassword() */
497const char* tr_sessionGetRPCPassword( const tr_session * session );
498
499const char* tr_sessionGetRPCUsername( const tr_session * session  );
500
501void  tr_sessionSetRPCPasswordEnabled( tr_session * session,
502                                       bool         isEnabled );
503
504bool tr_sessionIsRPCPasswordEnabled( const tr_session * session );
505
506const char* tr_sessionGetRPCBindAddress( const tr_session * session );
507
508
509typedef enum
510{
511    TR_RPC_TORRENT_ADDED,
512    TR_RPC_TORRENT_STARTED,
513    TR_RPC_TORRENT_STOPPED,
514    TR_RPC_TORRENT_REMOVING,
515    TR_RPC_TORRENT_TRASHING, /* _REMOVING + delete local data */
516    TR_RPC_TORRENT_CHANGED, /* catch-all for the "torrent-set" rpc method */
517    TR_RPC_TORRENT_MOVED,
518    TR_RPC_SESSION_CHANGED,
519    TR_RPC_SESSION_CLOSE
520}
521tr_rpc_callback_type;
522
523typedef enum
524{
525    /* no special handling is needed by the caller */
526    TR_RPC_OK            = 0,
527
528    /* indicates to the caller that the client will take care of
529     * removing the torrent itself. For example the client may
530     * need to keep the torrent alive long enough to cleanly close
531     * some resources in another thread. */
532    TR_RPC_NOREMOVE   = ( 1 << 1 )
533}
534tr_rpc_callback_status;
535
536typedef tr_rpc_callback_status (*tr_rpc_func)(tr_session          * session,
537                                              tr_rpc_callback_type  type,
538                                              struct tr_torrent   * tor_or_null,
539                                              void                * user_data );
540
541/**
542 * Register to be notified whenever something is changed via RPC,
543 * such as a torrent being added, removed, started, stopped, etc.
544 *
545 * func is invoked FROM LIBTRANSMISSION'S THREAD!
546 * This means func must be fast (to avoid blocking peers),
547 * shouldn't call libtransmission functions (to avoid deadlock),
548 * and shouldn't modify client-level memory without using a mutex!
549 */
550void tr_sessionSetRPCCallback( tr_session   * session,
551                               tr_rpc_func    func,
552                               void         * user_data );
553
554/**
555***
556**/
557
558/** @brief Used by tr_sessionGetStats() and tr_sessionGetCumulativeStats() */
559typedef struct tr_session_stats
560{
561    float       ratio;        /* TR_RATIO_INF, TR_RATIO_NA, or total up/down */
562    uint64_t    uploadedBytes; /* total up */
563    uint64_t    downloadedBytes; /* total down */
564    uint64_t    filesAdded;   /* number of files added */
565    uint64_t    sessionCount; /* program started N times */
566    uint64_t    secondsActive; /* how long Transmisson's been running */
567}
568tr_session_stats;
569
570/** @brief Get bandwidth use statistics for the current session */
571void tr_sessionGetStats( const tr_session * session,
572                         tr_session_stats * setme );
573
574/** @brief Get cumulative bandwidth statistics for current and past sessions */
575void tr_sessionGetCumulativeStats( const tr_session * session,
576                                   tr_session_stats * setme );
577
578void tr_sessionClearStats( tr_session * session );
579
580/**
581 * @brief Set whether or not torrents are allowed to do peer exchanges.
582 *
583 * PEX is always disabled in private torrents regardless of this.
584 * In public torrents, PEX is enabled by default.
585 */
586void  tr_sessionSetPexEnabled( tr_session  * session, bool isEnabled );
587bool  tr_sessionIsPexEnabled( const tr_session * session );
588
589bool  tr_sessionIsDHTEnabled( const tr_session * session );
590void  tr_sessionSetDHTEnabled( tr_session * session, bool );
591
592bool  tr_sessionIsUTPEnabled( const tr_session * session );
593void  tr_sessionSetUTPEnabled( tr_session * session, bool );
594
595bool  tr_sessionIsLPDEnabled( const tr_session * session );
596void  tr_sessionSetLPDEnabled( tr_session * session, bool enabled );
597
598void  tr_sessionSetCacheLimit_MB( tr_session * session, int mb );
599int   tr_sessionGetCacheLimit_MB( const tr_session * session );
600
601tr_encryption_mode tr_sessionGetEncryption( tr_session * session );
602void               tr_sessionSetEncryption( tr_session * session,
603                                            tr_encryption_mode    mode );
604
605
606/***********************************************************************
607** Incoming Peer Connections Port
608*/
609
610void  tr_sessionSetPortForwardingEnabled( tr_session  * session,
611                                          bool          enabled );
612
613bool tr_sessionIsPortForwardingEnabled( const tr_session  * session );
614
615void  tr_sessionSetPeerPort( tr_session  * session,
616                             tr_port       port);
617
618tr_port tr_sessionGetPeerPort( const tr_session * session );
619
620tr_port tr_sessionSetPeerPortRandom( tr_session  * session );
621
622void  tr_sessionSetPeerPortRandomOnStart( tr_session * session, bool random );
623
624bool  tr_sessionGetPeerPortRandomOnStart( tr_session * session );
625
626typedef enum
627{
628    TR_PORT_ERROR,
629    TR_PORT_UNMAPPED,
630    TR_PORT_UNMAPPING,
631    TR_PORT_MAPPING,
632    TR_PORT_MAPPED
633}
634tr_port_forwarding;
635
636tr_port_forwarding tr_sessionGetPortForwarding( const tr_session * session );
637
638typedef enum
639{
640    TR_CLIENT_TO_PEER = 0, TR_UP = 0,
641    TR_PEER_TO_CLIENT = 1, TR_DOWN = 1
642}
643tr_direction;
644
645/***
646****
647***/
648
649/***
650****  Primary session speed limits
651***/
652
653void  tr_sessionSetSpeedLimit_KBps ( tr_session *, tr_direction, int KBps );
654int   tr_sessionGetSpeedLimit_KBps ( const tr_session *, tr_direction );
655
656void  tr_sessionLimitSpeed         ( tr_session *, tr_direction, bool );
657bool  tr_sessionIsSpeedLimited     ( const tr_session *, tr_direction );
658
659
660/***
661****  Alternative speed limits that are used during scheduled times
662***/
663
664void     tr_sessionSetAltSpeed_KBps   ( tr_session *, tr_direction, int Bps );
665int      tr_sessionGetAltSpeed_KBps   ( const tr_session *, tr_direction );
666
667void     tr_sessionUseAltSpeed        ( tr_session *, bool );
668bool     tr_sessionUsesAltSpeed       ( const tr_session * );
669
670void     tr_sessionUseAltSpeedTime    ( tr_session *, bool );
671bool  tr_sessionUsesAltSpeedTime      ( const tr_session * );
672
673void     tr_sessionSetAltSpeedBegin   ( tr_session *, int minsSinceMidnight );
674int      tr_sessionGetAltSpeedBegin   ( const tr_session * );
675
676void     tr_sessionSetAltSpeedEnd     ( tr_session *, int minsSinceMidnight );
677int      tr_sessionGetAltSpeedEnd     ( const tr_session * );
678
679typedef enum
680{
681    TR_SCHED_SUN      = (1<<0),
682    TR_SCHED_MON      = (1<<1),
683    TR_SCHED_TUES     = (1<<2),
684    TR_SCHED_WED      = (1<<3),
685    TR_SCHED_THURS    = (1<<4),
686    TR_SCHED_FRI      = (1<<5),
687    TR_SCHED_SAT      = (1<<6),
688    TR_SCHED_WEEKDAY  = (TR_SCHED_MON|TR_SCHED_TUES|TR_SCHED_WED|
689                         TR_SCHED_THURS|TR_SCHED_FRI),
690    TR_SCHED_WEEKEND  = (TR_SCHED_SUN|TR_SCHED_SAT),
691    TR_SCHED_ALL      = (TR_SCHED_WEEKDAY|TR_SCHED_WEEKEND)
692}
693tr_sched_day;
694
695void         tr_sessionSetAltSpeedDay ( tr_session *, tr_sched_day day );
696tr_sched_day tr_sessionGetAltSpeedDay ( const tr_session * );
697
698typedef void ( tr_altSpeedFunc )( tr_session *,
699                                  bool active,
700                                  bool userDriven,
701                                  void * );
702
703void  tr_sessionClearAltSpeedFunc  ( tr_session * );
704void  tr_sessionSetAltSpeedFunc    ( tr_session *, tr_altSpeedFunc *, void * );
705
706
707bool  tr_sessionGetActiveSpeedLimit_KBps( const tr_session  * session,
708                                          tr_direction        dir,
709                                          double            * setme );
710
711/***
712****
713***/
714
715double     tr_sessionGetRawSpeed_KBps  ( const tr_session *, tr_direction );
716
717void       tr_sessionSetRatioLimited  ( tr_session *, bool isLimited );
718bool       tr_sessionIsRatioLimited   ( const tr_session * );
719
720void       tr_sessionSetRatioLimit    ( tr_session *, double desiredRatio );
721double     tr_sessionGetRatioLimit    ( const tr_session * );
722
723void       tr_sessionSetIdleLimited  ( tr_session *, bool isLimited );
724bool       tr_sessionIsIdleLimited   ( const tr_session * );
725
726void       tr_sessionSetIdleLimit ( tr_session *, uint16_t idleMinutes );
727uint16_t   tr_sessionGetIdleLimit ( const tr_session * );
728
729void       tr_sessionSetPeerLimit( tr_session *, uint16_t maxGlobalPeers );
730uint16_t   tr_sessionGetPeerLimit( const tr_session * );
731
732void       tr_sessionSetPeerLimitPerTorrent( tr_session *, uint16_t maxPeers );
733uint16_t   tr_sessionGetPeerLimitPerTorrent( const tr_session * );
734
735void       tr_sessionSetPaused        ( tr_session *, bool isPaused );
736bool       tr_sessionGetPaused        ( const tr_session * );
737
738void       tr_sessionSetDeleteSource  ( tr_session *, bool deleteSource );
739bool       tr_sessionGetDeleteSource  ( const tr_session * );
740
741tr_priority_t   tr_torrentGetPriority( const tr_torrent * );
742void            tr_torrentSetPriority( tr_torrent *, tr_priority_t );
743
744/***
745****
746****  Torrent Queueing
747****
748****  There are independent queues for seeding (TR_UP) and leeching (TR_DOWN).
749****
750****  If the session already has enough non-stalled seeds/leeches when
751****  tr_torrentStart() is called, the torrent will be moved into the
752****  appropriate queue and its state will be TR_STATUS_{DOWNLOAD,SEED}_WAIT.
753****
754****  To bypass the queue and unconditionally start the torrent use
755****  tr_torrentStartNow().
756****
757****  Torrents can be moved in the queue using the simple functions
758****  tr_torrentQueueMove{Top,Up,Down,Bottom}. They can be moved to
759****  arbitrary points in the queue with tr_torrentSetQueuePosition().
760**** 
761***/
762
763
764/** @brief Like tr_torrentStart(), but resumes right away regardless of the queues. */
765void tr_torrentStartNow         ( tr_torrent * );
766
767/** @brief Return the queued torrent's position in the queue it's in. [0...n) */
768int  tr_torrentGetQueuePosition ( const tr_torrent * );
769
770/** @brief Set the queued torrent's position in the queue it's in.
771 * Special cases: pos <= 0 moves to the front; pos >= queue length moves to the back */
772void tr_torrentSetQueuePosition ( tr_torrent *, int queuePosition );
773
774/**
775**/
776
777/** @brief Convenience function for moving a batch of torrents to the front of their queue(s) */
778void tr_torrentsQueueMoveTop    ( tr_torrent ** torrents, int torrentCount );
779
780/** @brief Convenience function for moving a batch of torrents ahead one step in their queue(s) */
781void tr_torrentsQueueMoveUp     ( tr_torrent ** torrents, int torrentCount );
782
783/** @brief Convenience function for moving a batch of torrents back one step in their queue(s) */
784void tr_torrentsQueueMoveDown   ( tr_torrent ** torrents, int torrentCount );
785
786/** @brief Convenience function for moving a batch of torrents to the back of their queue(s) */
787void tr_torrentsQueueMoveBottom ( tr_torrent ** torrents, int torrentCount );
788
789/**
790**/
791
792/** @brief Set the number of torrents allowed to download (if direction is TR_DOWN) or seed (if direction is TR_UP) at the same time */
793void tr_sessionSetQueueSize     ( tr_session *, tr_direction, int max_simultaneous_seed_torrents );
794
795/** @brief Return the number of torrents allowed to download (if direction is TR_DOWN) or seed (if direction is TR_UP) at the same time */
796int  tr_sessionGetQueueSize     ( const tr_session *, tr_direction );
797
798/** @brief Set whether or not to limit how many torrents can download (TR_DOWN) or seed (TR_UP) at the same time  */
799void tr_sessionSetQueueEnabled  ( tr_session *, tr_direction, bool do_limit_simultaneous_seed_torrents );
800
801/** @brief Return true if we're limiting how many torrents can concurrently download (TR_DOWN) or seed (TR_UP) at the same time */
802bool tr_sessionGetQueueEnabled  ( const tr_session *, tr_direction );
803
804/** @brief Consider torrent as 'stalled' when it's been inactive for N minutes.
805    Stalled torrents are left running but are not counted by tr_sessionGetQueueSize(). */
806void tr_sessionSetQueueStalledMinutes( tr_session *, int minutes );
807
808/** @return the number of minutes a torrent can be idle before being considered as stalled */
809int  tr_sessionGetQueueStalledMinutes( const tr_session * );
810
811/** @brief Set a callback that is invoked when the queue starts a torrent */
812void tr_torrentSetQueueStartCallback( tr_torrent * torrent, void (*callback)( tr_torrent * ) );
813
814
815/***
816****
817****
818***/
819
820/**
821 *  Load all the torrents in tr_getTorrentDir().
822 *  This can be used at startup to kickstart all the torrents
823 *  from the previous session.
824 */
825tr_torrent ** tr_sessionLoadTorrents( tr_session  * session,
826                                      tr_ctor     * ctor,
827                                      int         * setmeCount );
828
829/**
830***
831**/
832
833bool tr_sessionIsTorrentDoneScriptEnabled( const tr_session * );
834
835void tr_sessionSetTorrentDoneScriptEnabled( tr_session *, bool isEnabled );
836
837const char * tr_sessionGetTorrentDoneScript( const tr_session * );
838
839void tr_sessionSetTorrentDoneScript( tr_session *, const char * scriptFilename );
840
841
842/** @} */
843
844/**
845***
846**/
847
848
849/***********************************************************************
850** Message Logging
851*/
852
853typedef enum
854{
855    TR_MSG_ERR = 1,
856    TR_MSG_INF = 2,
857    TR_MSG_DBG = 3
858}
859tr_msg_level;
860
861void tr_setMessageLevel( tr_msg_level );
862
863typedef struct tr_msg_list
864{
865    /* TR_MSG_ERR, TR_MSG_INF, or TR_MSG_DBG */
866    tr_msg_level level;
867
868    /* The line number in the source file where this message originated */
869    int line;
870
871    /* Time the message was generated */
872    time_t when;
873
874    /* The torrent associated with this message,
875     * or a module name such as "Port Forwarding" for non-torrent messages,
876     * or NULL. */
877    char *  name;
878
879    /* The message */
880    char *  message;
881
882    /* The source file where this message originated */
883    const char * file;
884
885    /* linked list of messages */
886    struct tr_msg_list * next;
887}
888tr_msg_list;
889
890void          tr_setMessageQueuing( bool isEnabled );
891
892bool          tr_getMessageQueuing( void );
893
894tr_msg_list * tr_getQueuedMessages( void );
895
896void          tr_freeMessageList( tr_msg_list * freeme );
897
898/** @addtogroup Blocklists
899    @{ */
900
901/**
902 * Specify a range of IPs for Transmission to block.
903 *
904 * Filename must be an uncompressed ascii file.
905 *
906 * libtransmission does not keep a handle to `filename'
907 * after this call returns, so the caller is free to
908 * keep or delete `filename' as it wishes.
909 * libtransmission makes its own copy of the file
910 * massaged into a binary format easier to search.
911 *
912 * The caller only needs to invoke this when the blocklist
913 * has changed.
914 *
915 * Passing NULL for a filename will clear the blocklist.
916 */
917int     tr_blocklistSetContent   ( tr_session       * session,
918                                   const char       * filename );
919
920int     tr_blocklistGetRuleCount ( const tr_session * session );
921
922bool    tr_blocklistExists       ( const tr_session * session );
923
924bool    tr_blocklistIsEnabled    ( const tr_session * session );
925
926void    tr_blocklistSetEnabled   ( tr_session       * session,
927                                   bool               isEnabled );
928
929/** @brief The blocklist that ges updated when an RPC client
930           invokes the "blocklist-update" method */
931void tr_blocklistSetURL         ( tr_session *, const char * url );
932
933const char * tr_blocklistGetURL ( const tr_session * );
934
935/** @brief the file in the $config/blocklists/ directory that's
936           used by tr_blocklistSetContent() and "blocklist-update" */
937#define DEFAULT_BLOCKLIST_FILENAME "blocklist.bin"
938
939/** @} */
940
941
942/** @addtogroup tr_ctor Torrent Constructors
943    @{
944
945    Instantiating a tr_torrent had gotten more complicated as features were
946    added. At one point there were four functions to check metainfo and five
947    to create a tr_torrent object.
948
949    To remedy this, a Torrent Constructor (struct tr_ctor) has been introduced:
950    - Simplifies the API to two functions: tr_torrentParse() and tr_torrentNew()
951    - You can set the fields you want; the system sets defaults for the rest.
952    - You can specify whether or not your fields should supercede resume's.
953    - We can add new features to tr_ctor without breaking tr_torrentNew()'s API.
954
955    All the tr_ctor{Get,Set}*() functions with a return value return
956    an error number, or zero if no error occurred.
957
958    You must call one of the SetMetainfo() functions before creating
959    a torrent with a tr_ctor. The other functions are optional.
960
961    You can reuse a single tr_ctor to create a batch of torrents --
962    just call one of the SetMetainfo() functions between each
963    tr_torrentNew() call.
964
965    Every call to tr_ctorSetMetainfo*() frees the previous metainfo.
966 */
967
968typedef enum
969{
970    TR_FALLBACK, /* indicates the ctor value should be used only
971                    in case of missing resume settings */
972
973    TR_FORCE, /* indicates the ctor value should be used
974                 regardless of what's in the resume settings */
975}
976tr_ctorMode;
977
978struct tr_benc;
979
980/** @brief Create a torrent constructor object used to instantiate a tr_torrent
981    @param session the tr_session. This is required if you're going to call
982                   tr_torrentNew(), but you can use NULL for tr_torrentParse().
983    @see tr_torrentNew(), tr_torrentParse() */
984tr_ctor* tr_ctorNew( const tr_session * session_or_NULL );
985
986/** @brief Free a torrent constructor object */
987void  tr_ctorFree( tr_ctor * ctor );
988
989/** @brief Set whether or not to delete the source .torrent file
990           when the torrent is added. (Default: False) */
991void  tr_ctorSetDeleteSource( tr_ctor * ctor, bool doDelete );
992
993/** @brief Set the constructor's metainfo from a magnet link */
994int tr_ctorSetMetainfoFromMagnetLink( tr_ctor * ctor, const char * magnet );
995
996/** @brief Set the constructor's metainfo from a raw benc already in memory */
997int tr_ctorSetMetainfo( tr_ctor * ctor, const uint8_t * metainfo, size_t len );
998
999/** @brief Set the constructor's metainfo from a local .torrent file */
1000int tr_ctorSetMetainfoFromFile( tr_ctor * ctor, const char * filename );
1001
1002/**
1003 * @brief Set the metainfo from an existing file in tr_getTorrentDir().
1004 *
1005 * This is used by the Mac client on startup to pick and choose which
1006 * torrents to load
1007 */
1008int tr_ctorSetMetainfoFromHash( tr_ctor * ctor, const char * hashString );
1009
1010/** @brief Set how many peers this torrent can connect to. (Default: 50) */
1011void tr_ctorSetPeerLimit( tr_ctor * ctor, tr_ctorMode mode, uint16_t limit );
1012
1013/** @brief Set the download folder for the torrent being added with this ctor.
1014    @see tr_ctorSetDownloadDir()
1015    @see tr_sessionInit() */
1016void  tr_ctorSetDownloadDir( tr_ctor      * ctor,
1017                             tr_ctorMode    mode,
1018                             const char   * directory );
1019
1020/**
1021 * @brief Set the incompleteDir for this torrent.
1022 *
1023 * This is not a supported API call.
1024 * It only exists so the mac client can migrate
1025 * its older incompleteDir settings, and that's
1026 * the only place where it should be used.
1027 */
1028void tr_ctorSetIncompleteDir( tr_ctor * ctor, const char * directory );
1029
1030/** Set whether or not the torrent begins downloading/seeding when created.
1031    (Default: not paused) */
1032void        tr_ctorSetPaused( tr_ctor      * ctor,
1033                              tr_ctorMode    mode,
1034                              bool           isPaused );
1035
1036/** @brief Set the priorities for files in a torrent */
1037void        tr_ctorSetFilePriorities( tr_ctor                * ctor,
1038                                      const tr_file_index_t  * files,
1039                                      tr_file_index_t          fileCount,
1040                                      tr_priority_t            priority );
1041
1042/** @brief Set the download flag for files in a torrent */
1043void        tr_ctorSetFilesWanted( tr_ctor                * ctor,
1044                                   const tr_file_index_t  * fileIndices,
1045                                   tr_file_index_t          fileCount,
1046                                   bool                     wanted );
1047
1048
1049/** @brief Get this peer constructor's peer limit */
1050int         tr_ctorGetPeerLimit( const tr_ctor * ctor,
1051                                 tr_ctorMode     mode,
1052                                 uint16_t *      setmeCount );
1053
1054/** @brief Get the "isPaused" flag from this peer constructor */
1055int         tr_ctorGetPaused( const tr_ctor * ctor,
1056                              tr_ctorMode     mode,
1057                              bool          * setmeIsPaused );
1058
1059/** @brief Get the download path from this peer constructor */
1060int         tr_ctorGetDownloadDir( const tr_ctor  * ctor,
1061                                   tr_ctorMode      mode,
1062                                   const char    ** setmeDownloadDir );
1063
1064/** @brief Get the incomplete directory from this peer constructor */
1065int         tr_ctorGetIncompleteDir( const tr_ctor  * ctor,
1066                                     const char    ** setmeIncompleteDir );
1067
1068/** @brief Get the metainfo from this peer constructor */
1069int         tr_ctorGetMetainfo( const tr_ctor         * ctor,
1070                                const struct tr_benc ** setme );
1071
1072/** @brief Get the "delete .torrent file" flag from this peer constructor */
1073int         tr_ctorGetDeleteSource( const tr_ctor  * ctor,
1074                                    bool           * setmeDoDelete );
1075
1076/** @brief Get the tr_session poiner from this peer constructor */
1077tr_session* tr_ctorGetSession( const tr_ctor * ctor );
1078
1079/** @brief Get the .torrent file that this ctor's metainfo came from,
1080           or NULL if tr_ctorSetMetainfoFromFile() wasn't used */
1081const char* tr_ctorGetSourceFile( const tr_ctor * ctor );
1082
1083typedef enum
1084{
1085    TR_PARSE_OK,
1086    TR_PARSE_ERR,
1087    TR_PARSE_DUPLICATE
1088}
1089tr_parse_result;
1090
1091/**
1092 * @brief Parses the specified metainfo
1093 *
1094 * @return TR_PARSE_ERR if parsing failed;
1095 *         TR_PARSE_OK if parsing succeeded and it's not a duplicate;
1096 *         TR_PARSE_DUPLICATE if parsing succeeded but it's a duplicate.
1097 *
1098 * @param setme_info If parsing is successful and setme_info is non-NULL,
1099 *                   the parsed metainfo is stored there and sould be freed
1100 *                   by calling tr_metainfoFree() when no longer needed.
1101 *
1102 * Notes:
1103 *
1104 * 1. tr_torrentParse() won't be able to check for duplicates -- and therefore
1105 *    won't return TR_PARSE_DUPLICATE -- unless ctor's "download-dir" and
1106 *    session variable is set.
1107 *
1108 * 2. setme_info->torrent's value can't be set unless ctor's session variable
1109 *    is set.
1110 */
1111tr_parse_result  tr_torrentParse( const tr_ctor  * ctor,
1112                                  tr_info        * setme_info_or_NULL );
1113
1114/** @brief free a metainfo
1115    @see tr_torrentParse */
1116void tr_metainfoFree( tr_info * inf );
1117
1118
1119/** Instantiate a single torrent.
1120    @return 0 on success,
1121            TR_EINVALID if the torrent couldn't be parsed, or
1122            TR_EDUPLICATE if there's already a matching torrent object. */
1123tr_torrent * tr_torrentNew( const tr_ctor   * ctor,
1124                            int             * setmeError );
1125
1126/** @} */
1127
1128/***********************************************************************
1129 ***
1130 ***  TORRENTS
1131 **/
1132
1133/** @addtogroup tr_torrent Torrents
1134    @{ */
1135
1136/** @brief Frees memory allocated by tr_torrentNew().
1137           Running torrents are stopped first. */
1138void tr_torrentFree( tr_torrent * torrent );
1139
1140typedef int tr_fileFunc( const char * filename );
1141
1142/** @brief Removes our .torrent and .resume files for
1143           this torrent, then calls tr_torrentFree(). */
1144void tr_torrentRemove( tr_torrent  * torrent,
1145                       bool          removeLocalData,
1146                       tr_fileFunc   removeFunc );
1147
1148/** @brief Start a torrent */
1149void tr_torrentStart( tr_torrent * torrent );
1150
1151/** @brief Stop (pause) a torrent */
1152void tr_torrentStop( tr_torrent * torrent );
1153
1154enum
1155{
1156    TR_LOC_MOVING,
1157    TR_LOC_DONE,
1158    TR_LOC_ERROR
1159};
1160
1161/**
1162 * @brief Tell transmsision where to find this torrent's local data.
1163 *
1164 * if move_from_previous_location is `true', the torrent's incompleteDir
1165 * will be clobberred s.t. additional files being added will be saved
1166 * to the torrent's downloadDir.
1167 */
1168void tr_torrentSetLocation( tr_torrent       * torrent,
1169                            const char       * location,
1170                            bool               move_from_previous_location,
1171                            volatile double  * setme_progress,
1172                            volatile int     * setme_state );
1173
1174uint64_t tr_torrentGetBytesLeftToAllocate( const tr_torrent * torrent );
1175
1176/**
1177 * @brief Returns this torrent's unique ID.
1178 *
1179 * IDs are good as simple lookup keys, but are not persistent
1180 * between sessions. If you need that, use tr_info.hash or
1181 * tr_info.hashString.
1182 */
1183int tr_torrentId( const tr_torrent * torrent );
1184
1185tr_torrent* tr_torrentFindFromId( tr_session * session, int id );
1186
1187tr_torrent* tr_torrentFindFromHash( tr_session     * session,
1188                                    const uint8_t  * hash );
1189
1190/** @brief Convenience function similar to tr_torrentFindFromHash() */
1191tr_torrent* tr_torrentFindFromMagnetLink( tr_session * session,
1192                                          const char * link );
1193
1194/**
1195 * @return this torrent's name.
1196 */
1197const char* tr_torrentName( const tr_torrent * );
1198
1199/**
1200 * @brief find the location of a torrent's file by looking with and without
1201 *        the ".part" suffix, looking in downloadDir and incompleteDir, etc.
1202 * @return a newly-allocated string (that must be tr_freed() by the caller
1203 *         when done) that gives the location of this file on disk,
1204 *         or NULL if no file exists yet.
1205 * @param tor the torrent whose file we're looking for
1206 * @param fileNum the fileIndex, in [0...tr_info.fileCount)
1207 */
1208char* tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNo );
1209
1210
1211/***
1212****  Torrent speed limits
1213****
1214***/
1215
1216void     tr_torrentSetSpeedLimit_KBps  ( tr_torrent *, tr_direction, int KBps );
1217int      tr_torrentGetSpeedLimit_KBps  ( const tr_torrent *, tr_direction );
1218
1219void     tr_torrentUseSpeedLimit      ( tr_torrent *, tr_direction, bool );
1220bool     tr_torrentUsesSpeedLimit     ( const tr_torrent *, tr_direction );
1221
1222void     tr_torrentUseSessionLimits   ( tr_torrent *, bool );
1223bool     tr_torrentUsesSessionLimits  ( const tr_torrent * );
1224
1225
1226/****
1227*****  Ratio Limits
1228****/
1229
1230typedef enum
1231{
1232    /* follow the global settings */
1233    TR_RATIOLIMIT_GLOBAL    = 0,
1234
1235    /* override the global settings, seeding until a certain ratio */
1236    TR_RATIOLIMIT_SINGLE    = 1,
1237
1238    /* override the global settings, seeding regardless of ratio */
1239    TR_RATIOLIMIT_UNLIMITED = 2
1240}
1241tr_ratiolimit;
1242
1243void          tr_torrentSetRatioMode( tr_torrent         * tor,
1244                                      tr_ratiolimit        mode );
1245
1246tr_ratiolimit tr_torrentGetRatioMode( const tr_torrent   * tor );
1247
1248void          tr_torrentSetRatioLimit( tr_torrent        * tor,
1249                                       double              ratio );
1250
1251double        tr_torrentGetRatioLimit( const tr_torrent  * tor );
1252
1253
1254bool          tr_torrentGetSeedRatio( const tr_torrent *, double * ratio );
1255
1256
1257/****
1258*****  Idle Time Limits
1259****/
1260
1261typedef enum
1262{
1263    /* follow the global settings */
1264    TR_IDLELIMIT_GLOBAL    = 0,
1265
1266    /* override the global settings, seeding until a certain idle time */
1267    TR_IDLELIMIT_SINGLE    = 1,
1268
1269    /* override the global settings, seeding regardless of activity */
1270    TR_IDLELIMIT_UNLIMITED = 2
1271}
1272tr_idlelimit;
1273
1274void          tr_torrentSetIdleMode ( tr_torrent         * tor,
1275                                      tr_idlelimit         mode );
1276
1277tr_idlelimit  tr_torrentGetIdleMode ( const tr_torrent   * tor );
1278
1279void          tr_torrentSetIdleLimit( tr_torrent         * tor,
1280                                      uint16_t             idleMinutes );
1281
1282uint16_t      tr_torrentGetIdleLimit( const tr_torrent   * tor );
1283
1284
1285bool          tr_torrentGetSeedIdle( const tr_torrent *, uint16_t * minutes );
1286
1287/****
1288*****  Peer Limits
1289****/
1290
1291void          tr_torrentSetPeerLimit( tr_torrent * tor, uint16_t peerLimit );
1292
1293uint16_t      tr_torrentGetPeerLimit( const tr_torrent * tor );
1294
1295/****
1296*****  File Priorities
1297****/
1298
1299enum
1300{
1301    TR_PRI_LOW    = -1,
1302    TR_PRI_NORMAL =  0, /* since NORMAL is 0, memset initializes nicely */
1303    TR_PRI_HIGH   =  1
1304};
1305
1306/**
1307 * @brief Set a batch of files to a particular priority.
1308 *
1309 * @param priority must be one of TR_PRI_NORMAL, _HIGH, or _LOW
1310 */
1311void tr_torrentSetFilePriorities( tr_torrent             * torrent,
1312                                  const tr_file_index_t  * files,
1313                                  tr_file_index_t          fileCount,
1314                                  tr_priority_t            priority );
1315
1316/**
1317 * @brief Get this torrent's file priorities.
1318 *
1319 * @return A malloc()ed array of tor->info.fileCount items,
1320 *         each holding a TR_PRI_NORMAL, TR_PRI_HIGH, or TR_PRI_LOW.
1321 *         It's the caller's responsibility to free() this.
1322 */
1323tr_priority_t*  tr_torrentGetFilePriorities( const tr_torrent * torrent );
1324
1325/** @brief Set a batch of files to be downloaded or not. */
1326void tr_torrentSetFileDLs( tr_torrent             * torrent,
1327                           const tr_file_index_t  * files,
1328                           tr_file_index_t          fileCount,
1329                           bool                     do_download );
1330
1331
1332const tr_info * tr_torrentInfo( const tr_torrent * torrent );
1333
1334/* Raw function to change the torrent's downloadDir field.
1335   This should only be used by libtransmission or to bootstrap
1336   a newly-instantiated tr_torrent object. */
1337void tr_torrentSetDownloadDir( tr_torrent  * torrent, const char * path );
1338
1339const char * tr_torrentGetDownloadDir( const tr_torrent * torrent );
1340
1341/**
1342 * Returns the root directory of where the torrent is.
1343 *
1344 * This will usually be the downloadDir. However if the torrent
1345 * has an incompleteDir enabled and hasn't finished downloading
1346 * yet, that will be returned instead.
1347 */
1348const char * tr_torrentGetCurrentDir( const tr_torrent * tor );
1349
1350
1351/**
1352 * Returns a newly-allocated string with a magnet link of the torrent.
1353 * Use tr_free() to free the string when done.
1354 */
1355char* tr_torrentGetMagnetLink( const tr_torrent * tor );
1356
1357/**
1358***
1359**/
1360
1361
1362/** @brief a part of tr_info that represents a single tracker */
1363typedef struct tr_tracker_info
1364{
1365    int      tier;
1366    char *   announce;
1367    char *   scrape;
1368    uint32_t id; /* unique identifier used to match to a tr_tracker_stat */
1369}
1370tr_tracker_info;
1371
1372/**
1373 * @brief Modify a torrent's tracker list.
1374 *
1375 * This updates both the `torrent' object's tracker list
1376 * and the metainfo file in tr_sessionGetConfigDir()'s torrent subdirectory.
1377 *
1378 * @param torrent The torrent whose tracker list is to be modified
1379 * @param trackers An array of trackers, sorted by tier from first to last.
1380 *                 NOTE: only the `tier' and `announce' fields are used.
1381 *                 libtransmission derives `scrape' from `announce'
1382 *                 and reassigns 'id'.
1383 * @param trackerCount size of the `trackers' array
1384 */
1385bool
1386tr_torrentSetAnnounceList( tr_torrent             * torrent,
1387                           const tr_tracker_info  * trackers,
1388                           int                      trackerCount );
1389
1390
1391/**
1392***
1393**/
1394
1395typedef enum
1396{
1397    TR_LEECH,        /* doesn't have all the desired pieces */
1398    TR_SEED,         /* has the entire torrent */
1399    TR_PARTIAL_SEED  /* has the desired pieces, but not the entire torrent */
1400}
1401tr_completeness;
1402
1403/**
1404 * @param wasRunning whether or not the torrent was running when
1405 *                   it changed its completeness state
1406 */
1407typedef void ( tr_torrent_completeness_func )( tr_torrent       * torrent,
1408                                               tr_completeness    completeness,
1409                                               bool               wasRunning,
1410                                               void             * user_data );
1411
1412typedef void ( tr_torrent_ratio_limit_hit_func )( tr_torrent   * torrent,
1413                                                  void         * user_data );
1414
1415typedef void ( tr_torrent_idle_limit_hit_func )( tr_torrent   * torrent,
1416                                                 void         * user_data );
1417
1418
1419/**
1420 * Register to be notified whenever a torrent's "completeness"
1421 * changes. This will be called, for example, when a torrent
1422 * finishes downloading and changes from TR_LEECH to
1423 * either TR_SEED or TR_PARTIAL_SEED.
1424 *
1425 * func is invoked FROM LIBTRANSMISSION'S THREAD!
1426 * This means func must be fast (to avoid blocking peers),
1427 * shouldn't call libtransmission functions (to avoid deadlock),
1428 * and shouldn't modify client-level memory without using a mutex!
1429 *
1430 * @see tr_completeness
1431 */
1432void tr_torrentSetCompletenessCallback(
1433         tr_torrent                    * torrent,
1434         tr_torrent_completeness_func    func,
1435         void                          * user_data );
1436
1437void tr_torrentClearCompletenessCallback( tr_torrent * torrent );
1438
1439
1440
1441typedef void ( tr_torrent_metadata_func )( tr_torrent  * torrent,
1442                                           void        * user_data );
1443/**
1444 * Register to be notified whenever a torrent changes from
1445 * having incomplete metadata to having complete metadata.
1446 * This happens when a magnet link finishes downloading
1447 * metadata from its peers.
1448 */
1449void tr_torrentSetMetadataCallback (
1450         tr_torrent                * tor,
1451         tr_torrent_metadata_func     func,
1452         void                      * user_data );
1453
1454/**
1455 * Register to be notified whenever a torrent's ratio limit
1456 * has been hit. This will be called when the torrent's
1457 * ul/dl ratio has met or exceeded the designated ratio limit.
1458 *
1459 * Has the same restrictions as tr_torrentSetCompletenessCallback
1460 */
1461void tr_torrentSetRatioLimitHitCallback(
1462     tr_torrent                     * torrent,
1463     tr_torrent_ratio_limit_hit_func  func,
1464     void                           * user_data );
1465
1466void tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent );
1467
1468/**
1469 * Register to be notified whenever a torrent's idle limit
1470 * has been hit. This will be called when the seeding torrent's
1471 * idle time has met or exceeded the designated idle limit.
1472 *
1473 * Has the same restrictions as tr_torrentSetCompletenessCallback
1474 */
1475void tr_torrentSetIdleLimitHitCallback(
1476     tr_torrent                          * torrent,
1477     tr_torrent_idle_limit_hit_func        func,
1478     void                                * user_data );
1479
1480void tr_torrentClearIdleLimitHitCallback( tr_torrent * torrent );
1481
1482
1483/**
1484 * MANUAL ANNOUNCE
1485 *
1486 * Trackers usually set an announce interval of 15 or 30 minutes.
1487 * Users can send one-time announce requests that override this
1488 * interval by calling tr_torrentManualUpdate().
1489 *
1490 * The wait interval for tr_torrentManualUpdate() is much smaller.
1491 * You can test whether or not a manual update is possible
1492 * (for example, to desensitize the button) by calling
1493 * tr_torrentCanManualUpdate().
1494 */
1495
1496void tr_torrentManualUpdate( tr_torrent * torrent );
1497
1498bool tr_torrentCanManualUpdate( const tr_torrent * torrent );
1499
1500/***
1501****  tr_peer_stat
1502***/
1503
1504typedef struct tr_peer_stat
1505{
1506    bool  isUTP;
1507
1508    bool  isEncrypted;
1509    bool  isDownloadingFrom;
1510    bool  isUploadingTo;
1511    bool  isSeed;
1512
1513    bool  peerIsChoked;
1514    bool  peerIsInterested;
1515    bool  clientIsChoked;
1516    bool  clientIsInterested;
1517    bool  isIncoming;
1518
1519    uint8_t  from;
1520    tr_port  port;
1521
1522    char     addr[TR_INET6_ADDRSTRLEN];
1523    char     client[80];
1524    char     flagStr[32];
1525
1526    float    progress;
1527    double   rateToPeer_KBps;
1528    double   rateToClient_KBps;
1529
1530
1531/***
1532****  THESE NEXT FOUR FIELDS ARE EXPERIMENTAL.
1533****  Don't rely on them; they'll probably go away
1534***/
1535    /* how many blocks we've sent to this peer in the last 120 seconds */
1536    uint32_t  blocksToPeer;
1537    /* how many blocks this client's sent to us in the last 120 seconds */
1538    uint32_t  blocksToClient;
1539    /* how many requests to this peer that we've cancelled in the last 120 seconds */
1540    uint32_t  cancelsToPeer;
1541    /* how many requests this peer made of us, then cancelled, in the last 120 seconds */
1542    uint32_t  cancelsToClient;
1543
1544    /* how many requests the peer has made that we haven't responded to yet */
1545    int      pendingReqsToClient;
1546
1547    /* how many requests we've made and are currently awaiting a response for */
1548    int      pendingReqsToPeer;
1549}
1550tr_peer_stat;
1551
1552tr_peer_stat * tr_torrentPeers( const tr_torrent * torrent,
1553                                int *              peerCount );
1554
1555void           tr_torrentPeersFree( tr_peer_stat * peerStats,
1556                                    int            peerCount );
1557
1558/***
1559****  tr_tracker_stat
1560***/
1561
1562typedef enum
1563{
1564    /* we won't (announce,scrape) this torrent to this tracker because
1565     * the torrent is stopped, or because of an error, or whatever */
1566    TR_TRACKER_INACTIVE = 0,
1567
1568    /* we will (announce,scrape) this torrent to this tracker, and are
1569     * waiting for enough time to pass to satisfy the tracker's interval */
1570    TR_TRACKER_WAITING = 1,
1571
1572    /* it's time to (announce,scrape) this torrent, and we're waiting on a
1573     * a free slot to open up in the announce manager */
1574    TR_TRACKER_QUEUED = 2,
1575
1576    /* we're (announcing,scraping) this torrent right now */
1577    TR_TRACKER_ACTIVE = 3
1578}
1579tr_tracker_state;
1580
1581typedef struct
1582{
1583    /* how many downloads this tracker knows of (-1 means it does not know) */
1584    int downloadCount;
1585
1586    /* whether or not we've ever sent this tracker an announcement */
1587    bool hasAnnounced;
1588
1589    /* whether or not we've ever scraped to this tracker */
1590    bool hasScraped;
1591
1592    /* human-readable string identifying the tracker */
1593    char host[1024];
1594
1595    /* the full announce URL */
1596    char announce[1024];
1597
1598    /* the full scrape URL */
1599    char scrape[1024];
1600
1601    /* Transmission uses one tracker per tier,
1602     * and the others are kept as backups */
1603    bool isBackup;
1604
1605    /* is the tracker announcing, waiting, queued, etc */
1606    tr_tracker_state announceState;
1607
1608    /* is the tracker scraping, waiting, queued, etc */
1609    tr_tracker_state scrapeState;
1610
1611    /* number of peers the tracker told us about last time.
1612     * if "lastAnnounceSucceeded" is false, this field is undefined */
1613    int lastAnnouncePeerCount;
1614
1615    /* human-readable string with the result of the last announce.
1616       if "hasAnnounced" is false, this field is undefined */
1617    char lastAnnounceResult[128];
1618
1619    /* when the last announce was sent to the tracker.
1620     * if "hasAnnounced" is false, this field is undefined */
1621    time_t lastAnnounceStartTime;
1622
1623    /* whether or not the last announce was a success.
1624       if "hasAnnounced" is false, this field is undefined */
1625    bool lastAnnounceSucceeded;
1626
1627    /* whether or not the last announce timed out. */
1628    bool lastAnnounceTimedOut;
1629
1630    /* when the last announce was completed.
1631       if "hasAnnounced" is false, this field is undefined */
1632    time_t lastAnnounceTime;
1633
1634    /* human-readable string with the result of the last scrape.
1635     * if "hasScraped" is false, this field is undefined */
1636    char lastScrapeResult[128];
1637
1638    /* when the last scrape was sent to the tracker.
1639     * if "hasScraped" is false, this field is undefined */
1640    time_t lastScrapeStartTime;
1641
1642    /* whether or not the last scrape was a success.
1643       if "hasAnnounced" is false, this field is undefined */
1644    bool lastScrapeSucceeded;
1645
1646    /* whether or not the last scrape timed out. */
1647    bool lastScrapeTimedOut;
1648
1649    /* when the last scrape was completed.
1650       if "hasScraped" is false, this field is undefined */
1651    time_t lastScrapeTime;
1652
1653    /* number of leechers this tracker knows of (-1 means it does not know) */
1654    int leecherCount;
1655
1656    /* when the next periodic announce message will be sent out.
1657       if announceState isn't TR_TRACKER_WAITING, this field is undefined */
1658    time_t nextAnnounceTime;
1659
1660    /* when the next periodic scrape message will be sent out.
1661       if scrapeState isn't TR_TRACKER_WAITING, this field is undefined */
1662    time_t nextScrapeTime;
1663
1664    /* number of seeders this tracker knows of (-1 means it does not know) */
1665    int seederCount;
1666
1667    /* which tier this tracker is in */
1668    int tier;
1669
1670    /* used to match to a tr_tracker_info */
1671    uint32_t id;
1672}
1673tr_tracker_stat;
1674
1675tr_tracker_stat * tr_torrentTrackers( const tr_torrent * torrent,
1676                                      int              * setmeTrackerCount );
1677
1678void tr_torrentTrackersFree( tr_tracker_stat * trackerStats,
1679                             int               trackerCount );
1680
1681
1682
1683/**
1684 * @brief get the download speeds for each of this torrent's webseed sources.
1685 *
1686 * @return an array of tor->info.webseedCount floats giving download speeds.
1687 *         Each speed in the array corresponds to the webseed at the same
1688 *         array index in tor->info.webseeds.
1689 *         To differentiate "idle" and "stalled" status, idle webseeds will
1690 *         return -1 instead of 0 KiB/s.
1691 *         NOTE: always free this array with tr_free() when you're done with it.
1692 */
1693double*  tr_torrentWebSpeeds_KBps( const tr_torrent * torrent );
1694
1695typedef struct tr_file_stat
1696{
1697    uint64_t    bytesCompleted;
1698    float       progress;
1699}
1700tr_file_stat;
1701
1702tr_file_stat * tr_torrentFiles( const tr_torrent  * torrent,
1703                                tr_file_index_t   * fileCount );
1704
1705void tr_torrentFilesFree( tr_file_stat     * files,
1706                          tr_file_index_t    fileCount );
1707
1708
1709/***********************************************************************
1710 * tr_torrentAvailability
1711 ***********************************************************************
1712 * Use this to draw an advanced progress bar which is 'size' pixels
1713 * wide. Fills 'tab' which you must have allocated: each byte is set
1714 * to either -1 if we have the piece, otherwise it is set to the number
1715 * of connected peers who have the piece.
1716 **********************************************************************/
1717void tr_torrentAvailability( const tr_torrent  * torrent,
1718                             int8_t            * tab,
1719                             int                  size );
1720
1721void tr_torrentAmountFinished( const tr_torrent  * torrent,
1722                               float *             tab,
1723                               int                 size );
1724
1725void tr_torrentVerify( tr_torrent * torrent );
1726
1727/***********************************************************************
1728 * tr_info
1729 **********************************************************************/
1730
1731/** @brief a part of tr_info that represents a single file of the torrent's content */
1732typedef struct tr_file
1733{
1734    uint64_t          length;      /* Length of the file, in bytes */
1735    char *            name;        /* Path to the file */
1736    int8_t            priority;    /* TR_PRI_HIGH, _NORMAL, or _LOW */
1737    int8_t            dnd;         /* "do not download" flag */
1738    tr_piece_index_t  firstPiece;  /* We need pieces [firstPiece... */
1739    tr_piece_index_t  lastPiece;   /* ...lastPiece] to dl this file */
1740    uint64_t          offset;      /* file begins at the torrent's nth byte */
1741}
1742tr_file;
1743
1744/** @brief a part of tr_info that represents a single piece of the torrent's content */
1745typedef struct tr_piece
1746{
1747    time_t   timeChecked;              /* the last time we tested this piece */
1748    uint8_t  hash[SHA_DIGEST_LENGTH];  /* pieces hash */
1749    int8_t   priority;                 /* TR_PRI_HIGH, _NORMAL, or _LOW */
1750    int8_t   dnd;                      /* "do not download" flag */
1751}
1752tr_piece;
1753
1754/** @brief information about a torrent that comes from its metainfo file */
1755struct tr_info
1756{
1757    /* total size of the torrent, in bytes */
1758    uint64_t           totalSize;
1759
1760    /* the torrent's name */
1761    char             * name;
1762
1763    /* Path to torrent Transmission's internal copy of the .torrent file. */
1764    char             * torrent;
1765
1766    char            ** webseeds;
1767
1768    char             * comment;
1769    char             * creator;
1770    tr_file          * files;
1771    tr_piece         * pieces;
1772
1773    /* these trackers are sorted by tier */
1774    tr_tracker_info  * trackers;
1775
1776    /* Torrent info */
1777    time_t             dateCreated;
1778
1779    int                trackerCount;
1780    int                webseedCount;
1781    tr_file_index_t    fileCount;
1782    uint32_t           pieceSize;
1783    tr_piece_index_t   pieceCount;
1784
1785    /* General info */
1786    uint8_t            hash[SHA_DIGEST_LENGTH];
1787    char               hashString[2 * SHA_DIGEST_LENGTH + 1];
1788
1789    /* Flags */
1790    bool               isPrivate;
1791    bool               isMultifile;
1792};
1793
1794static inline bool tr_torrentHasMetadata( const tr_torrent * tor )
1795{
1796    return tr_torrentInfo( tor )->fileCount > 0;
1797}
1798
1799/**
1800 * What the torrent is doing right now.
1801 *
1802 * Note: these values will become a straight enum at some point in the future.
1803 * Do not rely on their current `bitfield' implementation
1804 */
1805typedef enum
1806{
1807    TR_STATUS_STOPPED        = 0, /* Torrent is stopped */
1808    TR_STATUS_CHECK_WAIT     = 1, /* Queued to check files */
1809    TR_STATUS_CHECK          = 2, /* Checking files */
1810    TR_STATUS_DOWNLOAD_WAIT  = 3, /* Queued to download */
1811    TR_STATUS_DOWNLOAD       = 4, /* Downloading */
1812    TR_STATUS_SEED_WAIT      = 5, /* Queued to seed */
1813    TR_STATUS_SEED           = 6  /* Seeding */
1814}
1815tr_torrent_activity;
1816
1817enum
1818{
1819    TR_PEER_FROM_INCOMING  = 0, /* connections made to the listening port */
1820    TR_PEER_FROM_LPD,           /* peers found by local announcements */
1821    TR_PEER_FROM_TRACKER,       /* peers found from a tracker */
1822    TR_PEER_FROM_DHT,           /* peers found from the DHT */
1823    TR_PEER_FROM_PEX,           /* peers found from PEX */
1824    TR_PEER_FROM_RESUME,        /* peers found in the .resume file */
1825    TR_PEER_FROM_LTEP,          /* peer address provided in an LTEP handshake */
1826    TR_PEER_FROM__MAX
1827};
1828
1829typedef enum
1830{
1831    /* everything's fine */
1832    TR_STAT_OK               = 0,
1833
1834    /* when we anounced to the tracker, we got a warning in the response */
1835    TR_STAT_TRACKER_WARNING  = 1,
1836
1837    /* when we anounced to the tracker, we got an error in the response */
1838    TR_STAT_TRACKER_ERROR    = 2,
1839
1840    /* local trouble, such as disk full or permissions error */
1841    TR_STAT_LOCAL_ERROR      = 3
1842}
1843tr_stat_errtype;
1844
1845/** @brief Used by tr_torrentStat() to tell clients about a torrent's state and statistics */
1846typedef struct tr_stat
1847{
1848    /** The torrent's unique Id.
1849        @see tr_torrentId() */
1850    int    id;
1851
1852    /** What is this torrent doing right now? */
1853    tr_torrent_activity activity;
1854
1855    /** Defines what kind of text is in errorString.
1856        @see errorString */
1857    tr_stat_errtype error;
1858
1859    /** A warning or error message regarding the torrent.
1860        @see error */
1861    char errorString[512];
1862
1863    /** When tr_stat.activity is TR_STATUS_CHECK or TR_STATUS_CHECK_WAIT,
1864        this is the percentage of how much of the files has been
1865        verified. When it gets to 1, the verify process is done.
1866        Range is [0..1]
1867        @see tr_stat.activity */
1868    float recheckProgress;
1869
1870    /** How much has been downloaded of the entire torrent.
1871        Range is [0..1] */
1872    float percentComplete;
1873
1874    /** How much of the metadata the torrent has.
1875        For torrents added from a .torrent this will always be 1.
1876        For magnet links, this number will from from 0 to 1 as the metadata is downloaded.
1877        Range is [0..1] */
1878    float metadataPercentComplete;
1879
1880    /** How much has been downloaded of the files the user wants. This differs
1881        from percentComplete if the user wants only some of the torrent's files.
1882        Range is [0..1]
1883        @see tr_stat.leftUntilDone */
1884    float percentDone;
1885
1886    /** How much has been uploaded to satisfy the seed ratio.
1887        This is 1 if the ratio is reached or the torrent is set to seed forever.
1888        Range is [0..1] */
1889    float seedRatioPercentDone;
1890
1891    /** Speed all data being sent for this torrent.
1892        This includes piece data, protocol messages, and TCP overhead */
1893    float rawUploadSpeed_KBps;
1894
1895    /** Speed all data being received for this torrent.
1896        This includes piece data, protocol messages, and TCP overhead */
1897    float rawDownloadSpeed_KBps;
1898
1899    /** Speed all piece being sent for this torrent.
1900        This ONLY counts piece data. */
1901    float pieceUploadSpeed_KBps;
1902
1903    /** Speed all piece being received for this torrent.
1904        This ONLY counts piece data. */
1905    float pieceDownloadSpeed_KBps;
1906
1907#define TR_ETA_NOT_AVAIL -1
1908#define TR_ETA_UNKNOWN -2
1909    /** If downloading, estimated number of seconds left until the torrent is done.
1910        If seeding, estimated number of seconds left until seed ratio is reached. */
1911    int    eta;
1912    /** If seeding, number of seconds left until the idle time limit is reached. */
1913    int    etaIdle;
1914
1915    /** Number of peers that we're connected to */
1916    int    peersConnected;
1917
1918    /** How many peers we found out about from the tracker, or from pex,
1919        or from incoming connections, or from our resume file. */
1920    int    peersFrom[TR_PEER_FROM__MAX];
1921
1922    /** Number of peers that are sending data to us. */
1923    int    peersSendingToUs;
1924
1925    /** Number of peers that we're sending data to */
1926    int    peersGettingFromUs;
1927
1928    /** Number of webseeds that are sending data to us. */
1929    int    webseedsSendingToUs;
1930
1931    /** Byte count of all the piece data we'll have downloaded when we're done,
1932        whether or not we have it yet. This may be less than tr_info.totalSize
1933        if only some of the torrent's files are wanted.
1934        [0...tr_info.totalSize] */
1935    uint64_t    sizeWhenDone;
1936
1937    /** Byte count of how much data is left to be downloaded until we've got
1938        all the pieces that we want. [0...tr_info.sizeWhenDone] */
1939    uint64_t    leftUntilDone;
1940
1941    /** Byte count of all the piece data we want and don't have yet,
1942        but that a connected peer does have. [0...leftUntilDone] */
1943    uint64_t    desiredAvailable;
1944
1945    /** Byte count of all the corrupt data you've ever downloaded for
1946        this torrent. If you're on a poisoned torrent, this number can
1947        grow very large. */
1948    uint64_t    corruptEver;
1949
1950    /** Byte count of all data you've ever uploaded for this torrent. */
1951    uint64_t    uploadedEver;
1952
1953    /** Byte count of all the non-corrupt data you've ever downloaded
1954        for this torrent. If you deleted the files and downloaded a second
1955        time, this will be 2*totalSize.. */
1956    uint64_t    downloadedEver;
1957
1958    /** Byte count of all the checksum-verified data we have for this torrent.
1959      */
1960    uint64_t    haveValid;
1961
1962    /** Byte count of all the partial piece data we have for this torrent.
1963        As pieces become complete, this value may decrease as portions of it
1964        are moved to `corrupt' or `haveValid'. */
1965    uint64_t    haveUnchecked;
1966
1967    /** time when one or more of the torrent's trackers will
1968        allow you to manually ask for more peers,
1969        or 0 if you can't */
1970    time_t manualAnnounceTime;
1971
1972#define TR_RATIO_NA  -1
1973#define TR_RATIO_INF -2
1974    /** TR_RATIO_INF, TR_RATIO_NA, or a regular ratio */
1975    float    ratio;
1976
1977    /** When the torrent was first added. */
1978    time_t    addedDate;
1979
1980    /** When the torrent finished downloading. */
1981    time_t    doneDate;
1982
1983    /** When the torrent was last started. */
1984    time_t    startDate;
1985
1986    /** The last time we uploaded or downloaded piece data on this torrent. */
1987    time_t    activityDate;
1988
1989    /** Number of seconds since the last activity (or since started).
1990        -1 if activity is not seeding or downloading. */
1991    int    idleSecs;
1992
1993    /** Cumulative seconds the torrent's ever spent downloading */
1994    int    secondsDownloading;
1995
1996    /** Cumulative seconds the torrent's ever spent seeding */
1997    int    secondsSeeding;
1998
1999    /** A torrent is considered finished if it has met its seed ratio.
2000        As a result, only paused torrents can be finished. */
2001    bool   finished;
2002
2003    /** This torrent's queue position.
2004        All torrents have a queue position, even if it's not queued. */
2005    int queuePosition;
2006
2007    /** True if the torrent is running, but has been idle for long enough
2008        to be considered stalled.  @see tr_sessionGetQueueStalledMinutes() */
2009    bool isStalled;
2010}
2011tr_stat;
2012
2013/** Return a pointer to an tr_stat structure with updated information
2014    on the torrent. This is typically called by the GUI clients every
2015    second or so to get a new snapshot of the torrent's status. */
2016const tr_stat * tr_torrentStat( tr_torrent * torrent );
2017
2018/** Like tr_torrentStat(), but only recalculates the statistics if it's
2019    been longer than a second since they were last calculated. This can
2020    reduce the CPU load if you're calling tr_torrentStat() frequently. */
2021const tr_stat * tr_torrentStatCached( tr_torrent * torrent );
2022
2023/** @deprecated */
2024void tr_torrentSetAddedDate( tr_torrent * torrent,
2025                             time_t       addedDate );
2026
2027/** @deprecated */
2028void tr_torrentSetActivityDate( tr_torrent * torrent,
2029                                time_t       activityDate );
2030
2031/** @deprecated */
2032void tr_torrentSetDoneDate( tr_torrent * torrent, time_t doneDate );
2033
2034/** @} */
2035
2036/** @brief Sanity checker to test that the direction is TR_UP or TR_DOWN */
2037static inline bool tr_isDirection( tr_direction d ) { return d==TR_UP || d==TR_DOWN; }
2038
2039/** @brief Sanity checker to test that a bool is true or false */
2040static inline bool tr_isBool( bool b ) { return b==1 || b==0; }
2041
2042#ifdef __cplusplus
2043}
2044#endif
2045
2046#endif
Note: See TracBrowser for help on using the repository browser.