source: trunk/libtransmission/announcer.c @ 9190

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

(trunk libT) possibly fix a crash-on-shutdown reported by John_

File size: 46.5 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
1100    *gotScrape = scrapeFields >= 2;
1101
1102    return success;
1103}
1104
1105struct announce_data
1106{
1107    int torrentId;
1108    int tierId;
1109    time_t timeSent;
1110
1111    /** If the request succeeds, the value for tier's "isRunning" flag */
1112    tr_bool isRunningOnSuccess;
1113};
1114
1115static void
1116onAnnounceDone( tr_session   * session,
1117                long           responseCode,
1118                const void   * response,
1119                size_t         responseLen,
1120                void         * vdata )
1121{
1122    tr_announcer * announcer = session->announcer;
1123    struct announce_data * data = vdata;
1124    tr_tier * tier = getTier( announcer, data->torrentId, data->tierId );
1125    tr_bool gotScrape = FALSE;
1126    tr_bool success = FALSE;
1127    const time_t now = time ( NULL );
1128
1129    if( announcer && tier )
1130    {
1131        tier->lastAnnouncePeerCount = 0;
1132
1133        if( tier->currentTracker->host )
1134        {
1135            tr_host * host = tier->currentTracker->host;
1136            host->lastRequestTime = data->timeSent;
1137            host->lastResponseInterval = now - data->timeSent;
1138        }
1139
1140        if( responseCode == HTTP_OK )
1141        {
1142            tier->lastAnnounceTime = now;
1143            success = parseAnnounceResponse( tier, response, responseLen, &gotScrape );
1144            dbgmsg( tier, "success is %d", success );
1145        }
1146        else if( responseCode )
1147        {
1148            /* %1$ld - http status code, such as 404
1149             * %2$s - human-readable explanation of the http status code */
1150            char * buf = tr_strdup_printf(
1151                _( "Announce failed: tracker gave HTTP Response Code %1$ld (%2$s)" ),
1152                responseCode,
1153                tr_webGetResponseStr( responseCode ) );
1154
1155            tr_strlcpy( tier->lastAnnounceStr, buf,
1156                        sizeof( tier->lastAnnounceStr ) );
1157
1158            /* if the repsonse may require intervention, notify the user;
1159             * otherwise, just log it */
1160            if( responseCode >= 400 )
1161                publishWarning( tier, buf );
1162            tr_torinf( tier->tor, "%s", buf );
1163            dbgmsg( tier, "%s", buf );
1164
1165            tr_free( buf );
1166        }
1167        else
1168        {
1169            tr_strlcpy( tier->lastAnnounceStr,
1170                        _( "tracker did not respond" ),
1171                        sizeof( tier->lastAnnounceStr ) );
1172            dbgmsg( tier, "%s", tier->lastAnnounceStr );
1173        }
1174    }
1175
1176    if( tier )
1177    {
1178        tier->isAnnouncing = FALSE;
1179
1180        if( responseCode == 0 )
1181        {
1182            dbgmsg( tier, "No response from tracker... retrying in two minutes." );
1183            tier->manualAnnounceAllowedAt = ~(time_t)0;
1184            tierSetNextAnnounce( tier, tier->announceEvent, now + tier->randOffset + 120 );
1185        }
1186        else if( 200 <= responseCode && responseCode <= 299 )
1187        {
1188            const int interval = tier->announceIntervalSec + tier->randOffset;
1189            dbgmsg( tier, "request succeeded. reannouncing in %d seconds", interval );
1190
1191            if( gotScrape )
1192            {
1193                tier->lastScrapeTime = now;
1194                tier->scrapeAt = now + tier->scrapeIntervalSec + tier->randOffset;
1195            }
1196
1197            tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1198
1199            if( strcmp( tier->announceEvent, "stopped" ) == 0 )
1200                tierClearNextAnnounce( tier );
1201            else
1202                tierSetNextAnnounce( tier, "", now + interval );
1203        }
1204        else if( 300 <= responseCode && responseCode <= 399 )
1205        {
1206            /* how did this get here?  libcurl handles this */
1207            const int interval = 5;
1208            dbgmsg( tier, "got a redirect. retrying in %d seconds", interval );
1209            tierSetNextAnnounce( tier, tier->announceEvent, now + interval );
1210            tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1211        }
1212        else if( 400 <= responseCode && responseCode <= 499 )
1213        {
1214            /* The request could not be understood by the server due to
1215             * malformed syntax. The client SHOULD NOT repeat the
1216             * request without modifications. */
1217            publishErrorMessageAndStop( tier, _( "Tracker returned a 4xx message" ) );
1218            tier->manualAnnounceAllowedAt = ~(time_t)0;
1219        }
1220        else if( 500 <= responseCode && responseCode <= 599 )
1221        {
1222            /* Response status codes beginning with the digit "5" indicate
1223             * cases in which the server is aware that it has erred or is
1224             * incapable of performing the request.  So we pause a bit and
1225             * try again. */
1226            tier->manualAnnounceAllowedAt = ~(time_t)0;
1227            tierSetNextAnnounce( tier, tier->announceEvent, now + tier->retryAnnounceIntervalSec );
1228            tier->retryAnnounceIntervalSec *= 2;
1229        }
1230        else
1231        {
1232            /* WTF did we get?? */
1233            const int interval = tier->randOffset + 120;
1234            dbgmsg( tier, "Invalid response from tracker... retrying in two minutes." );
1235            tier->manualAnnounceAllowedAt = ~(time_t)0;
1236            tierSetNextAnnounce( tier, tier->announceEvent, now + interval );
1237        }
1238
1239        tier->lastAnnounceSucceeded = success;
1240
1241        if( success )
1242            tier->isRunning = data->isRunningOnSuccess;
1243
1244        if( !success )
1245            tierIncrementTracker( tier );
1246    }
1247
1248    if( announcer != NULL )
1249    {
1250        ++announcer->announceSlotsAvailable;
1251    }
1252
1253    tr_free( data );
1254}
1255
1256static const char *
1257getAnnounceEvent( const tr_tier * tier )
1258{
1259    const char * event;
1260
1261    assert( tier != NULL );
1262    assert( tier->announceEvent != NULL );
1263    assert( tr_isTorrent( tier->tor ) );
1264
1265    /* BEP 21: "In order to tell the tracker that a peer is a partial seed,
1266     * it MUST send an event=paused parameter in every announce while
1267     * it is a partial seed." */
1268    if( tr_cpGetStatus( &tier->tor->completion ) == TR_PARTIAL_SEED )
1269        return "paused";
1270
1271    event = tier->announceEvent;
1272
1273    if( !strcmp( event, "manual" ) )
1274        return "started";
1275
1276    return event;
1277}
1278
1279static void
1280tierAnnounce( tr_announcer * announcer, tr_tier * tier )
1281{
1282    char * url;
1283    struct announce_data * data;
1284    const tr_torrent * tor = tier->tor;
1285    const time_t now = time( NULL );
1286
1287    assert( !tier->isAnnouncing );
1288
1289    data = tr_new0( struct announce_data, 1 );
1290    data->torrentId = tr_torrentId( tor );
1291    data->tierId = tier->key;
1292    data->isRunningOnSuccess = tor->isRunning;
1293    data->timeSent = now;
1294
1295    url = createAnnounceURL( announcer, tor, tier, getAnnounceEvent( tier ) );
1296
1297    tier->isAnnouncing = TRUE;
1298    tier->lastAnnounceStartTime = now;
1299    --announcer->announceSlotsAvailable;
1300    tr_webRun( announcer->session, url, NULL, onAnnounceDone, data );
1301
1302    tr_free( url );
1303}
1304
1305static tr_bool
1306parseScrapeResponse( tr_tier     * tier,
1307                     const char  * response,
1308                     size_t        responseLen )
1309{
1310    tr_bool success = FALSE;
1311    tr_benc benc, *files;
1312    const int bencLoaded = !tr_bencLoad( response, responseLen, &benc, NULL );
1313    if( bencLoaded && tr_bencDictFindDict( &benc, "files", &files ) )
1314    {
1315        const char * key;
1316        tr_benc * val;
1317        int i = 0;
1318        while( tr_bencDictChild( files, i++, &key, &val ))
1319        {
1320            int64_t intVal;
1321            tr_benc * flags;
1322
1323            if( memcmp( tier->tor->info.hash, key, SHA_DIGEST_LENGTH ) )
1324                continue;
1325
1326            success = TRUE;
1327            publishErrorClear( tier );
1328
1329            if( ( tr_bencDictFindInt( val, "complete", &intVal ) ) )
1330                tier->currentTracker->seederCount = intVal;
1331
1332            if( ( tr_bencDictFindInt( val, "incomplete", &intVal ) ) )
1333                tier->currentTracker->leecherCount = intVal;
1334
1335            if( ( tr_bencDictFindInt( val, "downloaded", &intVal ) ) )
1336                tier->currentTracker->downloadCount = intVal;
1337
1338            if( ( tr_bencDictFindInt( val, "downloaders", &intVal ) ) )
1339                tier->currentTracker->downloaderCount = intVal;
1340
1341            if( tr_bencDictFindDict( val, "flags", &flags ) )
1342                if( ( tr_bencDictFindInt( flags, "min_request_interval", &intVal ) ) )
1343                    tier->scrapeIntervalSec = intVal;
1344
1345            /* as per ticket #1045, safeguard against trackers returning
1346             * a very low min_request_interval... */
1347            if( tier->scrapeIntervalSec < DEFAULT_SCRAPE_INTERVAL_SEC )
1348                tier->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
1349
1350            tr_tordbg( tier->tor,
1351                       "Scrape successful. Rescraping in %d seconds.",
1352                       tier->scrapeIntervalSec );
1353
1354            tier->retryScrapeIntervalSec = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
1355        }
1356    }
1357
1358    if( bencLoaded )
1359        tr_bencFree( &benc );
1360
1361    return success;
1362}
1363
1364static void
1365onScrapeDone( tr_session   * session,
1366              long           responseCode,
1367              const void   * response,
1368              size_t         responseLen,
1369              void         * vdata )
1370{
1371    tr_announcer * announcer = session->announcer;
1372    struct announce_data * data = vdata;
1373    tr_tier * tier = getTier( announcer, data->torrentId, data->tierId );
1374    const time_t now = time( NULL );
1375    tr_bool success = FALSE;
1376
1377    if( announcer )
1378        ++announcer->scrapeSlotsAvailable;
1379
1380    if( announcer && tier )
1381    {
1382        tier->isScraping = FALSE;
1383        tier->lastScrapeTime = now;
1384   
1385        if( tier->currentTracker->host )
1386        {
1387            tr_host * host = tier->currentTracker->host;
1388            host->lastRequestTime = data->timeSent;
1389            host->lastResponseInterval = now - data->timeSent;
1390        }
1391
1392        if( responseCode == HTTP_OK )
1393        {
1394            success = parseScrapeResponse( tier, response, responseLen );
1395        }
1396
1397        if( 200 <= responseCode && responseCode <= 299 )
1398        {
1399            const int interval = tier->scrapeIntervalSec + tier->randOffset;
1400            tier->scrapeAt = now + interval;
1401
1402            tr_strlcpy( tier->lastScrapeStr, _( "Success" ), sizeof( tier->lastScrapeStr ) );
1403            tr_tordbg( tier->tor, "Request succeeded. Rescraping in %d seconds", interval );
1404        }
1405        else if( 300 <= responseCode && responseCode <= 399 )
1406        {
1407            /* this shouldn't happen; libcurl should handle this */
1408            const int interval = 5;
1409            tier->scrapeAt = now + interval;
1410            tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1411                         "Got a redirect. Retrying in %d seconds", interval );
1412            tr_tordbg( tier->tor, "%s", tier->lastScrapeStr );
1413        }
1414        else
1415        {
1416            const int interval = tier->retryScrapeIntervalSec + tier->randOffset;
1417            tier->retryScrapeIntervalSec *= 2;
1418            tier->scrapeAt = now + interval;
1419
1420            /* %1$ld - http status code, such as 404
1421             * %2$s - human-readable explanation of the http status code */
1422            if( !responseCode )
1423                tr_strlcpy( tier->lastScrapeStr, _( "tracker did not respond" ),
1424                            sizeof( tier->lastScrapeStr ) );
1425            else
1426                tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1427                             _( "tracker gave HTTP Response Code %1$ld (%2$s)" ),
1428                             responseCode, tr_webGetResponseStr( responseCode ) );
1429        }
1430
1431        tier->lastScrapeSucceeded = success;
1432    }
1433
1434    tr_free( data );
1435}
1436
1437static void
1438tierScrape( tr_announcer * announcer, tr_tier * tier )
1439{
1440    const char * scrape;
1441    struct evbuffer * buf;
1442    struct announce_data * data;
1443    const time_t now = time( NULL );
1444
1445    assert( tier );
1446    assert( !tier->isScraping );
1447    assert( tier->currentTracker != NULL );
1448    assert( tr_isTorrent( tier->tor ) );
1449
1450    data = tr_new0( struct announce_data, 1 );
1451    data->torrentId = tr_torrentId( tier->tor );
1452    data->tierId = tier->key;
1453
1454    scrape = tier->currentTracker->scrape;
1455
1456    buf = evbuffer_new( );
1457    evbuffer_add_printf( buf, "%s%cinfo_hash=%s",
1458                         scrape,
1459                         strchr( scrape, '?' ) ? '&' : '?',
1460                         tier->tor->info.hashEscaped );
1461
1462    tier->isScraping = TRUE;
1463    tier->lastScrapeStartTime = now;
1464    --announcer->scrapeSlotsAvailable;
1465    dbgmsg( tier, "scraping \"%s\"", (const char*)EVBUFFER_DATA(buf) );
1466    tr_webRun( announcer->session, (const char*)EVBUFFER_DATA(buf), NULL, onScrapeDone, data );
1467
1468    evbuffer_free( buf );
1469}
1470
1471static void
1472flushCloseMessages( tr_announcer * announcer )
1473{
1474    int i;
1475    const int n = tr_ptrArraySize( &announcer->stops );
1476
1477    for( i=0; i<n; ++i )
1478    {
1479        struct stop_message * stop = tr_ptrArrayNth( &announcer->stops, i );
1480        tr_webRun( announcer->session, stop->url, NULL, NULL, NULL );
1481        stopFree( stop );
1482    }
1483
1484    tr_ptrArrayClear( &announcer->stops );
1485}
1486
1487static tr_bool
1488tierNeedsToAnnounce( const tr_tier * tier, const time_t now )
1489{
1490    return !tier->isAnnouncing
1491        && !tier->isScraping
1492        && ( tier->announceEvent != NULL )
1493        && ( tier->announceAt <= now );
1494}
1495
1496static tr_bool
1497tierNeedsToScrape( const tr_tier * tier, const time_t now )
1498{
1499    return !tier->isScraping
1500        && ( tier->scrapeAt <= now )
1501        && ( tier->currentTracker != NULL )
1502        && ( tier->currentTracker->scrape != NULL );
1503}
1504
1505static void
1506announceMore( tr_announcer * announcer )
1507{
1508    const tr_bool canAnnounce = announcer->announceSlotsAvailable > 0;
1509    const tr_bool canScrape = announcer->scrapeSlotsAvailable > 0;
1510
1511    if( announcer->announceSlotsAvailable > 0 )
1512    {
1513        int i;
1514        int n;
1515        const time_t now = time( NULL );
1516        tr_torrent * tor = NULL;
1517        tr_ptrArray announceMe = TR_PTR_ARRAY_INIT;
1518        tr_ptrArray scrapeMe = TR_PTR_ARRAY_INIT;
1519
1520        /* build a list of tiers that need to be announced */
1521        while(( tor = tr_torrentNext( announcer->session, tor ))) {
1522            if( tor->tiers ) {
1523                n = tr_ptrArraySize( &tor->tiers->tiers );
1524                for( i=0; i<n; ++i ) {
1525                    tr_tier * tier = tr_ptrArrayNth( &tor->tiers->tiers, i );
1526                    if( canAnnounce && tierNeedsToAnnounce( tier, now ) )
1527                        tr_ptrArrayAppend( &announceMe, tier );
1528                    else if( canScrape && tierNeedsToScrape( tier, now ) )
1529                        tr_ptrArrayAppend( &scrapeMe, tier );
1530                }
1531            }
1532        }
1533
1534        /* if there are more tiers than slots available, prioritize */
1535        n = tr_ptrArraySize( &announceMe );
1536        if( n > announcer->announceSlotsAvailable )
1537            qsort( tr_ptrArrayBase( &announceMe ), n, sizeof( tr_tier * ), compareTiers );
1538
1539        /* announce some */
1540        n = MIN( tr_ptrArraySize( &announceMe ), announcer->announceSlotsAvailable );
1541        for( i=0; i<n; ++i ) {
1542            tr_tier * tier = tr_ptrArrayNth( &announceMe, i );
1543            dbgmsg( tier, "announcing tier %d of %d", i, n );
1544            tierAnnounce( announcer, tier );
1545        }
1546
1547
1548        /* scrape some */
1549        n = MIN( tr_ptrArraySize( &scrapeMe ), announcer->scrapeSlotsAvailable );
1550        for( i=0; i<n; ++i ) {
1551            tr_tier * tier = tr_ptrArrayNth( &scrapeMe, i );
1552            dbgmsg( tier, "scraping tier %d of %d", (i+1), n );
1553            tierScrape( announcer, tier );
1554        }
1555
1556        /* cleanup */
1557        tr_ptrArrayDestruct( &scrapeMe, NULL );
1558        tr_ptrArrayDestruct( &announceMe, NULL );
1559    }
1560}
1561
1562static void
1563onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer )
1564{
1565    tr_announcer * announcer = vannouncer;
1566
1567    /* maybe send out some "stopped" messages for closed torrents */
1568    flushCloseMessages( announcer );
1569
1570    /* maybe send out some announcements to trackers */
1571    announceMore( announcer );
1572
1573    /* set up the next timer */
1574    tr_timerAdd( announcer->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
1575}
1576
1577/***
1578****
1579***/
1580
1581tr_tracker_stat *
1582tr_announcerStats( const tr_torrent * torrent,
1583                   int              * setmeTrackerCount )
1584{
1585    int i;
1586    int n;
1587    int out = 0;
1588    int tierCount;
1589    tr_tracker_stat * ret;
1590
1591    assert( tr_isTorrent( torrent ) );
1592
1593    /* count the trackers... */
1594    for( i=n=0, tierCount=tr_ptrArraySize( &torrent->tiers->tiers ); i<tierCount; ++i ) {
1595        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1596        n += tr_ptrArraySize( &tier->trackers );
1597    }
1598
1599    /* alloc the stats */
1600    *setmeTrackerCount = n;
1601    ret = tr_new0( tr_tracker_stat, n );
1602
1603    /* populate the stats */
1604    for( i=0, tierCount=tr_ptrArraySize( &torrent->tiers->tiers ); i<tierCount; ++i )
1605    {
1606        int j;
1607        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1608        n = tr_ptrArraySize( &tier->trackers );
1609        for( j=0; j<n; ++j )
1610        {
1611            const tr_tracker_item * tracker = tr_ptrArrayNth( (tr_ptrArray*)&tier->trackers, j );
1612            tr_tracker_stat * st = ret + out++;
1613
1614            tr_strlcpy( st->host, tracker->host->name, sizeof( st->host ) );
1615            tr_strlcpy( st->announce, tracker->announce, sizeof( st->announce ) );
1616            st->tier = i + 1;
1617            st->isActive = tracker == tier->currentTracker;
1618            st->lastScrapeStartTime = tier->lastScrapeStartTime;
1619            if(( st->hasScraped = tier->lastScrapeTime != 0 )) {
1620                st->lastScrapeTime = tier->lastScrapeTime;
1621                st->lastScrapeSucceeded = tier->lastScrapeSucceeded;
1622                tr_strlcpy( st->lastScrapeResult, tier->lastScrapeStr, sizeof( st->lastScrapeResult ) );
1623            }
1624            st->isScraping = tier->isScraping;
1625            if(( st->willScrape = st->isActive && !tier->isScraping )) {
1626                st->nextScrapeTime = tier->scrapeAt;
1627            }
1628            st->lastAnnounceStartTime = tier->lastAnnounceStartTime;
1629            if(( st->hasAnnounced = tier->lastAnnounceTime != 0 )) {
1630                st->lastAnnounceTime = tier->lastAnnounceTime;
1631                tr_strlcpy( st->lastAnnounceResult, tier->lastAnnounceStr, sizeof( st->lastAnnounceResult ) );
1632                if(( st->lastAnnounceSucceeded = tier->lastAnnounceSucceeded )) {
1633                    st->lastAnnouncePeerCount = tier->lastAnnouncePeerCount;
1634                }
1635            }
1636            st->isAnnouncing = tier->isAnnouncing;
1637            if(( st->willAnnounce = torrent->isRunning && !tier->isAnnouncing )) {
1638                st->nextAnnounceTime = tier->announceAt;
1639            }
1640            st->seederCount = tracker->seederCount;
1641            st->leecherCount = tracker->leecherCount;
1642            st->downloadCount = tracker->downloadCount;
1643        }
1644    }
1645
1646    return ret;
1647}
1648
1649void
1650tr_announcerStatsFree( tr_tracker_stat * trackers,
1651                       int trackerCount UNUSED )
1652{
1653    tr_free( trackers );
1654}
Note: See TracBrowser for help on using the repository browser.