source: trunk/libtransmission/rpcimpl.c @ 12990

Last change on this file since 12990 was 12990, checked in by jordan, 5 years ago

(trunk libT) #4571 "can't edit UDP trackers via RPC" -- fixed.

  • Property svn:keywords set to Date Rev Author Id
File size: 70.6 KB
Line 
1/*
2 * This file Copyright (C) Mnemosyne LLC
3 *
4 * This file is licensed by the GPL version 2. Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: rpcimpl.c 12990 2011-10-17 12:44:17Z jordan $
11 */
12
13#include <assert.h>
14#include <ctype.h> /* isdigit */
15#include <errno.h>
16#include <stdlib.h> /* strtol */
17#include <string.h> /* strcmp */
18#include <unistd.h> /* unlink */
19
20#ifdef HAVE_ZLIB
21 #include <zlib.h>
22#endif
23
24#include <event2/buffer.h>
25
26#include "transmission.h"
27#include "bencode.h"
28#include "completion.h"
29#include "fdlimit.h"
30#include "json.h"
31#include "rpcimpl.h"
32#include "session.h"
33#include "torrent.h"
34#include "utils.h"
35#include "version.h"
36#include "web.h"
37
38#define RPC_VERSION     14
39#define RPC_VERSION_MIN 1
40
41#define RECENTLY_ACTIVE_SECONDS 60
42
43#define TR_N_ELEMENTS( ary ) ( sizeof( ary ) / sizeof( *ary ) )
44
45#if 0
46#define dbgmsg(fmt, ...) \
47    do { \
48        fprintf( stderr, "%s:%d"#fmt, __FILE__, __LINE__, __VA_ARGS__ ); \
49        fprintf( stderr, "\n" ); \
50    } while( 0 )
51#else
52#define dbgmsg( ... ) \
53    do { \
54        if( tr_deepLoggingIsActive( ) ) \
55            tr_deepLog( __FILE__, __LINE__, "RPC", __VA_ARGS__ ); \
56    } while( 0 )
57#endif
58
59
60/***
61****
62***/
63
64static tr_rpc_callback_status
65notify( tr_session * session,
66        int          type,
67        tr_torrent * tor )
68{
69    tr_rpc_callback_status status = 0;
70
71    if( session->rpc_func )
72        status = session->rpc_func( session, type, tor,
73                                    session->rpc_func_user_data );
74
75    return status;
76}
77
78/***
79****
80***/
81
82/* For functions that can't be immediately executed, like torrentAdd,
83 * this is the callback data used to pass a response to the caller
84 * when the task is complete */
85struct tr_rpc_idle_data
86{
87    tr_session            * session;
88    tr_benc               * response;
89    tr_benc               * args_out;
90    tr_rpc_response_func    callback;
91    void                  * callback_user_data;
92};
93
94static void
95tr_idle_function_done( struct tr_rpc_idle_data * data, const char * result )
96{
97    struct evbuffer * buf;
98
99    if( result == NULL )
100        result = "success";
101    tr_bencDictAddStr( data->response, "result", result );
102
103    buf = tr_bencToBuf( data->response, TR_FMT_JSON_LEAN );
104    (*data->callback)( data->session, buf, data->callback_user_data );
105    evbuffer_free( buf );
106
107    tr_bencFree( data->response );
108    tr_free( data->response );
109    tr_free( data );
110}
111
112/***
113****
114***/
115
116static tr_torrent **
117getTorrents( tr_session * session,
118             tr_benc    * args,
119             int        * setmeCount )
120{
121    int           torrentCount = 0;
122    int64_t       id;
123    tr_torrent ** torrents = NULL;
124    tr_benc *     ids;
125    const char * str;
126
127    if( tr_bencDictFindList( args, "ids", &ids ) )
128    {
129        int       i;
130        const int n = tr_bencListSize( ids );
131
132        torrents = tr_new0( tr_torrent *, n );
133
134        for( i = 0; i < n; ++i )
135        {
136            tr_torrent * tor = NULL;
137            tr_benc *    node = tr_bencListChild( ids, i );
138            const char * str;
139            if( tr_bencGetInt( node, &id ) )
140                tor = tr_torrentFindFromId( session, id );
141            else if( tr_bencGetStr( node, &str ) )
142                tor = tr_torrentFindFromHashString( session, str );
143            if( tor )
144                torrents[torrentCount++] = tor;
145        }
146    }
147    else if( tr_bencDictFindInt( args, "ids", &id )
148           || tr_bencDictFindInt( args, "id", &id ) )
149    {
150        tr_torrent * tor;
151        torrents = tr_new0( tr_torrent *, 1 );
152        if( ( tor = tr_torrentFindFromId( session, id ) ) )
153            torrents[torrentCount++] = tor;
154    }
155    else if( tr_bencDictFindStr( args, "ids", &str ) )
156    {
157        if( !strcmp( str, "recently-active" ) )
158        {
159            tr_torrent * tor = NULL;
160            const time_t now = tr_time( );
161            const time_t window = RECENTLY_ACTIVE_SECONDS;
162            const int n = tr_sessionCountTorrents( session );
163            torrents = tr_new0( tr_torrent *, n );
164            while( ( tor = tr_torrentNext( session, tor ) ) )
165                if( tor->anyDate >= now - window )
166                    torrents[torrentCount++] = tor;
167        }
168        else
169        {
170            tr_torrent * tor;
171            torrents = tr_new0( tr_torrent *, 1 );
172            if(( tor = tr_torrentFindFromHashString( session, str )))
173                torrents[torrentCount++] = tor;
174        }
175    }
176    else /* all of them */
177    {
178        tr_torrent * tor = NULL;
179        const int n = tr_sessionCountTorrents( session );
180        torrents = tr_new0( tr_torrent *, n );
181        while( ( tor = tr_torrentNext( session, tor ) ) )
182            torrents[torrentCount++] = tor;
183    }
184
185    *setmeCount = torrentCount;
186    return torrents;
187}
188
189static void
190notifyBatchQueueChange( tr_session * session, tr_torrent ** torrents, int n )
191{
192    int i;
193    for( i=0; i<n; ++i )
194        notify( session, TR_RPC_TORRENT_CHANGED, torrents[i] );
195    notify( session, TR_RPC_SESSION_QUEUE_POSITIONS_CHANGED, NULL );
196}
197
198static const char*
199queueMoveTop( tr_session               * session,
200              tr_benc                  * args_in,
201              tr_benc                  * args_out UNUSED,
202              struct tr_rpc_idle_data  * idle_data UNUSED )
203{
204    int n;
205    tr_torrent ** torrents = getTorrents( session, args_in, &n );
206    tr_torrentsQueueMoveTop( torrents, n );
207    notifyBatchQueueChange( session, torrents, n );
208    tr_free( torrents );
209    return NULL;
210}
211
212static const char*
213queueMoveUp( tr_session               * session,
214             tr_benc                  * args_in,
215             tr_benc                  * args_out UNUSED,
216             struct tr_rpc_idle_data  * idle_data UNUSED )
217{
218    int n;
219    tr_torrent ** torrents = getTorrents( session, args_in, &n );
220    tr_torrentsQueueMoveUp( torrents, n );
221    notifyBatchQueueChange( session, torrents, n );
222    tr_free( torrents );
223    return NULL;
224}
225
226static const char*
227queueMoveDown( tr_session               * session,
228               tr_benc                  * args_in,
229               tr_benc                  * args_out UNUSED,
230               struct tr_rpc_idle_data  * idle_data UNUSED )
231{
232    int n;
233    tr_torrent ** torrents = getTorrents( session, args_in, &n );
234    tr_torrentsQueueMoveDown( torrents, n );
235    notifyBatchQueueChange( session, torrents, n );
236    tr_free( torrents );
237    return NULL;
238}
239
240static const char*
241queueMoveBottom( tr_session               * session,
242                 tr_benc                  * args_in,
243                 tr_benc                  * args_out UNUSED,
244                 struct tr_rpc_idle_data  * idle_data UNUSED )
245{
246    int n;
247    tr_torrent ** torrents = getTorrents( session, args_in, &n );
248    tr_torrentsQueueMoveBottom( torrents, n );
249    notifyBatchQueueChange( session, torrents, n );
250    tr_free( torrents );
251    return NULL;
252}
253
254static const char*
255torrentStart( tr_session               * session,
256              tr_benc                  * args_in,
257              tr_benc                  * args_out UNUSED,
258              struct tr_rpc_idle_data  * idle_data UNUSED )
259{
260    int           i, torrentCount;
261    tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
262
263    assert( idle_data == NULL );
264
265    for( i = 0; i < torrentCount; ++i )
266    {
267        tr_torrent * tor = torrents[i];
268        if( !tor->isRunning )
269        {
270            tr_torrentStart( tor );
271            notify( session, TR_RPC_TORRENT_STARTED, tor );
272        }
273    }
274    tr_free( torrents );
275    return NULL;
276}
277
278static const char*
279torrentStartNow( tr_session               * session,
280                 tr_benc                  * args_in,
281                 tr_benc                  * args_out UNUSED,
282                 struct tr_rpc_idle_data  * idle_data UNUSED )
283{
284    int           i, torrentCount;
285    tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
286
287    assert( idle_data == NULL );
288
289    for( i = 0; i < torrentCount; ++i )
290    {
291        tr_torrent * tor = torrents[i];
292        if( !tor->isRunning )
293        {
294            tr_torrentStartNow( tor );
295            notify( session, TR_RPC_TORRENT_STARTED, tor );
296        }
297    }
298    tr_free( torrents );
299    return NULL;
300}
301
302static const char*
303torrentStop( tr_session               * session,
304             tr_benc                  * args_in,
305             tr_benc                  * args_out UNUSED,
306             struct tr_rpc_idle_data  * idle_data UNUSED )
307{
308    int           i, torrentCount;
309    tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
310
311    assert( idle_data == NULL );
312
313    for( i = 0; i < torrentCount; ++i )
314    {
315        tr_torrent * tor = torrents[i];
316
317        if( tor->isRunning || tr_torrentIsQueued( tor ) )
318        {
319            tor->isStopping = true;
320            notify( session, TR_RPC_TORRENT_STOPPED, tor );
321        }
322    }
323    tr_free( torrents );
324    return NULL;
325}
326
327static const char*
328torrentRemove( tr_session               * session,
329               tr_benc                  * args_in,
330               tr_benc                  * args_out UNUSED,
331               struct tr_rpc_idle_data  * idle_data UNUSED )
332{
333    int i;
334    int torrentCount;
335    tr_rpc_callback_type type;
336    bool deleteFlag = false;
337    tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
338
339    assert( idle_data == NULL );
340
341    tr_bencDictFindBool( args_in, "delete-local-data", &deleteFlag );
342    type = deleteFlag ? TR_RPC_TORRENT_TRASHING
343                      : TR_RPC_TORRENT_REMOVING;
344
345    for( i=0; i<torrentCount; ++i )
346    {
347        tr_torrent * tor = torrents[i];
348        const tr_rpc_callback_status status = notify( session, type, tor );
349        if( !( status & TR_RPC_NOREMOVE ) )
350            tr_torrentRemove( tor, deleteFlag, NULL );
351    }
352
353    tr_free( torrents );
354    return NULL;
355}
356
357static const char*
358torrentReannounce( tr_session               * session,
359                   tr_benc                  * args_in,
360                   tr_benc                  * args_out UNUSED,
361                   struct tr_rpc_idle_data  * idle_data UNUSED )
362{
363    int i, torrentCount;
364    tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
365
366    assert( idle_data == NULL );
367
368    for( i=0; i<torrentCount; ++i )
369    {
370        tr_torrent * tor = torrents[i];
371        if( tr_torrentCanManualUpdate( tor ) )
372        {
373            tr_torrentManualUpdate( tor );
374            notify( session, TR_RPC_TORRENT_CHANGED, tor );
375        }
376    }
377
378    tr_free( torrents );
379    return NULL;
380}
381
382static const char*
383torrentVerify( tr_session               * session,
384               tr_benc                  * args_in,
385               tr_benc                  * args_out UNUSED,
386               struct tr_rpc_idle_data  * idle_data UNUSED )
387{
388    int           i, torrentCount;
389    tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
390
391    assert( idle_data == NULL );
392
393    for( i = 0; i < torrentCount; ++i )
394    {
395        tr_torrent * tor = torrents[i];
396        tr_torrentVerify( tor );
397        notify( session, TR_RPC_TORRENT_CHANGED, tor );
398    }
399
400    tr_free( torrents );
401    return NULL;
402}
403
404/***
405****
406***/
407
408static void
409addFileStats( const tr_torrent * tor, tr_benc * list )
410{
411    tr_file_index_t i;
412    tr_file_index_t n;
413    const tr_info * info = tr_torrentInfo( tor );
414    tr_file_stat * files = tr_torrentFiles( tor, &n );
415
416    for( i = 0; i < info->fileCount; ++i )
417    {
418        const tr_file * file = &info->files[i];
419        tr_benc * d = tr_bencListAddDict( list, 3 );
420        tr_bencDictAddInt( d, "bytesCompleted", files[i].bytesCompleted );
421        tr_bencDictAddInt( d, "priority", file->priority );
422        tr_bencDictAddBool( d, "wanted", !file->dnd );
423    }
424
425    tr_torrentFilesFree( files, n );
426}
427
428static void
429addFiles( const tr_torrent * tor,
430          tr_benc *          list )
431{
432    tr_file_index_t i;
433    tr_file_index_t n;
434    const tr_info * info = tr_torrentInfo( tor );
435    tr_file_stat *  files = tr_torrentFiles( tor, &n );
436
437    for( i = 0; i < info->fileCount; ++i )
438    {
439        const tr_file * file = &info->files[i];
440        tr_benc *       d = tr_bencListAddDict( list, 3 );
441        tr_bencDictAddInt( d, "bytesCompleted", files[i].bytesCompleted );
442        tr_bencDictAddInt( d, "length", file->length );
443        tr_bencDictAddStr( d, "name", file->name );
444    }
445
446    tr_torrentFilesFree( files, n );
447}
448
449static void
450addWebseeds( const tr_info * info,
451             tr_benc *       webseeds )
452{
453    int i;
454
455    for( i = 0; i < info->webseedCount; ++i )
456        tr_bencListAddStr( webseeds, info->webseeds[i] );
457}
458
459static void
460addTrackers( const tr_info * info,
461             tr_benc *       trackers )
462{
463    int i;
464
465    for( i = 0; i < info->trackerCount; ++i )
466    {
467        const tr_tracker_info * t = &info->trackers[i];
468        tr_benc *               d = tr_bencListAddDict( trackers, 4 );
469        tr_bencDictAddStr( d, "announce", t->announce );
470        tr_bencDictAddInt( d, "id", t->id );
471        tr_bencDictAddStr( d, "scrape", t->scrape );
472        tr_bencDictAddInt( d, "tier", t->tier );
473    }
474}
475
476static void
477addTrackerStats( const tr_tracker_stat * st, int n, tr_benc * list )
478{
479    int i;
480
481    for( i=0; i<n; ++i )
482    {
483        const tr_tracker_stat * s = &st[i];
484        tr_benc * d = tr_bencListAddDict( list, 26 );
485        tr_bencDictAddStr ( d, "announce", s->announce );
486        tr_bencDictAddInt ( d, "announceState", s->announceState );
487        tr_bencDictAddInt ( d, "downloadCount", s->downloadCount );
488        tr_bencDictAddBool( d, "hasAnnounced", s->hasAnnounced );
489        tr_bencDictAddBool( d, "hasScraped", s->hasScraped );
490        tr_bencDictAddStr ( d, "host", s->host );
491        tr_bencDictAddInt ( d, "id", s->id );
492        tr_bencDictAddBool( d, "isBackup", s->isBackup );
493        tr_bencDictAddInt ( d, "lastAnnouncePeerCount", s->lastAnnouncePeerCount );
494        tr_bencDictAddStr ( d, "lastAnnounceResult", s->lastAnnounceResult );
495        tr_bencDictAddInt ( d, "lastAnnounceStartTime", s->lastAnnounceStartTime );
496        tr_bencDictAddBool( d, "lastAnnounceSucceeded", s->lastAnnounceSucceeded );
497        tr_bencDictAddInt ( d, "lastAnnounceTime", s->lastAnnounceTime );
498        tr_bencDictAddBool( d, "lastAnnounceTimedOut", s->lastAnnounceTimedOut );
499        tr_bencDictAddStr ( d, "lastScrapeResult", s->lastScrapeResult );
500        tr_bencDictAddInt ( d, "lastScrapeStartTime", s->lastScrapeStartTime );
501        tr_bencDictAddBool( d, "lastScrapeSucceeded", s->lastScrapeSucceeded );
502        tr_bencDictAddInt ( d, "lastScrapeTime", s->lastScrapeTime );
503        tr_bencDictAddInt ( d, "lastScrapeTimedOut", s->lastScrapeTimedOut );
504        tr_bencDictAddInt ( d, "leecherCount", s->leecherCount );
505        tr_bencDictAddInt ( d, "nextAnnounceTime", s->nextAnnounceTime );
506        tr_bencDictAddInt ( d, "nextScrapeTime", s->nextScrapeTime );
507        tr_bencDictAddStr ( d, "scrape", s->scrape );
508        tr_bencDictAddInt ( d, "scrapeState", s->scrapeState );
509        tr_bencDictAddInt ( d, "seederCount", s->seederCount );
510        tr_bencDictAddInt ( d, "tier", s->tier );
511    }
512}
513
514static void
515addPeers( const tr_torrent * tor,
516          tr_benc *          list )
517{
518    int            i;
519    int            peerCount;
520    tr_peer_stat * peers = tr_torrentPeers( tor, &peerCount );
521
522    tr_bencInitList( list, peerCount );
523
524    for( i = 0; i < peerCount; ++i )
525    {
526        tr_benc *            d = tr_bencListAddDict( list, 14 );
527        const tr_peer_stat * peer = peers + i;
528        tr_bencDictAddStr ( d, "address", peer->addr );
529        tr_bencDictAddStr ( d, "clientName", peer->client );
530        tr_bencDictAddBool( d, "clientIsChoked", peer->clientIsChoked );
531        tr_bencDictAddBool( d, "clientIsInterested", peer->clientIsInterested );
532        tr_bencDictAddStr ( d, "flagStr", peer->flagStr );
533        tr_bencDictAddBool( d, "isDownloadingFrom", peer->isDownloadingFrom );
534        tr_bencDictAddBool( d, "isEncrypted", peer->isEncrypted );
535        tr_bencDictAddBool( d, "isIncoming", peer->isIncoming );
536        tr_bencDictAddBool( d, "isUploadingTo", peer->isUploadingTo );
537        tr_bencDictAddBool( d, "isUTP", peer->isUTP );
538        tr_bencDictAddBool( d, "peerIsChoked", peer->peerIsChoked );
539        tr_bencDictAddBool( d, "peerIsInterested", peer->peerIsInterested );
540        tr_bencDictAddInt ( d, "port", peer->port );
541        tr_bencDictAddReal( d, "progress", peer->progress );
542        tr_bencDictAddInt ( d, "rateToClient", toSpeedBytes( peer->rateToClient_KBps ) );
543        tr_bencDictAddInt ( d, "rateToPeer", toSpeedBytes( peer->rateToPeer_KBps ) );
544    }
545
546    tr_torrentPeersFree( peers, peerCount );
547}
548
549/* faster-than-strcmp() optimization. This is kind of clumsy,
550   but addField() was in the profiler's top 10 list, and this
551   makes it 4x faster... */
552#define tr_streq(a,alen,b) ((alen+1==sizeof(b)) && !memcmp(a,b,alen))
553
554static void
555addField( const tr_torrent * const tor,
556          const tr_info    * const inf,
557          const tr_stat    * const st,
558          tr_benc          * const d,
559          const char       * const key )
560{
561    const size_t keylen = strlen( key );
562
563    if( tr_streq( key, keylen, "activityDate" ) )
564        tr_bencDictAddInt( d, key, st->activityDate );
565    else if( tr_streq( key, keylen, "addedDate" ) )
566        tr_bencDictAddInt( d, key, st->addedDate );
567    else if( tr_streq( key, keylen, "bandwidthPriority" ) )
568        tr_bencDictAddInt( d, key, tr_torrentGetPriority( tor ) );
569    else if( tr_streq( key, keylen, "comment" ) )
570        tr_bencDictAddStr( d, key, inf->comment ? inf->comment : "" );
571    else if( tr_streq( key, keylen, "corruptEver" ) )
572        tr_bencDictAddInt( d, key, st->corruptEver );
573    else if( tr_streq( key, keylen, "creator" ) )
574        tr_bencDictAddStr( d, key, inf->creator ? inf->creator : "" );
575    else if( tr_streq( key, keylen, "dateCreated" ) )
576        tr_bencDictAddInt( d, key, inf->dateCreated );
577    else if( tr_streq( key, keylen, "desiredAvailable" ) )
578        tr_bencDictAddInt( d, key, st->desiredAvailable );
579    else if( tr_streq( key, keylen, "doneDate" ) )
580        tr_bencDictAddInt( d, key, st->doneDate );
581    else if( tr_streq( key, keylen, "downloadDir" ) )
582        tr_bencDictAddStr( d, key, tr_torrentGetDownloadDir( tor ) );
583    else if( tr_streq( key, keylen, "downloadedEver" ) )
584        tr_bencDictAddInt( d, key, st->downloadedEver );
585    else if( tr_streq( key, keylen, "downloadLimit" ) )
586        tr_bencDictAddInt( d, key, tr_torrentGetSpeedLimit_KBps( tor, TR_DOWN ) );
587    else if( tr_streq( key, keylen, "downloadLimited" ) )
588        tr_bencDictAddBool( d, key, tr_torrentUsesSpeedLimit( tor, TR_DOWN ) );
589    else if( tr_streq( key, keylen, "error" ) )
590        tr_bencDictAddInt( d, key, st->error );
591    else if( tr_streq( key, keylen, "errorString" ) )
592        tr_bencDictAddStr( d, key, st->errorString );
593    else if( tr_streq( key, keylen, "eta" ) )
594        tr_bencDictAddInt( d, key, st->eta );
595    else if( tr_streq( key, keylen, "files" ) )
596        addFiles( tor, tr_bencDictAddList( d, key, inf->fileCount ) );
597    else if( tr_streq( key, keylen, "fileStats" ) )
598        addFileStats( tor, tr_bencDictAddList( d, key, inf->fileCount ) );
599    else if( tr_streq( key, keylen, "hashString" ) )
600        tr_bencDictAddStr( d, key, tor->info.hashString );
601    else if( tr_streq( key, keylen, "haveUnchecked" ) )
602        tr_bencDictAddInt( d, key, st->haveUnchecked );
603    else if( tr_streq( key, keylen, "haveValid" ) )
604        tr_bencDictAddInt( d, key, st->haveValid );
605    else if( tr_streq( key, keylen, "honorsSessionLimits" ) )
606        tr_bencDictAddBool( d, key, tr_torrentUsesSessionLimits( tor ) );
607    else if( tr_streq( key, keylen, "id" ) )
608        tr_bencDictAddInt( d, key, st->id );
609    else if( tr_streq( key, keylen, "isFinished" ) )
610        tr_bencDictAddBool( d, key, st->finished );
611    else if( tr_streq( key, keylen, "isPrivate" ) )
612        tr_bencDictAddBool( d, key, tr_torrentIsPrivate( tor ) );
613    else if( tr_streq( key, keylen, "isStalled" ) )
614        tr_bencDictAddBool( d, key, st->isStalled );
615    else if( tr_streq( key, keylen, "leftUntilDone" ) )
616        tr_bencDictAddInt( d, key, st->leftUntilDone );
617    else if( tr_streq( key, keylen, "manualAnnounceTime" ) )
618        tr_bencDictAddInt( d, key, st->manualAnnounceTime );
619    else if( tr_streq( key, keylen, "maxConnectedPeers" ) )
620        tr_bencDictAddInt( d, key,  tr_torrentGetPeerLimit( tor ) );
621    else if( tr_streq( key, keylen, "magnetLink" ) ) {
622        char * str = tr_torrentGetMagnetLink( tor );
623        tr_bencDictAddStr( d, key, str );
624        tr_free( str );
625    }
626    else if( tr_streq( key, keylen, "metadataPercentComplete" ) )
627        tr_bencDictAddReal( d, key, st->metadataPercentComplete );
628    else if( tr_streq( key, keylen, "name" ) )
629        tr_bencDictAddStr( d, key, tr_torrentName( tor ) );
630    else if( tr_streq( key, keylen, "percentDone" ) )
631        tr_bencDictAddReal( d, key, st->percentDone );
632    else if( tr_streq( key, keylen, "peer-limit" ) )
633        tr_bencDictAddInt( d, key, tr_torrentGetPeerLimit( tor ) );
634    else if( tr_streq( key, keylen, "peers" ) )
635        addPeers( tor, tr_bencDictAdd( d, key ) );
636    else if( tr_streq( key, keylen, "peersConnected" ) )
637        tr_bencDictAddInt( d, key, st->peersConnected );
638    else if( tr_streq( key, keylen, "peersFrom" ) )
639    {
640        tr_benc *   tmp = tr_bencDictAddDict( d, key, 6 );
641        const int * f = st->peersFrom;
642        tr_bencDictAddInt( tmp, "fromCache",    f[TR_PEER_FROM_RESUME] );
643        tr_bencDictAddInt( tmp, "fromDht",      f[TR_PEER_FROM_DHT] );
644        tr_bencDictAddInt( tmp, "fromIncoming", f[TR_PEER_FROM_INCOMING] );
645        tr_bencDictAddInt( tmp, "fromLpd",      f[TR_PEER_FROM_LPD] );
646        tr_bencDictAddInt( tmp, "fromLtep",     f[TR_PEER_FROM_LTEP] );
647        tr_bencDictAddInt( tmp, "fromPex",      f[TR_PEER_FROM_PEX] );
648        tr_bencDictAddInt( tmp, "fromTracker",  f[TR_PEER_FROM_TRACKER] );
649    }
650    else if( tr_streq( key, keylen, "peersGettingFromUs" ) )
651        tr_bencDictAddInt( d, key, st->peersGettingFromUs );
652    else if( tr_streq( key, keylen, "peersSendingToUs" ) )
653        tr_bencDictAddInt( d, key, st->peersSendingToUs );
654    else if( tr_streq( key, keylen, "pieces" ) ) {
655        size_t byte_count = 0;
656        void * bytes = tr_cpCreatePieceBitfield( &tor->completion, &byte_count );
657        char * str = tr_base64_encode( bytes, byte_count, NULL );
658        tr_bencDictAddStr( d, key, str!=NULL ? str : "" );
659        tr_free( str );
660        tr_free( bytes );
661    }
662    else if( tr_streq( key, keylen, "pieceCount" ) )
663        tr_bencDictAddInt( d, key, inf->pieceCount );
664    else if( tr_streq( key, keylen, "pieceSize" ) )
665        tr_bencDictAddInt( d, key, inf->pieceSize );
666    else if( tr_streq( key, keylen, "priorities" ) )
667    {
668        tr_file_index_t i;
669        tr_benc *       p = tr_bencDictAddList( d, key, inf->fileCount );
670        for( i = 0; i < inf->fileCount; ++i )
671            tr_bencListAddInt( p, inf->files[i].priority );
672    }
673    else if( tr_streq( key, keylen, "queuePosition" ) )
674        tr_bencDictAddInt( d, key, st->queuePosition );
675    else if( tr_streq( key, keylen, "rateDownload" ) )
676        tr_bencDictAddInt( d, key, toSpeedBytes( st->pieceDownloadSpeed_KBps ) );
677    else if( tr_streq( key, keylen, "rateUpload" ) )
678        tr_bencDictAddInt( d, key, toSpeedBytes( st->pieceUploadSpeed_KBps ) );
679    else if( tr_streq( key, keylen, "recheckProgress" ) )
680        tr_bencDictAddReal( d, key, st->recheckProgress );
681    else if( tr_streq( key, keylen, "seedIdleLimit" ) )
682        tr_bencDictAddInt( d, key, tr_torrentGetIdleLimit( tor ) );
683    else if( tr_streq( key, keylen, "seedIdleMode" ) )
684        tr_bencDictAddInt( d, key, tr_torrentGetIdleMode( tor ) );
685    else if( tr_streq( key, keylen, "seedRatioLimit" ) )
686        tr_bencDictAddReal( d, key, tr_torrentGetRatioLimit( tor ) );
687    else if( tr_streq( key, keylen, "seedRatioMode" ) )
688        tr_bencDictAddInt( d, key, tr_torrentGetRatioMode( tor ) );
689    else if( tr_streq( key, keylen, "sizeWhenDone" ) )
690        tr_bencDictAddInt( d, key, st->sizeWhenDone );
691    else if( tr_streq( key, keylen, "startDate" ) )
692        tr_bencDictAddInt( d, key, st->startDate );
693    else if( tr_streq( key, keylen, "status" ) )
694        tr_bencDictAddInt( d, key, st->activity );
695    else if( tr_streq( key, keylen, "secondsDownloading" ) )
696        tr_bencDictAddInt( d, key, st->secondsDownloading );
697    else if( tr_streq( key, keylen, "secondsSeeding" ) )
698        tr_bencDictAddInt( d, key, st->secondsSeeding );
699    else if( tr_streq( key, keylen, "trackers" ) )
700        addTrackers( inf, tr_bencDictAddList( d, key, inf->trackerCount ) );
701    else if( tr_streq( key, keylen, "trackerStats" ) ) {
702        int n;
703        tr_tracker_stat * s = tr_torrentTrackers( tor, &n );
704        addTrackerStats( s, n, tr_bencDictAddList( d, key, n ) );
705        tr_torrentTrackersFree( s, n );
706    }
707    else if( tr_streq( key, keylen, "torrentFile" ) )
708        tr_bencDictAddStr( d, key, inf->torrent );
709    else if( tr_streq( key, keylen, "totalSize" ) )
710        tr_bencDictAddInt( d, key, inf->totalSize );
711    else if( tr_streq( key, keylen, "uploadedEver" ) )
712        tr_bencDictAddInt( d, key, st->uploadedEver );
713    else if( tr_streq( key, keylen, "uploadLimit" ) )
714        tr_bencDictAddInt( d, key, tr_torrentGetSpeedLimit_KBps( tor, TR_UP ) );
715    else if( tr_streq( key, keylen, "uploadLimited" ) )
716        tr_bencDictAddBool( d, key, tr_torrentUsesSpeedLimit( tor, TR_UP ) );
717    else if( tr_streq( key, keylen, "uploadRatio" ) )
718        tr_bencDictAddReal( d, key, st->ratio );
719    else if( tr_streq( key, keylen, "wanted" ) )
720    {
721        tr_file_index_t i;
722        tr_benc *       w = tr_bencDictAddList( d, key, inf->fileCount );
723        for( i = 0; i < inf->fileCount; ++i )
724            tr_bencListAddInt( w, inf->files[i].dnd ? 0 : 1 );
725    }
726    else if( tr_streq( key, keylen, "webseeds" ) )
727        addWebseeds( inf, tr_bencDictAddList( d, key, inf->webseedCount ) );
728    else if( tr_streq( key, keylen, "webseedsSendingToUs" ) )
729        tr_bencDictAddInt( d, key, st->webseedsSendingToUs );
730}
731
732static void
733addInfo( const tr_torrent * tor, tr_benc * d, tr_benc * fields )
734{
735    const char * str;
736    const int n = tr_bencListSize( fields );
737
738    tr_bencInitDict( d, n );
739
740    if( n > 0 )
741    {
742        int i;
743        const tr_info const * inf = tr_torrentInfo( tor );
744        const tr_stat const * st = tr_torrentStat( (tr_torrent*)tor );
745
746        for( i=0; i<n; ++i )
747            if( tr_bencGetStr( tr_bencListChild( fields, i ), &str ) )
748                addField( tor, inf, st, d, str );
749    }
750}
751
752static const char*
753torrentGet( tr_session               * session,
754            tr_benc                  * args_in,
755            tr_benc                  * args_out,
756            struct tr_rpc_idle_data  * idle_data UNUSED )
757{
758    int           i, torrentCount;
759    tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
760    tr_benc *     list = tr_bencDictAddList( args_out, "torrents", torrentCount );
761    tr_benc *     fields;
762    const char *  msg = NULL;
763    const char *  strVal;
764
765    assert( idle_data == NULL );
766
767    if( tr_bencDictFindStr( args_in, "ids", &strVal ) && !strcmp( strVal, "recently-active" ) ) {
768        int n = 0;
769        tr_benc * d;
770        const time_t now = tr_time( );
771        const int interval = RECENTLY_ACTIVE_SECONDS;
772        tr_benc * removed_out = tr_bencDictAddList( args_out, "removed", 0 );
773        while(( d = tr_bencListChild( &session->removedTorrents, n++ ))) {
774            int64_t intVal;
775            if( tr_bencDictFindInt( d, "date", &intVal ) && ( intVal >= now - interval ) ) {
776                tr_bencDictFindInt( d, "id", &intVal );
777                tr_bencListAddInt( removed_out, intVal );
778            }
779        }
780    }
781
782    if( !tr_bencDictFindList( args_in, "fields", &fields ) )
783        msg = "no fields specified";
784    else for( i = 0; i < torrentCount; ++i )
785        addInfo( torrents[i], tr_bencListAdd( list ), fields );
786
787    tr_free( torrents );
788    return msg;
789}
790
791/***
792****
793***/
794
795static const char*
796setFilePriorities( tr_torrent * tor,
797                   int          priority,
798                   tr_benc *    list )
799{
800    int i;
801    int64_t tmp;
802    int fileCount = 0;
803    const int n = tr_bencListSize( list );
804    const char * errmsg = NULL;
805    tr_file_index_t * files = tr_new0( tr_file_index_t, tor->info.fileCount );
806
807    if( n )
808    {
809        for( i = 0; i < n; ++i ) {
810            if( tr_bencGetInt( tr_bencListChild( list, i ), &tmp ) ) {
811                if( 0 <= tmp && tmp < tor->info.fileCount ) {
812                    files[fileCount++] = tmp;
813                } else {
814                    errmsg = "file index out of range";
815                }
816            }
817        }
818    }
819    else /* if empty set, apply to all */
820    {
821        tr_file_index_t t;
822        for( t = 0; t < tor->info.fileCount; ++t )
823            files[fileCount++] = t;
824    }
825
826    if( fileCount )
827        tr_torrentSetFilePriorities( tor, files, fileCount, priority );
828
829    tr_free( files );
830    return errmsg;
831}
832
833static const char*
834setFileDLs( tr_torrent * tor,
835            int          do_download,
836            tr_benc *    list )
837{
838    int i;
839    int64_t tmp;
840    int fileCount = 0;
841    const int n = tr_bencListSize( list );
842    const char * errmsg = NULL;
843    tr_file_index_t * files = tr_new0( tr_file_index_t, tor->info.fileCount );
844
845    if( n ) /* if argument list, process them */
846    {
847        for( i = 0; i < n; ++i ) {
848            if( tr_bencGetInt( tr_bencListChild( list, i ), &tmp ) ) {
849                if( 0 <= tmp && tmp < tor->info.fileCount ) {
850                    files[fileCount++] = tmp;
851                } else {
852                    errmsg = "file index out of range";
853                }
854            }
855        }
856    }
857    else /* if empty set, apply to all */
858    {
859        tr_file_index_t t;
860        for( t = 0; t < tor->info.fileCount; ++t )
861            files[fileCount++] = t;
862    }
863
864    if( fileCount )
865        tr_torrentSetFileDLs( tor, files, fileCount, do_download );
866
867    tr_free( files );
868    return errmsg;
869}
870
871static bool
872findAnnounceUrl( const tr_tracker_info * t, int n, const char * url, int * pos )
873{
874    int i;
875    bool found = false;
876
877    for( i=0; i<n; ++i )
878    {
879        if( !strcmp( t[i].announce, url ) )
880        {
881            found = true;
882            if( pos ) *pos = i;
883            break;
884        }
885    }
886
887    return found;
888}
889
890static int
891copyTrackers( tr_tracker_info * tgt, const tr_tracker_info * src, int n )
892{
893    int i;
894    int maxTier = -1;
895
896    for( i=0; i<n; ++i )
897    {
898        tgt[i].tier = src[i].tier;
899        tgt[i].announce = tr_strdup( src[i].announce );
900        maxTier = MAX( maxTier, src[i].tier );
901    }
902
903    return maxTier;
904}
905
906static void
907freeTrackers( tr_tracker_info * trackers, int n )
908{
909    int i;
910
911    for( i=0; i<n; ++i )
912        tr_free( trackers[i].announce );
913
914    tr_free( trackers );
915}
916
917static const char*
918addTrackerUrls( tr_torrent * tor, tr_benc * urls )
919{
920    int i;
921    int n;
922    int tier;
923    tr_benc * val;
924    tr_tracker_info * trackers;
925    bool changed = false;
926    const tr_info * inf = tr_torrentInfo( tor );
927    const char * errmsg = NULL;
928
929    /* make a working copy of the existing announce list */
930    n = inf->trackerCount;
931    trackers = tr_new0( tr_tracker_info, n + tr_bencListSize( urls ) );
932    tier = copyTrackers( trackers, inf->trackers, n );
933
934    /* and add the new ones */
935    i = 0;
936    while(( val = tr_bencListChild( urls, i++ ) ))
937    {
938        const char * announce = NULL;
939
940        if(    tr_bencGetStr( val, &announce )
941            && tr_urlIsValidTracker( announce )
942            && !findAnnounceUrl( trackers, n, announce, NULL ) )
943        {
944            trackers[n].tier = ++tier; /* add a new tier */
945            trackers[n].announce = tr_strdup( announce );
946            ++n;
947            changed = true;
948        }
949    }
950
951    if( !changed )
952        errmsg = "invalid argument";
953    else if( !tr_torrentSetAnnounceList( tor, trackers, n ) )
954        errmsg = "error setting announce list";
955
956    freeTrackers( trackers, n );
957    return errmsg;
958}
959
960static const char*
961replaceTrackers( tr_torrent * tor, tr_benc * urls )
962{
963    int i;
964    tr_benc * pair[2];
965    tr_tracker_info * trackers;
966    bool changed = false;
967    const tr_info * inf = tr_torrentInfo( tor );
968    const int n = inf->trackerCount;
969    const char * errmsg = NULL;
970
971    /* make a working copy of the existing announce list */
972    trackers = tr_new0( tr_tracker_info, n );
973    copyTrackers( trackers, inf->trackers, n );
974
975    /* make the substitutions... */
976    i = 0;
977    while(((pair[0] = tr_bencListChild(urls,i))) &&
978          ((pair[1] = tr_bencListChild(urls,i+1))))
979    {
980        int64_t pos;
981        const char * newval;
982
983        if(    tr_bencGetInt( pair[0], &pos )
984            && tr_bencGetStr( pair[1], &newval )
985            && tr_urlIsValidTracker( newval )
986            && pos < n
987            && pos >= 0 )
988        {
989            tr_free( trackers[pos].announce );
990            trackers[pos].announce = tr_strdup( newval );
991            changed = true;
992        }
993
994        i += 2;
995    }
996
997    if( !changed )
998        errmsg = "invalid argument";
999    else if( !tr_torrentSetAnnounceList( tor, trackers, n ) )
1000        errmsg = "error setting announce list";
1001
1002    freeTrackers( trackers, n );
1003    return errmsg;
1004}
1005
1006static const char*
1007removeTrackers( tr_torrent * tor, tr_benc * ids )
1008{
1009    int i;
1010    int n;
1011    int t = 0;
1012    int dup = -1;
1013    int * tids;
1014    tr_benc * val;
1015    tr_tracker_info * trackers;
1016    bool changed = false;
1017    const tr_info * inf = tr_torrentInfo( tor );
1018    const char * errmsg = NULL;
1019
1020    /* make a working copy of the existing announce list */
1021    n = inf->trackerCount;
1022    tids = tr_new0( int, n );
1023    trackers = tr_new0( tr_tracker_info, n );
1024    copyTrackers( trackers, inf->trackers, n );
1025
1026    /* remove the ones specified in the urls list */
1027    i = 0;
1028    while(( val = tr_bencListChild( ids, i++ )))
1029    {
1030        int64_t pos;
1031
1032        if(    tr_bencGetInt( val, &pos )
1033            && pos < n
1034            && pos >= 0 )
1035            tids[t++] = pos;
1036    }
1037
1038    /* sort trackerIds and remove from largest to smallest so there is no need to recacluate array indicies */
1039    qsort( tids, t, sizeof(int), compareInt );
1040    while( t-- )
1041    {
1042        /* check for duplicates */
1043        if( tids[t] == dup )
1044            continue;
1045        tr_removeElementFromArray( trackers, tids[t], sizeof( tr_tracker_info ), n-- );
1046        dup = tids[t];
1047        changed = true;
1048    }
1049
1050    if( !changed )
1051        errmsg = "invalid argument";
1052    else if( !tr_torrentSetAnnounceList( tor, trackers, n ) )
1053        errmsg = "error setting announce list";
1054
1055    freeTrackers( trackers, n );
1056    tr_free( tids );
1057    return errmsg;
1058}
1059
1060static const char*
1061torrentSet( tr_session               * session,
1062            tr_benc                  * args_in,
1063            tr_benc                  * args_out UNUSED,
1064            struct tr_rpc_idle_data  * idle_data UNUSED )
1065{
1066    const char * errmsg = NULL;
1067    int i, torrentCount;
1068    tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
1069
1070    assert( idle_data == NULL );
1071
1072    for( i = 0; i < torrentCount; ++i )
1073    {
1074        int64_t      tmp;
1075        double       d;
1076        tr_benc *    files;
1077        tr_benc *    trackers;
1078        bool         boolVal;
1079        tr_torrent * tor = torrents[i];
1080
1081        if( tr_bencDictFindInt( args_in, "bandwidthPriority", &tmp ) )
1082            if( tr_isPriority( tmp ) )
1083                tr_torrentSetPriority( tor, tmp );
1084        if( !errmsg && tr_bencDictFindList( args_in, "files-unwanted", &files ) )
1085            errmsg = setFileDLs( tor, false, files );
1086        if( !errmsg && tr_bencDictFindList( args_in, "files-wanted", &files ) )
1087            errmsg = setFileDLs( tor, true, files );
1088        if( tr_bencDictFindInt( args_in, "peer-limit", &tmp ) )
1089            tr_torrentSetPeerLimit( tor, tmp );
1090        if( !errmsg &&  tr_bencDictFindList( args_in, "priority-high", &files ) )
1091            errmsg = setFilePriorities( tor, TR_PRI_HIGH, files );
1092        if( !errmsg && tr_bencDictFindList( args_in, "priority-low", &files ) )
1093            errmsg = setFilePriorities( tor, TR_PRI_LOW, files );
1094        if( !errmsg && tr_bencDictFindList( args_in, "priority-normal", &files ) )
1095            errmsg = setFilePriorities( tor, TR_PRI_NORMAL, files );
1096        if( tr_bencDictFindInt( args_in, "downloadLimit", &tmp ) )
1097            tr_torrentSetSpeedLimit_KBps( tor, TR_DOWN, tmp );
1098        if( tr_bencDictFindBool( args_in, "downloadLimited", &boolVal ) )
1099            tr_torrentUseSpeedLimit( tor, TR_DOWN, boolVal );
1100        if( tr_bencDictFindBool( args_in, "honorsSessionLimits", &boolVal ) )
1101            tr_torrentUseSessionLimits( tor, boolVal );
1102        if( tr_bencDictFindInt( args_in, "uploadLimit", &tmp ) )
1103            tr_torrentSetSpeedLimit_KBps( tor, TR_UP, tmp );
1104        if( tr_bencDictFindBool( args_in, "uploadLimited", &boolVal ) )
1105            tr_torrentUseSpeedLimit( tor, TR_UP, boolVal );
1106        if( tr_bencDictFindInt( args_in, "seedIdleLimit", &tmp ) )
1107            tr_torrentSetIdleLimit( tor, tmp );
1108        if( tr_bencDictFindInt( args_in, "seedIdleMode", &tmp ) )
1109            tr_torrentSetIdleMode( tor, tmp );
1110        if( tr_bencDictFindReal( args_in, "seedRatioLimit", &d ) )
1111            tr_torrentSetRatioLimit( tor, d );
1112        if( tr_bencDictFindInt( args_in, "seedRatioMode", &tmp ) )
1113            tr_torrentSetRatioMode( tor, tmp );
1114        if( tr_bencDictFindInt( args_in, "queuePosition", &tmp ) )
1115            tr_torrentSetQueuePosition( tor, tmp );
1116        if( !errmsg && tr_bencDictFindList( args_in, "trackerAdd", &trackers ) )
1117            errmsg = addTrackerUrls( tor, trackers );
1118        if( !errmsg && tr_bencDictFindList( args_in, "trackerRemove", &trackers ) )
1119            errmsg = removeTrackers( tor, trackers );
1120        if( !errmsg && tr_bencDictFindList( args_in, "trackerReplace", &trackers ) )
1121            errmsg = replaceTrackers( tor, trackers );
1122        notify( session, TR_RPC_TORRENT_CHANGED, tor );
1123    }
1124
1125    tr_free( torrents );
1126    return errmsg;
1127}
1128
1129static const char*
1130torrentSetLocation( tr_session               * session,
1131                    tr_benc                  * args_in,
1132                    tr_benc                  * args_out UNUSED,
1133                    struct tr_rpc_idle_data  * idle_data UNUSED )
1134{
1135    const char * errmsg = NULL;
1136    const char * location = NULL;
1137
1138    assert( idle_data == NULL );
1139
1140    if( !tr_bencDictFindStr( args_in, "location", &location ) )
1141    {
1142        errmsg = "no location";
1143    }
1144    else
1145    {
1146        bool move = false;
1147        int i, torrentCount;
1148        tr_torrent ** torrents = getTorrents( session, args_in, &torrentCount );
1149
1150        tr_bencDictFindBool( args_in, "move", &move );
1151
1152        for( i=0; i<torrentCount; ++i )
1153        {
1154            tr_torrent * tor = torrents[i];
1155            tr_torrentSetLocation( tor, location, move, NULL, NULL );
1156            notify( session, TR_RPC_TORRENT_MOVED, tor );
1157        }
1158
1159        tr_free( torrents );
1160    }
1161
1162    return errmsg;
1163}
1164
1165/***
1166****
1167***/
1168
1169static void
1170portTested( tr_session       * session UNUSED,
1171            bool               did_connect UNUSED,
1172            bool               did_timeout UNUSED,
1173            long               response_code,
1174            const void       * response,
1175            size_t             response_byte_count,
1176            void             * user_data )
1177{
1178    char result[1024];
1179    struct tr_rpc_idle_data * data = user_data;
1180
1181    if( response_code != 200 )
1182    {
1183        tr_snprintf( result, sizeof( result ), "portTested: http error %ld: %s",
1184                     response_code, tr_webGetResponseStr( response_code ) );
1185    }
1186    else /* success */
1187    {
1188        const bool isOpen = response_byte_count && *(char*)response == '1';
1189        tr_bencDictAddBool( data->args_out, "port-is-open", isOpen );
1190        tr_snprintf( result, sizeof( result ), "success" );
1191    }
1192
1193    tr_idle_function_done( data, result );
1194}
1195
1196static const char*
1197portTest( tr_session               * session,
1198          tr_benc                  * args_in UNUSED,
1199          tr_benc                  * args_out UNUSED,
1200          struct tr_rpc_idle_data  * idle_data )
1201{
1202    const int port = tr_sessionGetPeerPort( session );
1203    char * url = tr_strdup_printf( "http://portcheck.transmissionbt.com/%d", port );
1204    tr_webRun( session, url, NULL, NULL, portTested, idle_data );
1205    tr_free( url );
1206    return NULL;
1207}
1208
1209/***
1210****
1211***/
1212
1213static void
1214gotNewBlocklist( tr_session       * session,
1215                 bool               did_connect UNUSED,
1216                 bool               did_timeout UNUSED,
1217                 long               response_code,
1218                 const void       * response,
1219                 size_t             response_byte_count,
1220                 void             * user_data )
1221{
1222    char result[1024];
1223    struct tr_rpc_idle_data * data = user_data;
1224
1225    *result = '\0';
1226
1227    if( response_code != 200 )
1228    {
1229        tr_snprintf( result, sizeof( result ), "gotNewBlocklist: http error %ld: %s",
1230                     response_code, tr_webGetResponseStr( response_code ) );
1231    }
1232    else /* successfully fetched the blocklist... */
1233    {
1234        int fd;
1235        int err;
1236        char * filename;
1237        z_stream stream;
1238        const char * configDir = tr_sessionGetConfigDir( session );
1239        const size_t buflen = 1024 * 128; /* 128 KiB buffer */
1240        uint8_t * buf = tr_valloc( buflen );
1241
1242        /* this is an odd Magic Number required by zlib to enable gz support.
1243           See zlib's inflateInit2() documentation for a full description */
1244        const int windowBits = 15 + 32;
1245
1246        stream.zalloc = (alloc_func) Z_NULL;
1247        stream.zfree = (free_func) Z_NULL;
1248        stream.opaque = (voidpf) Z_NULL;
1249        stream.next_in = (void*) response;
1250        stream.avail_in = response_byte_count;
1251        inflateInit2( &stream, windowBits );
1252
1253        filename = tr_buildPath( configDir, "blocklist.tmp", NULL );
1254        fd = tr_open_file_for_writing( filename );
1255        if( fd < 0 )
1256            tr_snprintf( result, sizeof( result ), _( "Couldn't save file \"%1$s\": %2$s" ), filename, tr_strerror( errno ) );
1257
1258        for( ;; )
1259        {
1260            stream.next_out = (void*) buf;
1261            stream.avail_out = buflen;
1262            err = inflate( &stream, Z_NO_FLUSH );
1263
1264            if( stream.avail_out < buflen ) {
1265                const int e = write( fd, buf, buflen - stream.avail_out );
1266                if( e < 0 ) {
1267                    tr_snprintf( result, sizeof( result ), _( "Couldn't save file \"%1$s\": %2$s" ), filename, tr_strerror( errno ) );
1268                    break;
1269                }
1270            }
1271
1272            if( err != Z_OK ) {
1273                if( ( err != Z_STREAM_END ) && ( err != Z_DATA_ERROR ) )
1274                    tr_snprintf( result, sizeof( result ), _( "Error uncompressing blocklist: %s (%d)" ), zError( err ), err );
1275                break;
1276            }
1277        }
1278
1279        inflateEnd( &stream );
1280
1281        if( err == Z_DATA_ERROR ) /* couldn't inflate it... it's probably already uncompressed */
1282            if( write( fd, response, response_byte_count ) < 0 )
1283                tr_snprintf( result, sizeof( result ), _( "Couldn't save file \"%1$s\": %2$s" ), filename, tr_strerror( errno ) );
1284
1285        if( *result )
1286            tr_err( "%s", result );
1287        else {
1288            /* feed it to the session and give the client a response */
1289            const int rule_count = tr_blocklistSetContent( session, filename );
1290            tr_bencDictAddInt( data->args_out, "blocklist-size", rule_count );
1291            tr_snprintf( result, sizeof( result ), "success" );
1292        }
1293
1294        unlink( filename );
1295        tr_free( filename );
1296        tr_free( buf );
1297    }
1298
1299    tr_idle_function_done( data, result );
1300}
1301
1302static const char*
1303blocklistUpdate( tr_session               * session,
1304                 tr_benc                  * args_in UNUSED,
1305                 tr_benc                  * args_out UNUSED,
1306                 struct tr_rpc_idle_data  * idle_data )
1307{
1308    tr_webRun( session, session->blocklist_url, NULL, NULL, gotNewBlocklist, idle_data );
1309    return NULL;
1310}
1311
1312/***
1313****
1314***/
1315
1316static void
1317addTorrentImpl( struct tr_rpc_idle_data * data, tr_ctor * ctor )
1318{
1319    int err = 0;
1320    const char * result = NULL;
1321    tr_torrent * tor = tr_torrentNew( ctor, &err );
1322
1323    tr_ctorFree( ctor );
1324
1325    if( tor )
1326    {
1327        tr_benc fields;
1328        tr_bencInitList( &fields, 3 );
1329        tr_bencListAddStr( &fields, "id" );
1330        tr_bencListAddStr( &fields, "name" );
1331        tr_bencListAddStr( &fields, "hashString" );
1332        addInfo( tor, tr_bencDictAdd( data->args_out, "torrent-added" ), &fields );
1333        notify( data->session, TR_RPC_TORRENT_ADDED, tor );
1334        tr_bencFree( &fields );
1335    }
1336    else if( err == TR_PARSE_DUPLICATE )
1337    {
1338        result = "duplicate torrent";
1339    }
1340    else if( err == TR_PARSE_ERR )
1341    {
1342        result = "invalid or corrupt torrent file";
1343    }
1344
1345    tr_idle_function_done( data, result );
1346}
1347
1348
1349struct add_torrent_idle_data
1350{
1351    struct tr_rpc_idle_data * data;
1352    tr_ctor * ctor;
1353};
1354
1355static void
1356gotMetadataFromURL( tr_session       * session UNUSED,
1357                    bool               did_connect UNUSED,
1358                    bool               did_timeout UNUSED,
1359                    long               response_code,
1360                    const void       * response,
1361                    size_t             response_byte_count,
1362                    void             * user_data )
1363{
1364    struct add_torrent_idle_data * data = user_data;
1365
1366    dbgmsg( "torrentAdd: HTTP response code was %ld (%s); response length was %zu bytes",
1367            response_code, tr_webGetResponseStr( response_code ), response_byte_count );
1368
1369    if( response_code==200 || response_code==221 ) /* http or ftp success.. */
1370    {
1371        tr_ctorSetMetainfo( data->ctor, response, response_byte_count );
1372        addTorrentImpl( data->data, data->ctor );
1373    }
1374    else
1375    {
1376        char result[1024];
1377        tr_snprintf( result, sizeof( result ), "gotMetadataFromURL: http error %ld: %s",
1378                     response_code, tr_webGetResponseStr( response_code ) );
1379        tr_idle_function_done( data->data, result );
1380    }
1381
1382    tr_free( data );
1383}
1384
1385static bool
1386isCurlURL( const char * filename )
1387{
1388    if( filename == NULL )
1389        return false;
1390
1391    return !strncmp( filename, "ftp://", 6 ) ||
1392           !strncmp( filename, "http://", 7 ) ||
1393           !strncmp( filename, "https://", 8 );
1394}
1395
1396static tr_file_index_t*
1397fileListFromList( tr_benc * list, tr_file_index_t * setmeCount )
1398{
1399    size_t i;
1400    const size_t childCount = tr_bencListSize( list );
1401    tr_file_index_t n = 0;
1402    tr_file_index_t * files = tr_new0( tr_file_index_t, childCount );
1403
1404    for( i=0; i<childCount; ++i ) {
1405        int64_t intVal;
1406        if( tr_bencGetInt( tr_bencListChild( list, i ), &intVal ) )
1407            files[n++] = (tr_file_index_t)intVal;
1408    }
1409
1410    *setmeCount = n;
1411    return files;
1412}
1413
1414static const char*
1415torrentAdd( tr_session               * session,
1416            tr_benc                  * args_in,
1417            tr_benc                  * args_out UNUSED,
1418            struct tr_rpc_idle_data  * idle_data )
1419{
1420    const char * filename = NULL;
1421    const char * metainfo_base64 = NULL;
1422
1423    assert( idle_data != NULL );
1424
1425    tr_bencDictFindStr( args_in, "filename", &filename );
1426    tr_bencDictFindStr( args_in, "metainfo", &metainfo_base64 );
1427    if( !filename && !metainfo_base64 )
1428        return "no filename or metainfo specified";
1429    else
1430    {
1431        int64_t      i;
1432        bool         boolVal;
1433        tr_benc    * l;
1434        const char * str;
1435        const char * cookies = NULL;
1436        tr_ctor    * ctor = tr_ctorNew( session );
1437
1438        /* set the optional arguments */
1439
1440        tr_bencDictFindStr( args_in, "cookies", &cookies );
1441
1442        if( tr_bencDictFindStr( args_in, TR_PREFS_KEY_DOWNLOAD_DIR, &str ) )
1443            tr_ctorSetDownloadDir( ctor, TR_FORCE, str );
1444
1445        if( tr_bencDictFindBool( args_in, "paused", &boolVal ) )
1446            tr_ctorSetPaused( ctor, TR_FORCE, boolVal );
1447
1448        if( tr_bencDictFindInt( args_in, "peer-limit", &i ) )
1449            tr_ctorSetPeerLimit( ctor, TR_FORCE, i );
1450
1451        if( tr_bencDictFindInt( args_in, "bandwidthPriority", &i ) )
1452            tr_ctorSetBandwidthPriority( ctor, i );
1453
1454        if( tr_bencDictFindList( args_in, "files-unwanted", &l ) ) {
1455            tr_file_index_t fileCount;
1456            tr_file_index_t * files = fileListFromList( l, &fileCount );
1457            tr_ctorSetFilesWanted( ctor, files, fileCount, false );
1458            tr_free( files );
1459        }
1460        if( tr_bencDictFindList( args_in, "files-wanted", &l ) ) {
1461            tr_file_index_t fileCount;
1462            tr_file_index_t * files = fileListFromList( l, &fileCount );
1463            tr_ctorSetFilesWanted( ctor, files, fileCount, true );
1464            tr_free( files );
1465        }
1466
1467        if( tr_bencDictFindList( args_in, "priority-low", &l ) ) {
1468            tr_file_index_t fileCount;
1469            tr_file_index_t * files = fileListFromList( l, &fileCount );
1470            tr_ctorSetFilePriorities( ctor, files, fileCount, TR_PRI_LOW );
1471            tr_free( files );
1472        }
1473        if( tr_bencDictFindList( args_in, "priority-normal", &l ) ) {
1474            tr_file_index_t fileCount;
1475            tr_file_index_t * files = fileListFromList( l, &fileCount );
1476            tr_ctorSetFilePriorities( ctor, files, fileCount, TR_PRI_NORMAL );
1477            tr_free( files );
1478        }
1479        if( tr_bencDictFindList( args_in, "priority-high", &l ) ) {
1480            tr_file_index_t fileCount;
1481            tr_file_index_t * files = fileListFromList( l, &fileCount );
1482            tr_ctorSetFilePriorities( ctor, files, fileCount, TR_PRI_HIGH );
1483            tr_free( files );
1484        }
1485
1486        dbgmsg( "torrentAdd: filename is \"%s\"", filename ? filename : "(null)" );
1487
1488        if( isCurlURL( filename ) )
1489        {
1490            struct add_torrent_idle_data * d = tr_new0( struct add_torrent_idle_data, 1 );
1491            d->data = idle_data;
1492            d->ctor = ctor;
1493            tr_webRun( session, filename, NULL, cookies, gotMetadataFromURL, d );
1494        }
1495        else
1496        {
1497            char * fname = tr_strstrip( tr_strdup( filename ) );
1498
1499            if( fname == NULL )
1500            {
1501                int len;
1502                char * metainfo = tr_base64_decode( metainfo_base64, -1, &len );
1503                tr_ctorSetMetainfo( ctor, (uint8_t*)metainfo, len );
1504                tr_free( metainfo );
1505            }
1506            else if( !strncmp( fname, "magnet:?", 8 ) )
1507            {
1508                tr_ctorSetMetainfoFromMagnetLink( ctor, fname );
1509            }
1510            else
1511            {
1512                tr_ctorSetMetainfoFromFile( ctor, fname );
1513            }
1514
1515            addTorrentImpl( idle_data, ctor );
1516
1517            tr_free( fname );
1518        }
1519
1520    }
1521
1522    return NULL;
1523}
1524
1525/***
1526****
1527***/
1528
1529static const char*
1530sessionSet( tr_session               * session,
1531            tr_benc                  * args_in,
1532            tr_benc                  * args_out UNUSED,
1533            struct tr_rpc_idle_data  * idle_data UNUSED )
1534{
1535    int64_t      i;
1536    double       d;
1537    bool         boolVal;
1538    const char * str;
1539
1540    assert( idle_data == NULL );
1541
1542    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_MAX_CACHE_SIZE_MB, &i ) )
1543        tr_sessionSetCacheLimit_MB( session, i );
1544    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_ALT_SPEED_UP_KBps, &i ) )
1545        tr_sessionSetAltSpeed_KBps( session, TR_UP, i );
1546    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_ALT_SPEED_DOWN_KBps, &i ) )
1547        tr_sessionSetAltSpeed_KBps( session, TR_DOWN, i );
1548    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_ALT_SPEED_ENABLED, &boolVal ) )
1549        tr_sessionUseAltSpeed( session, boolVal );
1550    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN, &i ) )
1551        tr_sessionSetAltSpeedBegin( session, i );
1552    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_ALT_SPEED_TIME_END, &i ) )
1553        tr_sessionSetAltSpeedEnd( session, i );
1554    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_ALT_SPEED_TIME_DAY, &i ) )
1555        tr_sessionSetAltSpeedDay( session, i );
1556    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED, &boolVal ) )
1557        tr_sessionUseAltSpeedTime( session, boolVal );
1558    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_BLOCKLIST_ENABLED, &boolVal ) )
1559        tr_blocklistSetEnabled( session, boolVal );
1560    if( tr_bencDictFindStr( args_in, TR_PREFS_KEY_BLOCKLIST_URL, &str ) )
1561        tr_blocklistSetURL( session, str );
1562    if( tr_bencDictFindStr( args_in, TR_PREFS_KEY_DOWNLOAD_DIR, &str ) )
1563        tr_sessionSetDownloadDir( session, str );
1564    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_QUEUE_STALLED_MINUTES, &i ) )
1565        tr_sessionSetQueueStalledMinutes( session, i );
1566    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_QUEUE_STALLED_ENABLED, &boolVal ) )
1567        tr_sessionSetQueueStalledEnabled( session, boolVal );
1568    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_DOWNLOAD_QUEUE_SIZE, &i ) )
1569        tr_sessionSetQueueSize( session, TR_DOWN, i );
1570    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_DOWNLOAD_QUEUE_ENABLED, &boolVal ) )
1571        tr_sessionSetQueueEnabled ( session, TR_DOWN, boolVal );
1572    if( tr_bencDictFindStr( args_in, TR_PREFS_KEY_INCOMPLETE_DIR, &str ) )
1573        tr_sessionSetIncompleteDir( session, str );
1574    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED, &boolVal ) )
1575        tr_sessionSetIncompleteDirEnabled( session, boolVal );
1576    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, &i ) )
1577        tr_sessionSetPeerLimit( session, i );
1578    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_PEER_LIMIT_TORRENT, &i ) )
1579        tr_sessionSetPeerLimitPerTorrent( session, i );
1580    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_PEX_ENABLED, &boolVal ) )
1581        tr_sessionSetPexEnabled( session, boolVal );
1582    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_DHT_ENABLED, &boolVal ) )
1583        tr_sessionSetDHTEnabled( session, boolVal );
1584    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_UTP_ENABLED, &boolVal ) )
1585        tr_sessionSetUTPEnabled( session, boolVal );
1586    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_LPD_ENABLED, &boolVal ) )
1587        tr_sessionSetLPDEnabled( session, boolVal );
1588    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START, &boolVal ) )
1589        tr_sessionSetPeerPortRandomOnStart( session, boolVal );
1590    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_PEER_PORT, &i ) )
1591        tr_sessionSetPeerPort( session, i );
1592    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_PORT_FORWARDING, &boolVal ) )
1593        tr_sessionSetPortForwardingEnabled( session, boolVal );
1594    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_RENAME_PARTIAL_FILES, &boolVal ) )
1595        tr_sessionSetIncompleteFileNamingEnabled( session, boolVal );
1596    if( tr_bencDictFindReal( args_in, "seedRatioLimit", &d ) )
1597        tr_sessionSetRatioLimit( session, d );
1598    if( tr_bencDictFindBool( args_in, "seedRatioLimited", &boolVal ) )
1599        tr_sessionSetRatioLimited( session, boolVal );
1600    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_IDLE_LIMIT, &i ) )
1601        tr_sessionSetIdleLimit( session, i );
1602    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_IDLE_LIMIT_ENABLED, &boolVal ) )
1603        tr_sessionSetIdleLimited( session, boolVal );
1604    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_START, &boolVal ) )
1605        tr_sessionSetPaused( session, !boolVal );
1606    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_SEED_QUEUE_ENABLED, &boolVal ) )
1607        tr_sessionSetQueueEnabled ( session, TR_UP, boolVal );
1608    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_SEED_QUEUE_SIZE, &i ) )
1609        tr_sessionSetQueueSize( session, TR_UP, i );
1610    if( tr_bencDictFindStr( args_in, TR_PREFS_KEY_SCRIPT_TORRENT_DONE_FILENAME, &str ) )
1611        tr_sessionSetTorrentDoneScript( session, str );
1612    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_SCRIPT_TORRENT_DONE_ENABLED, &boolVal ) )
1613        tr_sessionSetTorrentDoneScriptEnabled( session, boolVal );
1614    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_TRASH_ORIGINAL, &boolVal ) )
1615        tr_sessionSetDeleteSource( session, boolVal );
1616    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_DSPEED_KBps, &i ) )
1617        tr_sessionSetSpeedLimit_KBps( session, TR_DOWN, i );
1618    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_DSPEED_ENABLED, &boolVal ) )
1619        tr_sessionLimitSpeed( session, TR_DOWN, boolVal );
1620    if( tr_bencDictFindInt( args_in, TR_PREFS_KEY_USPEED_KBps, &i ) )
1621        tr_sessionSetSpeedLimit_KBps( session, TR_UP, i );
1622    if( tr_bencDictFindBool( args_in, TR_PREFS_KEY_USPEED_ENABLED, &boolVal ) )
1623        tr_sessionLimitSpeed( session, TR_UP, boolVal );
1624    if( tr_bencDictFindStr( args_in, TR_PREFS_KEY_ENCRYPTION, &str ) ) {
1625        if( !strcmp( str, "required" ) )
1626            tr_sessionSetEncryption( session, TR_ENCRYPTION_REQUIRED );
1627        else if( !strcmp( str, "tolerated" ) )
1628            tr_sessionSetEncryption( session, TR_CLEAR_PREFERRED );
1629        else
1630            tr_sessionSetEncryption( session, TR_ENCRYPTION_PREFERRED );
1631    }
1632
1633    notify( session, TR_RPC_SESSION_CHANGED, NULL );
1634
1635    return NULL;
1636}
1637
1638static const char*
1639sessionStats( tr_session               * session,
1640              tr_benc                  * args_in UNUSED,
1641              tr_benc                  * args_out,
1642              struct tr_rpc_idle_data  * idle_data UNUSED )
1643{
1644    int running = 0;
1645    int total = 0;
1646    tr_benc * d;
1647    tr_session_stats currentStats = { 0.0f, 0, 0, 0, 0, 0 };
1648    tr_session_stats cumulativeStats = { 0.0f, 0, 0, 0, 0, 0 };
1649    tr_torrent * tor = NULL;
1650
1651    assert( idle_data == NULL );
1652
1653    while(( tor = tr_torrentNext( session, tor ))) {
1654        ++total;
1655        if( tor->isRunning )
1656            ++running;
1657    }
1658
1659    tr_sessionGetStats( session, &currentStats );
1660    tr_sessionGetCumulativeStats( session, &cumulativeStats );
1661
1662    tr_bencDictAddInt ( args_out, "activeTorrentCount", running );
1663    tr_bencDictAddReal( args_out, "downloadSpeed", tr_sessionGetPieceSpeed_Bps( session, TR_DOWN ) );
1664    tr_bencDictAddInt ( args_out, "pausedTorrentCount", total - running );
1665    tr_bencDictAddInt ( args_out, "torrentCount", total );
1666    tr_bencDictAddReal( args_out, "uploadSpeed", tr_sessionGetPieceSpeed_Bps( session, TR_UP ) );
1667
1668    d = tr_bencDictAddDict( args_out, "cumulative-stats", 5 );
1669    tr_bencDictAddInt( d, "downloadedBytes", cumulativeStats.downloadedBytes );
1670    tr_bencDictAddInt( d, "filesAdded", cumulativeStats.filesAdded );
1671    tr_bencDictAddInt( d, "secondsActive", cumulativeStats.secondsActive );
1672    tr_bencDictAddInt( d, "sessionCount", cumulativeStats.sessionCount );
1673    tr_bencDictAddInt( d, "uploadedBytes", cumulativeStats.uploadedBytes );
1674
1675    d = tr_bencDictAddDict( args_out, "current-stats", 5 );
1676    tr_bencDictAddInt( d, "downloadedBytes", currentStats.downloadedBytes );
1677    tr_bencDictAddInt( d, "filesAdded", currentStats.filesAdded );
1678    tr_bencDictAddInt( d, "secondsActive", currentStats.secondsActive );
1679    tr_bencDictAddInt( d, "sessionCount", currentStats.sessionCount );
1680    tr_bencDictAddInt( d, "uploadedBytes", currentStats.uploadedBytes );
1681
1682    return NULL;
1683}
1684
1685static const char*
1686sessionGet( tr_session               * s,
1687            tr_benc                  * args_in UNUSED,
1688            tr_benc                  * args_out,
1689            struct tr_rpc_idle_data  * idle_data UNUSED )
1690{
1691    const char * str;
1692    tr_benc * d = args_out;
1693
1694    assert( idle_data == NULL );
1695    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_UP_KBps, tr_sessionGetAltSpeed_KBps(s,TR_UP) );
1696    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_DOWN_KBps, tr_sessionGetAltSpeed_KBps(s,TR_DOWN) );
1697    tr_bencDictAddBool( d, TR_PREFS_KEY_ALT_SPEED_ENABLED, tr_sessionUsesAltSpeed(s) );
1698    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN, tr_sessionGetAltSpeedBegin(s) );
1699    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_END,tr_sessionGetAltSpeedEnd(s) );
1700    tr_bencDictAddInt ( d, TR_PREFS_KEY_ALT_SPEED_TIME_DAY,tr_sessionGetAltSpeedDay(s) );
1701    tr_bencDictAddBool( d, TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED, tr_sessionUsesAltSpeedTime(s) );
1702    tr_bencDictAddBool( d, TR_PREFS_KEY_BLOCKLIST_ENABLED, tr_blocklistIsEnabled( s ) );
1703    tr_bencDictAddStr ( d, TR_PREFS_KEY_BLOCKLIST_URL, tr_blocklistGetURL( s ) );
1704    tr_bencDictAddInt ( d, TR_PREFS_KEY_MAX_CACHE_SIZE_MB, tr_sessionGetCacheLimit_MB( s ) );
1705    tr_bencDictAddInt ( d, "blocklist-size", tr_blocklistGetRuleCount( s ) );
1706    tr_bencDictAddStr ( d, "config-dir", tr_sessionGetConfigDir( s ) );
1707    tr_bencDictAddStr ( d, TR_PREFS_KEY_DOWNLOAD_DIR, tr_sessionGetDownloadDir( s ) );
1708    tr_bencDictAddBool( d, TR_PREFS_KEY_DOWNLOAD_QUEUE_ENABLED, tr_sessionGetQueueEnabled( s, TR_DOWN ) );
1709    tr_bencDictAddInt ( d, TR_PREFS_KEY_DOWNLOAD_QUEUE_SIZE, tr_sessionGetQueueSize( s, TR_DOWN ) );
1710    tr_bencDictAddInt ( d, "download-dir-free-space",  tr_sessionGetDownloadDirFreeSpace( s ) );
1711    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, tr_sessionGetPeerLimit( s ) );
1712    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_LIMIT_TORRENT, tr_sessionGetPeerLimitPerTorrent( s ) );
1713    tr_bencDictAddStr ( d, TR_PREFS_KEY_INCOMPLETE_DIR, tr_sessionGetIncompleteDir( s ) );
1714    tr_bencDictAddBool( d, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED, tr_sessionIsIncompleteDirEnabled( s ) );
1715    tr_bencDictAddBool( d, TR_PREFS_KEY_PEX_ENABLED, tr_sessionIsPexEnabled( s ) );
1716    tr_bencDictAddBool( d, TR_PREFS_KEY_UTP_ENABLED, tr_sessionIsUTPEnabled( s ) );
1717    tr_bencDictAddBool( d, TR_PREFS_KEY_DHT_ENABLED, tr_sessionIsDHTEnabled( s ) );
1718    tr_bencDictAddBool( d, TR_PREFS_KEY_LPD_ENABLED, tr_sessionIsLPDEnabled( s ) );
1719    tr_bencDictAddInt ( d, TR_PREFS_KEY_PEER_PORT, tr_sessionGetPeerPort( s ) );
1720    tr_bencDictAddBool( d, TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START, tr_sessionGetPeerPortRandomOnStart( s ) );
1721    tr_bencDictAddBool( d, TR_PREFS_KEY_PORT_FORWARDING, tr_sessionIsPortForwardingEnabled( s ) );
1722    tr_bencDictAddBool( d, TR_PREFS_KEY_RENAME_PARTIAL_FILES, tr_sessionIsIncompleteFileNamingEnabled( s ) );
1723    tr_bencDictAddInt ( d, "rpc-version", RPC_VERSION );
1724    tr_bencDictAddInt ( d, "rpc-version-minimum", RPC_VERSION_MIN );
1725    tr_bencDictAddReal( d, "seedRatioLimit", tr_sessionGetRatioLimit( s ) );
1726    tr_bencDictAddBool( d, "seedRatioLimited", tr_sessionIsRatioLimited( s ) );
1727    tr_bencDictAddInt ( d, TR_PREFS_KEY_IDLE_LIMIT, tr_sessionGetIdleLimit( s ) );
1728    tr_bencDictAddBool( d, TR_PREFS_KEY_IDLE_LIMIT_ENABLED, tr_sessionIsIdleLimited( s ) );
1729    tr_bencDictAddBool( d, TR_PREFS_KEY_SEED_QUEUE_ENABLED, tr_sessionGetQueueEnabled( s, TR_UP ) );
1730    tr_bencDictAddInt ( d, TR_PREFS_KEY_SEED_QUEUE_SIZE, tr_sessionGetQueueSize( s, TR_UP ) );
1731    tr_bencDictAddBool( d, TR_PREFS_KEY_START, !tr_sessionGetPaused( s ) );
1732    tr_bencDictAddBool( d, TR_PREFS_KEY_TRASH_ORIGINAL, tr_sessionGetDeleteSource( s ) );
1733    tr_bencDictAddInt ( d, TR_PREFS_KEY_USPEED_KBps, tr_sessionGetSpeedLimit_KBps( s, TR_UP ) );
1734    tr_bencDictAddBool( d, TR_PREFS_KEY_USPEED_ENABLED, tr_sessionIsSpeedLimited( s, TR_UP ) );
1735    tr_bencDictAddInt ( d, TR_PREFS_KEY_DSPEED_KBps, tr_sessionGetSpeedLimit_KBps( s, TR_DOWN ) );
1736    tr_bencDictAddBool( d, TR_PREFS_KEY_DSPEED_ENABLED, tr_sessionIsSpeedLimited( s, TR_DOWN ) );
1737    tr_bencDictAddStr ( d, TR_PREFS_KEY_SCRIPT_TORRENT_DONE_FILENAME, tr_sessionGetTorrentDoneScript( s ) );
1738    tr_bencDictAddBool( d, TR_PREFS_KEY_SCRIPT_TORRENT_DONE_ENABLED, tr_sessionIsTorrentDoneScriptEnabled( s ) );
1739    tr_bencDictAddInt ( d, TR_PREFS_KEY_QUEUE_STALLED_MINUTES, tr_sessionGetQueueStalledMinutes( s ) );
1740    tr_bencDictAddBool( d, TR_PREFS_KEY_QUEUE_STALLED_ENABLED, tr_sessionGetQueueStalledEnabled( s ) );
1741    tr_formatter_get_units( tr_bencDictAddDict( d, "units", 0 ) );
1742    tr_bencDictAddStr ( d, "version", LONG_VERSION_STRING );
1743    switch( tr_sessionGetEncryption( s ) ) {
1744        case TR_CLEAR_PREFERRED: str = "tolerated"; break;
1745        case TR_ENCRYPTION_REQUIRED: str = "required"; break;
1746        default: str = "preferred"; break;
1747    }
1748    tr_bencDictAddStr( d, TR_PREFS_KEY_ENCRYPTION, str );
1749
1750    return NULL;
1751}
1752
1753/***
1754****
1755***/
1756
1757static const char*
1758sessionClose( tr_session               * session,
1759              tr_benc                  * args_in UNUSED,
1760              tr_benc                  * args_out UNUSED,
1761              struct tr_rpc_idle_data  * idle_data UNUSED )
1762{
1763    notify( session, TR_RPC_SESSION_CLOSE, NULL );
1764    return NULL;
1765}
1766
1767/***
1768****
1769***/
1770
1771typedef const char* ( *handler )( tr_session*, tr_benc*, tr_benc*, struct tr_rpc_idle_data * );
1772
1773static struct method
1774{
1775    const char *  name;
1776    bool          immediate;
1777    handler       func;
1778}
1779methods[] =
1780{
1781    { "port-test",             false, portTest            },
1782    { "blocklist-update",      false, blocklistUpdate     },
1783    { "session-close",         true,  sessionClose        },
1784    { "session-get",           true,  sessionGet          },
1785    { "session-set",           true,  sessionSet          },
1786    { "session-stats",         true,  sessionStats        },
1787    { "torrent-add",           false, torrentAdd          },
1788    { "torrent-get",           true,  torrentGet          },
1789    { "torrent-remove",        true,  torrentRemove       },
1790    { "torrent-set",           true,  torrentSet          },
1791    { "torrent-set-location",  true,  torrentSetLocation  },
1792    { "torrent-start",         true,  torrentStart        },
1793    { "torrent-start-now",     true,  torrentStartNow     },
1794    { "torrent-stop",          true,  torrentStop         },
1795    { "torrent-verify",        true,  torrentVerify       },
1796    { "torrent-reannounce",    true,  torrentReannounce   },
1797    { "queue-move-top",        true,  queueMoveTop        },
1798    { "queue-move-up",         true,  queueMoveUp         },
1799    { "queue-move-down",       true,  queueMoveDown       },
1800    { "queue-move-bottom",     true,  queueMoveBottom     }
1801};
1802
1803static void
1804noop_response_callback( tr_session       * session UNUSED,
1805                        struct evbuffer  * response UNUSED,
1806                        void             * user_data UNUSED )
1807{
1808}
1809
1810static void
1811request_exec( tr_session             * session,
1812              tr_benc                * request,
1813              tr_rpc_response_func     callback,
1814              void                   * callback_user_data )
1815{
1816    int i;
1817    const char * str;
1818    tr_benc * args_in = tr_bencDictFind( request, "arguments" );
1819    const char * result = NULL;
1820
1821    if( callback == NULL )
1822        callback = noop_response_callback;
1823
1824    /* parse the request */
1825    if( !tr_bencDictFindStr( request, "method", &str ) )
1826        result = "no method name";
1827    else {
1828        const int n = TR_N_ELEMENTS( methods );
1829        for( i = 0; i < n; ++i )
1830            if( !strcmp( str, methods[i].name ) )
1831                break;
1832        if( i ==n )
1833            result = "method name not recognized";
1834    }
1835
1836    /* if we couldn't figure out which method to use, return an error */
1837    if( result != NULL )
1838    {
1839        int64_t tag;
1840        tr_benc response;
1841        struct evbuffer * buf;
1842
1843        tr_bencInitDict( &response, 3 );
1844        tr_bencDictAddDict( &response, "arguments", 0 );
1845        tr_bencDictAddStr( &response, "result", result );
1846        if( tr_bencDictFindInt( request, "tag", &tag ) )
1847            tr_bencDictAddInt( &response, "tag", tag );
1848
1849        buf = tr_bencToBuf( &response, TR_FMT_JSON_LEAN );
1850        (*callback)( session, buf, callback_user_data );
1851        evbuffer_free( buf );
1852
1853        tr_bencFree( &response );
1854    }
1855    else if( methods[i].immediate )
1856    {
1857        int64_t tag;
1858        tr_benc response;
1859        tr_benc * args_out;
1860        struct evbuffer * buf;
1861
1862        tr_bencInitDict( &response, 3 );
1863        args_out = tr_bencDictAddDict( &response, "arguments", 0 );
1864        result = (*methods[i].func)( session, args_in, args_out, NULL );
1865        if( result == NULL )
1866            result = "success";
1867        tr_bencDictAddStr( &response, "result", result );
1868        if( tr_bencDictFindInt( request, "tag", &tag ) )
1869            tr_bencDictAddInt( &response, "tag", tag );
1870
1871        buf = tr_bencToBuf( &response, TR_FMT_JSON_LEAN );
1872        (*callback)( session, buf, callback_user_data );
1873        evbuffer_free( buf );
1874
1875        tr_bencFree( &response );
1876    }
1877    else
1878    {
1879        int64_t tag;
1880        struct tr_rpc_idle_data * data = tr_new0( struct tr_rpc_idle_data, 1 );
1881        data->session = session;
1882        data->response = tr_new0( tr_benc, 1 );
1883        tr_bencInitDict( data->response, 3 );
1884        if( tr_bencDictFindInt( request, "tag", &tag ) )
1885            tr_bencDictAddInt( data->response, "tag", tag );
1886        data->args_out = tr_bencDictAddDict( data->response, "arguments", 0 );
1887        data->callback = callback;
1888        data->callback_user_data = callback_user_data;
1889        (*methods[i].func)( session, args_in, data->args_out, data );
1890    }
1891}
1892
1893void
1894tr_rpc_request_exec_json( tr_session            * session,
1895                          const void            * request_json,
1896                          int                     request_len,
1897                          tr_rpc_response_func    callback,
1898                          void                  * callback_user_data )
1899{
1900    tr_benc top;
1901    int have_content;
1902
1903    if( request_len < 0 )
1904        request_len = strlen( request_json );
1905
1906    have_content = !tr_jsonParse( "rpc", request_json, request_len, &top, NULL );
1907    request_exec( session, have_content ? &top : NULL, callback, callback_user_data );
1908
1909    if( have_content )
1910        tr_bencFree( &top );
1911}
1912
1913/**
1914 * Munge the URI into a usable form.
1915 *
1916 * We have very loose typing on this to make the URIs as simple as possible:
1917 * - anything not a 'tag' or 'method' is automatically in 'arguments'
1918 * - values that are all-digits are numbers
1919 * - values that are all-digits or commas are number lists
1920 * - all other values are strings
1921 */
1922void
1923tr_rpc_parse_list_str( tr_benc     * setme,
1924                       const char  * str,
1925                       int           len )
1926
1927{
1928    int valueCount;
1929    int * values = tr_parseNumberRange( str, len, &valueCount );
1930
1931    if( valueCount == 0 )
1932        tr_bencInitStr( setme, str, len );
1933    else if( valueCount == 1 )
1934        tr_bencInitInt( setme, values[0] );
1935    else {
1936        int i;
1937        tr_bencInitList( setme, valueCount );
1938        for( i=0; i<valueCount; ++i )
1939            tr_bencListAddInt( setme, values[i] );
1940    }
1941
1942    tr_free( values );
1943}
1944
1945void
1946tr_rpc_request_exec_uri( tr_session           * session,
1947                         const void           * request_uri,
1948                         int                    request_len,
1949                         tr_rpc_response_func   callback,
1950                         void                 * callback_user_data )
1951{
1952    tr_benc      top, * args;
1953    char *       request = tr_strndup( request_uri, request_len );
1954    const char * pch;
1955
1956    tr_bencInitDict( &top, 3 );
1957    args = tr_bencDictAddDict( &top, "arguments", 0 );
1958
1959    pch = strchr( request, '?' );
1960    if( !pch ) pch = request;
1961    while( pch )
1962    {
1963        const char * delim = strchr( pch, '=' );
1964        const char * next = strchr( pch, '&' );
1965        if( delim )
1966        {
1967            char *    key = tr_strndup( pch, delim - pch );
1968            int       isArg = strcmp( key, "method" ) && strcmp( key, "tag" );
1969            tr_benc * parent = isArg ? args : &top;
1970            tr_rpc_parse_list_str( tr_bencDictAdd( parent, key ),
1971                                  delim + 1,
1972                                  next ? (size_t)(
1973                                       next -
1974                                      ( delim + 1 ) ) : strlen( delim + 1 ) );
1975            tr_free( key );
1976        }
1977        pch = next ? next + 1 : NULL;
1978    }
1979
1980    request_exec( session, &top, callback, callback_user_data );
1981
1982    /* cleanup */
1983    tr_bencFree( &top );
1984    tr_free( request );
1985}
Note: See TracBrowser for help on using the repository browser.