source: trunk/libtransmission/transmission.h @ 10635

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

(trunk) #3060 "Local Peer Discovery" -- in the code, rename LDS as LPD for Local Peer Discovery

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