source: trunk/libtransmission/announcer.c @ 10652

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

(trunk libT) code tweak

File size: 59.2 KB
Line 
1/*
2 * This file Copyright (C) 2009-2010 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:$
11 */
12
13#include <assert.h>
14#include <limits.h>
15
16#include <event.h>
17#include <evhttp.h> /* for HTTP_OK */
18
19#include "transmission.h"
20#include "announcer.h"
21#include "crypto.h"
22#include "net.h"
23#include "ptrarray.h"
24#include "publish.h"
25#include "session.h"
26#include "tr-dht.h"
27#include "tr-lpd.h"
28#include "torrent.h"
29#include "utils.h"
30#include "web.h"
31
32#define STARTED "started"
33
34#define dbgmsg( tier, ... ) \
35if( tr_deepLoggingIsActive( ) ) do { \
36  char name[128]; \
37  tr_snprintf( name, sizeof( name ), "[%s--%s]", tr_torrentName( tier->tor ), \
38      ( tier->currentTracker ? tier->currentTracker->host->name : "" ) ); \
39  tr_deepLog( __FILE__, __LINE__, name, __VA_ARGS__ ); \
40} while( 0 )
41
42enum
43{
44    /* unless the tracker says otherwise, rescrape this frequently */
45    DEFAULT_SCRAPE_INTERVAL_SEC = ( 60 * 30 ),
46
47    /* unless the tracker says otherwise, this is the announce interval */
48    DEFAULT_ANNOUNCE_INTERVAL_SEC = ( 60 * 10 ),
49
50    /* unless the tracker says otherwise, this is the announce min_interval */
51    DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC = ( 60 * 2 ),
52
53    /* the length of the 'key' argument passed in tracker requests */
54    KEYLEN = 8,
55
56    /* how many web tasks we allow at one time */
57    MAX_CONCURRENT_TASKS = 48,
58
59    /* if a tracker takes more than this long to respond,
60     * we treat it as nonresponsive */
61    MAX_TRACKER_RESPONSE_TIME_SECS = ( 60 * 2 ),
62
63    /* the value of the 'numwant' argument passed in tracker requests. */
64    NUMWANT = 200,
65
66    /* how long to put slow (nonresponsive) trackers in the penalty box */
67    SLOW_HOST_PENALTY_SECS = ( 60 * 10 ),
68
69    UPKEEP_INTERVAL_SECS = 1,
70
71    /* this is an upper limit for the frequency of LDS announces */
72    LPD_HOUSEKEEPING_INTERVAL_SECS = 30
73
74};
75
76/***
77****
78***/
79
80static int
81compareTransfer( int a_uploaded, int a_downloaded,
82                 int b_uploaded, int b_downloaded )
83{
84    /* higher upload count goes first */
85    if( a_uploaded != b_uploaded )
86        return a_uploaded > b_uploaded ? -1 : 1;
87
88    /* then higher download count goes first */
89    if( a_downloaded != b_downloaded )
90        return a_downloaded > b_downloaded ? -1 : 1;
91
92    return 0;
93}
94
95/***
96****
97***/
98
99/**
100 * used by tr_announcer to recognize nonresponsive
101 * trackers and de-prioritize them
102 */
103typedef struct
104{
105    char * name;
106
107    /* how many seconds it took to get the last tracker response */
108    int lastResponseInterval;
109
110    /* the last time we sent an announce or scrape message */
111    time_t lastRequestTime;
112
113    /* the last successful announce/scrape time for this host */
114    time_t lastSuccessfulRequest;
115}
116tr_host;
117
118static int
119compareHosts( const void * va, const void * vb )
120{
121    const tr_host * a = va;
122    const tr_host * b = vb;
123    return strcmp( a->name, b->name );
124}
125
126static int
127compareHostToName( const void * va, const void * vb )
128{
129    const tr_host * a = va;
130    return strcmp( a->name, vb );
131}
132
133/* format: hostname + ':' + port */
134static char *
135getHostName( const char * url )
136{
137    int port = 0;
138    char * host = NULL;
139    char * ret;
140    tr_urlParse( url, strlen( url ), NULL, &host, &port, NULL );
141    ret = tr_strdup_printf( "%s:%d", ( host ? host : "invalid" ), port );
142    tr_free( host );
143    return ret;
144}
145
146static tr_host*
147hostNew( const char * name )
148{
149    tr_host * host = tr_new0( tr_host, 1 );
150    host->name = tr_strdup( name );
151    return host;
152}
153
154static void
155hostFree( void * vhost )
156{
157    tr_host * host = vhost;
158
159    tr_free( host->name );
160    tr_free( host );
161}
162
163/***
164****
165***/
166
167/**
168 * Since we can't poll a tr_torrent's fields after it's destroyed,
169 * we pre-build the "stop" announcement message when a torrent
170 * is removed from Transmission
171 */
172struct stop_message
173{
174    tr_host * host;
175    char * url;
176    int up;
177    int down;
178};
179
180static void
181stopFree( struct stop_message * stop )
182{
183    tr_free( stop->url );
184    tr_free( stop );
185}
186
187static int
188compareStops( const void * va, const void * vb )
189{
190    const struct stop_message * a = va;
191    const struct stop_message * b = vb;
192    return compareTransfer( a->up, a->down, b->up, b->down);
193}
194
195/***
196****
197***/
198
199/**
200 * "global" (per-tr_session) fields
201 */
202typedef struct tr_announcer
203{
204    tr_ptrArray hosts; /* tr_host */
205    tr_ptrArray stops; /* struct stop_message */
206    tr_session * session;
207    struct event * upkeepTimer;
208    int slotsAvailable;
209    time_t lpdHouseKeepingAt;
210}
211tr_announcer;
212
213tr_bool
214tr_announcerHasBacklog( const struct tr_announcer * announcer )
215{
216    return announcer->slotsAvailable < 1;
217}
218
219static tr_host *
220getHost( tr_announcer * announcer, const char * url )
221{
222    char * name = getHostName( url );
223    tr_host * host;
224
225    host = tr_ptrArrayFindSorted( &announcer->hosts, name, compareHostToName );
226    if( host == NULL )
227    {
228        host = hostNew( name );
229        tr_ptrArrayInsertSorted( &announcer->hosts, host, compareHosts );
230    }
231
232    tr_free( name );
233    return host;
234}
235
236static void
237onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer );
238
239static inline time_t
240calcRescheduleWithJitter( const int minPeriod )
241{
242    const double jitterFac = 0.1;
243
244    assert( minPeriod > 0 );
245
246    return tr_time()
247        + minPeriod
248        + tr_cryptoWeakRandInt( (int) ( minPeriod * jitterFac ) + 1 );
249}
250
251void
252tr_announcerInit( tr_session * session )
253{
254    tr_announcer * a;
255
256    const time_t relaxUntil =
257        calcRescheduleWithJitter( LPD_HOUSEKEEPING_INTERVAL_SECS / 3 );
258
259    assert( tr_isSession( session ) );
260
261    a = tr_new0( tr_announcer, 1 );
262    a->hosts = TR_PTR_ARRAY_INIT;
263    a->stops = TR_PTR_ARRAY_INIT;
264    a->session = session;
265    a->slotsAvailable = MAX_CONCURRENT_TASKS;
266    a->lpdHouseKeepingAt = relaxUntil;
267    a->upkeepTimer = tr_new0( struct event, 1 );
268    evtimer_set( a->upkeepTimer, onUpkeepTimer, a );
269    tr_timerAdd( a->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
270
271    session->announcer = a;
272}
273
274static void flushCloseMessages( tr_announcer * announcer );
275
276void
277tr_announcerClose( tr_session * session )
278{
279    tr_announcer * announcer = session->announcer;
280
281    flushCloseMessages( announcer );
282
283    evtimer_del( announcer->upkeepTimer );
284    tr_free( announcer->upkeepTimer );
285    announcer->upkeepTimer = NULL;
286
287    tr_ptrArrayDestruct( &announcer->stops, NULL );
288    tr_ptrArrayDestruct( &announcer->hosts, hostFree );
289
290    session->announcer = NULL;
291    tr_free( announcer );
292}
293
294/***
295****
296***/
297
298/* a row in tr_tier's list of trackers */
299typedef struct
300{
301    tr_host * host;
302
303    char * announce;
304    char * scrape;
305
306    char * tracker_id;
307
308    int seederCount;
309    int leecherCount;
310    int downloadCount;
311    int downloaderCount;
312
313    uint32_t id;
314
315    /* sent as the "key" argument in tracker requests
316     * to verify us if our IP address changes.
317     * This is immutable for the life of the tracker object.
318     * The +1 is for '\0' */
319    char key_param[KEYLEN + 1];
320}
321tr_tracker_item;
322
323static void
324trackerItemCopyAttributes( tr_tracker_item * t, const tr_tracker_item * o )
325{
326    assert( t != o );
327    assert( t != NULL );
328    assert( o != NULL );
329
330    t->seederCount = o->seederCount;
331    t->leecherCount = o->leecherCount;
332    t->downloadCount = o->downloadCount;
333    t->downloaderCount = o->downloaderCount;
334    memcpy( t->key_param, o->key_param, sizeof( t->key_param ) );
335}
336
337static void
338generateKeyParam( char * msg, size_t msglen )
339{
340    size_t i;
341    const char * pool = "abcdefghijklmnopqrstuvwxyz0123456789";
342    const int poolSize = strlen( pool );
343
344    for( i=0; i<msglen; ++i )
345        *msg++ = pool[tr_cryptoRandInt( poolSize )];
346    *msg = '\0';
347}
348
349static tr_tracker_item*
350trackerNew( tr_announcer  * announcer,
351            const char    * announce,
352            const char    * scrape,
353            uint32_t        id )
354{
355    tr_tracker_item * tracker = tr_new0( tr_tracker_item, 1  );
356    tracker->host = getHost( announcer, announce );
357    tracker->announce = tr_strdup( announce );
358    tracker->scrape = tr_strdup( scrape );
359    tracker->id = id;
360    generateKeyParam( tracker->key_param, KEYLEN );
361    tracker->seederCount = -1;
362    tracker->leecherCount = -1;
363    tracker->downloadCount = -1;
364    return tracker;
365}
366
367static void
368trackerFree( void * vtracker )
369{
370    tr_tracker_item * tracker = vtracker;
371
372    tr_free( tracker->tracker_id );
373    tr_free( tracker->announce );
374    tr_free( tracker->scrape );
375    tr_free( tracker );
376}
377
378/***
379****
380***/
381
382struct tr_torrent_tiers;
383
384/** @brief A group of trackers in a single tier, as per the multitracker spec */
385typedef struct
386{
387    /* number of up/down/corrupt bytes since the last time we sent an
388     * "event=stopped" message that was acknowledged by the tracker */
389    uint64_t byteCounts[3];
390
391    tr_ptrArray trackers; /* tr_tracker_item */
392    tr_tracker_item * currentTracker;
393    int currentTrackerIndex;
394
395    tr_torrent * tor;
396
397    time_t scrapeAt;
398    time_t lastScrapeStartTime;
399    time_t lastScrapeTime;
400    tr_bool lastScrapeSucceeded;
401    tr_bool lastScrapeTimedOut;
402
403    time_t announceAt;
404    time_t manualAnnounceAllowedAt;
405    time_t lastAnnounceStartTime;
406    time_t lastAnnounceTime;
407    tr_bool lastAnnounceSucceeded;
408    tr_bool lastAnnounceTimedOut;
409
410    tr_ptrArray announceEvents; /* const char* */
411
412    /* unique lookup key */
413    int key;
414
415    int scrapeIntervalSec;
416    int announceIntervalSec;
417    int announceMinIntervalSec;
418
419    int lastAnnouncePeerCount;
420
421    tr_bool isRunning;
422    tr_bool isAnnouncing;
423    tr_bool isScraping;
424    tr_bool wasCopied;
425
426    char lastAnnounceStr[128];
427    char lastScrapeStr[128];
428}
429tr_tier;
430
431static tr_tier *
432tierNew( tr_torrent * tor )
433{
434    tr_tier * t;
435    static int nextKey = 1;
436    const time_t now = tr_time( );
437
438    t = tr_new0( tr_tier, 1 );
439    t->key = nextKey++;
440    t->announceEvents = TR_PTR_ARRAY_INIT;
441    t->trackers = TR_PTR_ARRAY_INIT;
442    t->currentTracker = NULL;
443    t->currentTrackerIndex = -1;
444    t->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
445    t->announceIntervalSec = DEFAULT_ANNOUNCE_INTERVAL_SEC;
446    t->announceMinIntervalSec = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
447    t->scrapeAt = now + tr_cryptoWeakRandInt( 60*5 );
448    t->tor = tor;
449
450    return t;
451}
452
453static void
454tierFree( void * vtier )
455{
456    tr_tier * tier = vtier;
457    tr_ptrArrayDestruct( &tier->trackers, trackerFree );
458    tr_ptrArrayDestruct( &tier->announceEvents, NULL );
459    tr_free( tier );
460}
461
462static void
463tierCopyAttributes( tr_tier * t, const tr_tier * o )
464{
465    int i, n;
466    tr_tier bak;
467
468    assert( t != NULL );
469    assert( o != NULL );
470    assert( t != o );
471
472    bak = *t;
473    *t = *o;
474    t->tor = bak.tor;
475    t->trackers = bak.trackers;
476    t->announceEvents = bak.announceEvents;
477    t->currentTracker = bak.currentTracker;
478    t->currentTrackerIndex = bak.currentTrackerIndex;
479
480    tr_ptrArrayClear( &t->announceEvents );
481    for( i=0, n=tr_ptrArraySize(&o->announceEvents); i<n; ++i )
482        tr_ptrArrayAppend( &t->announceEvents, tr_ptrArrayNth((tr_ptrArray*)&o->announceEvents,i) );
483}
484
485static void
486tierIncrementTracker( tr_tier * tier )
487{
488    /* move our index to the next tracker in the tier */
489    const int i = ( tier->currentTrackerIndex + 1 )
490                        % tr_ptrArraySize( &tier->trackers );
491    tier->currentTracker = tr_ptrArrayNth( &tier->trackers, i );
492    tier->currentTrackerIndex = i;
493
494    /* reset some of the tier's fields */
495    tier->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
496    tier->announceIntervalSec = DEFAULT_ANNOUNCE_INTERVAL_SEC;
497    tier->announceMinIntervalSec = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
498    tier->isAnnouncing = FALSE;
499    tier->isScraping = FALSE;
500    tier->lastAnnounceStartTime = 0;
501    tier->lastScrapeStartTime = 0;
502}
503
504static void
505tierAddTracker( tr_announcer * announcer,
506                tr_tier      * tier,
507                const char   * announce,
508                const char   * scrape,
509                uint32_t       id )
510{
511    tr_tracker_item * tracker = trackerNew( announcer, announce, scrape, id );
512
513    tr_ptrArrayAppend( &tier->trackers, tracker );
514    dbgmsg( tier, "adding tracker %s", announce );
515
516    if( !tier->currentTracker )
517        tierIncrementTracker( tier );
518}
519
520
521/***
522****
523***/
524
525/**
526 * @brief Opaque, per-torrent data structure for tracker announce information
527 *
528 * this opaque data structure can be found in tr_torrent.tiers
529 */
530typedef struct tr_torrent_tiers
531{
532    tr_ptrArray tiers;
533    tr_publisher publisher;
534}
535tr_torrent_tiers;
536
537static tr_torrent_tiers*
538tiersNew( void )
539{
540    tr_torrent_tiers * tiers = tr_new0( tr_torrent_tiers, 1 );
541    tiers->tiers = TR_PTR_ARRAY_INIT;
542    tiers->publisher = TR_PUBLISHER_INIT;
543    return tiers;
544}
545
546static void
547tiersFree( tr_torrent_tiers * tiers )
548{
549    tr_publisherDestruct( &tiers->publisher );
550    tr_ptrArrayDestruct( &tiers->tiers, tierFree );
551    tr_free( tiers );
552}
553
554static tr_tier*
555getTier( tr_announcer * announcer, int torrentId, int tierId )
556{
557    tr_tier * tier = NULL;
558
559    if( announcer )
560    {
561        tr_torrent * tor = tr_torrentFindFromId( announcer->session, torrentId );
562
563        if( tor && tor->tiers )
564        {
565            int i;
566            tr_ptrArray * tiers = &tor->tiers->tiers;
567            const int n = tr_ptrArraySize( tiers );
568            for( i=0; !tier && i<n; ++i )
569            {
570                tr_tier * tmp = tr_ptrArrayNth( tiers, i );
571                if( tmp->key == tierId )
572                    tier = tmp;
573            }
574        }
575    }
576
577    return tier;
578}
579
580/***
581****  PUBLISH
582***/
583
584static const tr_tracker_event emptyEvent = { 0, NULL, NULL, 0, 0 };
585
586static void
587publishMessage( tr_tier * tier, const char * msg, int type )
588{
589    if( tier && tier->tor && tier->tor->tiers )
590    {
591        tr_torrent_tiers * tiers = tier->tor->tiers;
592        tr_tracker_event event = emptyEvent;
593        event.messageType = type;
594        event.text = msg;
595        tr_publisherPublish( &tiers->publisher, tier, &event );
596    }
597}
598
599static void
600publishErrorClear( tr_tier * tier )
601{
602    publishMessage( tier, NULL, TR_TRACKER_ERROR_CLEAR );
603}
604
605static void
606publishErrorMessageAndStop( tr_tier * tier, const char * msg )
607{
608    tier->isRunning = FALSE;
609
610    publishMessage( tier, msg, TR_TRACKER_ERROR );
611}
612
613static void
614publishWarning( tr_tier * tier, const char * msg )
615{
616    publishMessage( tier, msg, TR_TRACKER_WARNING );
617}
618
619static int
620publishNewPeers( tr_tier * tier, int seeds, int leechers,
621                 const void * compact, int compactLen )
622{
623    tr_tracker_event e = emptyEvent;
624
625    e.messageType = TR_TRACKER_PEERS;
626    e.seedProbability = seeds+leechers ? (int)((100.0*seeds)/(seeds+leechers)) : -1;
627    e.compact = compact;
628    e.compactLen = compactLen;
629
630    tr_publisherPublish( &tier->tor->tiers->publisher, tier, &e );
631
632    return compactLen / 6;
633}
634
635static int
636publishNewPeersCompact( tr_tier * tier, int seeds, int leechers,
637                        const void * compact, int compactLen )
638{
639    int i;
640    const uint8_t *compactWalk;
641    uint8_t *array, *walk;
642    const int peerCount = compactLen / 6;
643    const int arrayLen = peerCount * ( sizeof( tr_address ) + 2 );
644    tr_address addr;
645    tr_port port;
646
647    addr.type = TR_AF_INET;
648    memset( &addr.addr, 0, sizeof( addr.addr ) );
649    array = tr_new( uint8_t, arrayLen );
650    for ( i=0, walk=array, compactWalk=compact ; i<peerCount ; ++i )
651    {
652        memcpy( &addr.addr.addr4, compactWalk, 4 );
653        memcpy( &port, compactWalk + 4, 2 );
654
655        memcpy( walk, &addr, sizeof( addr ) );
656        memcpy( walk + sizeof( addr ), &port, 2 );
657
658        walk += sizeof( tr_address ) + 2;
659        compactWalk += 6;
660    }
661
662    publishNewPeers( tier, seeds, leechers, array, arrayLen );
663
664    tr_free( array );
665
666    return peerCount;
667}
668
669static int
670publishNewPeersCompact6( tr_tier * tier, int seeds, int leechers,
671                         const void * compact, int compactLen )
672{
673    int i;
674    const uint8_t *compactWalk;
675    uint8_t *array, *walk;
676    const int peerCount = compactLen / 18;
677    const int arrayLen = peerCount * ( sizeof( tr_address ) + 2 );
678    tr_address addr;
679    tr_port port;
680
681    addr.type = TR_AF_INET6;
682    memset( &addr.addr, 0, sizeof( addr.addr ) );
683    array = tr_new( uint8_t, arrayLen );
684    for ( i = 0, walk = array, compactWalk = compact ; i < peerCount ; ++i )
685    {
686        memcpy( &addr.addr.addr6, compactWalk, 16 );
687        memcpy( &port, compactWalk + 16, 2 );
688        compactWalk += 18;
689
690        memcpy( walk, &addr, sizeof( addr ) );
691        memcpy( walk + sizeof( addr ), &port, 2 );
692        walk += sizeof( tr_address ) + 2;
693    }
694
695    publishNewPeers( tier, seeds, leechers, array, arrayLen );
696    tr_free( array );
697
698    return peerCount;
699}
700
701static char*
702createAnnounceURL( const tr_announcer     * announcer,
703                   const tr_torrent       * torrent,
704                   const tr_tier          * tier,
705                   const char             * eventName )
706{
707    const int isStopping = !strcmp( eventName, "stopped" );
708    const int numwant = isStopping ? 0 : NUMWANT;
709    const tr_tracker_item  * tracker = tier->currentTracker;
710    const char * ann = tracker->announce;
711    struct evbuffer * buf = evbuffer_new( );
712    char * ret;
713    const char * str;
714    const unsigned char * ipv6;
715
716    evbuffer_expand( buf, 2048 );
717
718    evbuffer_add_printf( buf, "%s"
719                              "%c"
720                              "info_hash=%s"
721                              "&peer_id=%s"
722                              "&port=%d"
723                              "&uploaded=%" PRIu64
724                              "&downloaded=%" PRIu64
725                              "&left=%" PRIu64
726                              "&numwant=%d"
727                              "&key=%s"
728                              "&compact=1"
729                              "&supportcrypto=1",
730                              ann,
731                              strchr( ann, '?' ) ? '&' : '?',
732                              torrent->info.hashEscaped,
733                              torrent->peer_id,
734                              (int)tr_sessionGetPeerPort( announcer->session ),
735                              tier->byteCounts[TR_ANN_UP],
736                              tier->byteCounts[TR_ANN_DOWN],
737                              tr_cpLeftUntilComplete( &torrent->completion ),
738                              numwant,
739                              tracker->key_param );
740
741    if( announcer->session->encryptionMode == TR_ENCRYPTION_REQUIRED )
742        evbuffer_add_printf( buf, "&requirecrypto=1" );
743
744    if( tier->byteCounts[TR_ANN_CORRUPT] )
745        evbuffer_add_printf( buf, "&corrupt=%" PRIu64, tier->byteCounts[TR_ANN_CORRUPT] );
746
747    str = eventName;
748    if( str && *str )
749        evbuffer_add_printf( buf, "&event=%s", str );
750
751    str = tracker->tracker_id;
752    if( str && *str )
753        evbuffer_add_printf( buf, "&trackerid=%s", str );
754
755    /* There are two incompatible techniques for announcing an IPv6 address.
756       BEP-7 suggests adding an "ipv6=" parameter to the announce URL,
757       while OpenTracker requires that peers announce twice, once over IPv4
758       and once over IPv6.
759
760       To be safe, we should do both: add the "ipv6=" parameter and
761       announce twice.  At any rate, we're already computing our IPv6
762       address (for the LTEP handshake), so this comes for free. */
763
764    ipv6 = tr_globalIPv6( );
765    if( ipv6 ) {
766        char ipv6_readable[INET6_ADDRSTRLEN];
767        inet_ntop( AF_INET6, ipv6, ipv6_readable, INET6_ADDRSTRLEN );
768        evbuffer_add_printf( buf, "&ipv6=");
769        tr_http_escape( buf, ipv6_readable, strlen(ipv6_readable), TRUE );
770    }
771
772    ret = tr_strndup( EVBUFFER_DATA( buf ), EVBUFFER_LENGTH( buf ) );
773    dbgmsg( tier, "announce URL is \"%s\"", ret );
774    evbuffer_free( buf );
775    return ret;
776}
777
778
779/***
780****
781***/
782
783static tr_bool
784announceURLIsSupported( const char * announce )
785{
786    return ( announce != NULL )
787        && ( ( strstr( announce, "http://" ) == announce ) ||
788             ( strstr( announce, "https://" ) == announce ) );
789}
790
791static void
792addTorrentToTier( tr_announcer * announcer, tr_torrent_tiers * tiers, tr_torrent * tor )
793{
794    int i, n;
795    const tr_tracker_info ** infos;
796    const int trackerCount = tor->info.trackerCount;
797    const tr_tracker_info  * trackers = tor->info.trackers;
798
799    /* get the trackers that we support... */
800    infos = tr_new0( const tr_tracker_info*, trackerCount );
801    for( i=n=0; i<trackerCount; ++i )
802        if( announceURLIsSupported( trackers[i].announce ) )
803            infos[n++] = &trackers[i];
804
805    /* build our private table of tiers... */
806    if( n > 0 )
807    {
808        int tierIndex = -1;
809        tr_tier * tier = NULL;
810
811        for( i=0; i<n; ++i )
812        {
813            const tr_tracker_info * info = infos[i];
814
815            if( info->tier != tierIndex )
816                tier = NULL;
817
818            tierIndex = info->tier;
819
820            if( tier == NULL ) {
821                tier = tierNew( tor );
822                dbgmsg( tier, "adding tier" );
823                tr_ptrArrayAppend( &tiers->tiers, tier );
824            }
825
826            tierAddTracker( announcer, tier, info->announce, info->scrape, info->id );
827        }
828    }
829
830    tr_free( infos );
831}
832
833tr_torrent_tiers *
834tr_announcerAddTorrent( tr_announcer * announcer, tr_torrent * tor )
835{
836    tr_torrent_tiers * tiers;
837
838    assert( announcer != NULL );
839    assert( tr_isTorrent( tor ) );
840
841    tiers = tiersNew( );
842
843    addTorrentToTier( announcer, tiers, tor );
844
845    return tiers;
846}
847
848static void
849tierAddAnnounce( tr_tier * tier, const char * announceEvent, time_t announceAt );
850
851void
852tr_announcerResetTorrent( tr_announcer * announcer, tr_torrent * tor )
853{
854    tr_ptrArray oldTiers = TR_PTR_ARRAY_INIT;
855
856    /* if we had tiers already, make a backup of them */
857    if( tor->tiers != NULL )
858    {
859        oldTiers = tor->tiers->tiers;
860        tor->tiers->tiers = TR_PTR_ARRAY_INIT;
861    }
862
863    /* create the new tier/tracker structs */
864    addTorrentToTier( announcer, tor->tiers, tor );
865
866    /* if we had tiers already, merge their state into the new structs */
867    if( !tr_ptrArrayEmpty( &oldTiers ) )
868    {
869        int i, in;
870        for( i=0, in=tr_ptrArraySize(&oldTiers); i<in; ++i )
871        {
872            int j, jn;
873            const tr_tier * o = tr_ptrArrayNth( &oldTiers, i );
874
875            if( o->currentTracker == NULL )
876                continue;
877
878            for( j=0, jn=tr_ptrArraySize(&tor->tiers->tiers); j<jn; ++j )
879            {
880                int k, kn;
881                tr_tier * t = tr_ptrArrayNth(&tor->tiers->tiers,j);
882
883                for( k=0, kn=tr_ptrArraySize(&t->trackers); k<kn; ++k )
884                {
885                    tr_tracker_item * item = tr_ptrArrayNth(&t->trackers,k);
886                    if( strcmp( o->currentTracker->announce, item->announce ) )
887                        continue;
888                    tierCopyAttributes( t, o );
889                    t->currentTracker = item;
890                    t->currentTrackerIndex = k;
891                    t->wasCopied = TRUE;
892                    trackerItemCopyAttributes( item, o->currentTracker );
893                    dbgmsg( t, "attributes copied to tier %d, tracker %d"
894                                               "from tier %d, tracker %d",
895                            i, o->currentTrackerIndex, j, k );
896
897                }
898            }
899        }
900    }
901
902    /* kickstart any tiers that didn't get started */
903    if( tor->isRunning )
904    {
905        int i, n;
906        const time_t now = tr_time( );
907        tr_tier ** tiers = (tr_tier**) tr_ptrArrayPeek( &tor->tiers->tiers, &n );
908        for( i=0; i<n; ++i ) {
909            tr_tier * tier = tiers[i];
910            if( !tier->wasCopied )
911                tierAddAnnounce( tier, STARTED, now );
912        }
913    }
914
915    /* cleanup */
916    tr_ptrArrayDestruct( &oldTiers, tierFree );
917}
918
919tr_publisher_tag
920tr_announcerSubscribe( struct tr_torrent_tiers   * tiers,
921                       tr_delivery_func            func,
922                       void                      * userData )
923{
924    return tr_publisherSubscribe( &tiers->publisher, func, userData );
925}
926
927void
928tr_announcerUnsubscribe( struct tr_torrent_tiers  * tiers,
929                         tr_publisher_tag           tag )
930{
931    if( tiers )
932        tr_publisherUnsubscribe( &tiers->publisher, tag );
933}
934
935static tr_bool
936tierCanManualAnnounce( const tr_tier * tier )
937{
938    return tier->isRunning
939        && tier->manualAnnounceAllowedAt <= tr_time( );
940}
941
942tr_bool
943tr_announcerCanManualAnnounce( const tr_torrent * tor )
944{
945    int i;
946    int n;
947    const tr_tier ** tiers;
948
949    assert( tr_isTorrent( tor ) );
950    assert( tor->tiers != NULL );
951
952    n = tr_ptrArraySize( &tor->tiers->tiers );
953    tiers = (const tr_tier**) tr_ptrArrayBase( &tor->tiers->tiers );
954    for( i=0; i<n; ++i )
955        if( tierCanManualAnnounce( tiers[i] ) )
956            return TRUE;
957
958    return FALSE;
959}
960
961time_t
962tr_announcerNextManualAnnounce( const tr_torrent * tor )
963{
964    int i;
965    int n;
966    const tr_torrent_tiers * tiers;
967    time_t ret = ~(time_t)0;
968
969    assert( tr_isTorrent( tor  ) );
970
971    tiers = tor->tiers;
972    n = tr_ptrArraySize( &tiers->tiers );
973    for( i=0; i<n; ++i ) {
974        tr_tier * tier = tr_ptrArrayNth( (tr_ptrArray*)&tiers->tiers, i );
975        if( tier->isRunning )
976            ret = MIN( ret, tier->manualAnnounceAllowedAt );
977    }
978
979    return ret;
980}
981
982static void
983tierAddAnnounce( tr_tier * tier, const char * announceEvent, time_t announceAt )
984{
985    assert( tier != NULL );
986    assert( announceEvent != NULL );
987
988    tr_ptrArrayAppend( &tier->announceEvents, (void*)announceEvent );
989    tier->announceAt = announceAt;
990
991    dbgmsg( tier, "appended event \"%s\"; announcing in %d seconds\n", announceEvent, (int)difftime(announceAt,time(NULL)) );
992}
993
994static void
995torrentAddAnnounce( tr_torrent * tor, const char * announceEvent, time_t announceAt )
996{
997    int i;
998    int n;
999    tr_torrent_tiers * tiers;
1000
1001    assert( tr_isTorrent( tor ) );
1002
1003    tiers = tor->tiers;
1004    n = tr_ptrArraySize( &tiers->tiers );
1005    for( i=0; i<n; ++i )
1006        tierAddAnnounce( tr_ptrArrayNth( &tiers->tiers, i ), announceEvent, announceAt );
1007}
1008
1009void
1010tr_announcerTorrentStarted( tr_torrent * tor )
1011{
1012    torrentAddAnnounce( tor, STARTED, tr_time( ) );
1013}
1014void
1015tr_announcerManualAnnounce( tr_torrent * tor )
1016{
1017    torrentAddAnnounce( tor, "", tr_time( ) );
1018}
1019void
1020tr_announcerTorrentStopped( tr_torrent * tor )
1021{
1022    torrentAddAnnounce( tor, "stopped", tr_time( ) );
1023}
1024void
1025tr_announcerTorrentCompleted( tr_torrent * tor )
1026{
1027    torrentAddAnnounce( tor, "completed", tr_time( ) );
1028}
1029void
1030tr_announcerChangeMyPort( tr_torrent * tor )
1031{
1032    tr_announcerTorrentStarted( tor );
1033}
1034
1035/***
1036****
1037***/
1038
1039void
1040tr_announcerAddBytes( tr_torrent * tor, int type, uint32_t byteCount )
1041{
1042    int i, n;
1043    tr_torrent_tiers * tiers;
1044
1045    assert( tr_isTorrent( tor ) );
1046    assert( type==TR_ANN_UP || type==TR_ANN_DOWN || type==TR_ANN_CORRUPT );
1047
1048    tiers = tor->tiers;
1049    n = tr_ptrArraySize( &tiers->tiers );
1050    for( i=0; i<n; ++i )
1051    {
1052        tr_tier * tier = tr_ptrArrayNth( &tiers->tiers, i );
1053        tier->byteCounts[ type ] += byteCount;
1054    }
1055}
1056
1057/***
1058****
1059***/
1060
1061void
1062tr_announcerRemoveTorrent( tr_announcer * announcer, tr_torrent * tor )
1063{
1064    assert( tr_isTorrent( tor ) );
1065
1066    if( tor->tiers )
1067    {
1068        int i;
1069        const int n = tr_ptrArraySize( &tor->tiers->tiers );
1070        for( i=0; i<n; ++i )
1071        {
1072            tr_tier * tier = tr_ptrArrayNth( &tor->tiers->tiers, i );
1073
1074            if( tier->isRunning )
1075            {
1076                struct stop_message * s = tr_new0( struct stop_message, 1 );
1077                s->up = tier->byteCounts[TR_ANN_UP];
1078                s->down = tier->byteCounts[TR_ANN_DOWN];
1079                s->url = createAnnounceURL( announcer, tor, tier, "stopped" );
1080                s->host = tier->currentTracker->host;
1081                tr_ptrArrayInsertSorted( &announcer->stops, s, compareStops );
1082            }
1083        }
1084
1085        tiersFree( tor->tiers );
1086        tor->tiers = NULL;
1087    }
1088}
1089
1090/* return true if (1) we've tried it recently AND (2) it didn't respond... */
1091static tr_bool
1092hostIsNotResponding( const tr_host * host, const time_t now )
1093{
1094    tr_bool b = ( host->lastRequestTime )
1095             && ( host->lastRequestTime >= ( now - SLOW_HOST_PENALTY_SECS ) )
1096             && ( host->lastResponseInterval > MAX_TRACKER_RESPONSE_TIME_SECS );
1097    return b;
1098}
1099
1100static tr_bool
1101tierIsNotResponding( const tr_tier * tier, const time_t now )
1102{
1103    return !tier->currentTracker
1104        || hostIsNotResponding( tier->currentTracker->host, now );
1105}
1106
1107static int
1108getRetryInterval( const tr_host * host )
1109{
1110    int interval;
1111    const int jitter = tr_cryptoWeakRandInt( 120 );
1112    const time_t timeSinceLastSuccess = tr_time() - host->lastSuccessfulRequest;
1113         if( timeSinceLastSuccess < 15*60 ) interval = 0;
1114    else if( timeSinceLastSuccess < 30*60 ) interval = 60*4;
1115    else if( timeSinceLastSuccess < 45*60 ) interval = 60*8;
1116    else if( timeSinceLastSuccess < 60*60 ) interval = 60*16;
1117    else                                    interval = 60*32;
1118    return interval + jitter;
1119}
1120
1121static int
1122compareTiers( const void * va, const void * vb )
1123{
1124    int ret = 0;
1125    tr_bool af, bf;
1126    const tr_tier * a = *(const tr_tier**)va;
1127    const tr_tier * b = *(const tr_tier**)vb;
1128
1129    /* working domains come before non-working */
1130    if( !ret ) {
1131        const time_t now = tr_time( );
1132        af = tierIsNotResponding( a, now );
1133        bf = tierIsNotResponding( b, now );
1134        if( af != bf )
1135            ret = !af ? -1 : 1;
1136    }
1137
1138    /* stops come before starts */
1139    if( !ret ) {
1140        af = a->tor->isRunning;
1141        bf = b->tor->isRunning;
1142        if( af != bf )
1143            ret = af ? 1 : -1;
1144    }
1145
1146    /* upload comes before download */
1147    if( !ret )
1148        ret = compareTransfer( a->byteCounts[TR_ANN_UP], a->byteCounts[TR_ANN_DOWN],
1149                               b->byteCounts[TR_ANN_UP], b->byteCounts[TR_ANN_DOWN] );
1150
1151    /* incomplete comes before complete */
1152    if( !ret ) {
1153        af = a->tor->completeness == TR_LEECH;
1154        bf = b->tor->completeness == TR_LEECH;
1155        if( af != bf )
1156            return af ? -1 : 1;
1157    }
1158
1159    /* private before public */
1160    if( !ret ) {
1161        af = tr_torrentIsPrivate( a->tor );
1162        bf = tr_torrentIsPrivate( b->tor );
1163        if( af != bf )
1164            ret = af ? -1 : 1;
1165    }
1166
1167    return ret;
1168}
1169
1170static uint8_t *
1171parseOldPeers( tr_benc * bePeers, size_t *  byteCount )
1172{
1173    int       i;
1174    uint8_t * array, *walk;
1175    const int peerCount = bePeers->val.l.count;
1176
1177    assert( tr_bencIsList( bePeers ) );
1178
1179    array = tr_new( uint8_t, peerCount * ( sizeof( tr_address ) + 2 ) );
1180
1181    for( i = 0, walk = array; i < peerCount; ++i )
1182    {
1183        const char * s;
1184        int64_t      itmp;
1185        tr_address   addr;
1186        tr_port      port;
1187        tr_benc    * peer = &bePeers->val.l.vals[i];
1188
1189        if( tr_bencDictFindStr( peer, "ip", &s ) )
1190            if( tr_pton( s, &addr ) == NULL )
1191                continue;
1192
1193        if( !tr_bencDictFindInt( peer, "port", &itmp )
1194                || itmp < 0
1195                || itmp > USHRT_MAX )
1196            continue;
1197
1198        memcpy( walk, &addr, sizeof( tr_address ) );
1199        port = htons( itmp );
1200        memcpy( walk + sizeof( tr_address ), &port, 2 );
1201        walk += sizeof( tr_address ) + 2;
1202    }
1203
1204    *byteCount = peerCount * sizeof( tr_address ) + 2;
1205    return array;
1206}
1207
1208static tr_bool
1209parseAnnounceResponse( tr_tier     * tier,
1210                       const char  * response,
1211                       size_t        responseLen,
1212                       tr_bool     * gotScrape )
1213{
1214    tr_benc benc;
1215    tr_bool success = FALSE;
1216    int scrapeFields = 0;
1217    const int bencLoaded = !tr_bencLoad( response, responseLen, &benc, NULL );
1218
1219    dbgmsg( tier, "response len: %d, isBenc: %d", (int)responseLen, (int)bencLoaded );
1220    publishErrorClear( tier );
1221    if( bencLoaded && tr_bencIsDict( &benc ) )
1222    {
1223        int peerCount = 0;
1224        size_t rawlen;
1225        int64_t i;
1226        tr_benc * tmp;
1227        const char * str;
1228        const uint8_t * raw;
1229        tr_bool gotPeers = FALSE;
1230
1231        success = TRUE;
1232
1233        if( tr_bencDictFindStr( &benc, "failure reason", &str ) )
1234        {
1235            tr_strlcpy( tier->lastAnnounceStr, str,
1236                        sizeof( tier->lastAnnounceStr ) );
1237            dbgmsg( tier, "tracker gave \"%s\"", str );
1238            publishMessage( tier, str, TR_TRACKER_ERROR );
1239            success = FALSE;
1240        }
1241
1242        if( tr_bencDictFindStr( &benc, "warning message", &str ) )
1243        {
1244            tr_strlcpy( tier->lastAnnounceStr, str,
1245                        sizeof( tier->lastAnnounceStr ) );
1246            dbgmsg( tier, "tracker gave \"%s\"", str );
1247            publishWarning( tier, str );
1248        }
1249
1250        if( tr_bencDictFindInt( &benc, "interval", &i ) )
1251        {
1252            dbgmsg( tier, "setting interval to %d", (int)i );
1253            tier->announceIntervalSec = i;
1254        }
1255
1256        if( tr_bencDictFindInt( &benc, "min interval", &i ) )
1257        {
1258            dbgmsg( tier, "setting min interval to %d", (int)i );
1259            tier->announceMinIntervalSec = i;
1260        }
1261
1262        if( tr_bencDictFindStr( &benc, "tracker id", &str ) )
1263        {
1264            tier->currentTracker->tracker_id = tr_strdup( str );
1265        }
1266
1267        if( !tr_bencDictFindInt( &benc, "complete", &i ) )
1268            tier->currentTracker->seederCount = 0;
1269        else {
1270            ++scrapeFields;
1271            tier->currentTracker->seederCount = i;
1272        }
1273
1274        if( !tr_bencDictFindInt( &benc, "incomplete", &i ) )
1275            tier->currentTracker->leecherCount = 0;
1276        else {
1277            ++scrapeFields;
1278            tier->currentTracker->leecherCount = i;
1279        }
1280
1281        if( tr_bencDictFindInt( &benc, "downloaded", &i ) )
1282        {
1283            ++scrapeFields;
1284            tier->currentTracker->downloadCount = i;
1285        }
1286
1287        if( tr_bencDictFindRaw( &benc, "peers", &raw, &rawlen ) )
1288        {
1289            /* "compact" extension */
1290            const int seeders = tier->currentTracker->seederCount;
1291            const int leechers = tier->currentTracker->leecherCount;
1292            peerCount += publishNewPeersCompact( tier, seeders, leechers, raw, rawlen );
1293            gotPeers = TRUE;
1294        }
1295        else if( tr_bencDictFindList( &benc, "peers", &tmp ) )
1296        {
1297            /* original version of peers */
1298            const int seeders = tier->currentTracker->seederCount;
1299            const int leechers = tier->currentTracker->leecherCount;
1300            size_t byteCount = 0;
1301            uint8_t * array = parseOldPeers( tmp, &byteCount );
1302            peerCount += publishNewPeers( tier, seeders, leechers, array, byteCount );
1303            gotPeers = TRUE;
1304            tr_free( array );
1305        }
1306
1307        if( tr_bencDictFindRaw( &benc, "peers6", &raw, &rawlen ) )
1308        {
1309            /* "compact" extension */
1310            const int seeders = tier->currentTracker->seederCount;
1311            const int leechers = tier->currentTracker->leecherCount;
1312            peerCount += publishNewPeersCompact6( tier, seeders, leechers, raw, rawlen );
1313            gotPeers = TRUE;
1314        }
1315
1316        if( tier->lastAnnounceStr[0] == '\0' )
1317            tr_strlcpy( tier->lastAnnounceStr, _( "Success" ),
1318                        sizeof( tier->lastAnnounceStr ) );
1319
1320        if( gotPeers )
1321            tier->lastAnnouncePeerCount = peerCount;
1322    }
1323
1324    if( bencLoaded )
1325        tr_bencFree( &benc );
1326
1327    *gotScrape = scrapeFields >= 2;
1328
1329    return success;
1330}
1331
1332struct announce_data
1333{
1334    int torrentId;
1335    int tierId;
1336    time_t timeSent;
1337    const char * event;
1338
1339    /** If the request succeeds, the value for tier's "isRunning" flag */
1340    tr_bool isRunningOnSuccess;
1341};
1342
1343static void
1344onAnnounceDone( tr_session   * session,
1345                long           responseCode,
1346                const void   * response,
1347                size_t         responseLen,
1348                void         * vdata )
1349{
1350    tr_announcer * announcer = session->announcer;
1351    struct announce_data * data = vdata;
1352    tr_tier * tier = getTier( announcer, data->torrentId, data->tierId );
1353    tr_bool gotScrape = FALSE;
1354    tr_bool success = FALSE;
1355    const time_t now = time ( NULL );
1356    const char * announceEvent = data->event;
1357    const tr_bool isStopped = !strcmp( announceEvent, "stopped" );
1358
1359    if( announcer && tier )
1360    {
1361        if( tier->currentTracker->host )
1362        {
1363            tr_host * host = tier->currentTracker->host;
1364            host->lastRequestTime = data->timeSent;
1365            host->lastResponseInterval = now - data->timeSent;
1366        }
1367
1368        tier->lastAnnounceTime = now;
1369
1370        if( responseCode == HTTP_OK )
1371        {
1372            success = parseAnnounceResponse( tier, response, responseLen, &gotScrape );
1373            dbgmsg( tier, "success is %d", success );
1374
1375            if( isStopped )
1376            {
1377                /* now that we've successfully stopped the torrent,
1378                 * we can reset the up/down/corrupt count we've kept
1379                 * for this tracker */
1380                tier->byteCounts[ TR_ANN_UP ] = 0;
1381                tier->byteCounts[ TR_ANN_DOWN ] = 0;
1382                tier->byteCounts[ TR_ANN_CORRUPT ] = 0;
1383            }
1384        }
1385        else if( responseCode )
1386        {
1387            /* %1$ld - http status code, such as 404
1388             * %2$s - human-readable explanation of the http status code */
1389            char * buf = tr_strdup_printf(
1390                _( "tracker gave HTTP Response Code %1$ld (%2$s)" ),
1391                responseCode,
1392                tr_webGetResponseStr( responseCode ) );
1393
1394            tr_strlcpy( tier->lastAnnounceStr, buf,
1395                        sizeof( tier->lastAnnounceStr ) );
1396
1397            /* if the response is serious, *and* if the response may require
1398             * human intervention, then notify the user... otherwise just log it */
1399            if( responseCode >= 400 )
1400                if( tr_torrentIsPrivate( tier->tor ) || ( tier->tor->info.trackerCount < 2 ) )
1401                    publishWarning( tier, buf );
1402            tr_torinf( tier->tor, "%s", buf );
1403            dbgmsg( tier, "%s", buf );
1404
1405            tr_free( buf );
1406        }
1407        else
1408        {
1409            tr_strlcpy( tier->lastAnnounceStr,
1410                        _( "tracker did not respond" ),
1411                        sizeof( tier->lastAnnounceStr ) );
1412            dbgmsg( tier, "%s", tier->lastAnnounceStr );
1413        }
1414    }
1415
1416    if( tier )
1417    {
1418        tier->isAnnouncing = FALSE;
1419
1420        if( responseCode == 0 )
1421        {
1422            const int interval = getRetryInterval( tier->currentTracker->host );
1423            dbgmsg( tier, "No response from tracker... retrying in %d seconds.", interval );
1424            tier->manualAnnounceAllowedAt = ~(time_t)0;
1425            tierAddAnnounce( tier, announceEvent, now + interval );
1426        }
1427        else if( 200 <= responseCode && responseCode <= 299 )
1428        {
1429            const int interval = tier->announceIntervalSec;
1430            dbgmsg( tier, "request succeeded. reannouncing in %d seconds", interval );
1431
1432            if( gotScrape )
1433            {
1434                tier->lastScrapeTime = now;
1435                tier->lastScrapeSucceeded = 1;
1436                tier->scrapeAt = now + tier->scrapeIntervalSec;
1437            }
1438
1439            tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1440
1441            /* if we're running and the queue is empty, add the next update */
1442            if( !isStopped && !tr_ptrArraySize( &tier->announceEvents ) )
1443            {
1444                tierAddAnnounce( tier, "", now + interval );
1445            }
1446        }
1447        else if( 300 <= responseCode && responseCode <= 399 )
1448        {
1449            /* how did this get here?  libcurl handles this */
1450            const int interval = 5;
1451            dbgmsg( tier, "got a redirect. retrying in %d seconds", interval );
1452            tierAddAnnounce( tier, announceEvent, now + interval );
1453            tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1454        }
1455        else if( ( responseCode == 404 ) || ( 500 <= responseCode && responseCode <= 599 ) )
1456        {
1457            /* 404: The requested resource could not be found but may be
1458             * available again in the future.  Subsequent requests by
1459             * the client are permissible. */
1460
1461            /* 5xx: indicate cases in which the server is aware that it
1462             * has erred or is incapable of performing the request.
1463             * So we pause a bit and try again. */
1464
1465            const int interval = getRetryInterval( tier->currentTracker->host );
1466            tier->manualAnnounceAllowedAt = ~(time_t)0;
1467            tierAddAnnounce( tier, announceEvent, now + interval );
1468        }
1469        else if( 400 <= responseCode && responseCode <= 499 )
1470        {
1471            /* The request could not be understood by the server due to
1472             * malformed syntax. The client SHOULD NOT repeat the
1473             * request without modifications. */
1474            if( tr_torrentIsPrivate( tier->tor ) || ( tier->tor->info.trackerCount < 2 ) )
1475                publishErrorMessageAndStop( tier, _( "Tracker returned a 4xx message" ) );
1476            tier->announceAt = 0;
1477            tier->manualAnnounceAllowedAt = ~(time_t)0;
1478        }
1479        else
1480        {
1481            /* WTF did we get?? */
1482            const int interval = 120;
1483            dbgmsg( tier, "Invalid response from tracker... retrying in two minutes." );
1484            tier->manualAnnounceAllowedAt = ~(time_t)0;
1485            tierAddAnnounce( tier, announceEvent, now + interval );
1486        }
1487
1488        tier->lastAnnounceSucceeded = success;
1489        tier->lastAnnounceTimedOut = responseCode == 0;
1490
1491        if( success )
1492        {
1493            tier->isRunning = data->isRunningOnSuccess;
1494
1495            if( tier->currentTracker->host )
1496                tier->currentTracker->host->lastSuccessfulRequest = now;
1497        }
1498        else if( responseCode != HTTP_OK )
1499        {
1500            tierIncrementTracker( tier );
1501
1502            tr_ptrArrayInsert( &tier->announceEvents, (void*)announceEvent, 0 );
1503        }
1504    }
1505
1506    if( announcer != NULL )
1507    {
1508        ++announcer->slotsAvailable;
1509    }
1510
1511    tr_free( data );
1512}
1513
1514static const char*
1515getNextAnnounceEvent( tr_tier * tier )
1516{
1517    int i, n;
1518    int pos = -1;
1519    tr_ptrArray tmp;
1520    const char ** events;
1521    const char * str = NULL;
1522
1523    assert( tier != NULL );
1524    assert( tr_isTorrent( tier->tor ) );
1525
1526    /* special case #1: if "stopped" is in the queue, ignore everything before it */
1527    events = (const char**) tr_ptrArrayPeek( &tier->announceEvents, &n );
1528    if( pos == -1 ) {
1529        for( i=0; i<n; ++i )
1530            if( !strcmp( events[i], "stopped" ) )
1531                break;
1532        if( i <  n )
1533            pos = i;
1534    }
1535
1536    /* special case #2: don't use empty strings if something follows them */
1537    if( pos == -1 ) {
1538        for( i = 0; i < n; ++i )
1539            if( *events[i] )
1540                break;
1541        if( i < n )
1542            pos = i;
1543    }
1544
1545    /* default: use the next in the queue */
1546    if( ( pos == -1 ) && ( n > 0 ) )
1547        pos = 0;
1548
1549    /* special case #3: if there are duplicate requests in a row, skip to the last one */
1550    if( pos >= 0 ) {
1551        for( i=pos+1; i<n; ++i )
1552            if( strcmp( events[pos], events[i] ) )
1553                break;
1554        pos = i - 1;
1555    }
1556
1557    /* special case #4: BEP 21: "In order to tell the tracker that a peer is a
1558     * partial seed, it MUST send an event=paused parameter in every
1559     * announce while it is a partial seed." */
1560    str = pos>=0 ? events[pos] : NULL;
1561    if( tr_cpGetStatus( &tier->tor->completion ) == TR_PARTIAL_SEED )
1562        if( !str || strcmp( str, "stopped" ) )
1563            str = "paused";
1564
1565#if 0
1566for( i=0; i<n; ++i ) fprintf( stderr, "(%d)\"%s\" ", i, events[i] );
1567fprintf( stderr, "\n" );
1568fprintf( stderr, "using (%d)\"%s\"\n", pos, events[pos] );
1569if( strcmp( events[pos], str ) ) fprintf( stderr, "...but really using [%s]\n", str );
1570#endif
1571
1572    /* announceEvents array upkeep */
1573    tmp = TR_PTR_ARRAY_INIT;
1574    for( i=pos+1; i<n; ++i )
1575        tr_ptrArrayAppend( &tmp, (void*)events[i] );
1576    tr_ptrArrayDestruct( &tier->announceEvents, NULL );
1577    tier->announceEvents = tmp;
1578
1579    return str;
1580}
1581
1582static void
1583tierAnnounce( tr_announcer * announcer, tr_tier * tier )
1584{
1585    const char * announceEvent = getNextAnnounceEvent( tier );
1586
1587    assert( !tier->isAnnouncing );
1588
1589    if( announceEvent != NULL )
1590    {
1591        char * url;
1592        struct announce_data * data;
1593        const tr_torrent * tor = tier->tor;
1594        const time_t now = tr_time( );
1595
1596        data = tr_new0( struct announce_data, 1 );
1597        data->torrentId = tr_torrentId( tor );
1598        data->tierId = tier->key;
1599        data->isRunningOnSuccess = tor->isRunning;
1600        data->timeSent = now;
1601        data->event = announceEvent;
1602        url = createAnnounceURL( announcer, tor, tier, data->event );
1603
1604        tier->isAnnouncing = TRUE;
1605        tier->lastAnnounceStartTime = now;
1606        --announcer->slotsAvailable;
1607        tr_webRun( announcer->session, url, NULL, onAnnounceDone, data );
1608
1609        tr_free( url );
1610    }
1611}
1612
1613static tr_bool
1614parseScrapeResponse( tr_tier     * tier,
1615                     const char  * response,
1616                     size_t        responseLen,
1617                     char        * result,
1618                     size_t        resultlen )
1619{
1620    tr_bool success = FALSE;
1621    tr_benc benc, *files;
1622    const int bencLoaded = !tr_bencLoad( response, responseLen, &benc, NULL );
1623    if( bencLoaded && tr_bencDictFindDict( &benc, "files", &files ) )
1624    {
1625        const char * key;
1626        tr_benc * val;
1627        int i = 0;
1628        while( tr_bencDictChild( files, i++, &key, &val ))
1629        {
1630            int64_t intVal;
1631            tr_benc * flags;
1632
1633            if( memcmp( tier->tor->info.hash, key, SHA_DIGEST_LENGTH ) )
1634                continue;
1635
1636            success = TRUE;
1637            publishErrorClear( tier );
1638
1639            if( ( tr_bencDictFindInt( val, "complete", &intVal ) ) )
1640                tier->currentTracker->seederCount = intVal;
1641
1642            if( ( tr_bencDictFindInt( val, "incomplete", &intVal ) ) )
1643                tier->currentTracker->leecherCount = intVal;
1644
1645            if( ( tr_bencDictFindInt( val, "downloaded", &intVal ) ) )
1646                tier->currentTracker->downloadCount = intVal;
1647
1648            if( ( tr_bencDictFindInt( val, "downloaders", &intVal ) ) )
1649                tier->currentTracker->downloaderCount = intVal;
1650
1651            if( tr_bencDictFindDict( val, "flags", &flags ) )
1652                if( ( tr_bencDictFindInt( flags, "min_request_interval", &intVal ) ) )
1653                    tier->scrapeIntervalSec = MAX( DEFAULT_SCRAPE_INTERVAL_SEC, (int)intVal );
1654
1655            tr_tordbg( tier->tor,
1656                       "Scrape successful. Rescraping in %d seconds.",
1657                       tier->scrapeIntervalSec );
1658        }
1659    }
1660
1661    if( bencLoaded )
1662        tr_bencFree( &benc );
1663
1664    if( success )
1665        tr_strlcpy( result, _( "Success" ), resultlen );
1666    else
1667        tr_strlcpy( result, _( "Error parsing response" ), resultlen );
1668
1669    return success;
1670}
1671
1672static void
1673onScrapeDone( tr_session   * session,
1674              long           responseCode,
1675              const void   * response,
1676              size_t         responseLen,
1677              void         * vdata )
1678{
1679    tr_bool success = FALSE;
1680    tr_announcer * announcer = session->announcer;
1681    struct announce_data * data = vdata;
1682    tr_tier * tier = getTier( announcer, data->torrentId, data->tierId );
1683    const time_t now = tr_time( );
1684
1685    if( announcer )
1686        ++announcer->slotsAvailable;
1687
1688    if( announcer && tier )
1689    {
1690        tier->isScraping = FALSE;
1691        tier->lastScrapeTime = now;
1692
1693        if( tier->currentTracker->host )
1694        {
1695            tr_host * host = tier->currentTracker->host;
1696            host->lastRequestTime = data->timeSent;
1697            host->lastResponseInterval = now - data->timeSent;
1698        }
1699
1700        if( 200 <= responseCode && responseCode <= 299 )
1701        {
1702            const int interval = tier->scrapeIntervalSec;
1703            tier->scrapeAt = now + interval;
1704
1705            if( responseCode == HTTP_OK )
1706                success = parseScrapeResponse( tier, response, responseLen,
1707                                               tier->lastScrapeStr, sizeof( tier->lastScrapeStr ) );
1708            else
1709                tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1710                             _( "tracker gave HTTP Response Code %1$ld (%2$s)" ),
1711                             responseCode, tr_webGetResponseStr( responseCode ) );
1712            tr_tordbg( tier->tor, "%s", tier->lastScrapeStr );
1713        }
1714        else if( 300 <= responseCode && responseCode <= 399 )
1715        {
1716            /* this shouldn't happen; libcurl should handle this */
1717            const int interval = 5;
1718            tier->scrapeAt = now + interval;
1719            tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1720                         "Got a redirect. Retrying in %d seconds", interval );
1721            tr_tordbg( tier->tor, "%s", tier->lastScrapeStr );
1722        }
1723        else
1724        {
1725            const int interval = getRetryInterval( tier->currentTracker->host );
1726
1727            /* Don't retry on a 4xx.
1728             * Retry at growing intervals on a 5xx */
1729            if( 400 <= responseCode && responseCode <= 499 )
1730                tier->scrapeAt = 0;
1731            else
1732                tier->scrapeAt = now + interval;
1733
1734            /* %1$ld - http status code, such as 404
1735             * %2$s - human-readable explanation of the http status code */
1736            if( !responseCode )
1737                tr_strlcpy( tier->lastScrapeStr, _( "tracker did not respond" ),
1738                            sizeof( tier->lastScrapeStr ) );
1739            else
1740                tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1741                             _( "tracker gave HTTP Response Code %1$ld (%2$s)" ),
1742                             responseCode, tr_webGetResponseStr( responseCode ) );
1743        }
1744
1745        tier->lastScrapeSucceeded = success;
1746        tier->lastScrapeTimedOut = responseCode == 0;
1747
1748        if( success && tier->currentTracker->host )
1749            tier->currentTracker->host->lastSuccessfulRequest = now;
1750    }
1751
1752    tr_free( data );
1753}
1754
1755static void
1756tierScrape( tr_announcer * announcer, tr_tier * tier )
1757{
1758    char * url;
1759    const char * scrape;
1760    struct announce_data * data;
1761    const time_t now = tr_time( );
1762
1763    assert( tier );
1764    assert( !tier->isScraping );
1765    assert( tier->currentTracker != NULL );
1766    assert( tr_isTorrent( tier->tor ) );
1767
1768    data = tr_new0( struct announce_data, 1 );
1769    data->torrentId = tr_torrentId( tier->tor );
1770    data->tierId = tier->key;
1771
1772    scrape = tier->currentTracker->scrape;
1773
1774    url = tr_strdup_printf( "%s%cinfo_hash=%s",
1775                            scrape,
1776                            strchr( scrape, '?' ) ? '&' : '?',
1777                            tier->tor->info.hashEscaped );
1778
1779    tier->isScraping = TRUE;
1780    tier->lastScrapeStartTime = now;
1781    --announcer->slotsAvailable;
1782    dbgmsg( tier, "scraping \"%s\"", url );
1783    tr_webRun( announcer->session, url, NULL, onScrapeDone, data );
1784
1785    tr_free( url );
1786}
1787
1788static void
1789flushCloseMessages( tr_announcer * announcer )
1790{
1791    int i;
1792    const int n = tr_ptrArraySize( &announcer->stops );
1793
1794    for( i=0; i<n; ++i )
1795    {
1796        struct stop_message * stop = tr_ptrArrayNth( &announcer->stops, i );
1797        tr_webRun( announcer->session, stop->url, NULL, NULL, NULL );
1798        stopFree( stop );
1799    }
1800
1801    tr_ptrArrayClear( &announcer->stops );
1802}
1803
1804static tr_bool
1805tierNeedsToAnnounce( const tr_tier * tier, const time_t now )
1806{
1807    return !tier->isAnnouncing
1808        && !tier->isScraping
1809        && ( tier->announceAt != 0 )
1810        && ( tier->announceAt <= now )
1811        && ( tr_ptrArraySize( &tier->announceEvents ) != 0 );
1812}
1813
1814static tr_bool
1815tierNeedsToScrape( const tr_tier * tier, const time_t now )
1816{
1817    return ( !tier->isScraping )
1818        && ( tier->scrapeAt != 0 )
1819        && ( tier->scrapeAt <= now )
1820        && ( tier->currentTracker != NULL )
1821        && ( tier->currentTracker->scrape != NULL );
1822}
1823
1824static void
1825announceMore( tr_announcer * announcer )
1826{
1827    tr_torrent * tor = NULL;
1828    const time_t now = tr_time( );
1829
1830    if( announcer->slotsAvailable > 0 )
1831    {
1832        int i;
1833        int n;
1834        tr_ptrArray announceMe = TR_PTR_ARRAY_INIT;
1835        tr_ptrArray scrapeMe = TR_PTR_ARRAY_INIT;
1836
1837        /* build a list of tiers that need to be announced */
1838        while(( tor = tr_torrentNext( announcer->session, tor ))) {
1839            if( tor->tiers ) {
1840                n = tr_ptrArraySize( &tor->tiers->tiers );
1841                for( i=0; i<n; ++i ) {
1842                    tr_tier * tier = tr_ptrArrayNth( &tor->tiers->tiers, i );
1843                    if( tierNeedsToAnnounce( tier, now ) )
1844                        tr_ptrArrayAppend( &announceMe, tier );
1845                    else if( tierNeedsToScrape( tier, now ) )
1846                        tr_ptrArrayAppend( &scrapeMe, tier );
1847                }
1848            }
1849        }
1850
1851        /* if there are more tiers than slots available, prioritize */
1852        n = tr_ptrArraySize( &announceMe );
1853        if( n > announcer->slotsAvailable )
1854            qsort( tr_ptrArrayBase( &announceMe ), n, sizeof( tr_tier * ), compareTiers );
1855
1856        /* announce some */
1857        n = MIN( tr_ptrArraySize( &announceMe ), announcer->slotsAvailable );
1858        for( i=0; i<n; ++i ) {
1859            tr_tier * tier = tr_ptrArrayNth( &announceMe, i );
1860            dbgmsg( tier, "announcing tier %d of %d", i, n );
1861            tierAnnounce( announcer, tier );
1862        }
1863
1864        /* scrape some */
1865        n = MIN( tr_ptrArraySize( &scrapeMe ), announcer->slotsAvailable );
1866        for( i=0; i<n; ++i ) {
1867            tr_tier * tier = tr_ptrArrayNth( &scrapeMe, i );
1868            dbgmsg( tier, "scraping tier %d of %d", (i+1), n );
1869            tierScrape( announcer, tier );
1870        }
1871
1872#if 0
1873char timebuf[64];
1874tr_getLogTimeStr( timebuf, 64 );
1875fprintf( stderr, "[%s] announce.c has %d requests ready to send (announce: %d, scrape: %d)\n", timebuf, (int)(tr_ptrArraySize(&announceMe)+tr_ptrArraySize(&scrapeMe)), (int)tr_ptrArraySize(&announceMe), (int)tr_ptrArraySize(&scrapeMe) );
1876#endif
1877
1878        /* cleanup */
1879        tr_ptrArrayDestruct( &scrapeMe, NULL );
1880        tr_ptrArrayDestruct( &announceMe, NULL );
1881    }
1882
1883    tor = NULL;
1884    while(( tor = tr_torrentNext( announcer->session, tor ))) {
1885        if( tor->dhtAnnounceAt <= now ) {
1886            if( tor->isRunning && tr_torrentAllowsDHT(tor) ) {
1887                int rc;
1888                rc = tr_dhtAnnounce(tor, AF_INET, 1);
1889                if(rc == 0)
1890                    /* The DHT is not ready yet.  Try again soon. */
1891                    tor->dhtAnnounceAt = now + 5 + tr_cryptoWeakRandInt( 5 );
1892                else
1893                    /* We should announce at least once every 30 minutes. */
1894                    tor->dhtAnnounceAt =
1895                        now + 25 * 60 + tr_cryptoWeakRandInt( 3 * 60 );
1896            }
1897        }
1898
1899        if( tor->dhtAnnounce6At <= now ) {
1900            if( tor->isRunning && tr_torrentAllowsDHT(tor) ) {
1901                int rc;
1902                rc = tr_dhtAnnounce(tor, AF_INET6, 1);
1903                if(rc == 0)
1904                    tor->dhtAnnounce6At = now + 5 + tr_cryptoWeakRandInt( 5 );
1905                else
1906                    tor->dhtAnnounce6At =
1907                        now + 25 * 60 + tr_cryptoWeakRandInt( 3 * 60 );
1908            }
1909        }
1910    }
1911
1912    /* Local Peer Discovery */
1913    if( announcer->lpdHouseKeepingAt <= now )
1914    {
1915        tr_lpdAnnounceMore( now, LPD_HOUSEKEEPING_INTERVAL_SECS );
1916
1917        /* reschedule more LDS announces for ( the future + jitter ) */
1918        announcer->lpdHouseKeepingAt =
1919            calcRescheduleWithJitter( LPD_HOUSEKEEPING_INTERVAL_SECS );
1920    }
1921}
1922
1923static void
1924onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer )
1925{
1926    tr_announcer * announcer = vannouncer;
1927    tr_sessionLock( announcer->session );
1928
1929    /* maybe send out some "stopped" messages for closed torrents */
1930    flushCloseMessages( announcer );
1931
1932    /* maybe send out some announcements to trackers */
1933    announceMore( announcer );
1934
1935    /* set up the next timer */
1936    tr_timerAdd( announcer->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
1937
1938    tr_sessionUnlock( announcer->session );
1939}
1940
1941/***
1942****
1943***/
1944
1945tr_tracker_stat *
1946tr_announcerStats( const tr_torrent * torrent,
1947                   int              * setmeTrackerCount )
1948{
1949    int i;
1950    int n;
1951    int out = 0;
1952    int tierCount;
1953    tr_tracker_stat * ret;
1954    const time_t now = tr_time( );
1955
1956    assert( tr_isTorrent( torrent ) );
1957
1958    /* count the trackers... */
1959    for( i=n=0, tierCount=tr_ptrArraySize( &torrent->tiers->tiers ); i<tierCount; ++i ) {
1960        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1961        n += tr_ptrArraySize( &tier->trackers );
1962    }
1963
1964    /* alloc the stats */
1965    *setmeTrackerCount = n;
1966    ret = tr_new0( tr_tracker_stat, n );
1967
1968    /* populate the stats */
1969    for( i=0, tierCount=tr_ptrArraySize( &torrent->tiers->tiers ); i<tierCount; ++i )
1970    {
1971        int j;
1972        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1973        n = tr_ptrArraySize( &tier->trackers );
1974        for( j=0; j<n; ++j )
1975        {
1976            const tr_tracker_item * tracker = tr_ptrArrayNth( (tr_ptrArray*)&tier->trackers, j );
1977            tr_tracker_stat * st = ret + out++;
1978
1979            st->id = tracker->id;
1980            tr_strlcpy( st->host, tracker->host->name, sizeof( st->host ) );
1981            tr_strlcpy( st->announce, tracker->announce, sizeof( st->announce ) );
1982            st->tier = i;
1983            st->isBackup = tracker != tier->currentTracker;
1984            st->lastScrapeStartTime = tier->lastScrapeStartTime;
1985
1986            st->seederCount = tracker->seederCount;
1987            st->leecherCount = tracker->leecherCount;
1988            st->downloadCount = tracker->downloadCount;
1989
1990            if( st->isBackup )
1991            {
1992                st->scrapeState = TR_TRACKER_INACTIVE;
1993                st->announceState = TR_TRACKER_INACTIVE;
1994                st->nextScrapeTime = 0;
1995                st->nextAnnounceTime = 0;
1996            }
1997            else
1998            {
1999                if(( st->hasScraped = tier->lastScrapeTime != 0 )) {
2000                    st->lastScrapeTime = tier->lastScrapeTime;
2001                    st->lastScrapeSucceeded = tier->lastScrapeSucceeded;
2002                    st->lastScrapeTimedOut = tier->lastScrapeTimedOut;
2003                    tr_strlcpy( st->lastScrapeResult, tier->lastScrapeStr, sizeof( st->lastScrapeResult ) );
2004                }
2005
2006                if( tier->isScraping )
2007                    st->scrapeState = TR_TRACKER_ACTIVE;
2008                else if( !tier->scrapeAt )
2009                    st->scrapeState = TR_TRACKER_INACTIVE;
2010                else if( tier->scrapeAt > now )
2011                {
2012                    st->scrapeState = TR_TRACKER_WAITING;
2013                    st->nextScrapeTime = tier->scrapeAt;
2014                }
2015                else
2016                    st->scrapeState = TR_TRACKER_QUEUED;
2017
2018                st->lastAnnounceStartTime = tier->lastAnnounceStartTime;
2019
2020                if(( st->hasAnnounced = tier->lastAnnounceTime != 0 )) {
2021                    st->lastAnnounceTime = tier->lastAnnounceTime;
2022                    tr_strlcpy( st->lastAnnounceResult, tier->lastAnnounceStr, sizeof( st->lastAnnounceResult ) );
2023                    st->lastAnnounceSucceeded = tier->lastAnnounceSucceeded;
2024                    st->lastAnnounceTimedOut = tier->lastAnnounceTimedOut;
2025                    st->lastAnnouncePeerCount = tier->lastAnnouncePeerCount;
2026                }
2027
2028                if( tier->isAnnouncing )
2029                    st->announceState = TR_TRACKER_ACTIVE;
2030                else if( !torrent->isRunning || !tier->announceAt )
2031                    st->announceState = TR_TRACKER_INACTIVE;
2032                else if( tier->announceAt > now )
2033                {
2034                    st->announceState = TR_TRACKER_WAITING;
2035                    st->nextAnnounceTime = tier->announceAt;
2036                }
2037                else
2038                    st->announceState = TR_TRACKER_QUEUED;
2039            }
2040        }
2041    }
2042
2043    return ret;
2044}
2045
2046void
2047tr_announcerStatsFree( tr_tracker_stat * trackers,
2048                       int trackerCount UNUSED )
2049{
2050    tr_free( trackers );
2051}
Note: See TracBrowser for help on using the repository browser.