source: trunk/libtransmission/transmission.h @ 10390

Last change on this file since 10390 was 10390, checked in by charles, 12 years ago

(trunk) one of the least interesting commits ever: remove trailing spaces from source code lines...

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