source: trunk/libtransmission/transmission.h @ 10438

Last change on this file since 10438 was 10438, checked in by livings124, 12 years ago

when the ratio is set to unlimited when resuming, reload the inspector

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