source: trunk/libtransmission/announcer.c @ 12340

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

(trunk libT) #4175 "bizarre and unwieldly logfile in 2.30b2" -- possible fix for gunzip to test

  • Property svn:keywords set to Date Rev Author Id
File size: 49.2 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 12340 2011-04-10 00:05:18Z 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    tr_torinf( tier->tor, "Retrying scrape in %d seconds.", interval );
969    tier_announce_event_push( tier, e, tr_time( ) + interval );
970}
971
972static void
973on_announce_done( const tr_announce_response  * response,
974                  void                        * vdata )
975{
976    struct announce_data * data = vdata;
977    tr_announcer * announcer = data->session->announcer;
978    tr_tier * tier = getTier( announcer, response->info_hash, data->tierId );
979    const time_t now = tr_time( );
980    const tr_announce_event event = data->event;
981
982    if( announcer )
983        ++announcer->slotsAvailable;
984
985    if( tier != NULL )
986    {
987        tr_tracker * tracker;
988
989        dbgmsg( tier, "Got announce response: "
990                      "connected:%d "
991                      "timeout:%d "
992                      "seeders:%d "
993                      "leechers:%d "
994                      "downloads:%d "
995                      "interval:%d "
996                      "min_interval:%d "
997                      "tracker_id_str:%s "
998                      "pex:%zu "
999                      "pex6:%zu "
1000                      "err:%s "
1001                      "warn:%s",
1002                      (int)response->did_connect,
1003                      (int)response->did_timeout,
1004                      response->seeders,
1005                      response->leechers,
1006                      response->downloads,
1007                      response->interval,
1008                      response->min_interval,
1009                      response->tracker_id_str ? response->tracker_id_str : "none",
1010                      response->pex_count,
1011                      response->pex6_count,
1012                      response->errmsg ? response->errmsg : "none",
1013                      response->warning ? response->warning : "none" );
1014
1015        tier->lastAnnounceTime = now;
1016        tier->lastAnnounceTimedOut = response->did_timeout;
1017        tier->lastAnnounceSucceeded = false;
1018        tier->isAnnouncing = false;
1019        tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1020
1021        if( !response->did_connect )
1022        {
1023            on_announce_error( tier, _( "Could not connect to tracker" ), event );
1024        }
1025        else if( response->did_timeout )
1026        {
1027            on_announce_error( tier, _( "Tracker did not respond" ), event );
1028        }
1029        else if( response->errmsg )
1030        {
1031            publishError( tier, response->errmsg );
1032            on_announce_error( tier, response->errmsg, event );
1033        }
1034        else
1035        {
1036            int i;
1037            const char * str;
1038            const bool isStopped = event == TR_ANNOUNCE_EVENT_STOPPED;
1039
1040            publishErrorClear( tier );
1041
1042            if(( tracker = tier->currentTracker ))
1043            {
1044                tracker->consecutiveFailures = 0;
1045                tracker->seederCount = response->seeders;
1046                tracker->leecherCount = response->leechers;
1047                tracker->downloadCount = response->downloads;
1048
1049                if(( str = response->tracker_id_str ))
1050                {
1051                    tr_free( tracker->tracker_id_str );
1052                    tracker->tracker_id_str = tr_strdup( str );
1053                }
1054            }
1055
1056            if(( str = response->warning ))
1057            {
1058                tr_strlcpy( tier->lastAnnounceStr, str,
1059                            sizeof( tier->lastAnnounceStr ) );
1060                dbgmsg( tier, "tracker gave \"%s\"", str );
1061                publishWarning( tier, str );
1062            }
1063
1064            if(( i = response->min_interval ))
1065                tier->announceMinIntervalSec = i;
1066
1067            if(( i = response->interval ))
1068                tier->announceIntervalSec = i;
1069
1070            if( response->pex_count > 0 )
1071                publishPeersPex( tier, response->seeders, response->leechers,
1072                                 response->pex, response->pex_count );
1073
1074            if( response->pex6_count > 0 )
1075                publishPeersPex( tier, response->seeders, response->leechers,
1076                                 response->pex6, response->pex6_count );
1077
1078            if( !*tier->lastAnnounceStr )
1079                tr_strlcpy( tier->lastAnnounceStr, _( "Success" ),
1080                            sizeof( tier->lastAnnounceStr ) );
1081
1082            tier->isRunning = data->isRunningOnSuccess;
1083            tier->scrapeAt = get_next_scrape_time( tier->scrapeIntervalSec );
1084            tier->lastScrapeTime = now;
1085            tier->lastScrapeSucceeded = true;
1086            tier->lastAnnounceSucceeded = true;
1087            tier->lastAnnouncePeerCount = response->pex_count
1088                                        + response->pex6_count;
1089
1090            if( isStopped )
1091            {
1092                /* now that we've successfully stopped the torrent,
1093                 * we can reset the up/down/corrupt count we've kept
1094                 * for this tracker */
1095                tier->byteCounts[ TR_ANN_UP ] = 0;
1096                tier->byteCounts[ TR_ANN_DOWN ] = 0;
1097                tier->byteCounts[ TR_ANN_CORRUPT ] = 0;
1098            }
1099
1100            if( !isStopped && !tier->announce_event_count )
1101            {
1102                /* the queue is empty, so enqueue a perodic update */
1103                i = tier->announceIntervalSec;
1104                dbgmsg( tier, "Sending periodic reannounce in %d seconds", i );
1105                tier_announce_event_push( tier, TR_ANNOUNCE_EVENT_NONE, now + i );
1106            }
1107        }
1108    }
1109
1110    tr_free( data );
1111}
1112
1113static void
1114announce_request_delegate( tr_announcer               * announcer,
1115                           tr_announce_request        * request,
1116                           tr_announce_response_func  * callback,
1117                           void                       * callback_data )
1118{
1119    tr_session * session = announcer->session;
1120
1121    if( !memcmp( request->url, "http", 4 ) )
1122        tr_tracker_http_announce( session, request, callback, callback_data );
1123    else if( !memcmp( request->url, "udp://", 6 ) )
1124        tr_tracker_udp_announce( session, request, callback, callback_data );
1125    else
1126        tr_err( "Unsupported url: %s", request->url );
1127
1128    tr_free( request->tracker_id_str );
1129    tr_free( request->url );
1130    tr_free( request );
1131}
1132
1133static void
1134tierAnnounce( tr_announcer * announcer, tr_tier * tier )
1135{
1136    tr_announce_event announce_event;
1137    tr_announce_request * req;
1138    struct announce_data * data;
1139    const tr_torrent * tor = tier->tor;
1140    const time_t now = tr_time( );
1141
1142    assert( !tier->isAnnouncing );
1143    assert( tier->announce_event_count > 0 );
1144
1145    announce_event = tier_announce_event_pull( tier );
1146    req = announce_request_new( announcer, tor, tier, announce_event );
1147
1148    data = tr_new0( struct announce_data, 1 );
1149    data->session = announcer->session;
1150    data->tierId = tier->key;
1151    data->isRunningOnSuccess = tor->isRunning;
1152    data->timeSent = now;
1153    data->event = announce_event;
1154
1155    tier->isAnnouncing = true;
1156    tier->lastAnnounceStartTime = now;
1157    --announcer->slotsAvailable;
1158
1159    announce_request_delegate( announcer, req, on_announce_done, data );
1160}
1161
1162/***
1163****
1164****  SCRAPE
1165****
1166***/
1167
1168static void
1169on_scrape_error( tr_tier * tier, const char * errmsg )
1170{
1171    time_t interval;
1172
1173    /* increment the error count */
1174    if( tier->currentTracker != NULL )
1175        ++tier->currentTracker->consecutiveFailures;
1176
1177    /* set the error message */
1178    dbgmsg( tier, "Scrape error: %s", errmsg );
1179    tr_torinf( tier->tor, "Scrape error: %s", errmsg );
1180    tr_strlcpy( tier->lastScrapeStr, errmsg, sizeof( tier->lastScrapeStr ) );
1181
1182    /* switch to the next tracker */
1183    tierIncrementTracker( tier );
1184
1185    /* schedule a rescrape */
1186    interval = get_next_scrape_time( getRetryInterval( tier->currentTracker ) );
1187    dbgmsg( tier, "Retrying scrape in %zu seconds.", (size_t)interval );
1188    tr_torinf( tier->tor, "Retrying scrape in %zu seconds.", (size_t)interval );
1189    tier->lastScrapeSucceeded = false;
1190    tier->scrapeAt = get_next_scrape_time( interval );
1191}
1192
1193static tr_tier *
1194find_tier( tr_torrent * tor, const char * scrape )
1195{
1196    int i;
1197    struct tr_torrent_tiers * tt = tor->tiers;
1198
1199    for( i=0; tt && i<tt->tier_count; ++i ) {
1200        const tr_tracker * const tracker = tt->tiers[i].currentTracker;
1201        if( tracker && !tr_strcmp0( scrape, tracker->scrape ) )
1202            return &tt->tiers[i];
1203    }
1204
1205    return NULL;
1206}
1207
1208static void
1209on_scrape_done( const tr_scrape_response  * response, void * vsession )
1210{
1211    int i;
1212    const time_t now = tr_time( );
1213    tr_session * session = vsession;
1214    tr_announcer * announcer = session->announcer;
1215
1216    for( i=0; i<response->row_count; ++i )
1217    {
1218        const struct tr_scrape_response_row * row = &response->rows[i];
1219        tr_torrent * tor = tr_torrentFindFromHash( session, row->info_hash );
1220
1221        if( tor != NULL )
1222        {
1223            tr_tier * tier = find_tier( tor, response->url );
1224
1225            if( tier != NULL )
1226            {
1227                dbgmsg( tier, "scraped url:%s -- "
1228                              "did_connect:%d "
1229                              "did_timeout:%d "
1230                              "seeders:%d "
1231                              "leechers:%d "
1232                              "downloads:%d "
1233                              "downloaders:%d "
1234                              "min_request_interval:%d "
1235                              "err:%s ",
1236                              response->url,
1237                              (int)response->did_connect,
1238                              (int)response->did_timeout,
1239                              row->seeders,
1240                              row->leechers,
1241                              row->downloads,
1242                              row->downloaders,
1243                              response->min_request_interval,
1244                              response->errmsg ? response->errmsg : "none" );
1245
1246                tier->isScraping = false;
1247                tier->lastScrapeTime = now;
1248                tier->lastScrapeSucceeded = false;
1249                tier->lastScrapeTimedOut = response->did_timeout;
1250
1251                if( !response->did_connect )
1252                {
1253                    on_scrape_error( tier, _( "Could not connect to tracker" ) );
1254                }
1255                else if( response->did_timeout )
1256                {
1257                    on_scrape_error( tier, _( "Tracker did not respond" ) );
1258                }
1259                else if( response->errmsg )
1260                {
1261                    on_scrape_error( tier, response->errmsg );
1262                }
1263                else
1264                {
1265                    tr_tracker * tracker;
1266
1267                    tier->lastScrapeSucceeded = true;
1268                    tier->scrapeIntervalSec = MAX( DEFAULT_SCRAPE_INTERVAL_SEC,
1269                                                   response->min_request_interval );
1270                    tier->scrapeAt = get_next_scrape_time( tier->scrapeIntervalSec );
1271                    tr_tordbg( tier->tor, "Scrape successful. Rescraping in %d seconds.",
1272                               tier->scrapeIntervalSec );
1273
1274                    if(( tracker = tier->currentTracker ))
1275                    {
1276                        tracker->seederCount = row->seeders;
1277                        tracker->leecherCount = row->leechers;
1278                        tracker->downloadCount = row->downloads;
1279                        tracker->downloaderCount = row->downloaders;
1280                        tracker->consecutiveFailures = 0;
1281                    }
1282
1283                    if( tr_torrentIsPrivate( tier->tor ) && !row->downloaders )
1284                        tr_peerMgrMarkAllAsSeeds( tier->tor );
1285                }
1286            }
1287        }
1288    }
1289
1290    if( announcer )
1291        ++announcer->slotsAvailable;
1292}
1293
1294static void
1295scrape_request_delegate( tr_announcer             * announcer,
1296                         tr_scrape_request        * request,
1297                         tr_scrape_response_func  * callback,
1298                         void                     * callback_data )
1299{
1300    tr_session * session = announcer->session;
1301
1302    if( !memcmp( request->url, "http", 4 ) )
1303        tr_tracker_http_scrape( session, request, callback, callback_data );
1304    else if( !memcmp( request->url, "udp://", 6 ) )
1305        tr_tracker_udp_scrape( session, request, callback, callback_data );
1306    else
1307        tr_err( "Unsupported url: %s", request->url );
1308}
1309
1310static void
1311multiscrape( tr_announcer * announcer, tr_ptrArray * tiers )
1312{
1313    int i;
1314    int request_count = 0;
1315    const time_t now = tr_time( );
1316    const int tier_count = tr_ptrArraySize( tiers );
1317    const int max_request_count = MIN( announcer->slotsAvailable, tier_count );
1318    tr_scrape_request * requests = tr_new0( tr_scrape_request, max_request_count );
1319
1320    /* batch as many info_hashes into a request as we can */
1321    for( i=0; i<tier_count; ++i )
1322    {
1323        int j;
1324        tr_tier * tier = tr_ptrArrayNth( tiers, i );
1325        char * url = tier->currentTracker->scrape;
1326        const uint8_t * hash = tier->tor->info.hash;
1327
1328        /* if there's a request with this scrape URL and a free slot, use it */
1329        for( j=0; j<request_count; ++j )
1330        {
1331            tr_scrape_request * req = &requests[j];
1332
1333            if( req->info_hash_count >= TR_MULTISCRAPE_MAX )
1334                continue;
1335            if( tr_strcmp0( req->url, url ) )
1336                continue;
1337
1338            memcpy( req->info_hash[req->info_hash_count++], hash, SHA_DIGEST_LENGTH );
1339            tier->isScraping = true;
1340            tier->lastScrapeStartTime = now;
1341            break;
1342        }
1343
1344        /* otherwise, if there's room for another request, build a new one */
1345        if( ( j==request_count ) && ( request_count < max_request_count ) )
1346        {
1347            tr_scrape_request * req = &requests[request_count++];
1348            req->url = url;
1349            tier_build_log_name( tier, req->log_name, sizeof( req->log_name ) );
1350
1351            memcpy( req->info_hash[req->info_hash_count++], hash, SHA_DIGEST_LENGTH );
1352            tier->isScraping = true;
1353            tier->lastScrapeStartTime = now;
1354        }
1355    }
1356
1357    /* send the requests we just built */
1358    for( i=0; i<request_count; ++i )
1359        scrape_request_delegate( announcer, &requests[i], on_scrape_done, announcer->session );
1360
1361    /* cleanup */
1362    tr_free( requests );
1363}
1364
1365static void
1366flushCloseMessages( tr_announcer * announcer )
1367{
1368    int i;
1369    const int n = tr_ptrArraySize( &announcer->stops );
1370
1371    for( i=0; i<n; ++i )
1372        announce_request_delegate( announcer, tr_ptrArrayNth( &announcer->stops, i ), NULL, NULL );
1373
1374    tr_ptrArrayClear( &announcer->stops );
1375}
1376
1377static bool
1378tierNeedsToAnnounce( const tr_tier * tier, const time_t now )
1379{
1380    return !tier->isAnnouncing
1381        && !tier->isScraping
1382        && ( tier->announceAt != 0 )
1383        && ( tier->announceAt <= now )
1384        && ( tier->announce_event_count > 0 );
1385}
1386
1387static bool
1388tierNeedsToScrape( const tr_tier * tier, const time_t now )
1389{
1390    return ( !tier->isScraping )
1391        && ( tier->scrapeAt != 0 )
1392        && ( tier->scrapeAt <= now )
1393        && ( tier->currentTracker != NULL )
1394        && ( tier->currentTracker->scrape != NULL );
1395}
1396
1397static int
1398compareTiers( const void * va, const void * vb )
1399{
1400    int ret;
1401    const tr_tier * a = *(const tr_tier**)va;
1402    const tr_tier * b = *(const tr_tier**)vb;
1403
1404    /* primary key: larger stats come before smaller */
1405    ret = compareTransfer( a->byteCounts[TR_ANN_UP], a->byteCounts[TR_ANN_DOWN],
1406                           b->byteCounts[TR_ANN_UP], b->byteCounts[TR_ANN_DOWN] );
1407
1408    /* secondary key: announcements that have been waiting longer go first */
1409    if( !ret && ( a->announceAt != b->announceAt ) )
1410        ret = a->announceAt < b->announceAt ? -1 : 1;
1411
1412    return ret;
1413}
1414
1415static void
1416announceMore( tr_announcer * announcer )
1417{
1418    int i;
1419    int n;
1420    tr_torrent * tor;
1421    tr_ptrArray announceMe = TR_PTR_ARRAY_INIT;
1422    tr_ptrArray scrapeMe = TR_PTR_ARRAY_INIT;
1423    const time_t now = tr_time( );
1424
1425    dbgmsg( NULL, "announceMore: slotsAvailable is %d", announcer->slotsAvailable );
1426
1427    if( announcer->slotsAvailable < 1 )
1428        return;
1429
1430    /* build a list of tiers that need to be announced */
1431    tor = NULL;
1432    while(( tor = tr_torrentNext( announcer->session, tor ))) {
1433        struct tr_torrent_tiers * tt = tor->tiers;
1434        for( i=0; tt && i<tt->tier_count; ++i ) {
1435            tr_tier * tier = &tt->tiers[i];
1436            if( tierNeedsToAnnounce( tier, now ) )
1437                tr_ptrArrayAppend( &announceMe, tier );
1438            else if( tierNeedsToScrape( tier, now ) )
1439                tr_ptrArrayAppend( &scrapeMe, tier );
1440        }
1441    }
1442
1443    /* if there are more tiers than slots available, prioritize */
1444    n = tr_ptrArraySize( &announceMe );
1445    if( n > announcer->slotsAvailable )
1446        qsort( tr_ptrArrayBase(&announceMe), n, sizeof(tr_tier*), compareTiers );
1447
1448    /* announce some */
1449    n = MIN( tr_ptrArraySize( &announceMe ), announcer->slotsAvailable );
1450    for( i=0; i<n; ++i ) {
1451        tr_tier * tier = tr_ptrArrayNth( &announceMe, i );
1452        tr_tordbg( tier->tor, "%s", "Announcing to tracker" );
1453        dbgmsg( tier, "announcing tier %d of %d", i, n );
1454        tierAnnounce( announcer, tier );
1455    }
1456
1457    /* scrape some */
1458    multiscrape( announcer, &scrapeMe );
1459
1460    /* cleanup */
1461    tr_ptrArrayDestruct( &scrapeMe, NULL );
1462    tr_ptrArrayDestruct( &announceMe, NULL );
1463}
1464
1465static void
1466onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer )
1467{
1468    tr_announcer * announcer = vannouncer;
1469    tr_session * session = announcer->session;
1470    const bool is_closing = session->isClosed;
1471    const time_t now = tr_time( );
1472
1473    tr_sessionLock( session );
1474
1475    /* maybe send out some "stopped" messages for closed torrents */
1476    flushCloseMessages( announcer );
1477
1478    /* maybe send out some announcements to trackers */
1479    if( !is_closing )
1480        announceMore( announcer );
1481
1482    /* TAU upkeep */
1483    if( announcer->tauUpkeepAt <= now ) {
1484        announcer->tauUpkeepAt = now + TAU_UPKEEP_INTERVAL_SECS;
1485        tr_tracker_udp_upkeep( session );
1486    }
1487
1488    /* set up the next timer */
1489    tr_timerAdd( announcer->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
1490
1491    tr_sessionUnlock( session );
1492}
1493
1494/***
1495****
1496***/
1497
1498tr_tracker_stat *
1499tr_announcerStats( const tr_torrent * torrent, int * setmeTrackerCount )
1500{
1501    int i;
1502    int out = 0;
1503    tr_tracker_stat * ret;
1504    struct tr_torrent_tiers * tt;
1505    const time_t now = tr_time( );
1506
1507    assert( tr_isTorrent( torrent ) );
1508    assert( tr_torrentIsLocked( torrent ) );
1509
1510    tt = torrent->tiers;
1511
1512    /* alloc the stats */
1513    *setmeTrackerCount = tt->tracker_count;
1514    ret = tr_new0( tr_tracker_stat, tt->tracker_count );
1515
1516    /* populate the stats */
1517    for( i=0; i<tt->tier_count; ++i )
1518    {
1519        int j;
1520        const tr_tier * const tier = &tt->tiers[i];
1521        for( j=0; j<tier->tracker_count; ++j )
1522        {
1523            const tr_tracker * const tracker = &tier->trackers[j];
1524            tr_tracker_stat * st = &ret[out++];
1525
1526            st->id = tracker->id;
1527            tr_strlcpy( st->host, tracker->key, sizeof( st->host ) );
1528            tr_strlcpy( st->announce, tracker->announce, sizeof( st->announce ) );
1529            st->tier = i;
1530            st->isBackup = tracker != tier->currentTracker;
1531            st->lastScrapeStartTime = tier->lastScrapeStartTime;
1532            if( tracker->scrape )
1533                tr_strlcpy( st->scrape, tracker->scrape, sizeof( st->scrape ) );
1534            else
1535                st->scrape[0] = '\0';
1536
1537            st->seederCount = tracker->seederCount;
1538            st->leecherCount = tracker->leecherCount;
1539            st->downloadCount = tracker->downloadCount;
1540
1541            if( st->isBackup )
1542            {
1543                st->scrapeState = TR_TRACKER_INACTIVE;
1544                st->announceState = TR_TRACKER_INACTIVE;
1545                st->nextScrapeTime = 0;
1546                st->nextAnnounceTime = 0;
1547            }
1548            else
1549            {
1550                if(( st->hasScraped = tier->lastScrapeTime != 0 )) {
1551                    st->lastScrapeTime = tier->lastScrapeTime;
1552                    st->lastScrapeSucceeded = tier->lastScrapeSucceeded;
1553                    st->lastScrapeTimedOut = tier->lastScrapeTimedOut;
1554                    tr_strlcpy( st->lastScrapeResult, tier->lastScrapeStr,
1555                                sizeof( st->lastScrapeResult ) );
1556                }
1557
1558                if( tier->isScraping )
1559                    st->scrapeState = TR_TRACKER_ACTIVE;
1560                else if( !tier->scrapeAt )
1561                    st->scrapeState = TR_TRACKER_INACTIVE;
1562                else if( tier->scrapeAt > now )
1563                {
1564                    st->scrapeState = TR_TRACKER_WAITING;
1565                    st->nextScrapeTime = tier->scrapeAt;
1566                }
1567                else
1568                    st->scrapeState = TR_TRACKER_QUEUED;
1569
1570                st->lastAnnounceStartTime = tier->lastAnnounceStartTime;
1571
1572                if(( st->hasAnnounced = tier->lastAnnounceTime != 0 )) {
1573                    st->lastAnnounceTime = tier->lastAnnounceTime;
1574                    tr_strlcpy( st->lastAnnounceResult, tier->lastAnnounceStr,
1575                                sizeof( st->lastAnnounceResult ) );
1576                    st->lastAnnounceSucceeded = tier->lastAnnounceSucceeded;
1577                    st->lastAnnounceTimedOut = tier->lastAnnounceTimedOut;
1578                    st->lastAnnouncePeerCount = tier->lastAnnouncePeerCount;
1579                }
1580
1581                if( tier->isAnnouncing )
1582                    st->announceState = TR_TRACKER_ACTIVE;
1583                else if( !torrent->isRunning || !tier->announceAt )
1584                    st->announceState = TR_TRACKER_INACTIVE;
1585                else if( tier->announceAt > now )
1586                {
1587                    st->announceState = TR_TRACKER_WAITING;
1588                    st->nextAnnounceTime = tier->announceAt;
1589                }
1590                else
1591                    st->announceState = TR_TRACKER_QUEUED;
1592            }
1593        }
1594    }
1595
1596    return ret;
1597}
1598
1599void
1600tr_announcerStatsFree( tr_tracker_stat * trackers,
1601                       int trackerCount UNUSED )
1602{
1603    tr_free( trackers );
1604}
1605
1606/***
1607****
1608***/
1609
1610static void
1611copy_tier_attributes_impl( struct tr_tier * tgt, int trackerIndex, const tr_tier * src )
1612{
1613    const tr_tier keep = *tgt;
1614
1615    /* sanity clause */
1616    assert( trackerIndex < tgt->tracker_count );
1617    assert( !tr_strcmp0( tgt->trackers[trackerIndex].announce, src->currentTracker->announce ) );
1618
1619    /* bitwise copy will handle most of tr_tier's fields... */
1620    *tgt = *src;
1621
1622    /* ...fix the fields that can't be cleanly bitwise-copied */
1623    tgt->wasCopied = true;
1624    tgt->trackers = keep.trackers;
1625    tgt->announce_events = tr_memdup( src->announce_events, sizeof( tr_announce_event ) * src->announce_event_count );
1626    tgt->announce_event_count = src->announce_event_count;
1627    tgt->announce_event_alloc = src->announce_event_count;
1628    tgt->currentTrackerIndex = trackerIndex;
1629    tgt->currentTracker = &tgt->trackers[trackerIndex];
1630    tgt->currentTracker->seederCount = src->currentTracker->seederCount;
1631    tgt->currentTracker->leecherCount = src->currentTracker->leecherCount;
1632    tgt->currentTracker->downloadCount = src->currentTracker->downloadCount;
1633    tgt->currentTracker->downloaderCount = src->currentTracker->downloaderCount;
1634}
1635
1636static void
1637copy_tier_attributes( struct tr_torrent_tiers * tt, const tr_tier * src )
1638{
1639    int i, j;
1640    bool found = false;
1641
1642    /* find a tier (if any) which has a match for src->currentTracker */
1643    for( i=0; !found && i<tt->tier_count; ++i )
1644        for( j=0; !found && j<tt->tiers[i].tracker_count; ++j )
1645            if(( found = !tr_strcmp0( src->currentTracker->announce, tt->tiers[i].trackers[j].announce )))
1646                copy_tier_attributes_impl( &tt->tiers[i], j, src );
1647}
1648
1649void
1650tr_announcerResetTorrent( tr_announcer * announcer UNUSED, tr_torrent * tor )
1651{
1652    int i;
1653    const time_t now = tr_time( );
1654    struct tr_torrent_tiers * tt = tor->tiers;
1655    tr_torrent_tiers old = *tt;
1656
1657    assert( tt != NULL );
1658
1659    /* remove the old tiers / trackers */
1660    tt->tiers = NULL;
1661    tt->trackers = NULL;
1662    tt->tier_count = 0;
1663    tt->tracker_count = 0;
1664
1665    /* create the new tiers / trackers */
1666    addTorrentToTier( tt, tor );
1667
1668    /* copy the old tiers' states into their replacements */
1669    for( i=0; i<old.tier_count; ++i )
1670        if( old.tiers[i].currentTracker != NULL )
1671            copy_tier_attributes( tt, &old.tiers[i] );
1672
1673    /* kickstart any tiers that didn't get started */
1674    if( tor->isRunning )
1675        for( i=0; i<tt->tier_count; ++i )
1676            if( !tt->tiers[i].wasCopied )
1677                tier_announce_event_push( &tt->tiers[i], TR_ANNOUNCE_EVENT_STARTED, now );
1678
1679    /* cleanup */
1680    tiersDestruct( &old );
1681}
Note: See TracBrowser for help on using the repository browser.