source: trunk/libtransmission/announcer.c @ 12331

Last change on this file since 12331 was 12331, checked in by jordan, 11 years ago

(trunk libT) trivial commit fixing typo in the comments from r12297

  • Property svn:keywords set to Date Rev Author Id
File size: 49.0 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: announcer.c 12331 2011-04-07 06:54:03Z jordan $
11 */
12
13#include <assert.h>
14#include <limits.h> /* INT_MAX */
15#include <stdio.h>
16#include <stdlib.h> /* qsort() */
17#include <string.h> /* strcmp(), memcpy() */
18
19#include <event2/buffer.h>
20#include <event2/event.h> /* evtimer */
21
22#define __LIBTRANSMISSION_ANNOUNCER_MODULE___
23
24#include "transmission.h"
25#include "announcer.h"
26#include "announcer-common.h"
27#include "crypto.h" /* tr_cryptoRandInt(), tr_cryptoWeakRandInt() */
28#include "peer-mgr.h" /* tr_peerMgrCompactToPex() */
29#include "ptrarray.h"
30#include "session.h"
31#include "torrent.h"
32#include "utils.h"
33
34struct tr_tier;
35
36static void tier_build_log_name( const struct tr_tier * tier,
37                                 char * buf, size_t buflen );
38
39#define dbgmsg( tier, ... ) \
40if( tr_deepLoggingIsActive( ) ) do { \
41  char name[128]; \
42  tier_build_log_name( tier, name, sizeof( name ) ); \
43  tr_deepLog( __FILE__, __LINE__, name, __VA_ARGS__ ); \
44} while( 0 )
45
46enum
47{
48    /* unless the tracker says otherwise, rescrape this frequently */
49    DEFAULT_SCRAPE_INTERVAL_SEC = ( 60 * 30 ),
50
51    /* unless the tracker says otherwise, this is the announce interval */
52    DEFAULT_ANNOUNCE_INTERVAL_SEC = ( 60 * 10 ),
53
54    /* unless the tracker says otherwise, this is the announce min_interval */
55    DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC = ( 60 * 2 ),
56
57    /* how many web tasks we allow at one time */
58    MAX_CONCURRENT_TASKS = 48,
59
60    /* the value of the 'numwant' argument passed in tracker requests. */
61    NUMWANT = 80,
62
63    UPKEEP_INTERVAL_SECS = 1,
64
65    /* this is how often to call the UDP tracker upkeep */
66    TAU_UPKEEP_INTERVAL_SECS = 5
67};
68
69/***
70****
71***/
72
73const char*
74tr_announce_event_get_string( tr_announce_event e )
75{
76    switch( e )
77    {
78        case TR_ANNOUNCE_EVENT_COMPLETED:  return "completed";
79        case TR_ANNOUNCE_EVENT_STARTED:    return "started";
80        case TR_ANNOUNCE_EVENT_STOPPED:    return "stopped";
81        default:                           return "";
82    }
83}
84
85/***
86****
87***/
88
89static int
90compareTransfer( uint64_t a_uploaded, uint64_t a_downloaded,
91                 uint64_t b_uploaded, uint64_t b_downloaded )
92{
93    /* higher upload count goes first */
94    if( a_uploaded != b_uploaded )
95        return a_uploaded > b_uploaded ? -1 : 1;
96
97    /* then higher download count goes first */
98    if( a_downloaded != b_downloaded )
99        return a_downloaded > b_downloaded ? -1 : 1;
100
101    return 0;
102}
103
104static int
105compareStops( const void * va, const void * vb )
106{
107    const tr_announce_request * a = va;
108    const tr_announce_request * b = vb;
109    return compareTransfer( a->up, a->down, b->up, b->down);
110}
111
112/***
113****
114***/
115
116/**
117 * "global" (per-tr_session) fields
118 */
119typedef struct tr_announcer
120{
121    tr_ptrArray stops; /* tr_announce_request */
122
123    tr_session * session;
124    struct event * upkeepTimer;
125    int slotsAvailable;
126    int key;
127    time_t tauUpkeepAt;
128}
129tr_announcer;
130
131bool
132tr_announcerHasBacklog( const struct tr_announcer * announcer )
133{
134    return announcer->slotsAvailable < 1;
135}
136
137static void
138onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer );
139
140void
141tr_announcerInit( tr_session * session )
142{
143    tr_announcer * a;
144
145    assert( tr_isSession( session ) );
146
147    a = tr_new0( tr_announcer, 1 );
148    a->stops = TR_PTR_ARRAY_INIT;
149    a->key = tr_cryptoRandInt( INT_MAX );
150    a->session = session;
151    a->slotsAvailable = MAX_CONCURRENT_TASKS;
152    a->upkeepTimer = evtimer_new( session->event_base, onUpkeepTimer, a );
153    tr_timerAdd( a->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
154
155    session->announcer = a;
156}
157
158static void flushCloseMessages( tr_announcer * announcer );
159
160void
161tr_announcerClose( tr_session * session )
162{
163    tr_announcer * announcer = session->announcer;
164
165    flushCloseMessages( announcer );
166
167    tr_tracker_udp_start_shutdown( session );
168
169    event_free( announcer->upkeepTimer );
170    announcer->upkeepTimer = NULL;
171
172    tr_ptrArrayDestruct( &announcer->stops, NULL );
173
174    session->announcer = NULL;
175    tr_free( announcer );
176}
177
178/***
179****
180***/
181
182/* a row in tr_tier's list of trackers */
183typedef struct
184{
185    char * key;
186    char * announce;
187    char * scrape;
188
189    char * tracker_id_str;
190
191    int seederCount;
192    int leecherCount;
193    int downloadCount;
194    int downloaderCount;
195
196    int consecutiveFailures;
197
198    uint32_t id;
199}
200tr_tracker;
201
202/* format: host+':'+ port */
203static char *
204getKey( const char * url )
205{
206    char * ret;
207    char * scheme = NULL;
208    char * host = NULL;
209    int port = 0;
210
211    tr_urlParse( url, -1, &scheme, &host, &port, NULL );
212    ret = tr_strdup_printf( "%s://%s:%d", (scheme?scheme:"invalid"), (host?host:"invalid"), port );
213
214    tr_free( host );
215    tr_free( scheme );
216    return ret;
217}
218
219static void
220trackerConstruct( tr_tracker * tracker, const tr_tracker_info * inf )
221{
222    memset( tracker, 0, sizeof( tr_tracker ) );
223    tracker->key = getKey( inf->announce );
224    tracker->announce = tr_strdup( inf->announce );
225    tracker->scrape = tr_strdup( inf->scrape );
226    tracker->id = inf->id;
227    tracker->seederCount = -1;
228    tracker->leecherCount = -1;
229    tracker->downloadCount = -1;
230}
231
232static void
233trackerDestruct( tr_tracker * tracker )
234{
235    tr_free( tracker->tracker_id_str );
236    tr_free( tracker->scrape );
237    tr_free( tracker->announce );
238    tr_free( tracker->key );
239}
240
241/***
242****
243***/
244
245struct tr_torrent_tiers;
246
247/** @brief A group of trackers in a single tier, as per the multitracker spec */
248typedef struct tr_tier
249{
250    /* number of up/down/corrupt bytes since the last time we sent an
251     * "event=stopped" message that was acknowledged by the tracker */
252    uint64_t byteCounts[3];
253
254    tr_tracker * trackers;
255    int tracker_count;
256    tr_tracker * currentTracker;
257    int currentTrackerIndex;
258
259    tr_torrent * tor;
260
261    time_t scrapeAt;
262    time_t lastScrapeStartTime;
263    time_t lastScrapeTime;
264    bool lastScrapeSucceeded;
265    bool lastScrapeTimedOut;
266
267    time_t announceAt;
268    time_t manualAnnounceAllowedAt;
269    time_t lastAnnounceStartTime;
270    time_t lastAnnounceTime;
271    bool lastAnnounceSucceeded;
272    bool lastAnnounceTimedOut;
273
274    tr_announce_event * announce_events;
275    int announce_event_count;
276    int announce_event_alloc;
277
278    /* unique lookup key */
279    int key;
280
281    int scrapeIntervalSec;
282    int announceIntervalSec;
283    int announceMinIntervalSec;
284
285    int lastAnnouncePeerCount;
286
287    bool isRunning;
288    bool isAnnouncing;
289    bool isScraping;
290    bool wasCopied;
291
292    char lastAnnounceStr[128];
293    char lastScrapeStr[128];
294}
295tr_tier;
296
297static time_t
298get_next_scrape_time( int interval )
299{
300    const time_t now = tr_time( );
301
302    /* Add the interval, and then increment to the nearest 10th second.
303     * The latter step is to increase the odds of several torrents coming
304     * due at the same time to improve multiscrape. */
305    return (now+interval) + (10-((now+interval)%10));
306}
307
308static void
309tierConstruct( tr_tier * tier, tr_torrent * tor )
310{
311    static int nextKey = 1;
312
313    memset( tier, 0, sizeof( tr_tier ) );
314
315    tier->key = nextKey++;
316    tier->currentTrackerIndex = -1;
317    tier->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
318    tier->announceIntervalSec = DEFAULT_ANNOUNCE_INTERVAL_SEC;
319    tier->announceMinIntervalSec = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
320    tier->scrapeAt = get_next_scrape_time( tr_cryptoWeakRandInt( 180 ) );
321    tier->tor = tor;
322}
323
324static void
325tierDestruct( tr_tier * tier )
326{
327    tr_free( tier->announce_events );
328}
329
330static void
331tier_build_log_name( const tr_tier * tier, char * buf, size_t buflen )
332{
333    tr_snprintf( buf, buflen, "[%s---%s]",
334       ( tier && tier->tor ) ? tr_torrentName( tier->tor ) : "?",
335       ( tier && tier->currentTracker ) ? tier->currentTracker->key : "?" );
336}
337
338static void
339tierIncrementTracker( tr_tier * tier )
340{
341    /* move our index to the next tracker in the tier */
342    const int i = ( tier->currentTracker == NULL )
343                ? 0
344                : ( tier->currentTrackerIndex + 1 ) % tier->tracker_count;
345    tier->currentTrackerIndex = i;
346    tier->currentTracker = &tier->trackers[i];
347
348    /* reset some of the tier's fields */
349    tier->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
350    tier->announceIntervalSec = DEFAULT_ANNOUNCE_INTERVAL_SEC;
351    tier->announceMinIntervalSec = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
352    tier->isAnnouncing = false;
353    tier->isScraping = false;
354    tier->lastAnnounceStartTime = 0;
355    tier->lastScrapeStartTime = 0;
356}
357
358/***
359****
360***/
361
362/**
363 * @brief Opaque, per-torrent data structure for tracker announce information
364 *
365 * this opaque data structure can be found in tr_torrent.tiers
366 */
367typedef struct tr_torrent_tiers
368{
369    tr_tier * tiers;
370    int tier_count;
371
372    tr_tracker * trackers;
373    int tracker_count;
374
375    tr_tracker_callback * callback;
376    void * callbackData;
377}
378tr_torrent_tiers;
379
380static tr_torrent_tiers*
381tiersNew( void )
382{
383    return tr_new0( tr_torrent_tiers, 1 );
384}
385
386static void
387tiersDestruct( tr_torrent_tiers * tt )
388{
389    int i;
390
391    for( i=0; i<tt->tracker_count; ++i )
392        trackerDestruct( &tt->trackers[i] );
393    tr_free( tt->trackers );
394
395    for( i=0; i<tt->tier_count; ++i )
396        tierDestruct( &tt->tiers[i] );
397    tr_free( tt->tiers );
398}
399
400static void
401tiersFree( tr_torrent_tiers * tt )
402{
403    tiersDestruct( tt );
404    tr_free( tt );
405}
406
407static tr_tier*
408getTier( tr_announcer * announcer, const uint8_t * info_hash, int tierId )
409{
410    tr_tier * tier = NULL;
411
412    if( announcer != NULL )
413    {
414        tr_session * session = announcer->session;
415        tr_torrent * tor = tr_torrentFindFromHash( session, info_hash );
416
417        if( tor && tor->tiers )
418        {
419            int i;
420            tr_torrent_tiers * tt = tor->tiers;
421
422            for( i=0; !tier && i<tt->tier_count; ++i )
423                if( tt->tiers[i].key == tierId )
424                    tier = &tt->tiers[i];
425        }
426    }
427
428    return tier;
429}
430
431/***
432****  PUBLISH
433***/
434
435static const tr_tracker_event TRACKER_EVENT_INIT = { 0, 0, 0, 0, 0, 0 };
436
437static void
438publishMessage( tr_tier * tier, const char * msg, int type )
439{
440    if( tier && tier->tor && tier->tor->tiers && tier->tor->tiers->callback )
441    {
442        tr_torrent_tiers * tiers = tier->tor->tiers;
443        tr_tracker_event event = TRACKER_EVENT_INIT;
444        event.messageType = type;
445        event.text = msg;
446        if( tier->currentTracker )
447            event.tracker = tier->currentTracker->announce;
448
449        tiers->callback( tier->tor, &event, tiers->callbackData );
450    }
451}
452
453static void
454publishErrorClear( tr_tier * tier )
455{
456    publishMessage( tier, NULL, TR_TRACKER_ERROR_CLEAR );
457}
458
459static void
460publishWarning( tr_tier * tier, const char * msg )
461{
462    publishMessage( tier, msg, TR_TRACKER_WARNING );
463}
464
465static void
466publishError( tr_tier * tier, const char * msg )
467{
468    publishMessage( tier, msg, TR_TRACKER_ERROR );
469}
470
471static int8_t
472getSeedProbability( tr_tier * tier, int seeds, int leechers, int pex_count )
473{
474    /* special case optimization:
475       ocelot omits seeds from peer lists sent to seeds on private trackers.
476       so check for that case... */
477    if( ( leechers == pex_count ) && tr_torrentIsPrivate( tier->tor )
478                                  && tr_torrentIsSeed( tier->tor )
479                                  && ( seeds + leechers < NUMWANT ) )
480        return 0;
481
482    if( !seeds )
483        return 0;
484
485    if( seeds>=0 && leechers>=0 )
486        return (int8_t)((100.0*seeds)/(seeds+leechers));
487
488    return -1; /* unknown */
489}
490
491static void
492publishPeersPex( tr_tier * tier, int seeds, int leechers,
493                 const tr_pex * pex, int n )
494{
495    if( tier->tor->tiers->callback )
496    {
497        tr_tracker_event e = TRACKER_EVENT_INIT;
498        e.messageType = TR_TRACKER_PEERS;
499        e.seedProbability = getSeedProbability( tier, seeds, leechers, n );
500        e.pex = pex;
501        e.pexCount = n;
502        dbgmsg( tier, "got %d peers; seed prob %d", n, (int)e.seedProbability );
503
504        tier->tor->tiers->callback( tier->tor, &e, NULL );
505    }
506}
507
508/***
509****
510***/
511
512struct ann_tracker_info
513{
514    tr_tracker_info info;
515
516    char * scheme;
517    char * host;
518    char * path;
519    int port;
520};
521
522
523/* primary key: tier
524 * secondary key: udp comes before http */
525static int
526filter_trackers_compare_func( const void * va, const void * vb )
527{
528    const struct ann_tracker_info * a = va;
529    const struct ann_tracker_info * b = vb;
530    if( a->info.tier != b->info.tier )
531        return a->info.tier - b->info.tier;
532    return -strcmp( a->scheme, b->scheme );
533}
534
535/**
536 * Massages the incoming list of trackers into something we can use.
537 */
538static tr_tracker_info *
539filter_trackers( tr_tracker_info * input, int input_count, int * setme_count )
540{
541    int i, in;
542    int j, jn;
543    int n = 0;
544    struct tr_tracker_info * ret;
545    struct ann_tracker_info * tmp = tr_new0( struct ann_tracker_info, input_count );
546
547    /*for( i=0, in=input_count; i<in; ++i ) fprintf( stderr, "IN: [%d][%s]\n", input[i].tier, input[i].announce );*/
548
549    /* build a list of valid trackers */
550    for( i=0, in=input_count; i<in; ++i ) {
551        if( tr_urlIsValidTracker( input[i].announce ) ) {
552            int port;
553            char * scheme;
554            char * host;
555            char * path;
556            bool is_duplicate = false;
557            tr_urlParse( input[i].announce, -1, &scheme, &host, &port, &path );
558
559            /* weed out one common source of duplicates:
560             * "http://tracker/announce" +
561             * "http://tracker:80/announce"
562             */
563            for( j=0, jn=n; !is_duplicate && j<jn; ++j )
564                is_duplicate = (tmp[j].port==port)
565                            && !strcmp(tmp[j].scheme,scheme)
566                            && !strcmp(tmp[j].host,host)
567                            && !strcmp(tmp[j].path,path);
568
569            if( is_duplicate ) {
570                tr_free( path );
571                tr_free( host );
572                tr_free( scheme );
573                continue;
574            }
575            tmp[n].info = input[i];
576            tmp[n].scheme = scheme;
577            tmp[n].host = host;
578            tmp[n].port = port;
579            tmp[n].path = path;
580            n++;
581        }
582    }
583
584    /* if two announce URLs differ only by scheme, put them in the same tier.
585     * (note: this can leave gaps in the `tier' values, but since the calling
586     * function doesn't care, there's no point in removing the gaps...) */
587    for( i=0, in=n; i<in; ++i )
588        for( j=i+1, jn=n; j<jn; ++j )
589            if( (tmp[i].info.tier!=tmp[j].info.tier)
590                       && (tmp[i].port==tmp[j].port)
591                       && !tr_strcmp0(tmp[i].host,tmp[j].host)
592                       && !tr_strcmp0(tmp[i].path,tmp[j].path) )
593                tmp[j].info.tier = tmp[i].info.tier;
594
595    /* sort them, for two reasons:
596     * (1) unjumble the tiers from the previous step
597     * (2) move the UDP trackers to the front of each tier */
598    qsort( tmp, n, sizeof(struct ann_tracker_info), filter_trackers_compare_func );
599
600    /* build the output */
601    *setme_count = n;
602    ret = tr_new0( tr_tracker_info, n );
603    for( i=0, in=n; i<in; ++i )
604        ret[i] = tmp[i].info;
605
606    /* cleanup */
607    for( i=0, in=n; i<in; ++i ) {
608        tr_free( tmp[i].path );
609        tr_free( tmp[i].host );
610        tr_free( tmp[i].scheme );
611    }
612    tr_free( tmp );
613
614    /*for( i=0, in=n; i<in; ++i ) fprintf( stderr, "OUT: [%d][%s]\n", ret[i].tier, ret[i].announce );*/
615    return ret;
616}
617
618
619static void
620addTorrentToTier( tr_torrent_tiers * tt, tr_torrent * tor )
621{
622    int i, n;
623    int tier_count;
624    tr_tier * tier;
625    tr_tracker_info * infos = filter_trackers( tor->info.trackers,
626                                               tor->info.trackerCount, &n );
627
628    /* build the array of trackers */ 
629    tt->trackers = tr_new0( tr_tracker, n );
630    tt->tracker_count = n;
631    for( i=0; i<n; ++i )
632        trackerConstruct( &tt->trackers[i], &infos[i] );
633
634    /* count how many tiers there are */
635    tier_count = 0;
636    for( i=0; i<n; ++i )
637        if( !i || ( infos[i].tier != infos[i-1].tier ) )
638            ++tier_count;
639
640    /* build the array of tiers */
641    tier = NULL;
642    tt->tiers = tr_new0( tr_tier, tier_count );
643    tt->tier_count = 0;
644    for( i=0; i<n; ++i ) {
645        if( i && ( infos[i].tier == infos[i-1].tier ) )
646            ++tier->tracker_count;
647        else {
648            tier = &tt->tiers[tt->tier_count++];
649            tierConstruct( tier, tor );
650            tier->trackers = &tt->trackers[i];
651            tier->tracker_count = 1;
652            tierIncrementTracker( tier );
653        }
654    }
655
656    /* cleanup */
657    tr_free( infos );
658}
659
660tr_torrent_tiers *
661tr_announcerAddTorrent( tr_torrent           * tor,
662                        tr_tracker_callback  * callback,
663                        void                 * callbackData )
664{
665    tr_torrent_tiers * tiers;
666
667    assert( tr_isTorrent( tor ) );
668
669    tiers = tiersNew( );
670    tiers->callback = callback;
671    tiers->callbackData = callbackData;
672
673    addTorrentToTier( tiers, tor );
674
675    return tiers;
676}
677
678/***
679****
680***/
681
682static bool
683tierCanManualAnnounce( const tr_tier * tier )
684{
685    return tier->manualAnnounceAllowedAt <= tr_time( );
686}
687
688bool
689tr_announcerCanManualAnnounce( const tr_torrent * tor )
690{
691    int i;
692    struct tr_torrent_tiers * tt = NULL;
693
694    assert( tr_isTorrent( tor ) );
695    assert( tor->tiers != NULL );
696
697    if( tor->isRunning )
698        tt = tor->tiers;
699
700    /* return true if any tier can manual announce */
701    for( i=0; tt && i<tt->tier_count; ++i )
702        if( tierCanManualAnnounce( &tt->tiers[i] ) )
703            return true;
704
705    return false;
706}
707
708time_t
709tr_announcerNextManualAnnounce( const tr_torrent * tor )
710{
711    int i;
712    time_t ret = ~(time_t)0;
713    struct tr_torrent_tiers * tt = tor->tiers;
714
715    /* find the earliest manual announce time from all peers */
716    for( i=0; tt && i<tt->tier_count; ++i )
717        if( tt->tiers[i].isRunning )
718            ret = MIN( ret, tt->tiers[i].manualAnnounceAllowedAt );
719
720    return ret;
721}
722
723static void
724dbgmsg_tier_announce_queue( const tr_tier * tier )
725{
726    if( tr_deepLoggingIsActive( ) )
727    {
728        int i;
729        char * str;
730        char name[128];
731        struct evbuffer * buf = evbuffer_new( );
732
733        tier_build_log_name( tier, name, sizeof( name ) );
734        for( i=0; i<tier->announce_event_count; ++i )
735        {
736            const tr_announce_event e = tier->announce_events[i];
737            const char * str = tr_announce_event_get_string( e );
738            evbuffer_add_printf( buf, "[%d:%s]", i, str );
739        }
740        str = evbuffer_free_to_str( buf );
741        tr_deepLog( __FILE__, __LINE__, name, "announce queue is %s", str );
742        tr_free( str );
743    }
744}
745
746static void
747tier_announce_remove_trailing( tr_tier * tier, tr_announce_event e )
748{
749    while( ( tier->announce_event_count > 0 )
750        && ( tier->announce_events[tier->announce_event_count-1] == e ) )
751        --tier->announce_event_count;
752}
753
754static void
755tier_announce_event_push( tr_tier            * tier,
756                          tr_announce_event    e,
757                          time_t               announceAt )
758{
759    int i;
760
761    assert( tier != NULL );
762
763    dbgmsg_tier_announce_queue( tier );
764    dbgmsg( tier, "queued \"%s\"", tr_announce_event_get_string( e ) );
765
766    if( tier->announce_event_count > 0 )
767    {
768        /* special case #1: if we're adding a "stopped" event,
769         * dump everything leading up to it except "completed" */
770        if( e == TR_ANNOUNCE_EVENT_STOPPED ) {
771            bool has_completed = false;
772            const tr_announce_event c = TR_ANNOUNCE_EVENT_COMPLETED;
773            for( i=0; !has_completed && i<tier->announce_event_count; ++i )
774                has_completed = c == tier->announce_events[i];
775            tier->announce_event_count = 0;
776            if( has_completed )
777                tier->announce_events[tier->announce_event_count++] = c;
778        }
779
780        /* special case #2: dump all empty strings leading up to this event */
781        tier_announce_remove_trailing( tier, TR_ANNOUNCE_EVENT_NONE );
782
783        /* special case #3: no consecutive duplicates */
784        tier_announce_remove_trailing( tier, e );
785    }
786
787    /* make room in the array for another event */
788    if( tier->announce_event_alloc <= tier->announce_event_count ) {
789        tier->announce_event_alloc += 4;
790        tier->announce_events = tr_renew( tr_announce_event,
791                                          tier->announce_events,
792                                          tier->announce_event_alloc );
793    }
794
795    /* add it */
796    tier->announce_events[tier->announce_event_count++] = e;
797    tier->announceAt = announceAt;
798
799    dbgmsg_tier_announce_queue( tier );
800    dbgmsg( tier, "announcing in %d seconds", (int)difftime(announceAt,tr_time()) );
801}
802
803static tr_announce_event
804tier_announce_event_pull( tr_tier * tier )
805{
806    const tr_announce_event e = tier->announce_events[0];
807
808    tr_removeElementFromArray( tier->announce_events,
809                               0, sizeof( tr_announce_event ),
810                               tier->announce_event_count-- );
811
812    return e;
813}
814
815static void
816torrentAddAnnounce( tr_torrent * tor, tr_announce_event e, time_t announceAt )
817{
818    int i;
819    struct tr_torrent_tiers * tt = tor->tiers;
820
821    /* walk through each tier and tell them to announce */
822    for( i=0; i<tt->tier_count; ++i )
823        tier_announce_event_push( &tt->tiers[i], e, announceAt );
824}
825
826void
827tr_announcerTorrentStarted( tr_torrent * tor )
828{
829    torrentAddAnnounce( tor, TR_ANNOUNCE_EVENT_STARTED, tr_time( ) );
830}
831void
832tr_announcerManualAnnounce( tr_torrent * tor )
833{
834    torrentAddAnnounce( tor, TR_ANNOUNCE_EVENT_NONE, tr_time( ) );
835}
836void
837tr_announcerTorrentStopped( tr_torrent * tor )
838{
839    torrentAddAnnounce( tor, TR_ANNOUNCE_EVENT_STOPPED, tr_time( ) );
840}
841void
842tr_announcerTorrentCompleted( tr_torrent * tor )
843{
844    torrentAddAnnounce( tor, TR_ANNOUNCE_EVENT_COMPLETED, tr_time( ) );
845}
846void
847tr_announcerChangeMyPort( tr_torrent * tor )
848{
849    tr_announcerTorrentStarted( tor );
850}
851
852/***
853****
854***/
855
856void
857tr_announcerAddBytes( tr_torrent * tor, int type, uint32_t byteCount )
858{
859    int i;
860    struct tr_torrent_tiers * tt = tor->tiers;
861
862    assert( tr_isTorrent( tor ) );
863    assert( type==TR_ANN_UP || type==TR_ANN_DOWN || type==TR_ANN_CORRUPT );
864
865    for( i=0; i<tt->tier_count; ++i )
866        tt->tiers[i].byteCounts[ type ] += byteCount;
867}
868
869/***
870****
871***/
872
873static tr_announce_request *
874announce_request_new( const tr_announcer  * announcer,
875                      const tr_torrent    * tor,
876                      const tr_tier       * tier,
877                      tr_announce_event     event )
878{
879    tr_announce_request * req = tr_new0( tr_announce_request, 1 );
880    req->port = tr_sessionGetPublicPeerPort( announcer->session );
881    req->url = tr_strdup( tier->currentTracker->announce );
882    req->tracker_id_str = tr_strdup( tier->currentTracker->tracker_id_str );
883    memcpy( req->info_hash, tor->info.hash, SHA_DIGEST_LENGTH );
884    memcpy( req->peer_id, tor->peer_id, PEER_ID_LEN );
885    req->up = tier->byteCounts[TR_ANN_UP];
886    req->down = tier->byteCounts[TR_ANN_DOWN];
887    req->corrupt = tier->byteCounts[TR_ANN_CORRUPT];
888    req->left = tr_cpLeftUntilComplete( &tor->completion ),
889    req->event = event;
890    req->numwant = event == TR_ANNOUNCE_EVENT_STOPPED ? 0 : NUMWANT;
891    req->key = announcer->key;
892    req->partial_seed = tr_cpGetStatus( &tor->completion ) == TR_PARTIAL_SEED;
893    tier_build_log_name( tier, req->log_name, sizeof( req->log_name ) );
894    return req;
895}
896
897void
898tr_announcerRemoveTorrent( tr_announcer * announcer, tr_torrent * tor )
899{
900    struct tr_torrent_tiers * tt = tor->tiers;
901
902    if( tt != NULL )
903    {
904        int i;
905        for( i=0; i<tt->tier_count; ++i )
906        {
907            tr_tier * tier = &tt->tiers[i];
908            if( tier->isRunning )
909            {
910                const tr_announce_event e = TR_ANNOUNCE_EVENT_STOPPED;
911                tr_announce_request * req = announce_request_new( announcer, tor, tier, e );
912                tr_ptrArrayInsertSorted( &announcer->stops, req, compareStops );
913            }
914        }
915
916        tiersFree( tor->tiers );
917        tor->tiers = NULL;
918    }
919}
920
921static int
922getRetryInterval( const tr_tracker * t )
923{
924    int minutes;
925    const unsigned int jitter_seconds = tr_cryptoWeakRandInt( 60 );
926    switch( t->consecutiveFailures ) {
927        case 0:  minutes =   1; break;
928        case 1:  minutes =   5; break;
929        case 2:  minutes =  15; break;
930        case 3:  minutes =  30; break;
931        case 4:  minutes =  60; break;
932        default: minutes = 120; break;
933    }
934    return ( minutes * 60 ) + jitter_seconds;
935}
936
937struct announce_data
938{
939    int tierId;
940    time_t timeSent;
941    tr_announce_event event;
942    tr_session * session;
943
944    /** If the request succeeds, the value for tier's "isRunning" flag */
945    bool isRunningOnSuccess;
946};
947
948static void
949on_announce_error( tr_tier * tier, const char * err, tr_announce_event e )
950{
951    int interval;
952
953    /* increment the error count */
954    if( tier->currentTracker != NULL )
955        ++tier->currentTracker->consecutiveFailures;
956
957    /* set the error message */
958    dbgmsg( tier, "%s", err );
959    tr_torinf( tier->tor, "%s", err );
960    tr_strlcpy( tier->lastAnnounceStr, err, sizeof( tier->lastAnnounceStr ) );
961
962    /* switch to the next tracker */
963    tierIncrementTracker( tier );
964
965    /* schedule a reannounce */
966    interval = getRetryInterval( tier->currentTracker );
967    dbgmsg( tier, "Retrying announce in %d seconds.", interval );
968    tier_announce_event_push( tier, e, tr_time( ) + interval );
969}
970
971static void
972on_announce_done( const tr_announce_response  * response,
973                  void                        * vdata )
974{
975    struct announce_data * data = vdata;
976    tr_announcer * announcer = data->session->announcer;
977    tr_tier * tier = getTier( announcer, response->info_hash, data->tierId );
978    const time_t now = tr_time( );
979    const tr_announce_event event = data->event;
980
981    if( announcer )
982        ++announcer->slotsAvailable;
983
984    if( tier != NULL )
985    {
986        tr_tracker * tracker;
987
988        dbgmsg( tier, "Got announce response: "
989                      "connected:%d "
990                      "timeout:%d "
991                      "seeders:%d "
992                      "leechers:%d "
993                      "downloads:%d "
994                      "interval:%d "
995                      "min_interval:%d "
996                      "tracker_id_str:%s "
997                      "pex:%zu "
998                      "pex6:%zu "
999                      "err:%s "
1000                      "warn:%s",
1001                      (int)response->did_connect,
1002                      (int)response->did_timeout,
1003                      response->seeders,
1004                      response->leechers,
1005                      response->downloads,
1006                      response->interval,
1007                      response->min_interval,
1008                      response->tracker_id_str ? response->tracker_id_str : "none",
1009                      response->pex_count,
1010                      response->pex6_count,
1011                      response->errmsg ? response->errmsg : "none",
1012                      response->warning ? response->warning : "none" );
1013
1014        tier->lastAnnounceTime = now;
1015        tier->lastAnnounceTimedOut = response->did_timeout;
1016        tier->lastAnnounceSucceeded = false;
1017        tier->isAnnouncing = false;
1018        tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1019
1020        if( !response->did_connect )
1021        {
1022            on_announce_error( tier, _( "Could not connect to tracker" ), event );
1023        }
1024        else if( response->did_timeout )
1025        {
1026            on_announce_error( tier, _( "Tracker did not respond" ), event );
1027        }
1028        else if( response->errmsg )
1029        {
1030            publishError( tier, response->errmsg );
1031            on_announce_error( tier, response->errmsg, event );
1032        }
1033        else
1034        {
1035            int i;
1036            const char * str;
1037            const bool isStopped = event == TR_ANNOUNCE_EVENT_STOPPED;
1038
1039            publishErrorClear( tier );
1040
1041            if(( tracker = tier->currentTracker ))
1042            {
1043                tracker->consecutiveFailures = 0;
1044                tracker->seederCount = response->seeders;
1045                tracker->leecherCount = response->leechers;
1046                tracker->downloadCount = response->downloads;
1047
1048                if(( str = response->tracker_id_str ))
1049                {
1050                    tr_free( tracker->tracker_id_str );
1051                    tracker->tracker_id_str = tr_strdup( str );
1052                }
1053            }
1054
1055            if(( str = response->warning ))
1056            {
1057                tr_strlcpy( tier->lastAnnounceStr, str,
1058                            sizeof( tier->lastAnnounceStr ) );
1059                dbgmsg( tier, "tracker gave \"%s\"", str );
1060                publishWarning( tier, str );
1061            }
1062
1063            if(( i = response->min_interval ))
1064                tier->announceMinIntervalSec = i;
1065
1066            if(( i = response->interval ))
1067                tier->announceIntervalSec = i;
1068
1069            if( response->pex_count > 0 )
1070                publishPeersPex( tier, response->seeders, response->leechers,
1071                                 response->pex, response->pex_count );
1072
1073            if( response->pex6_count > 0 )
1074                publishPeersPex( tier, response->seeders, response->leechers,
1075                                 response->pex6, response->pex6_count );
1076
1077            if( !*tier->lastAnnounceStr )
1078                tr_strlcpy( tier->lastAnnounceStr, _( "Success" ),
1079                            sizeof( tier->lastAnnounceStr ) );
1080
1081            tier->isRunning = data->isRunningOnSuccess;
1082            tier->scrapeAt = get_next_scrape_time( tier->scrapeIntervalSec );
1083            tier->lastScrapeTime = now;
1084            tier->lastScrapeSucceeded = true;
1085            tier->lastAnnounceSucceeded = true;
1086            tier->lastAnnouncePeerCount = response->pex_count
1087                                        + response->pex6_count;
1088
1089            if( isStopped )
1090            {
1091                /* now that we've successfully stopped the torrent,
1092                 * we can reset the up/down/corrupt count we've kept
1093                 * for this tracker */
1094                tier->byteCounts[ TR_ANN_UP ] = 0;
1095                tier->byteCounts[ TR_ANN_DOWN ] = 0;
1096                tier->byteCounts[ TR_ANN_CORRUPT ] = 0;
1097            }
1098
1099            if( !isStopped && !tier->announce_event_count )
1100            {
1101                /* the queue is empty, so enqueue a perodic update */
1102                i = tier->announceIntervalSec;
1103                dbgmsg( tier, "Sending periodic reannounce in %d seconds", i );
1104                tier_announce_event_push( tier, TR_ANNOUNCE_EVENT_NONE, now + i );
1105            }
1106        }
1107    }
1108
1109    tr_free( data );
1110}
1111
1112static void
1113announce_request_delegate( tr_announcer               * announcer,
1114                           tr_announce_request        * request,
1115                           tr_announce_response_func  * callback,
1116                           void                       * callback_data )
1117{
1118    tr_session * session = announcer->session;
1119
1120    if( !memcmp( request->url, "http", 4 ) )
1121        tr_tracker_http_announce( session, request, callback, callback_data );
1122    else if( !memcmp( request->url, "udp://", 6 ) )
1123        tr_tracker_udp_announce( session, request, callback, callback_data );
1124    else
1125        tr_err( "Unsupported url: %s", request->url );
1126
1127    tr_free( request->tracker_id_str );
1128    tr_free( request->url );
1129    tr_free( request );
1130}
1131
1132static void
1133tierAnnounce( tr_announcer * announcer, tr_tier * tier )
1134{
1135    tr_announce_event announce_event;
1136    tr_announce_request * req;
1137    struct announce_data * data;
1138    const tr_torrent * tor = tier->tor;
1139    const time_t now = tr_time( );
1140
1141    assert( !tier->isAnnouncing );
1142    assert( tier->announce_event_count > 0 );
1143
1144    announce_event = tier_announce_event_pull( tier );
1145    req = announce_request_new( announcer, tor, tier, announce_event );
1146
1147    data = tr_new0( struct announce_data, 1 );
1148    data->session = announcer->session;
1149    data->tierId = tier->key;
1150    data->isRunningOnSuccess = tor->isRunning;
1151    data->timeSent = now;
1152    data->event = announce_event;
1153
1154    tier->isAnnouncing = true;
1155    tier->lastAnnounceStartTime = now;
1156    --announcer->slotsAvailable;
1157
1158    announce_request_delegate( announcer, req, on_announce_done, data );
1159}
1160
1161/***
1162****
1163****  SCRAPE
1164****
1165***/
1166
1167static void
1168on_scrape_error( tr_tier * tier, const char * errmsg )
1169{
1170    int interval;
1171
1172    /* increment the error count */
1173    if( tier->currentTracker != NULL )
1174        ++tier->currentTracker->consecutiveFailures;
1175
1176    /* set the error message */
1177    dbgmsg( tier, "Scrape error: %s", errmsg );
1178    tr_torinf( tier->tor, "Scrape error: %s", errmsg );
1179    tr_strlcpy( tier->lastScrapeStr, errmsg, sizeof( tier->lastScrapeStr ) );
1180
1181    /* switch to the next tracker */
1182    tierIncrementTracker( tier );
1183
1184    /* schedule a rescrape */
1185    interval = getRetryInterval( tier->currentTracker );
1186    dbgmsg( tier, "Retrying scrape in %d seconds.", interval );
1187    tier->lastScrapeSucceeded = false;
1188    tier->scrapeAt = get_next_scrape_time( interval );
1189}
1190
1191static tr_tier *
1192find_tier( tr_torrent * tor, const char * scrape )
1193{
1194    int i;
1195    struct tr_torrent_tiers * tt = tor->tiers;
1196
1197    for( i=0; tt && i<tt->tier_count; ++i ) {
1198        const tr_tracker * const tracker = tt->tiers[i].currentTracker;
1199        if( tracker && !tr_strcmp0( scrape, tracker->scrape ) )
1200            return &tt->tiers[i];
1201    }
1202
1203    return NULL;
1204}
1205
1206static void
1207on_scrape_done( const tr_scrape_response  * response, void * vsession )
1208{
1209    int i;
1210    const time_t now = tr_time( );
1211    tr_session * session = vsession;
1212    tr_announcer * announcer = session->announcer;
1213
1214    for( i=0; i<response->row_count; ++i )
1215    {
1216        const struct tr_scrape_response_row * row = &response->rows[i];
1217        tr_torrent * tor = tr_torrentFindFromHash( session, row->info_hash );
1218
1219        if( tor != NULL )
1220        {
1221            tr_tier * tier = find_tier( tor, response->url );
1222
1223            if( tier != NULL )
1224            {
1225                dbgmsg( tier, "scraped url:%s -- "
1226                              "did_connect:%d "
1227                              "did_timeout:%d "
1228                              "seeders:%d "
1229                              "leechers:%d "
1230                              "downloads:%d "
1231                              "downloaders:%d "
1232                              "min_request_interval:%d "
1233                              "err:%s ",
1234                              response->url,
1235                              (int)response->did_connect,
1236                              (int)response->did_timeout,
1237                              row->seeders,
1238                              row->leechers,
1239                              row->downloads,
1240                              row->downloaders,
1241                              response->min_request_interval,
1242                              response->errmsg ? response->errmsg : "none" );
1243
1244                tier->isScraping = false;
1245                tier->lastScrapeTime = now;
1246                tier->lastScrapeSucceeded = false;
1247                tier->lastScrapeTimedOut = response->did_timeout;
1248
1249                if( !response->did_connect )
1250                {
1251                    on_scrape_error( tier, _( "Could not connect to tracker" ) );
1252                }
1253                else if( response->did_timeout )
1254                {
1255                    on_scrape_error( tier, _( "Tracker did not respond" ) );
1256                }
1257                else if( response->errmsg )
1258                {
1259                    on_scrape_error( tier, response->errmsg );
1260                }
1261                else
1262                {
1263                    tr_tracker * tracker;
1264
1265                    tier->lastScrapeSucceeded = true;
1266                    tier->scrapeIntervalSec = MAX( DEFAULT_SCRAPE_INTERVAL_SEC,
1267                                                   response->min_request_interval );
1268                    tier->scrapeAt = get_next_scrape_time( tier->scrapeIntervalSec );
1269                    tr_tordbg( tier->tor, "Scrape successful. Rescraping in %d seconds.",
1270                               tier->scrapeIntervalSec );
1271
1272                    if(( tracker = tier->currentTracker ))
1273                    {
1274                        tracker->seederCount = row->seeders;
1275                        tracker->leecherCount = row->leechers;
1276                        tracker->downloadCount = row->downloads;
1277                        tracker->downloaderCount = row->downloaders;
1278                        tracker->consecutiveFailures = 0;
1279                    }
1280
1281                    if( tr_torrentIsPrivate( tier->tor ) && !row->downloaders )
1282                        tr_peerMgrMarkAllAsSeeds( tier->tor );
1283                }
1284            }
1285        }
1286    }
1287
1288    if( announcer )
1289        ++announcer->slotsAvailable;
1290}
1291
1292static void
1293scrape_request_delegate( tr_announcer             * announcer,
1294                         tr_scrape_request        * request,
1295                         tr_scrape_response_func  * callback,
1296                         void                     * callback_data )
1297{
1298    tr_session * session = announcer->session;
1299
1300    if( !memcmp( request->url, "http", 4 ) )
1301        tr_tracker_http_scrape( session, request, callback, callback_data );
1302    else if( !memcmp( request->url, "udp://", 6 ) )
1303        tr_tracker_udp_scrape( session, request, callback, callback_data );
1304    else
1305        tr_err( "Unsupported url: %s", request->url );
1306}
1307
1308static void
1309multiscrape( tr_announcer * announcer, tr_ptrArray * tiers )
1310{
1311    int i;
1312    int request_count = 0;
1313    const time_t now = tr_time( );
1314    const int tier_count = tr_ptrArraySize( tiers );
1315    const int max_request_count = MIN( announcer->slotsAvailable, tier_count );
1316    tr_scrape_request * requests = tr_new0( tr_scrape_request, max_request_count );
1317
1318    /* batch as many info_hashes into a request as we can */
1319    for( i=0; i<tier_count; ++i )
1320    {
1321        int j;
1322        tr_tier * tier = tr_ptrArrayNth( tiers, i );
1323        char * url = tier->currentTracker->scrape;
1324        const uint8_t * hash = tier->tor->info.hash;
1325
1326        /* if there's a request with this scrape URL and a free slot, use it */
1327        for( j=0; j<request_count; ++j )
1328        {
1329            tr_scrape_request * req = &requests[j];
1330
1331            if( req->info_hash_count >= TR_MULTISCRAPE_MAX )
1332                continue;
1333            if( tr_strcmp0( req->url, url ) )
1334                continue;
1335
1336            memcpy( req->info_hash[req->info_hash_count++], hash, SHA_DIGEST_LENGTH );
1337            tier->isScraping = true;
1338            tier->lastScrapeStartTime = now;
1339            break;
1340        }
1341
1342        /* otherwise, if there's room for another request, build a new one */
1343        if( ( j==request_count ) && ( request_count < max_request_count ) )
1344        {
1345            tr_scrape_request * req = &requests[request_count++];
1346            req->url = url;
1347            tier_build_log_name( tier, req->log_name, sizeof( req->log_name ) );
1348
1349            memcpy( req->info_hash[req->info_hash_count++], hash, SHA_DIGEST_LENGTH );
1350            tier->isScraping = true;
1351            tier->lastScrapeStartTime = now;
1352        }
1353    }
1354
1355    /* send the requests we just built */
1356    for( i=0; i<request_count; ++i )
1357        scrape_request_delegate( announcer, &requests[i], on_scrape_done, announcer->session );
1358
1359    /* cleanup */
1360    tr_free( requests );
1361}
1362
1363static void
1364flushCloseMessages( tr_announcer * announcer )
1365{
1366    int i;
1367    const int n = tr_ptrArraySize( &announcer->stops );
1368
1369    for( i=0; i<n; ++i )
1370        announce_request_delegate( announcer, tr_ptrArrayNth( &announcer->stops, i ), NULL, NULL );
1371
1372    tr_ptrArrayClear( &announcer->stops );
1373}
1374
1375static bool
1376tierNeedsToAnnounce( const tr_tier * tier, const time_t now )
1377{
1378    return !tier->isAnnouncing
1379        && !tier->isScraping
1380        && ( tier->announceAt != 0 )
1381        && ( tier->announceAt <= now )
1382        && ( tier->announce_event_count > 0 );
1383}
1384
1385static bool
1386tierNeedsToScrape( const tr_tier * tier, const time_t now )
1387{
1388    return ( !tier->isScraping )
1389        && ( tier->scrapeAt != 0 )
1390        && ( tier->scrapeAt <= now )
1391        && ( tier->currentTracker != NULL )
1392        && ( tier->currentTracker->scrape != NULL );
1393}
1394
1395static int
1396compareTiers( const void * va, const void * vb )
1397{
1398    int ret;
1399    const tr_tier * a = *(const tr_tier**)va;
1400    const tr_tier * b = *(const tr_tier**)vb;
1401
1402    /* primary key: larger stats come before smaller */
1403    ret = compareTransfer( a->byteCounts[TR_ANN_UP], a->byteCounts[TR_ANN_DOWN],
1404                           b->byteCounts[TR_ANN_UP], b->byteCounts[TR_ANN_DOWN] );
1405
1406    /* secondary key: announcements that have been waiting longer go first */
1407    if( !ret && ( a->announceAt != b->announceAt ) )
1408        ret = a->announceAt < b->announceAt ? -1 : 1;
1409
1410    return ret;
1411}
1412
1413static void
1414announceMore( tr_announcer * announcer )
1415{
1416    int i;
1417    int n;
1418    tr_torrent * tor;
1419    tr_ptrArray announceMe = TR_PTR_ARRAY_INIT;
1420    tr_ptrArray scrapeMe = TR_PTR_ARRAY_INIT;
1421    const time_t now = tr_time( );
1422
1423    dbgmsg( NULL, "announceMore: slotsAvailable is %d", announcer->slotsAvailable );
1424
1425    if( announcer->slotsAvailable < 1 )
1426        return;
1427
1428    /* build a list of tiers that need to be announced */
1429    tor = NULL;
1430    while(( tor = tr_torrentNext( announcer->session, tor ))) {
1431        struct tr_torrent_tiers * tt = tor->tiers;
1432        for( i=0; tt && i<tt->tier_count; ++i ) {
1433            tr_tier * tier = &tt->tiers[i];
1434            if( tierNeedsToAnnounce( tier, now ) )
1435                tr_ptrArrayAppend( &announceMe, tier );
1436            else if( tierNeedsToScrape( tier, now ) )
1437                tr_ptrArrayAppend( &scrapeMe, tier );
1438        }
1439    }
1440
1441    /* if there are more tiers than slots available, prioritize */
1442    n = tr_ptrArraySize( &announceMe );
1443    if( n > announcer->slotsAvailable )
1444        qsort( tr_ptrArrayBase(&announceMe), n, sizeof(tr_tier*), compareTiers );
1445
1446    /* announce some */
1447    n = MIN( tr_ptrArraySize( &announceMe ), announcer->slotsAvailable );
1448    for( i=0; i<n; ++i ) {
1449        tr_tier * tier = tr_ptrArrayNth( &announceMe, i );
1450        dbgmsg( tier, "announcing tier %d of %d", i, n );
1451        tierAnnounce( announcer, tier );
1452    }
1453
1454    /* scrape some */
1455    multiscrape( announcer, &scrapeMe );
1456
1457    /* cleanup */
1458    tr_ptrArrayDestruct( &scrapeMe, NULL );
1459    tr_ptrArrayDestruct( &announceMe, NULL );
1460}
1461
1462static void
1463onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer )
1464{
1465    tr_announcer * announcer = vannouncer;
1466    tr_session * session = announcer->session;
1467    const bool is_closing = session->isClosed;
1468    const time_t now = tr_time( );
1469
1470    tr_sessionLock( session );
1471
1472    /* maybe send out some "stopped" messages for closed torrents */
1473    flushCloseMessages( announcer );
1474
1475    /* maybe send out some announcements to trackers */
1476    if( !is_closing )
1477        announceMore( announcer );
1478
1479    /* TAU upkeep */
1480    if( announcer->tauUpkeepAt <= now ) {
1481        announcer->tauUpkeepAt = now + TAU_UPKEEP_INTERVAL_SECS;
1482        tr_tracker_udp_upkeep( session );
1483    }
1484
1485    /* set up the next timer */
1486    tr_timerAdd( announcer->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
1487
1488    tr_sessionUnlock( session );
1489}
1490
1491/***
1492****
1493***/
1494
1495tr_tracker_stat *
1496tr_announcerStats( const tr_torrent * torrent, int * setmeTrackerCount )
1497{
1498    int i;
1499    int out = 0;
1500    tr_tracker_stat * ret;
1501    struct tr_torrent_tiers * tt;
1502    const time_t now = tr_time( );
1503
1504    assert( tr_isTorrent( torrent ) );
1505    assert( tr_torrentIsLocked( torrent ) );
1506
1507    tt = torrent->tiers;
1508
1509    /* alloc the stats */
1510    *setmeTrackerCount = tt->tracker_count;
1511    ret = tr_new0( tr_tracker_stat, tt->tracker_count );
1512
1513    /* populate the stats */
1514    for( i=0; i<tt->tier_count; ++i )
1515    {
1516        int j;
1517        const tr_tier * const tier = &tt->tiers[i];
1518        for( j=0; j<tier->tracker_count; ++j )
1519        {
1520            const tr_tracker * const tracker = &tier->trackers[j];
1521            tr_tracker_stat * st = &ret[out++];
1522
1523            st->id = tracker->id;
1524            tr_strlcpy( st->host, tracker->key, sizeof( st->host ) );
1525            tr_strlcpy( st->announce, tracker->announce, sizeof( st->announce ) );
1526            st->tier = i;
1527            st->isBackup = tracker != tier->currentTracker;
1528            st->lastScrapeStartTime = tier->lastScrapeStartTime;
1529            if( tracker->scrape )
1530                tr_strlcpy( st->scrape, tracker->scrape, sizeof( st->scrape ) );
1531            else
1532                st->scrape[0] = '\0';
1533
1534            st->seederCount = tracker->seederCount;
1535            st->leecherCount = tracker->leecherCount;
1536            st->downloadCount = tracker->downloadCount;
1537
1538            if( st->isBackup )
1539            {
1540                st->scrapeState = TR_TRACKER_INACTIVE;
1541                st->announceState = TR_TRACKER_INACTIVE;
1542                st->nextScrapeTime = 0;
1543                st->nextAnnounceTime = 0;
1544            }
1545            else
1546            {
1547                if(( st->hasScraped = tier->lastScrapeTime != 0 )) {
1548                    st->lastScrapeTime = tier->lastScrapeTime;
1549                    st->lastScrapeSucceeded = tier->lastScrapeSucceeded;
1550                    st->lastScrapeTimedOut = tier->lastScrapeTimedOut;
1551                    tr_strlcpy( st->lastScrapeResult, tier->lastScrapeStr,
1552                                sizeof( st->lastScrapeResult ) );
1553                }
1554
1555                if( tier->isScraping )
1556                    st->scrapeState = TR_TRACKER_ACTIVE;
1557                else if( !tier->scrapeAt )
1558                    st->scrapeState = TR_TRACKER_INACTIVE;
1559                else if( tier->scrapeAt > now )
1560                {
1561                    st->scrapeState = TR_TRACKER_WAITING;
1562                    st->nextScrapeTime = tier->scrapeAt;
1563                }
1564                else
1565                    st->scrapeState = TR_TRACKER_QUEUED;
1566
1567                st->lastAnnounceStartTime = tier->lastAnnounceStartTime;
1568
1569                if(( st->hasAnnounced = tier->lastAnnounceTime != 0 )) {
1570                    st->lastAnnounceTime = tier->lastAnnounceTime;
1571                    tr_strlcpy( st->lastAnnounceResult, tier->lastAnnounceStr,
1572                                sizeof( st->lastAnnounceResult ) );
1573                    st->lastAnnounceSucceeded = tier->lastAnnounceSucceeded;
1574                    st->lastAnnounceTimedOut = tier->lastAnnounceTimedOut;
1575                    st->lastAnnouncePeerCount = tier->lastAnnouncePeerCount;
1576                }
1577
1578                if( tier->isAnnouncing )
1579                    st->announceState = TR_TRACKER_ACTIVE;
1580                else if( !torrent->isRunning || !tier->announceAt )
1581                    st->announceState = TR_TRACKER_INACTIVE;
1582                else if( tier->announceAt > now )
1583                {
1584                    st->announceState = TR_TRACKER_WAITING;
1585                    st->nextAnnounceTime = tier->announceAt;
1586                }
1587                else
1588                    st->announceState = TR_TRACKER_QUEUED;
1589            }
1590        }
1591    }
1592
1593    return ret;
1594}
1595
1596void
1597tr_announcerStatsFree( tr_tracker_stat * trackers,
1598                       int trackerCount UNUSED )
1599{
1600    tr_free( trackers );
1601}
1602
1603/***
1604****
1605***/
1606
1607static void
1608copy_tier_attributes_impl( struct tr_tier * tgt, int trackerIndex, const tr_tier * src )
1609{
1610    const tr_tier keep = *tgt;
1611
1612    /* sanity clause */
1613    assert( trackerIndex < tgt->tracker_count );
1614    assert( !tr_strcmp0( tgt->trackers[trackerIndex].announce, src->currentTracker->announce ) );
1615
1616    /* bitwise copy will handle most of tr_tier's fields... */
1617    *tgt = *src;
1618
1619    /* ...fix the fields that can't be cleanly bitwise-copied */
1620    tgt->wasCopied = true;
1621    tgt->trackers = keep.trackers;
1622    tgt->announce_events = tr_memdup( src->announce_events, sizeof( tr_announce_event ) * src->announce_event_count );
1623    tgt->announce_event_count = src->announce_event_count;
1624    tgt->announce_event_alloc = src->announce_event_count;
1625    tgt->currentTrackerIndex = trackerIndex;
1626    tgt->currentTracker = &tgt->trackers[trackerIndex];
1627    tgt->currentTracker->seederCount = src->currentTracker->seederCount;
1628    tgt->currentTracker->leecherCount = src->currentTracker->leecherCount;
1629    tgt->currentTracker->downloadCount = src->currentTracker->downloadCount;
1630    tgt->currentTracker->downloaderCount = src->currentTracker->downloaderCount;
1631}
1632
1633static void
1634copy_tier_attributes( struct tr_torrent_tiers * tt, const tr_tier * src )
1635{
1636    int i, j;
1637    bool found = false;
1638
1639    /* find a tier (if any) which has a match for src->currentTracker */
1640    for( i=0; !found && i<tt->tier_count; ++i )
1641        for( j=0; !found && j<tt->tiers[i].tracker_count; ++j )
1642            if(( found = !tr_strcmp0( src->currentTracker->announce, tt->tiers[i].trackers[j].announce )))
1643                copy_tier_attributes_impl( &tt->tiers[i], j, src );
1644}
1645
1646void
1647tr_announcerResetTorrent( tr_announcer * announcer UNUSED, tr_torrent * tor )
1648{
1649    int i;
1650    const time_t now = tr_time( );
1651    struct tr_torrent_tiers * tt = tor->tiers;
1652    tr_torrent_tiers old = *tt;
1653
1654    assert( tt != NULL );
1655
1656    /* remove the old tiers / trackers */
1657    tt->tiers = NULL;
1658    tt->trackers = NULL;
1659    tt->tier_count = 0;
1660    tt->tracker_count = 0;
1661
1662    /* create the new tiers / trackers */
1663    addTorrentToTier( tt, tor );
1664
1665    /* copy the old tiers' states into their replacements */
1666    for( i=0; i<old.tier_count; ++i )
1667        if( old.tiers[i].currentTracker != NULL )
1668            copy_tier_attributes( tt, &old.tiers[i] );
1669
1670    /* kickstart any tiers that didn't get started */
1671    if( tor->isRunning )
1672        for( i=0; i<tt->tier_count; ++i )
1673            if( !tt->tiers[i].wasCopied )
1674                tier_announce_event_push( &tt->tiers[i], TR_ANNOUNCE_EVENT_STARTED, now );
1675
1676    /* cleanup */
1677    tiersDestruct( &old );
1678}
Note: See TracBrowser for help on using the repository browser.