source: trunk/libtransmission/announcer.c @ 9176

Last change on this file since 9176 was 9176, checked in by charles, 13 years ago

(trunk libT) remove some debug printfs

File size: 47.6 KB
Line 
1/*
2 * This file Copyright (C) 2009 Charles Kerr <charles@transmissionbt.com>
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id:$
11 */
12
13#include <assert.h>
14#include <limits.h>
15
16#include <event.h>
17#include <evhttp.h> /* for HTTP_OK */
18
19#include "transmission.h"
20#include "announcer.h"
21#include "crypto.h"
22#include "net.h"
23#include "ptrarray.h"
24#include "publish.h"
25#include "session.h"
26#include "torrent.h"
27#include "utils.h"
28#include "web.h"
29
30#define dbgmsg( tier, ... ) \
31if( tr_deepLoggingIsActive( ) ) do { \
32  char name[128]; \
33  tr_snprintf( name, sizeof( name ), "[%s--%s]", tr_torrentName( tier->tor ), \
34      ( tier->currentTracker ? tier->currentTracker->host->name : "" ) ); \
35  tr_deepLog( __FILE__, __LINE__, name, __VA_ARGS__ ); \
36} while( 0 )
37
38enum
39{
40    /* unless the tracker says otherwise, rescrape this frequently */
41    DEFAULT_SCRAPE_INTERVAL_SEC = ( 60 * 15 ),
42
43    /* unless the tracker says otherwise, this is the announce interval */
44    DEFAULT_ANNOUNCE_INTERVAL_SEC = ( 60 * 10 ),
45
46    /* unless the tracker says otherwise, this is the announce min_interval */
47    DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC = ( 60 * 2 ),
48
49    /* how long to wait before a reannounce the first time we get an error */
50    FIRST_ANNOUNCE_RETRY_INTERVAL_SEC = 30,
51
52    /* how long to wait before a rescrape the first time we get an error */
53    FIRST_SCRAPE_RETRY_INTERVAL_SEC = 120,
54
55    /* the length of the 'key' argument passed in tracker requests */
56    KEYLEN = 8,
57
58    /* how many scrapes we allow at one time */
59    MAX_CONCURRENT_SCRAPES = 16,
60
61    /* how many announces we allow at one time */
62    MAX_CONCURRENT_ANNOUNCES = 48,
63
64    /* if a tracker takes more than this long to respond,
65     * we treat it as nonresponsive */
66    MAX_TRACKER_RESPONSE_TIME_SECS = ( 60 * 2 ),
67
68    /* the value of the 'numwant' argument passed in tracker requests. */
69    NUMWANT = 200,
70
71    /* how long to put slow (nonresponsive) trackers in the penalty box */
72    SLOW_HOST_PENALTY_SECS = ( 60 * 10 ),
73
74    UPKEEP_INTERVAL_SECS = 1
75
76};
77
78/***
79****
80***/
81
82static int
83compareTransfer( int a_uploaded, int a_downloaded,
84                 int b_uploaded, int b_downloaded )
85{
86    /* higher upload count goes first */
87    if( a_uploaded != b_uploaded )
88        return a_uploaded > b_uploaded ? -1 : 1;
89
90    /* then higher download count goes first */
91    if( a_downloaded != b_downloaded )
92        return a_downloaded > b_downloaded ? -1 : 1;
93
94    return 0;
95}
96
97/***
98****
99***/
100
101/**
102 * used by tr_announcer to recognize nonresponsive
103 * trackers and de-prioritize them
104 */
105typedef struct
106{
107    char * name;
108
109    /* how many seconds it took to get the last tracker response */
110    int lastResponseInterval;
111
112    /* the last time we sent an announce or scrape message */
113    time_t lastRequestTime;
114}
115tr_host;
116
117static int
118compareHosts( const void * va, const void * vb )
119{
120    const tr_host * a = va;
121    const tr_host * b = vb;
122    return strcmp( a->name, b->name );
123}
124
125static int
126compareHostToName( const void * va, const void * vb )
127{
128    const tr_host * a = va;
129    return strcmp( a->name, vb );
130}
131
132static char *
133getHostName( const char * url )
134{
135    int port = 0;
136    char * host = NULL;
137    char * ret;
138    tr_httpParseURL( url, strlen( url ), &host, &port, NULL );
139    ret = tr_strdup_printf( "%s:%d", ( host ? host : "invalid" ), port );
140    tr_free( host );
141    return ret;
142}
143
144static tr_host*
145hostNew( const char * name )
146{
147    tr_host * host = tr_new0( tr_host, 1 );
148    host->name = tr_strdup( name );
149    return host;
150}
151
152static void
153hostFree( void * vhost )
154{
155    tr_host * host = vhost;
156
157    tr_free( host->name );
158    tr_free( host );
159}
160
161/***
162****
163***/
164
165/**
166 * Since we can't poll a tr_torrent's fields after it's destroyed,
167 * we pre-build the "stop" announcement message when a torrent
168 * is removed from Transmission
169 */
170struct stop_message
171{
172    tr_host * host;
173    char * url;
174    int up;
175    int down;
176};
177
178static void
179stopFree( struct stop_message * stop )
180{
181    tr_free( stop->url );
182    tr_free( stop );
183}
184
185static int
186compareStops( const void * va, const void * vb )
187{
188    const struct stop_message * a = va;
189    const struct stop_message * b = vb;
190    return compareTransfer( a->up, a->down, b->up, b->down);
191}
192
193/***
194****
195***/
196
197/**
198 * "global" (per-tr_session) fields
199 */
200typedef struct tr_announcer
201{
202    tr_ptrArray hosts; /* tr_host */
203    tr_ptrArray stops; /* struct stop_message */
204    tr_session * session;
205    struct event * upkeepTimer;
206    int announceSlotsAvailable;
207    int scrapeSlotsAvailable;
208}
209tr_announcer;
210
211static tr_host *
212getHost( tr_announcer * announcer, const char * url )
213{
214    char * name = getHostName( url );
215    tr_host * host;
216
217    host = tr_ptrArrayFindSorted( &announcer->hosts, name, compareHostToName );
218    if( host == NULL )
219    {
220        host = hostNew( name );
221        tr_ptrArrayInsertSorted( &announcer->hosts, host, compareHosts );
222    }
223
224    tr_free( name );
225    return host;
226}
227
228static void
229onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer );
230
231void
232tr_announcerInit( tr_session * session )
233{
234    tr_announcer * a;
235
236    assert( tr_isSession( session ) );
237
238    a = tr_new0( tr_announcer, 1 );
239    a->hosts = TR_PTR_ARRAY_INIT;
240    a->stops = TR_PTR_ARRAY_INIT;
241    a->session = session;
242    a->announceSlotsAvailable = MAX_CONCURRENT_ANNOUNCES;
243    a->scrapeSlotsAvailable = MAX_CONCURRENT_SCRAPES;
244    a->upkeepTimer = tr_new0( struct event, 1 );
245    evtimer_set( a->upkeepTimer, onUpkeepTimer, a );
246    tr_timerAdd( a->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
247
248    session->announcer = a;
249}
250
251static void flushCloseMessages( tr_announcer * announcer );
252
253void
254tr_announcerClose( tr_session * session )
255{
256    tr_announcer * announcer = session->announcer;
257
258    flushCloseMessages( announcer );
259
260    evtimer_del( announcer->upkeepTimer );
261    tr_free( announcer->upkeepTimer );
262    announcer->upkeepTimer = NULL;
263
264    tr_ptrArrayDestruct( &announcer->stops, NULL );
265    tr_ptrArrayDestruct( &announcer->hosts, hostFree );
266
267    session->announcer = NULL;
268    tr_free( announcer );
269}
270
271/***
272****
273***/
274
275/* a row in tr_tier's list of trackers */
276typedef struct
277{
278    tr_host * host;
279
280    char * announce;
281    char * scrape;
282
283    char * tracker_id;
284
285    int seederCount;
286    int leecherCount;
287    int downloadCount;
288    int downloaderCount;
289
290    /* sent as the "key" argument in tracker requests
291     * to verify us if our IP address changes.
292     * This is immutable for the life of the tracker object. */
293    char key_param[KEYLEN + 1];
294}
295tr_tracker_item;
296
297static void
298generateKeyParam( char * msg, size_t msglen )
299{
300    size_t i;
301    const char * pool = "abcdefghijklmnopqrstuvwxyz0123456789";
302    const int poolSize = strlen( pool );
303
304    for( i=0; i<msglen; ++i )
305        *msg++ = pool[tr_cryptoRandInt( poolSize )];
306    *msg = '\0';
307}
308
309static tr_tracker_item*
310trackerNew( tr_announcer  * announcer,
311            const char    * announce,
312            const char    * scrape )
313{
314    tr_tracker_item * tracker = tr_new0( tr_tracker_item, 1  );
315    tracker->host = getHost( announcer, announce );
316    tracker->announce = tr_strdup( announce );
317    tracker->scrape = tr_strdup( scrape );
318    generateKeyParam( tracker->key_param, KEYLEN );
319    return tracker;
320}
321
322static void
323trackerFree( void * vtracker )
324{
325    tr_tracker_item * tracker = vtracker;
326
327    tr_free( tracker->tracker_id );
328    tr_free( tracker->announce );
329    tr_free( tracker->scrape );
330    tr_free( tracker );
331}
332
333/***
334****
335***/
336
337struct tr_torrent_tiers;
338
339/**
340 * A group of trackers in a single tier,
341 * as per the multitracker spec
342 */
343typedef struct
344{
345    tr_ptrArray trackers; /* tr_tracker_item */
346    tr_tracker_item * currentTracker;
347
348    tr_torrent * tor;
349
350    time_t lastScrapeTime;
351    time_t lastAnnounceTime;
352    time_t lastScrapeStartTime;
353    time_t lastAnnounceStartTime;
354    tr_bool lastScrapeSucceeded;
355    tr_bool lastAnnounceSucceeded;
356
357    time_t scrapeAt;
358    time_t manualAnnounceAllowedAt;
359
360    time_t announceAt;
361    const char * announceEvent;
362
363    /* unique lookup key */
364    int key;
365
366    int currentTrackerIndex;
367    int scrapeIntervalSec;
368    int announceIntervalSec;
369    int announceMinIntervalSec;
370    int retryAnnounceIntervalSec;
371    int retryScrapeIntervalSec;
372
373    int randOffset;
374    int lastAnnouncePeerCount;
375
376    tr_bool isRunning;
377    tr_bool isAnnouncing;
378    tr_bool isScraping;
379
380    char lastAnnounceStr[128];
381    char lastScrapeStr[128];
382}
383tr_tier;
384
385static tr_tier *
386tierNew( tr_torrent * tor )
387{
388    tr_tier * t;
389    static int nextKey = 1;
390    const time_t now = time( NULL );
391
392    t = tr_new0( tr_tier, 1 );
393    t->randOffset = tr_cryptoRandInt( 60 );
394    t->key = nextKey++;
395    t->trackers = TR_PTR_ARRAY_INIT;
396    t->currentTracker = NULL;
397    t->currentTrackerIndex = -1;
398    t->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
399    t->announceIntervalSec = DEFAULT_ANNOUNCE_INTERVAL_SEC;
400    t->announceMinIntervalSec = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
401    t->scrapeAt = now + t->randOffset;
402    t->tor = tor;
403
404    return t;
405}
406
407static void
408tierFree( void * vtier )
409{
410    tr_tier * tier = vtier;
411    tr_ptrArrayDestruct( &tier->trackers, trackerFree );
412    tr_free( tier );
413}
414
415static void
416tierIncrementTracker( tr_tier * tier )
417{
418    const int i = ( tier->currentTrackerIndex + 1 )
419                        % tr_ptrArraySize( &tier->trackers );
420    tier->currentTracker = tr_ptrArrayNth( &tier->trackers, i );
421    tier->currentTrackerIndex = i;
422
423    /* reset some of the tier's fields */
424    tier->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
425    tier->announceIntervalSec = DEFAULT_ANNOUNCE_INTERVAL_SEC;
426    tier->announceMinIntervalSec = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
427    tier->retryAnnounceIntervalSec = FIRST_ANNOUNCE_RETRY_INTERVAL_SEC;
428    tier->retryScrapeIntervalSec = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
429    tier->isAnnouncing = FALSE;
430    tier->isScraping = FALSE;
431    tier->lastAnnounceStartTime = 0;
432    tier->lastScrapeStartTime = 0;
433}
434
435static void
436tierAddTracker( tr_announcer * announcer,
437                tr_tier      * tier,
438                const char   * announce,
439                const char   * scrape )
440{
441    tr_tracker_item * tracker = trackerNew( announcer, announce, scrape );
442
443    tr_ptrArrayAppend( &tier->trackers, tracker );
444    dbgmsg( tier, "adding tracker %s", announce );
445
446    if( !tier->currentTracker )
447        tierIncrementTracker( tier );
448}
449
450
451/***
452****
453***/
454
455/*
456 * per-torrent info.
457 * this opaque data structure can be found in tr_torrent.tiers
458 */
459typedef struct tr_torrent_tiers
460{
461    tr_ptrArray tiers;
462    tr_publisher publisher;
463}
464tr_torrent_tiers;
465
466static tr_torrent_tiers*
467tiersNew( void )
468{
469    tr_torrent_tiers * tiers = tr_new0( tr_torrent_tiers, 1 );
470    tiers->tiers = TR_PTR_ARRAY_INIT;
471    tiers->publisher = TR_PUBLISHER_INIT;
472    return tiers;
473}
474
475static void
476tiersFree( tr_torrent_tiers * tiers )
477{
478    tr_publisherDestruct( &tiers->publisher );
479    tr_ptrArrayDestruct( &tiers->tiers, tierFree );
480    tr_free( tiers );
481}
482
483static tr_tier*
484getTier( tr_announcer * announcer, int torrentId, int tierId )
485{
486    tr_tier * tier = NULL;
487
488    if( announcer )
489    {
490        tr_torrent * tor = tr_torrentFindFromId( announcer->session, torrentId );
491
492        if( tor && tor->tiers )
493        {
494            int i;
495            tr_ptrArray * tiers = &tor->tiers->tiers;
496            const int n = tr_ptrArraySize( tiers );
497            for( i=0; !tier && i<n; ++i )
498            {
499                tr_tier * tmp = tr_ptrArrayNth( tiers, i );
500                if( tmp->key == tierId )
501                    tier = tmp;
502            }
503        }
504    }
505
506    return tier;
507}
508
509/***
510****  PUBLISH
511***/
512
513static const tr_tracker_event emptyEvent = { 0, NULL, NULL, 0, 0 };
514
515static void
516publishMessage( tr_tier * tier, const char * msg, int type )
517{
518    if( tier && tier->tor && tier->tor->tiers )
519    {
520        tr_torrent_tiers * tiers = tier->tor->tiers;
521        tr_tracker_event event = emptyEvent;
522        event.messageType = type;
523        event.text = msg;
524        tr_publisherPublish( &tiers->publisher, tier, &event );
525    }
526}
527
528static void
529publishErrorClear( tr_tier * tier )
530{
531    publishMessage( tier, NULL, TR_TRACKER_ERROR_CLEAR );
532}
533
534static void
535publishErrorMessageAndStop( tr_tier * tier, const char * msg )
536{
537    tier->isRunning = FALSE;
538
539    publishMessage( tier, msg, TR_TRACKER_ERROR );
540}
541
542static void
543publishWarning( tr_tier * tier, const char * msg )
544{
545    publishMessage( tier, msg, TR_TRACKER_WARNING );
546}
547
548static int
549publishNewPeers( tr_tier * tier, tr_bool allAreSeeds,
550                 const void * compact, int compactLen )
551{
552    tr_tracker_event e = emptyEvent;
553
554    e.messageType = TR_TRACKER_PEERS;
555    e.allAreSeeds = allAreSeeds;
556    e.compact = compact;
557    e.compactLen = compactLen;
558
559    if( compactLen )
560        tr_publisherPublish( &tier->tor->tiers->publisher, tier, &e );
561
562    return compactLen / 6;
563}
564
565static int
566publishNewPeersCompact( tr_tier * tier, tr_bool allAreSeeds,
567                        const void * compact, int compactLen )
568{
569    int i;
570    const uint8_t *compactWalk;
571    uint8_t *array, *walk;
572    const int peerCount = compactLen / 6;
573    const int arrayLen = peerCount * ( sizeof( tr_address ) + 2 );
574    tr_address addr;
575    tr_port port;
576
577    addr.type = TR_AF_INET;
578    memset( &addr.addr, 0, sizeof( addr.addr ) );
579    array = tr_new( uint8_t, arrayLen );
580    for ( i=0, walk=array, compactWalk=compact ; i<peerCount ; ++i )
581    {
582        memcpy( &addr.addr.addr4, compactWalk, 4 );
583        memcpy( &port, compactWalk + 4, 2 );
584
585        memcpy( walk, &addr, sizeof( addr ) );
586        memcpy( walk + sizeof( addr ), &port, 2 );
587
588        walk += sizeof( tr_address ) + 2;
589        compactWalk += 6;
590    }
591
592    publishNewPeers( tier, allAreSeeds, array, arrayLen );
593
594    tr_free( array );
595
596    return peerCount;
597}
598
599static int
600publishNewPeersCompact6( tr_tier * tier, tr_bool allAreSeeds,
601                         const void * compact, int compactLen )
602{
603    int i;
604    const uint8_t *compactWalk;
605    uint8_t *array, *walk;
606    const int peerCount = compactLen / 18;
607    const int arrayLen = peerCount * ( sizeof( tr_address ) + 2 );
608    tr_address addr;
609    tr_port port;
610
611    addr.type = TR_AF_INET6;
612    memset( &addr.addr, 0, sizeof( addr.addr ) );
613    array = tr_new( uint8_t, arrayLen );
614    for ( i = 0, walk = array, compactWalk = compact ; i < peerCount ; ++i )
615    {
616        memcpy( &addr.addr.addr6, compactWalk, 16 );
617        memcpy( &port, compactWalk + 16, 2 );
618        compactWalk += 18;
619
620        memcpy( walk, &addr, sizeof( addr ) );
621        memcpy( walk + sizeof( addr ), &port, 2 );
622        walk += sizeof( tr_address ) + 2;
623    }
624    publishNewPeers( tier, allAreSeeds, array, arrayLen );
625    tr_free( array );
626
627    return peerCount;
628}
629
630static char*
631createAnnounceURL( const tr_announcer     * announcer,
632                   const tr_torrent       * torrent,
633                   const tr_tier          * tier,
634                   const char             * eventName )
635{
636    const int isStopping = !strcmp( eventName, "stopped" );
637    const int numwant = isStopping ? 0 : NUMWANT;
638    const tr_tracker_item  * tracker = tier->currentTracker;
639    const char * ann = tracker->announce;
640    struct evbuffer * buf = evbuffer_new( );
641    char * ret;
642
643    evbuffer_add_printf( buf, "%s"
644                              "%c"
645                              "info_hash=%s"
646                              "&peer_id=%s"
647                              "&port=%d"
648                              "&uploaded=%" PRIu64
649                              "&downloaded=%" PRIu64
650                              "&left=%" PRIu64
651                              "&numwant=%d"
652                              "&key=%s"
653                              "&compact=1"
654                              "&supportcrypto=1",
655                              ann,
656                              strchr( ann, '?' ) ? '&' : '?',
657                              torrent->info.hashEscaped,
658                              torrent->peer_id,
659                              tr_sessionGetPeerPort( announcer->session ),
660                              torrent->uploadedCur,
661                              torrent->downloadedCur,
662                              tr_cpLeftUntilComplete( &torrent->completion ),
663                              numwant,
664                              tracker->key_param );
665
666    if( torrent->corruptCur )
667        evbuffer_add_printf( buf, "&corrupt=%" PRIu64, torrent->corruptCur );
668
669    if( !isStopping )
670        evbuffer_add_printf( buf, "&upload_only=%d", tr_torrentIsSeed( torrent ) ? 1 : 0 );
671
672    if( announcer->session->encryptionMode == TR_ENCRYPTION_REQUIRED )
673        evbuffer_add_printf( buf, "&requirecrypto=1" );
674
675    if( eventName && *eventName )
676        evbuffer_add_printf( buf, "&event=%s", eventName );
677
678    if( tracker->tracker_id && *tracker->tracker_id )
679        evbuffer_add_printf( buf, "&trackerid=%s", tracker->tracker_id );
680
681    ret = tr_strndup( EVBUFFER_DATA( buf ), EVBUFFER_LENGTH( buf ) );
682    evbuffer_free( buf );
683
684    dbgmsg( tier, "announce URL is \"%s\"", ret );
685    return ret;
686}
687
688
689/***
690****
691***/
692
693tr_torrent_tiers *
694tr_announcerAddTorrent( tr_announcer * announcer, tr_torrent * tor )
695{
696    tr_torrent_tiers * tiers;
697
698    assert( announcer != NULL );
699    assert( tr_isTorrent( tor ) );
700
701    tiers = tiersNew( );
702
703    /* build our private table of tiers... */
704    if( tor->info.trackerCount )
705    {
706        int i;
707        int tierIndex = -1;
708        tr_tier * tier = NULL;
709
710        for( i=0; i<tor->info.trackerCount; ++i )
711        {
712            if( tor->info.trackers[i].tier != tierIndex )
713                tier = NULL;
714
715            tierIndex = tor->info.trackers[i].tier;
716
717            if( tier == NULL ) {
718                tier = tierNew( tor );
719                dbgmsg( tier, "adding tier" );
720                tr_ptrArrayAppend( &tiers->tiers, tier );
721            }
722
723            tierAddTracker( announcer, tier, tor->info.trackers[i].announce,
724                                             tor->info.trackers[i].scrape );
725        }
726    }
727
728    return tiers;
729}
730
731tr_publisher_tag
732tr_announcerSubscribe( struct tr_torrent_tiers   * tiers,
733                       tr_delivery_func            func,
734                       void                      * userData )
735{
736    return tr_publisherSubscribe( &tiers->publisher, func, userData );
737}
738
739void
740tr_announcerUnsubscribe( struct tr_torrent_tiers  * tiers,
741                         tr_publisher_tag           tag )
742{
743    if( tiers )
744        tr_publisherUnsubscribe( &tiers->publisher, tag );
745}
746
747static tr_bool
748tierCanManualAnnounce( const tr_tier * tier )
749{
750    return tier->isRunning
751        && tier->manualAnnounceAllowedAt <= time( NULL );
752}
753
754tr_bool
755tr_announcerCanManualAnnounce( const tr_torrent * tor )
756{
757    int i;
758    int n;
759    const tr_tier ** tiers;
760
761    assert( tr_isTorrent( tor ) );
762    assert( tor->tiers != NULL );
763
764    n = tr_ptrArraySize( &tor->tiers->tiers );
765    tiers = (const tr_tier**) tr_ptrArrayBase( &tor->tiers->tiers );
766    for( i=0; i<n; ++i )
767        if( tierCanManualAnnounce( tiers[i] ) )
768            return TRUE;
769
770    return FALSE;
771}
772
773time_t
774tr_announcerNextManualAnnounce( const tr_torrent * tor )
775{
776    int i;
777    int n;
778    const tr_torrent_tiers * tiers;
779    time_t ret = ~(time_t)0;
780
781    assert( tr_isTorrent( tor  ) );
782
783    tiers = tor->tiers;
784    n = tr_ptrArraySize( &tiers->tiers );
785    for( i=0; i<n; ++i ) {
786        tr_tier * tier = tr_ptrArrayNth( (tr_ptrArray*)&tiers->tiers, i );
787        if( tier->isRunning )
788            ret = MIN( ret, tier->manualAnnounceAllowedAt );
789    }
790
791    return ret;
792}
793
794static void
795tierClearNextAnnounce( tr_tier * tier )
796{
797    tier->announceAt = 0;
798    tier->announceEvent = NULL;
799    dbgmsg( tier, "cleared out announceEvent -- no announces pending." );
800}
801
802static void
803tierSetNextAnnounce( tr_tier * tier, const char * announceEvent, time_t announceAt )
804{
805    assert( tier != NULL );
806    assert( announceEvent != NULL );
807
808    if( !strcmp( announceEvent, "manual" ) && !tierCanManualAnnounce( tier ) )
809        return;
810
811    tier->announceAt = announceAt;
812    tier->announceEvent = announceEvent;
813    dbgmsg( tier, "next announce event is \"%s\" in %d seconds\n", announceEvent, (int)difftime(announceAt,time(NULL)) );
814}
815
816static void
817torrentSetNextAnnounce( tr_torrent * tor, const char * announceEvent, time_t announceAt )
818{
819    int i;
820    int n;
821    tr_torrent_tiers * tiers;
822
823    assert( tr_isTorrent( tor ) );
824
825    tiers = tor->tiers;
826    n = tr_ptrArraySize( &tiers->tiers );
827    for( i=0; i<n; ++i )
828        tierSetNextAnnounce( tr_ptrArrayNth( &tiers->tiers, i ), announceEvent, announceAt );
829}
830
831void
832tr_announcerManualAnnounce( tr_torrent * tor )
833{
834    torrentSetNextAnnounce( tor, "manual", time( NULL ) );
835}
836void
837tr_announcerTorrentStarted( tr_torrent * tor )
838{
839    torrentSetNextAnnounce( tor, "started", time( NULL ) );
840}
841void
842tr_announcerTorrentStopped( tr_torrent * tor )
843{
844    torrentSetNextAnnounce( tor, "stopped", time( NULL ) );
845}
846void
847tr_announcerTorrentCompleted( tr_torrent * tor )
848{
849    torrentSetNextAnnounce( tor, "completed", time( NULL ) );
850}
851void
852tr_announcerChangeMyPort( tr_torrent * tor )
853{
854    tr_announcerTorrentStarted( tor );
855}
856
857
858void
859tr_announcerRemoveTorrent( tr_announcer * announcer, tr_torrent * tor )
860{
861    assert( tr_isTorrent( tor ) );
862
863    if( tor->tiers )
864    {
865        int i;
866        const int n = tr_ptrArraySize( &tor->tiers->tiers );
867        for( i=0; i<n; ++i )
868        {
869            tr_tier * tier = tr_ptrArrayNth( &tor->tiers->tiers, i );
870
871            if( tier->isRunning )
872            {
873                struct stop_message * s = tr_new0( struct stop_message, 1 );
874                s->up = tor->uploadedCur;
875                s->down = tor->downloadedCur;
876                s->url = createAnnounceURL( announcer, tor, tier, "stopped" );
877                s->host = tier->currentTracker->host;
878                tr_ptrArrayInsertSorted( &announcer->stops, s, compareStops );
879            }
880        }
881
882        tiersFree( tor->tiers );
883        tor->tiers = NULL;
884    }
885}
886
887/* return true if (1) we've tried it recently AND (2) it didn't respond... */
888static tr_bool
889hostIsNotResponding( const tr_host * host, const time_t now )
890{
891    tr_bool b = ( host->lastRequestTime )
892             && ( host->lastRequestTime >= ( now - SLOW_HOST_PENALTY_SECS ) )
893             && ( host->lastResponseInterval > MAX_TRACKER_RESPONSE_TIME_SECS );
894    return b;
895}
896
897static tr_bool
898tierIsNotResponding( const tr_tier * tier, const time_t now )
899{
900    return !tier->currentTracker
901        || hostIsNotResponding( tier->currentTracker->host, now );
902}
903
904static int
905compareTiers( const void * va, const void * vb )
906{
907    int ret = 0;
908    tr_bool af, bf;
909    const tr_tier * a = *(const tr_tier**)va;
910    const tr_tier * b = *(const tr_tier**)vb;
911
912    /* working domains come before non-working */
913    if( !ret ) {
914        const time_t now = time( NULL );
915        af = tierIsNotResponding( a, now );
916        bf = tierIsNotResponding( b, now );
917        if( af != bf )
918            ret = !af ? -1 : 1;
919    }
920
921    /* stops come before starts */
922    if( !ret ) {
923        af = a->tor->isRunning;
924        bf = b->tor->isRunning;
925        if( af != bf )
926            ret = af ? 1 : -1;
927    }
928
929    /* upload comes before download */
930    if( !ret )
931        ret = compareTransfer( a->tor->uploadedCur, a->tor->downloadedCur,
932                               b->tor->uploadedCur, b->tor->downloadedCur );
933
934    /* incomplete comes before complete */
935    if( !ret ) {
936        af = a->tor->completeness == TR_LEECH;
937        bf = b->tor->completeness == TR_LEECH;
938        if( af != bf )
939            return af ? -1 : 1;
940    }
941
942    /* private before public */
943    if( !ret ) {
944        af = tr_torrentIsPrivate( a->tor );
945        bf = tr_torrentIsPrivate( b->tor );
946        if( af != bf )
947            ret = af ? -1 : 1;
948    }
949
950    return ret;
951}
952
953static uint8_t *
954parseOldPeers( tr_benc * bePeers, size_t *  byteCount )
955{
956    int       i;
957    uint8_t * array, *walk;
958    const int peerCount = bePeers->val.l.count;
959
960    assert( tr_bencIsList( bePeers ) );
961
962    array = tr_new( uint8_t, peerCount * ( sizeof( tr_address ) + 2 ) );
963
964    for( i = 0, walk = array; i < peerCount; ++i )
965    {
966        const char * s;
967        int64_t      itmp;
968        tr_address   addr;
969        tr_port      port;
970        tr_benc    * peer = &bePeers->val.l.vals[i];
971
972        if( tr_bencDictFindStr( peer, "ip", &s ) )
973            if( tr_pton( s, &addr ) == NULL )
974                continue;
975
976        if( !tr_bencDictFindInt( peer, "port", &itmp )
977                || itmp < 0
978                || itmp > USHRT_MAX )
979            continue;
980
981        memcpy( walk, &addr, sizeof( tr_address ) );
982        port = htons( itmp );
983        memcpy( walk + sizeof( tr_address ), &port, 2 );
984        walk += sizeof( tr_address ) + 2;
985    }
986
987    *byteCount = peerCount * sizeof( tr_address ) + 2;
988    return array;
989}
990
991static tr_bool
992parseAnnounceResponse( tr_tier     * tier,
993                       const char  * response,
994                       size_t        responseLen,
995                       tr_bool     * gotScrape )
996{
997    tr_benc benc;
998    tr_bool success = FALSE;
999    int scrapeFields = 0;
1000    const int bencLoaded = !tr_bencLoad( response, responseLen, &benc, NULL );
1001
1002    dbgmsg( tier, "response len: %d, isBenc: %d", (int)responseLen, (int)bencLoaded );
1003    publishErrorClear( tier );
1004    if( bencLoaded && tr_bencIsDict( &benc ) )
1005    {
1006        int incomplete = -1;
1007        size_t rawlen;
1008        int64_t i;
1009        tr_benc * tmp;
1010        const char * str;
1011        const uint8_t * raw;
1012
1013        success = TRUE;
1014
1015        tier->retryAnnounceIntervalSec = FIRST_ANNOUNCE_RETRY_INTERVAL_SEC;
1016
1017        if( tr_bencDictFindStr( &benc, "failure reason", &str ) )
1018        {
1019            tr_strlcpy( tier->lastAnnounceStr, str,
1020                        sizeof( tier->lastAnnounceStr ) );
1021            dbgmsg( tier, "tracker gave \"%s\"", str );
1022            publishMessage( tier, str, TR_TRACKER_ERROR );
1023            success = FALSE;
1024        }
1025
1026        if( tr_bencDictFindStr( &benc, "warning message", &str ) )
1027        {
1028            tr_strlcpy( tier->lastAnnounceStr, str,
1029                        sizeof( tier->lastAnnounceStr ) );
1030            dbgmsg( tier, "tracker gave \"%s\"", str );
1031            publishWarning( tier, str );
1032        }
1033
1034        if( tr_bencDictFindInt( &benc, "interval", &i ) )
1035        {
1036            dbgmsg( tier, "setting interval to %d", (int)i );
1037            tier->announceIntervalSec = i;
1038        }
1039
1040        if( tr_bencDictFindInt( &benc, "min interval", &i ) )
1041        {
1042            dbgmsg( tier, "setting min interval to %d", (int)i );
1043            tier->announceMinIntervalSec = i;
1044        }
1045
1046        if( tr_bencDictFindStr( &benc, "tracker id", &str ) )
1047        {
1048            tier->currentTracker->tracker_id = tr_strdup( str );
1049        }
1050
1051        if( tr_bencDictFindInt( &benc, "complete", &i ) )
1052        {
1053            ++scrapeFields;
1054            tier->currentTracker->seederCount = i;
1055        }
1056
1057        if( tr_bencDictFindInt( &benc, "incomplete", &i ) )
1058        {
1059            ++scrapeFields;
1060            tier->currentTracker->leecherCount = incomplete = i;
1061        }
1062
1063        if( tr_bencDictFindInt( &benc, "downloaded", &i ) )
1064        {
1065            ++scrapeFields;
1066            tier->currentTracker->downloadCount = i;
1067        }
1068
1069        if( tr_bencDictFindRaw( &benc, "peers", &raw, &rawlen ) )
1070        {
1071            /* "compact" extension */
1072            const int allAreSeeds = incomplete == 0;
1073            tier->lastAnnouncePeerCount = publishNewPeersCompact( tier, allAreSeeds, raw, rawlen );
1074        }
1075        else if( tr_bencDictFindList( &benc, "peers", &tmp ) )
1076        {
1077            /* original version of peers */
1078            const tr_bool allAreSeeds = incomplete == 0;
1079            size_t byteCount = 0;
1080            uint8_t * array = parseOldPeers( tmp, &byteCount );
1081            tier->lastAnnouncePeerCount = publishNewPeers( tier, allAreSeeds, array, byteCount );
1082            tr_free( array );
1083        }
1084
1085        if( tr_bencDictFindRaw( &benc, "peers6", &raw, &rawlen ) )
1086        {
1087            /* "compact" extension */
1088            const tr_bool allAreSeeds = incomplete == 0;
1089            tier->lastAnnouncePeerCount += publishNewPeersCompact6( tier, allAreSeeds, raw, rawlen );
1090        }
1091
1092        if( tier->lastAnnounceStr[0] == '\0' )
1093            tr_strlcpy( tier->lastAnnounceStr, _( "Success" ),
1094                        sizeof( tier->lastAnnounceStr ) );
1095    }
1096
1097    if( bencLoaded )
1098        tr_bencFree( &benc );
1099
1100fprintf( stderr, "scrapeField count is %d\n", scrapeFields );
1101    *gotScrape = scrapeFields >= 2;
1102
1103    return success;
1104}
1105
1106struct announce_data
1107{
1108    int torrentId;
1109    int tierId;
1110    time_t timeSent;
1111
1112    /** If the request succeeds, the value for tier's "isRunning" flag */
1113    tr_bool isRunningOnSuccess;
1114};
1115
1116static void
1117onAnnounceDone( tr_session   * session,
1118                long           responseCode,
1119                const void   * response,
1120                size_t         responseLen,
1121                void         * vdata )
1122{
1123    tr_announcer * announcer = session->announcer;
1124    struct announce_data * data = vdata;
1125    tr_tier * tier = getTier( announcer, data->torrentId, data->tierId );
1126    tr_bool gotScrape = FALSE;
1127    tr_bool success = FALSE;
1128    const time_t now = time ( NULL );
1129
1130    if( announcer && tier )
1131    {
1132        tier->lastAnnouncePeerCount = 0;
1133
1134        if( tier->currentTracker->host )
1135        {
1136            tr_host * host = tier->currentTracker->host;
1137            host->lastRequestTime = data->timeSent;
1138            host->lastResponseInterval = now - data->timeSent;
1139        }
1140
1141        if( responseCode == HTTP_OK )
1142        {
1143            tier->lastAnnounceTime = now;
1144            success = parseAnnounceResponse( tier, response, responseLen, &gotScrape );
1145            dbgmsg( tier, "success is %d", success );
1146        }
1147        else if( responseCode )
1148        {
1149            /* %1$ld - http status code, such as 404
1150             * %2$s - human-readable explanation of the http status code */
1151            char * buf = tr_strdup_printf(
1152                _( "Announce failed: tracker gave HTTP Response Code %1$ld (%2$s)" ),
1153                responseCode,
1154                tr_webGetResponseStr( responseCode ) );
1155
1156            tr_strlcpy( tier->lastAnnounceStr, buf,
1157                        sizeof( tier->lastAnnounceStr ) );
1158
1159            /* if the repsonse may require intervention, notify the user;
1160             * otherwise, just log it */
1161            if( responseCode >= 400 )
1162                publishWarning( tier, buf );
1163            tr_torinf( tier->tor, "%s", buf );
1164            dbgmsg( tier, "%s", buf );
1165
1166            tr_free( buf );
1167        }
1168        else
1169        {
1170            tr_strlcpy( tier->lastAnnounceStr,
1171                        _( "tracker did not respond" ),
1172                        sizeof( tier->lastAnnounceStr ) );
1173            dbgmsg( tier, "%s", tier->lastAnnounceStr );
1174        }
1175    }
1176
1177    if( tier )
1178    {
1179        tier->isAnnouncing = FALSE;
1180
1181        if( responseCode == 0 )
1182        {
1183            dbgmsg( tier, "No response from tracker... retrying in two minutes." );
1184            tier->manualAnnounceAllowedAt = ~(time_t)0;
1185            tierSetNextAnnounce( tier, tier->announceEvent, now + tier->randOffset + 120 );
1186        }
1187        else if( 200 <= responseCode && responseCode <= 299 )
1188        {
1189            const int interval = tier->announceIntervalSec + tier->randOffset;
1190            dbgmsg( tier, "request succeeded. reannouncing in %d seconds", interval );
1191
1192            if( gotScrape )
1193            {
1194                tier->lastScrapeTime = now;
1195                tier->scrapeAt = now + tier->scrapeIntervalSec + tier->randOffset;
1196            }
1197
1198            tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1199
1200            if( strcmp( tier->announceEvent, "stopped" ) == 0 )
1201                tierClearNextAnnounce( tier );
1202            else
1203                tierSetNextAnnounce( tier, "", now + interval );
1204        }
1205        else if( 300 <= responseCode && responseCode <= 399 )
1206        {
1207            /* how did this get here?  libcurl handles this */
1208            const int interval = 5;
1209            dbgmsg( tier, "got a redirect. retrying in %d seconds", interval );
1210            tierSetNextAnnounce( tier, tier->announceEvent, now + interval );
1211            tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1212        }
1213        else if( 400 <= responseCode && responseCode <= 499 )
1214        {
1215            /* The request could not be understood by the server due to
1216             * malformed syntax. The client SHOULD NOT repeat the
1217             * request without modifications. */
1218            publishErrorMessageAndStop( tier, _( "Tracker returned a 4xx message" ) );
1219            tier->manualAnnounceAllowedAt = ~(time_t)0;
1220        }
1221        else if( 500 <= responseCode && responseCode <= 599 )
1222        {
1223            /* Response status codes beginning with the digit "5" indicate
1224             * cases in which the server is aware that it has erred or is
1225             * incapable of performing the request.  So we pause a bit and
1226             * try again. */
1227            tier->manualAnnounceAllowedAt = ~(time_t)0;
1228            tierSetNextAnnounce( tier, tier->announceEvent, now + tier->retryAnnounceIntervalSec );
1229            tier->retryAnnounceIntervalSec *= 2;
1230        }
1231        else
1232        {
1233            /* WTF did we get?? */
1234            const int interval = tier->randOffset + 120;
1235            dbgmsg( tier, "Invalid response from tracker... retrying in two minutes." );
1236            tier->manualAnnounceAllowedAt = ~(time_t)0;
1237            tierSetNextAnnounce( tier, tier->announceEvent, now + interval );
1238        }
1239
1240        tier->lastAnnounceSucceeded = success;
1241
1242        if( success )
1243            tier->isRunning = data->isRunningOnSuccess;
1244
1245        if( !success )
1246            tierIncrementTracker( tier );
1247    }
1248
1249    ++announcer->announceSlotsAvailable;
1250
1251    tr_free( data );
1252}
1253
1254static const char *
1255getAnnounceEvent( const tr_tier * tier )
1256{
1257    const char * event;
1258
1259    assert( tier != NULL );
1260    assert( tier->announceEvent != NULL );
1261    assert( tr_isTorrent( tier->tor ) );
1262
1263    /* BEP 21: "In order to tell the tracker that a peer is a partial seed,
1264     * it MUST send an event=paused parameter in every announce while
1265     * it is a partial seed." */
1266    if( tr_cpGetStatus( &tier->tor->completion ) == TR_PARTIAL_SEED )
1267        return "paused";
1268
1269    event = tier->announceEvent;
1270
1271    if( !strcmp( event, "manual" ) )
1272        return "started";
1273
1274    return event;
1275}
1276
1277static void
1278tierAnnounce( tr_announcer * announcer, tr_tier * tier )
1279{
1280    char * url;
1281    struct announce_data * data;
1282    const tr_torrent * tor = tier->tor;
1283    const time_t now = time( NULL );
1284
1285    assert( !tier->isAnnouncing );
1286
1287    data = tr_new0( struct announce_data, 1 );
1288    data->torrentId = tr_torrentId( tor );
1289    data->tierId = tier->key;
1290    data->isRunningOnSuccess = tor->isRunning;
1291    data->timeSent = now;
1292
1293    url = createAnnounceURL( announcer, tor, tier, getAnnounceEvent( tier ) );
1294
1295    tier->isAnnouncing = TRUE;
1296    tier->lastAnnounceStartTime = now;
1297    --announcer->announceSlotsAvailable;
1298    tr_webRun( announcer->session, url, NULL, onAnnounceDone, data );
1299
1300    tr_free( url );
1301}
1302
1303static tr_bool
1304parseScrapeResponse( tr_tier     * tier,
1305                     const char  * response,
1306                     size_t        responseLen )
1307{
1308    tr_bool success = FALSE;
1309    tr_benc benc, *files;
1310    const int bencLoaded = !tr_bencLoad( response, responseLen, &benc, NULL );
1311    if( bencLoaded && tr_bencDictFindDict( &benc, "files", &files ) )
1312    {
1313        const char * key;
1314        tr_benc * val;
1315        int i = 0;
1316        while( tr_bencDictChild( files, i++, &key, &val ))
1317        {
1318            int64_t intVal;
1319            tr_benc * flags;
1320
1321            if( memcmp( tier->tor->info.hash, key, SHA_DIGEST_LENGTH ) )
1322                continue;
1323
1324            success = TRUE;
1325            publishErrorClear( tier );
1326
1327            if( ( tr_bencDictFindInt( val, "complete", &intVal ) ) )
1328                tier->currentTracker->seederCount = intVal;
1329
1330            if( ( tr_bencDictFindInt( val, "incomplete", &intVal ) ) )
1331                tier->currentTracker->leecherCount = intVal;
1332
1333            if( ( tr_bencDictFindInt( val, "downloaded", &intVal ) ) )
1334                tier->currentTracker->downloadCount = intVal;
1335
1336            if( ( tr_bencDictFindInt( val, "downloaders", &intVal ) ) )
1337                tier->currentTracker->downloaderCount = intVal;
1338
1339            if( tr_bencDictFindDict( val, "flags", &flags ) )
1340                if( ( tr_bencDictFindInt( flags, "min_request_interval", &intVal ) ) )
1341                    tier->scrapeIntervalSec = intVal;
1342
1343            /* as per ticket #1045, safeguard against trackers returning
1344             * a very low min_request_interval... */
1345            if( tier->scrapeIntervalSec < DEFAULT_SCRAPE_INTERVAL_SEC )
1346                tier->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
1347
1348            tr_tordbg( tier->tor,
1349                       "Scrape successful. Rescraping in %d seconds.",
1350                       tier->scrapeIntervalSec );
1351
1352            tier->retryScrapeIntervalSec = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
1353        }
1354    }
1355
1356    if( bencLoaded )
1357        tr_bencFree( &benc );
1358
1359    return success;
1360}
1361
1362static void
1363onScrapeDone( tr_session   * session,
1364              long           responseCode,
1365              const void   * response,
1366              size_t         responseLen,
1367              void         * vdata )
1368{
1369    tr_announcer * announcer = session->announcer;
1370    struct announce_data * data = vdata;
1371    tr_tier * tier = getTier( announcer, data->torrentId, data->tierId );
1372    const time_t now = time( NULL );
1373    tr_bool success = FALSE;
1374
1375    if( announcer )
1376        ++announcer->scrapeSlotsAvailable;
1377
1378    if( announcer && tier )
1379    {
1380        tier->isScraping = FALSE;
1381        tier->lastScrapeTime = now;
1382   
1383        if( tier->currentTracker->host )
1384        {
1385            tr_host * host = tier->currentTracker->host;
1386            host->lastRequestTime = data->timeSent;
1387            host->lastResponseInterval = now - data->timeSent;
1388        }
1389
1390        if( responseCode == HTTP_OK )
1391        {
1392            success = parseScrapeResponse( tier, response, responseLen );
1393        }
1394
1395        if( 200 <= responseCode && responseCode <= 299 )
1396        {
1397            const int interval = tier->scrapeIntervalSec + tier->randOffset;
1398            tier->scrapeAt = now + interval;
1399
1400            tr_strlcpy( tier->lastScrapeStr, _( "Success" ), sizeof( tier->lastScrapeStr ) );
1401            tr_tordbg( tier->tor, "Request succeeded. Rescraping in %d seconds", interval );
1402        }
1403        else if( 300 <= responseCode && responseCode <= 399 )
1404        {
1405            /* this shouldn't happen; libcurl should handle this */
1406            const int interval = 5;
1407            tier->scrapeAt = now + interval;
1408            tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1409                         "Got a redirect. Retrying in %d seconds", interval );
1410            tr_tordbg( tier->tor, "%s", tier->lastScrapeStr );
1411        }
1412        else
1413        {
1414            const int interval = tier->retryScrapeIntervalSec + tier->randOffset;
1415            tier->retryScrapeIntervalSec *= 2;
1416            tier->scrapeAt = now + interval;
1417
1418            /* %1$ld - http status code, such as 404
1419             * %2$s - human-readable explanation of the http status code */
1420            if( !responseCode )
1421                tr_strlcpy( tier->lastScrapeStr, _( "tracker did not respond" ),
1422                            sizeof( tier->lastScrapeStr ) );
1423            else
1424                tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1425                             _( "tracker gave HTTP Response Code %1$ld (%2$s)" ),
1426                             responseCode, tr_webGetResponseStr( responseCode ) );
1427        }
1428
1429        tier->lastScrapeSucceeded = success;
1430    }
1431
1432    tr_free( data );
1433}
1434
1435static void
1436tierScrape( tr_announcer * announcer, tr_tier * tier )
1437{
1438    const char * scrape;
1439    struct evbuffer * buf;
1440    struct announce_data * data;
1441    const time_t now = time( NULL );
1442
1443    assert( tier );
1444    assert( !tier->isScraping );
1445    assert( tier->currentTracker != NULL );
1446    assert( tr_isTorrent( tier->tor ) );
1447
1448    data = tr_new0( struct announce_data, 1 );
1449    data->torrentId = tr_torrentId( tier->tor );
1450    data->tierId = tier->key;
1451
1452    scrape = tier->currentTracker->scrape;
1453
1454    buf = evbuffer_new( );
1455    evbuffer_add_printf( buf, "%s%cinfo_hash=%s",
1456                         scrape,
1457                         strchr( scrape, '?' ) ? '&' : '?',
1458                         tier->tor->info.hashEscaped );
1459
1460    tier->isScraping = TRUE;
1461    tier->lastScrapeStartTime = now;
1462    --announcer->scrapeSlotsAvailable;
1463    dbgmsg( tier, "scraping \"%s\"", (const char*)EVBUFFER_DATA(buf) );
1464    tr_webRun( announcer->session, (const char*)EVBUFFER_DATA(buf), NULL, onScrapeDone, data );
1465
1466    evbuffer_free( buf );
1467}
1468
1469static void
1470flushCloseMessages( tr_announcer * announcer )
1471{
1472    int i;
1473    const int n = tr_ptrArraySize( &announcer->stops );
1474
1475    for( i=0; i<n; ++i )
1476    {
1477        struct stop_message * stop = tr_ptrArrayNth( &announcer->stops, i );
1478        fprintf( stderr, "sending close message: [%s]\n", stop->url );
1479        tr_webRun( announcer->session, stop->url, NULL, NULL, NULL );
1480        stopFree( stop );
1481    }
1482
1483    tr_ptrArrayClear( &announcer->stops );
1484}
1485
1486static tr_bool
1487tierNeedsToAnnounce( const tr_tier * tier, const time_t now )
1488{
1489    return !tier->isAnnouncing
1490        && !tier->isScraping
1491        && ( tier->announceEvent != NULL )
1492        && ( tier->announceAt <= now );
1493}
1494
1495static tr_bool
1496tierNeedsToScrape( const tr_tier * tier, const time_t now )
1497{
1498    return !tier->isScraping && tier->scrapeAt <= now;
1499}
1500
1501static void
1502announceMore( tr_announcer * announcer )
1503{
1504    const tr_bool canAnnounce = announcer->announceSlotsAvailable > 0;
1505    const tr_bool canScrape = announcer->scrapeSlotsAvailable > 0;
1506
1507    if( announcer->announceSlotsAvailable > 0 )
1508    {
1509        int i;
1510        int n;
1511        const time_t now = time( NULL );
1512        tr_torrent * tor = NULL;
1513        tr_ptrArray announceMe = TR_PTR_ARRAY_INIT;
1514        tr_ptrArray scrapeMe = TR_PTR_ARRAY_INIT;
1515
1516        /* build a list of tiers that need to be announced */
1517        while(( tor = tr_torrentNext( announcer->session, tor ))) {
1518            if( tor->tiers ) {
1519                n = tr_ptrArraySize( &tor->tiers->tiers );
1520                for( i=0; i<n; ++i ) {
1521                    tr_tier * tier = tr_ptrArrayNth( &tor->tiers->tiers, i );
1522                    if( canAnnounce && tierNeedsToAnnounce( tier, now ) )
1523                        tr_ptrArrayAppend( &announceMe, tier );
1524                    else if( canScrape && tierNeedsToScrape( tier, now ) )
1525                        tr_ptrArrayAppend( &scrapeMe, tier );
1526                }
1527            }
1528        }
1529
1530        /* if there are more tiers than slots available, prioritize */
1531        n = tr_ptrArraySize( &announceMe );
1532        if( n > announcer->announceSlotsAvailable )
1533            qsort( tr_ptrArrayBase( &announceMe ), n, sizeof( tr_tier * ), compareTiers );
1534
1535        /* announce some */
1536        n = MIN( tr_ptrArraySize( &announceMe ), announcer->announceSlotsAvailable );
1537        for( i=0; i<n; ++i ) {
1538            tr_tier * tier = tr_ptrArrayNth( &announceMe, i );
1539            dbgmsg( tier, "announcing tier %d of %d", i, n );
1540            tierAnnounce( announcer, tier );
1541        }
1542
1543
1544        /* scrape some */
1545        n = MIN( tr_ptrArraySize( &scrapeMe ), announcer->scrapeSlotsAvailable );
1546        for( i=0; i<n; ++i ) {
1547            tr_tier * tier = tr_ptrArrayNth( &scrapeMe, i );
1548            dbgmsg( tier, "scraping tier %d of %d", (i+1), n );
1549            tierScrape( announcer, tier );
1550        }
1551
1552        /* cleanup */
1553        tr_ptrArrayDestruct( &scrapeMe, NULL );
1554        tr_ptrArrayDestruct( &announceMe, NULL );
1555    }
1556}
1557
1558static void
1559onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer )
1560{
1561    tr_announcer * announcer = vannouncer;
1562
1563    /* maybe send out some "stopped" messages for closed torrents */
1564    flushCloseMessages( announcer );
1565
1566    /* maybe send out some announcements to trackers */
1567    announceMore( announcer );
1568
1569    /* set up the next timer */
1570    tr_timerAdd( announcer->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
1571}
1572
1573/***
1574****
1575***/
1576
1577void
1578tr_announcerGetCounts( tr_torrent * torrent,
1579                       int * setme_completedCount,
1580                       int * setme_leecherCount,
1581                       int * setme_seederCount,
1582                       int * setme_downloaderCount )
1583{
1584    int i;
1585    int n;
1586    int completed = 0;
1587    int leechers = 0;
1588    int seeders = 0;
1589    int downloaders = 0;
1590
1591    /* count the trackers... */
1592    for( i=0, n=tr_ptrArraySize( &torrent->tiers->tiers ); i<n; ++i )
1593    {
1594        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1595
1596        if( tier->currentTracker )
1597        {
1598            seeders += tier->currentTracker->seederCount;
1599            leechers += tier->currentTracker->leecherCount;
1600            completed += tier->currentTracker->downloadCount;
1601            downloaders += tier->currentTracker->downloaderCount;
1602        }
1603    }
1604
1605    if( setme_completedCount )  *setme_completedCount = completed;
1606    if( setme_leecherCount )    *setme_leecherCount = leechers;
1607    if( setme_seederCount )     *setme_seederCount = seeders;
1608    if( setme_downloaderCount ) *setme_downloaderCount = downloaders;
1609}
1610
1611tr_tracker_stat *
1612tr_announcerStats( const tr_torrent * torrent,
1613                   int              * setmeTrackerCount )
1614{
1615    int i;
1616    int n;
1617    int out = 0;
1618    int tierCount;
1619    tr_tracker_stat * ret;
1620
1621    assert( tr_isTorrent( torrent ) );
1622
1623    /* count the trackers... */
1624    for( i=n=0, tierCount=tr_ptrArraySize( &torrent->tiers->tiers ); i<tierCount; ++i ) {
1625        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1626        n += tr_ptrArraySize( &tier->trackers );
1627    }
1628
1629    /* alloc the stats */
1630    *setmeTrackerCount = n;
1631    ret = tr_new0( tr_tracker_stat, n );
1632
1633    /* populate the stats */
1634    for( i=0, tierCount=tr_ptrArraySize( &torrent->tiers->tiers ); i<tierCount; ++i )
1635    {
1636        int j;
1637        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1638        n = tr_ptrArraySize( &tier->trackers );
1639        for( j=0; j<n; ++j )
1640        {
1641            const tr_tracker_item * tracker = tr_ptrArrayNth( (tr_ptrArray*)&tier->trackers, j );
1642            tr_tracker_stat * st = ret + out++;
1643
1644            tr_strlcpy( st->host, tracker->host->name, sizeof( st->host ) );
1645            tr_strlcpy( st->announce, tracker->announce, sizeof( st->announce ) );
1646            st->tier = i + 1;
1647            st->isActive = tracker == tier->currentTracker;
1648            st->lastScrapeStartTime = tier->lastScrapeStartTime;
1649            if(( st->hasScraped = tier->lastScrapeTime != 0 )) {
1650                st->lastScrapeTime = tier->lastScrapeTime;
1651                st->lastScrapeSucceeded = tier->lastScrapeSucceeded;
1652                tr_strlcpy( st->lastScrapeResult, tier->lastScrapeStr, sizeof( st->lastScrapeResult ) );
1653            }
1654            st->isScraping = tier->isScraping;
1655            if(( st->willScrape = st->isActive && !tier->isScraping )) {
1656                st->nextScrapeTime = tier->scrapeAt;
1657            }
1658            st->lastAnnounceStartTime = tier->lastAnnounceStartTime;
1659            if(( st->hasAnnounced = tier->lastAnnounceTime != 0 )) {
1660                st->lastAnnounceTime = tier->lastAnnounceTime;
1661                tr_strlcpy( st->lastAnnounceResult, tier->lastAnnounceStr, sizeof( st->lastAnnounceResult ) );
1662                if(( st->lastAnnounceSucceeded = tier->lastAnnounceSucceeded )) {
1663                    st->lastAnnouncePeerCount = tier->lastAnnouncePeerCount;
1664                }
1665            }
1666            st->isAnnouncing = tier->isAnnouncing;
1667            if(( st->willAnnounce = torrent->isRunning && !tier->isAnnouncing )) {
1668                st->nextAnnounceTime = tier->announceAt;
1669            }
1670            st->seederCount = tracker->seederCount;
1671            st->leecherCount = tracker->leecherCount;
1672            st->downloadCount = tracker->downloadCount;
1673        }
1674    }
1675
1676    return ret;
1677}
1678
1679void
1680tr_announcerStatsFree( tr_tracker_stat * trackers,
1681                       int trackerCount UNUSED )
1682{
1683    tr_free( trackers );
1684}
Note: See TracBrowser for help on using the repository browser.