source: trunk/libtransmission/transmission.h @ 9891

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

(trunk libT) more documentation and doxygen markup

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