source: trunk/libtransmission/announcer.c @ 10639

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

(trunk libT) #3203 "torrents halted after 'Tracker returned a 4xx message'" -- fixed in trunk for 2.00

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