source: trunk/libtransmission/transmission.h @ 10508

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

(trunk libT) #3162 "allow optional end-user configuration of TCP_CONGESTION" -- add jch's implementation of this to trunk for 2.00

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