source: trunk/libtransmission/announcer.c @ 10654

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

(trunkn libT) #3192 "crash in most recent nightlies" -- fixed in trunk for 2.00

File size: 59.4 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
620getSeedProbability( int seeds, int leechers )
621{
622    if( !seeds )
623        return 0;
624
625    if( seeds>=0 && leechers>=0 )
626        return (int)((100.0*seeds)/(seeds+leechers));
627
628    return -1; /* unknown */
629}
630
631static int
632publishNewPeers( tr_tier * tier, int seeds, int leechers,
633                 const void * compact, int compactLen )
634{
635    tr_tracker_event e = emptyEvent;
636
637    e.messageType = TR_TRACKER_PEERS;
638    e.seedProbability = getSeedProbability( seeds, leechers );
639    e.compact = compact;
640    e.compactLen = compactLen;
641
642    tr_publisherPublish( &tier->tor->tiers->publisher, tier, &e );
643
644    return compactLen / 6;
645}
646
647static int
648publishNewPeersCompact( tr_tier * tier, int seeds, int leechers,
649                        const void * compact, int compactLen )
650{
651    int i;
652    const uint8_t *compactWalk;
653    uint8_t *array, *walk;
654    const int peerCount = compactLen / 6;
655    const int arrayLen = peerCount * ( sizeof( tr_address ) + 2 );
656    tr_address addr;
657    tr_port port;
658
659    addr.type = TR_AF_INET;
660    memset( &addr.addr, 0, sizeof( addr.addr ) );
661    array = tr_new( uint8_t, arrayLen );
662    for ( i=0, walk=array, compactWalk=compact ; i<peerCount ; ++i )
663    {
664        memcpy( &addr.addr.addr4, compactWalk, 4 );
665        memcpy( &port, compactWalk + 4, 2 );
666
667        memcpy( walk, &addr, sizeof( addr ) );
668        memcpy( walk + sizeof( addr ), &port, 2 );
669
670        walk += sizeof( tr_address ) + 2;
671        compactWalk += 6;
672    }
673
674    publishNewPeers( tier, seeds, leechers, array, arrayLen );
675
676    tr_free( array );
677
678    return peerCount;
679}
680
681static int
682publishNewPeersCompact6( tr_tier * tier, int seeds, int leechers,
683                         const void * compact, int compactLen )
684{
685    int i;
686    const uint8_t *compactWalk;
687    uint8_t *array, *walk;
688    const int peerCount = compactLen / 18;
689    const int arrayLen = peerCount * ( sizeof( tr_address ) + 2 );
690    tr_address addr;
691    tr_port port;
692
693    addr.type = TR_AF_INET6;
694    memset( &addr.addr, 0, sizeof( addr.addr ) );
695    array = tr_new( uint8_t, arrayLen );
696    for ( i = 0, walk = array, compactWalk = compact ; i < peerCount ; ++i )
697    {
698        memcpy( &addr.addr.addr6, compactWalk, 16 );
699        memcpy( &port, compactWalk + 16, 2 );
700        compactWalk += 18;
701
702        memcpy( walk, &addr, sizeof( addr ) );
703        memcpy( walk + sizeof( addr ), &port, 2 );
704        walk += sizeof( tr_address ) + 2;
705    }
706
707    publishNewPeers( tier, seeds, leechers, array, arrayLen );
708    tr_free( array );
709
710    return peerCount;
711}
712
713static char*
714createAnnounceURL( const tr_announcer     * announcer,
715                   const tr_torrent       * torrent,
716                   const tr_tier          * tier,
717                   const char             * eventName )
718{
719    const int isStopping = !strcmp( eventName, "stopped" );
720    const int numwant = isStopping ? 0 : NUMWANT;
721    const tr_tracker_item  * tracker = tier->currentTracker;
722    const char * ann = tracker->announce;
723    struct evbuffer * buf = evbuffer_new( );
724    char * ret;
725    const char * str;
726    const unsigned char * ipv6;
727
728    evbuffer_expand( buf, 2048 );
729
730    evbuffer_add_printf( buf, "%s"
731                              "%c"
732                              "info_hash=%s"
733                              "&peer_id=%s"
734                              "&port=%d"
735                              "&uploaded=%" PRIu64
736                              "&downloaded=%" PRIu64
737                              "&left=%" PRIu64
738                              "&numwant=%d"
739                              "&key=%s"
740                              "&compact=1"
741                              "&supportcrypto=1",
742                              ann,
743                              strchr( ann, '?' ) ? '&' : '?',
744                              torrent->info.hashEscaped,
745                              torrent->peer_id,
746                              (int)tr_sessionGetPeerPort( announcer->session ),
747                              tier->byteCounts[TR_ANN_UP],
748                              tier->byteCounts[TR_ANN_DOWN],
749                              tr_cpLeftUntilComplete( &torrent->completion ),
750                              numwant,
751                              tracker->key_param );
752
753    if( announcer->session->encryptionMode == TR_ENCRYPTION_REQUIRED )
754        evbuffer_add_printf( buf, "&requirecrypto=1" );
755
756    if( tier->byteCounts[TR_ANN_CORRUPT] )
757        evbuffer_add_printf( buf, "&corrupt=%" PRIu64, tier->byteCounts[TR_ANN_CORRUPT] );
758
759    str = eventName;
760    if( str && *str )
761        evbuffer_add_printf( buf, "&event=%s", str );
762
763    str = tracker->tracker_id;
764    if( str && *str )
765        evbuffer_add_printf( buf, "&trackerid=%s", str );
766
767    /* There are two incompatible techniques for announcing an IPv6 address.
768       BEP-7 suggests adding an "ipv6=" parameter to the announce URL,
769       while OpenTracker requires that peers announce twice, once over IPv4
770       and once over IPv6.
771
772       To be safe, we should do both: add the "ipv6=" parameter and
773       announce twice.  At any rate, we're already computing our IPv6
774       address (for the LTEP handshake), so this comes for free. */
775
776    ipv6 = tr_globalIPv6( );
777    if( ipv6 ) {
778        char ipv6_readable[INET6_ADDRSTRLEN];
779        inet_ntop( AF_INET6, ipv6, ipv6_readable, INET6_ADDRSTRLEN );
780        evbuffer_add_printf( buf, "&ipv6=");
781        tr_http_escape( buf, ipv6_readable, strlen(ipv6_readable), TRUE );
782    }
783
784    ret = tr_strndup( EVBUFFER_DATA( buf ), EVBUFFER_LENGTH( buf ) );
785    dbgmsg( tier, "announce URL is \"%s\"", ret );
786    evbuffer_free( buf );
787    return ret;
788}
789
790
791/***
792****
793***/
794
795static tr_bool
796announceURLIsSupported( const char * announce )
797{
798    return ( announce != NULL )
799        && ( ( strstr( announce, "http://" ) == announce ) ||
800             ( strstr( announce, "https://" ) == announce ) );
801}
802
803static void
804addTorrentToTier( tr_announcer * announcer, tr_torrent_tiers * tiers, tr_torrent * tor )
805{
806    int i, n;
807    const tr_tracker_info ** infos;
808    const int trackerCount = tor->info.trackerCount;
809    const tr_tracker_info  * trackers = tor->info.trackers;
810
811    /* get the trackers that we support... */
812    infos = tr_new0( const tr_tracker_info*, trackerCount );
813    for( i=n=0; i<trackerCount; ++i )
814        if( announceURLIsSupported( trackers[i].announce ) )
815            infos[n++] = &trackers[i];
816
817    /* build our private table of tiers... */
818    if( n > 0 )
819    {
820        int tierIndex = -1;
821        tr_tier * tier = NULL;
822
823        for( i=0; i<n; ++i )
824        {
825            const tr_tracker_info * info = infos[i];
826
827            if( info->tier != tierIndex )
828                tier = NULL;
829
830            tierIndex = info->tier;
831
832            if( tier == NULL ) {
833                tier = tierNew( tor );
834                dbgmsg( tier, "adding tier" );
835                tr_ptrArrayAppend( &tiers->tiers, tier );
836            }
837
838            tierAddTracker( announcer, tier, info->announce, info->scrape, info->id );
839        }
840    }
841
842    tr_free( infos );
843}
844
845tr_torrent_tiers *
846tr_announcerAddTorrent( tr_announcer * announcer, tr_torrent * tor )
847{
848    tr_torrent_tiers * tiers;
849
850    assert( announcer != NULL );
851    assert( tr_isTorrent( tor ) );
852
853    tiers = tiersNew( );
854
855    addTorrentToTier( announcer, tiers, tor );
856
857    return tiers;
858}
859
860static void
861tierAddAnnounce( tr_tier * tier, const char * announceEvent, time_t announceAt );
862
863void
864tr_announcerResetTorrent( tr_announcer * announcer, tr_torrent * tor )
865{
866    tr_ptrArray oldTiers = TR_PTR_ARRAY_INIT;
867
868    /* if we had tiers already, make a backup of them */
869    if( tor->tiers != NULL )
870    {
871        oldTiers = tor->tiers->tiers;
872        tor->tiers->tiers = TR_PTR_ARRAY_INIT;
873    }
874
875    /* create the new tier/tracker structs */
876    addTorrentToTier( announcer, tor->tiers, tor );
877
878    /* if we had tiers already, merge their state into the new structs */
879    if( !tr_ptrArrayEmpty( &oldTiers ) )
880    {
881        int i, in;
882        for( i=0, in=tr_ptrArraySize(&oldTiers); i<in; ++i )
883        {
884            int j, jn;
885            const tr_tier * o = tr_ptrArrayNth( &oldTiers, i );
886
887            if( o->currentTracker == NULL )
888                continue;
889
890            for( j=0, jn=tr_ptrArraySize(&tor->tiers->tiers); j<jn; ++j )
891            {
892                int k, kn;
893                tr_tier * t = tr_ptrArrayNth(&tor->tiers->tiers,j);
894
895                for( k=0, kn=tr_ptrArraySize(&t->trackers); k<kn; ++k )
896                {
897                    tr_tracker_item * item = tr_ptrArrayNth(&t->trackers,k);
898                    if( strcmp( o->currentTracker->announce, item->announce ) )
899                        continue;
900                    tierCopyAttributes( t, o );
901                    t->currentTracker = item;
902                    t->currentTrackerIndex = k;
903                    t->wasCopied = TRUE;
904                    trackerItemCopyAttributes( item, o->currentTracker );
905                    dbgmsg( t, "attributes copied to tier %d, tracker %d"
906                                               "from tier %d, tracker %d",
907                            i, o->currentTrackerIndex, j, k );
908
909                }
910            }
911        }
912    }
913
914    /* kickstart any tiers that didn't get started */
915    if( tor->isRunning )
916    {
917        int i, n;
918        const time_t now = tr_time( );
919        tr_tier ** tiers = (tr_tier**) tr_ptrArrayPeek( &tor->tiers->tiers, &n );
920        for( i=0; i<n; ++i ) {
921            tr_tier * tier = tiers[i];
922            if( !tier->wasCopied )
923                tierAddAnnounce( tier, STARTED, now );
924        }
925    }
926
927    /* cleanup */
928    tr_ptrArrayDestruct( &oldTiers, tierFree );
929}
930
931tr_publisher_tag
932tr_announcerSubscribe( struct tr_torrent_tiers   * tiers,
933                       tr_delivery_func            func,
934                       void                      * userData )
935{
936    return tr_publisherSubscribe( &tiers->publisher, func, userData );
937}
938
939void
940tr_announcerUnsubscribe( struct tr_torrent_tiers  * tiers,
941                         tr_publisher_tag           tag )
942{
943    if( tiers )
944        tr_publisherUnsubscribe( &tiers->publisher, tag );
945}
946
947static tr_bool
948tierCanManualAnnounce( const tr_tier * tier )
949{
950    return tier->isRunning
951        && tier->manualAnnounceAllowedAt <= tr_time( );
952}
953
954tr_bool
955tr_announcerCanManualAnnounce( const tr_torrent * tor )
956{
957    int i;
958    int n;
959    const tr_tier ** tiers;
960
961    assert( tr_isTorrent( tor ) );
962    assert( tor->tiers != NULL );
963
964    n = tr_ptrArraySize( &tor->tiers->tiers );
965    tiers = (const tr_tier**) tr_ptrArrayBase( &tor->tiers->tiers );
966    for( i=0; i<n; ++i )
967        if( tierCanManualAnnounce( tiers[i] ) )
968            return TRUE;
969
970    return FALSE;
971}
972
973time_t
974tr_announcerNextManualAnnounce( const tr_torrent * tor )
975{
976    int i;
977    int n;
978    const tr_torrent_tiers * tiers;
979    time_t ret = ~(time_t)0;
980
981    assert( tr_isTorrent( tor  ) );
982
983    tiers = tor->tiers;
984    n = tr_ptrArraySize( &tiers->tiers );
985    for( i=0; i<n; ++i ) {
986        tr_tier * tier = tr_ptrArrayNth( (tr_ptrArray*)&tiers->tiers, i );
987        if( tier->isRunning )
988            ret = MIN( ret, tier->manualAnnounceAllowedAt );
989    }
990
991    return ret;
992}
993
994static void
995tierAddAnnounce( tr_tier * tier, const char * announceEvent, time_t announceAt )
996{
997    assert( tier != NULL );
998    assert( announceEvent != NULL );
999
1000    tr_ptrArrayAppend( &tier->announceEvents, (void*)announceEvent );
1001    tier->announceAt = announceAt;
1002
1003    dbgmsg( tier, "appended event \"%s\"; announcing in %d seconds\n", announceEvent, (int)difftime(announceAt,time(NULL)) );
1004}
1005
1006static void
1007torrentAddAnnounce( tr_torrent * tor, const char * announceEvent, time_t announceAt )
1008{
1009    int i;
1010    int n;
1011    tr_torrent_tiers * tiers;
1012
1013    assert( tr_isTorrent( tor ) );
1014
1015    tiers = tor->tiers;
1016    n = tr_ptrArraySize( &tiers->tiers );
1017    for( i=0; i<n; ++i )
1018        tierAddAnnounce( tr_ptrArrayNth( &tiers->tiers, i ), announceEvent, announceAt );
1019}
1020
1021void
1022tr_announcerTorrentStarted( tr_torrent * tor )
1023{
1024    torrentAddAnnounce( tor, STARTED, tr_time( ) );
1025}
1026void
1027tr_announcerManualAnnounce( tr_torrent * tor )
1028{
1029    torrentAddAnnounce( tor, "", tr_time( ) );
1030}
1031void
1032tr_announcerTorrentStopped( tr_torrent * tor )
1033{
1034    torrentAddAnnounce( tor, "stopped", tr_time( ) );
1035}
1036void
1037tr_announcerTorrentCompleted( tr_torrent * tor )
1038{
1039    torrentAddAnnounce( tor, "completed", tr_time( ) );
1040}
1041void
1042tr_announcerChangeMyPort( tr_torrent * tor )
1043{
1044    tr_announcerTorrentStarted( tor );
1045}
1046
1047/***
1048****
1049***/
1050
1051void
1052tr_announcerAddBytes( tr_torrent * tor, int type, uint32_t byteCount )
1053{
1054    int i, n;
1055    tr_torrent_tiers * tiers;
1056
1057    assert( tr_isTorrent( tor ) );
1058    assert( type==TR_ANN_UP || type==TR_ANN_DOWN || type==TR_ANN_CORRUPT );
1059
1060    tiers = tor->tiers;
1061    n = tr_ptrArraySize( &tiers->tiers );
1062    for( i=0; i<n; ++i )
1063    {
1064        tr_tier * tier = tr_ptrArrayNth( &tiers->tiers, i );
1065        tier->byteCounts[ type ] += byteCount;
1066    }
1067}
1068
1069/***
1070****
1071***/
1072
1073void
1074tr_announcerRemoveTorrent( tr_announcer * announcer, tr_torrent * tor )
1075{
1076    assert( tr_isTorrent( tor ) );
1077
1078    if( tor->tiers )
1079    {
1080        int i;
1081        const int n = tr_ptrArraySize( &tor->tiers->tiers );
1082        for( i=0; i<n; ++i )
1083        {
1084            tr_tier * tier = tr_ptrArrayNth( &tor->tiers->tiers, i );
1085
1086            if( tier->isRunning )
1087            {
1088                struct stop_message * s = tr_new0( struct stop_message, 1 );
1089                s->up = tier->byteCounts[TR_ANN_UP];
1090                s->down = tier->byteCounts[TR_ANN_DOWN];
1091                s->url = createAnnounceURL( announcer, tor, tier, "stopped" );
1092                s->host = tier->currentTracker->host;
1093                tr_ptrArrayInsertSorted( &announcer->stops, s, compareStops );
1094            }
1095        }
1096
1097        tiersFree( tor->tiers );
1098        tor->tiers = NULL;
1099    }
1100}
1101
1102/* return true if (1) we've tried it recently AND (2) it didn't respond... */
1103static tr_bool
1104hostIsNotResponding( const tr_host * host, const time_t now )
1105{
1106    tr_bool b = ( host->lastRequestTime )
1107             && ( host->lastRequestTime >= ( now - SLOW_HOST_PENALTY_SECS ) )
1108             && ( host->lastResponseInterval > MAX_TRACKER_RESPONSE_TIME_SECS );
1109    return b;
1110}
1111
1112static tr_bool
1113tierIsNotResponding( const tr_tier * tier, const time_t now )
1114{
1115    return !tier->currentTracker
1116        || hostIsNotResponding( tier->currentTracker->host, now );
1117}
1118
1119static int
1120getRetryInterval( const tr_host * host )
1121{
1122    int interval;
1123    const int jitter = tr_cryptoWeakRandInt( 120 );
1124    const time_t timeSinceLastSuccess = tr_time() - host->lastSuccessfulRequest;
1125         if( timeSinceLastSuccess < 15*60 ) interval = 0;
1126    else if( timeSinceLastSuccess < 30*60 ) interval = 60*4;
1127    else if( timeSinceLastSuccess < 45*60 ) interval = 60*8;
1128    else if( timeSinceLastSuccess < 60*60 ) interval = 60*16;
1129    else                                    interval = 60*32;
1130    return interval + jitter;
1131}
1132
1133static int
1134compareTiers( const void * va, const void * vb )
1135{
1136    int ret = 0;
1137    tr_bool af, bf;
1138    const tr_tier * a = *(const tr_tier**)va;
1139    const tr_tier * b = *(const tr_tier**)vb;
1140
1141    /* working domains come before non-working */
1142    if( !ret ) {
1143        const time_t now = tr_time( );
1144        af = tierIsNotResponding( a, now );
1145        bf = tierIsNotResponding( b, now );
1146        if( af != bf )
1147            ret = !af ? -1 : 1;
1148    }
1149
1150    /* stops come before starts */
1151    if( !ret ) {
1152        af = a->tor->isRunning;
1153        bf = b->tor->isRunning;
1154        if( af != bf )
1155            ret = af ? 1 : -1;
1156    }
1157
1158    /* upload comes before download */
1159    if( !ret )
1160        ret = compareTransfer( a->byteCounts[TR_ANN_UP], a->byteCounts[TR_ANN_DOWN],
1161                               b->byteCounts[TR_ANN_UP], b->byteCounts[TR_ANN_DOWN] );
1162
1163    /* incomplete comes before complete */
1164    if( !ret ) {
1165        af = a->tor->completeness == TR_LEECH;
1166        bf = b->tor->completeness == TR_LEECH;
1167        if( af != bf )
1168            return af ? -1 : 1;
1169    }
1170
1171    /* private before public */
1172    if( !ret ) {
1173        af = tr_torrentIsPrivate( a->tor );
1174        bf = tr_torrentIsPrivate( b->tor );
1175        if( af != bf )
1176            ret = af ? -1 : 1;
1177    }
1178
1179    return ret;
1180}
1181
1182static uint8_t *
1183parseOldPeers( tr_benc * bePeers, size_t *  byteCount )
1184{
1185    int       i;
1186    uint8_t * array, *walk;
1187    const int peerCount = bePeers->val.l.count;
1188
1189    assert( tr_bencIsList( bePeers ) );
1190
1191    array = tr_new( uint8_t, peerCount * ( sizeof( tr_address ) + 2 ) );
1192
1193    for( i = 0, walk = array; i < peerCount; ++i )
1194    {
1195        const char * s;
1196        int64_t      itmp;
1197        tr_address   addr;
1198        tr_port      port;
1199        tr_benc    * peer = &bePeers->val.l.vals[i];
1200
1201        if( tr_bencDictFindStr( peer, "ip", &s ) )
1202            if( tr_pton( s, &addr ) == NULL )
1203                continue;
1204
1205        if( !tr_bencDictFindInt( peer, "port", &itmp )
1206                || itmp < 0
1207                || itmp > USHRT_MAX )
1208            continue;
1209
1210        memcpy( walk, &addr, sizeof( tr_address ) );
1211        port = htons( itmp );
1212        memcpy( walk + sizeof( tr_address ), &port, 2 );
1213        walk += sizeof( tr_address ) + 2;
1214    }
1215
1216    *byteCount = peerCount * sizeof( tr_address ) + 2;
1217    return array;
1218}
1219
1220static tr_bool
1221parseAnnounceResponse( tr_tier     * tier,
1222                       const char  * response,
1223                       size_t        responseLen,
1224                       tr_bool     * gotScrape )
1225{
1226    tr_benc benc;
1227    tr_bool success = FALSE;
1228    int scrapeFields = 0;
1229    const int bencLoaded = !tr_bencLoad( response, responseLen, &benc, NULL );
1230
1231    dbgmsg( tier, "response len: %d, isBenc: %d", (int)responseLen, (int)bencLoaded );
1232    publishErrorClear( tier );
1233    if( bencLoaded && tr_bencIsDict( &benc ) )
1234    {
1235        int peerCount = 0;
1236        size_t rawlen;
1237        int64_t i;
1238        tr_benc * tmp;
1239        const char * str;
1240        const uint8_t * raw;
1241        tr_bool gotPeers = FALSE;
1242
1243        success = TRUE;
1244
1245        if( tr_bencDictFindStr( &benc, "failure reason", &str ) )
1246        {
1247            tr_strlcpy( tier->lastAnnounceStr, str,
1248                        sizeof( tier->lastAnnounceStr ) );
1249            dbgmsg( tier, "tracker gave \"%s\"", str );
1250            publishMessage( tier, str, TR_TRACKER_ERROR );
1251            success = FALSE;
1252        }
1253
1254        if( tr_bencDictFindStr( &benc, "warning message", &str ) )
1255        {
1256            tr_strlcpy( tier->lastAnnounceStr, str,
1257                        sizeof( tier->lastAnnounceStr ) );
1258            dbgmsg( tier, "tracker gave \"%s\"", str );
1259            publishWarning( tier, str );
1260        }
1261
1262        if( tr_bencDictFindInt( &benc, "interval", &i ) )
1263        {
1264            dbgmsg( tier, "setting interval to %d", (int)i );
1265            tier->announceIntervalSec = i;
1266        }
1267
1268        if( tr_bencDictFindInt( &benc, "min interval", &i ) )
1269        {
1270            dbgmsg( tier, "setting min interval to %d", (int)i );
1271            tier->announceMinIntervalSec = i;
1272        }
1273
1274        if( tr_bencDictFindStr( &benc, "tracker id", &str ) )
1275        {
1276            tier->currentTracker->tracker_id = tr_strdup( str );
1277        }
1278
1279        if( !tr_bencDictFindInt( &benc, "complete", &i ) )
1280            tier->currentTracker->seederCount = 0;
1281        else {
1282            ++scrapeFields;
1283            tier->currentTracker->seederCount = i;
1284        }
1285
1286        if( !tr_bencDictFindInt( &benc, "incomplete", &i ) )
1287            tier->currentTracker->leecherCount = 0;
1288        else {
1289            ++scrapeFields;
1290            tier->currentTracker->leecherCount = i;
1291        }
1292
1293        if( tr_bencDictFindInt( &benc, "downloaded", &i ) )
1294        {
1295            ++scrapeFields;
1296            tier->currentTracker->downloadCount = i;
1297        }
1298
1299        if( tr_bencDictFindRaw( &benc, "peers", &raw, &rawlen ) )
1300        {
1301            /* "compact" extension */
1302            const int seeders = tier->currentTracker->seederCount;
1303            const int leechers = tier->currentTracker->leecherCount;
1304            peerCount += publishNewPeersCompact( tier, seeders, leechers, raw, rawlen );
1305            gotPeers = TRUE;
1306        }
1307        else if( tr_bencDictFindList( &benc, "peers", &tmp ) )
1308        {
1309            /* original version of peers */
1310            const int seeders = tier->currentTracker->seederCount;
1311            const int leechers = tier->currentTracker->leecherCount;
1312            size_t byteCount = 0;
1313            uint8_t * array = parseOldPeers( tmp, &byteCount );
1314            peerCount += publishNewPeers( tier, seeders, leechers, array, byteCount );
1315            gotPeers = TRUE;
1316            tr_free( array );
1317        }
1318
1319        if( tr_bencDictFindRaw( &benc, "peers6", &raw, &rawlen ) )
1320        {
1321            /* "compact" extension */
1322            const int seeders = tier->currentTracker->seederCount;
1323            const int leechers = tier->currentTracker->leecherCount;
1324            peerCount += publishNewPeersCompact6( tier, seeders, leechers, raw, rawlen );
1325            gotPeers = TRUE;
1326        }
1327
1328        if( tier->lastAnnounceStr[0] == '\0' )
1329            tr_strlcpy( tier->lastAnnounceStr, _( "Success" ),
1330                        sizeof( tier->lastAnnounceStr ) );
1331
1332        if( gotPeers )
1333            tier->lastAnnouncePeerCount = peerCount;
1334    }
1335
1336    if( bencLoaded )
1337        tr_bencFree( &benc );
1338
1339    *gotScrape = scrapeFields >= 2;
1340
1341    return success;
1342}
1343
1344struct announce_data
1345{
1346    int torrentId;
1347    int tierId;
1348    time_t timeSent;
1349    const char * event;
1350
1351    /** If the request succeeds, the value for tier's "isRunning" flag */
1352    tr_bool isRunningOnSuccess;
1353};
1354
1355static void
1356onAnnounceDone( tr_session   * session,
1357                long           responseCode,
1358                const void   * response,
1359                size_t         responseLen,
1360                void         * vdata )
1361{
1362    tr_announcer * announcer = session->announcer;
1363    struct announce_data * data = vdata;
1364    tr_tier * tier = getTier( announcer, data->torrentId, data->tierId );
1365    tr_bool gotScrape = FALSE;
1366    tr_bool success = FALSE;
1367    const time_t now = time ( NULL );
1368    const char * announceEvent = data->event;
1369    const tr_bool isStopped = !strcmp( announceEvent, "stopped" );
1370
1371    if( announcer && tier )
1372    {
1373        if( tier->currentTracker->host )
1374        {
1375            tr_host * host = tier->currentTracker->host;
1376            host->lastRequestTime = data->timeSent;
1377            host->lastResponseInterval = now - data->timeSent;
1378        }
1379
1380        tier->lastAnnounceTime = now;
1381
1382        if( responseCode == HTTP_OK )
1383        {
1384            success = parseAnnounceResponse( tier, response, responseLen, &gotScrape );
1385            dbgmsg( tier, "success is %d", success );
1386
1387            if( isStopped )
1388            {
1389                /* now that we've successfully stopped the torrent,
1390                 * we can reset the up/down/corrupt count we've kept
1391                 * for this tracker */
1392                tier->byteCounts[ TR_ANN_UP ] = 0;
1393                tier->byteCounts[ TR_ANN_DOWN ] = 0;
1394                tier->byteCounts[ TR_ANN_CORRUPT ] = 0;
1395            }
1396        }
1397        else if( responseCode )
1398        {
1399            /* %1$ld - http status code, such as 404
1400             * %2$s - human-readable explanation of the http status code */
1401            char * buf = tr_strdup_printf(
1402                _( "tracker gave HTTP Response Code %1$ld (%2$s)" ),
1403                responseCode,
1404                tr_webGetResponseStr( responseCode ) );
1405
1406            tr_strlcpy( tier->lastAnnounceStr, buf,
1407                        sizeof( tier->lastAnnounceStr ) );
1408
1409            /* if the response is serious, *and* if the response may require
1410             * human intervention, then notify the user... otherwise just log it */
1411            if( responseCode >= 400 )
1412                if( tr_torrentIsPrivate( tier->tor ) || ( tier->tor->info.trackerCount < 2 ) )
1413                    publishWarning( tier, buf );
1414            tr_torinf( tier->tor, "%s", buf );
1415            dbgmsg( tier, "%s", buf );
1416
1417            tr_free( buf );
1418        }
1419        else
1420        {
1421            tr_strlcpy( tier->lastAnnounceStr,
1422                        _( "tracker did not respond" ),
1423                        sizeof( tier->lastAnnounceStr ) );
1424            dbgmsg( tier, "%s", tier->lastAnnounceStr );
1425        }
1426    }
1427
1428    if( tier )
1429    {
1430        tier->isAnnouncing = FALSE;
1431
1432        if( responseCode == 0 )
1433        {
1434            const int interval = getRetryInterval( tier->currentTracker->host );
1435            dbgmsg( tier, "No response from tracker... retrying in %d seconds.", interval );
1436            tier->manualAnnounceAllowedAt = ~(time_t)0;
1437            tierAddAnnounce( tier, announceEvent, now + interval );
1438        }
1439        else if( 200 <= responseCode && responseCode <= 299 )
1440        {
1441            const int interval = tier->announceIntervalSec;
1442            dbgmsg( tier, "request succeeded. reannouncing in %d seconds", interval );
1443
1444            if( gotScrape )
1445            {
1446                tier->lastScrapeTime = now;
1447                tier->lastScrapeSucceeded = 1;
1448                tier->scrapeAt = now + tier->scrapeIntervalSec;
1449            }
1450
1451            tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1452
1453            /* if we're running and the queue is empty, add the next update */
1454            if( !isStopped && !tr_ptrArraySize( &tier->announceEvents ) )
1455            {
1456                tierAddAnnounce( tier, "", now + interval );
1457            }
1458        }
1459        else if( 300 <= responseCode && responseCode <= 399 )
1460        {
1461            /* how did this get here?  libcurl handles this */
1462            const int interval = 5;
1463            dbgmsg( tier, "got a redirect. retrying in %d seconds", interval );
1464            tierAddAnnounce( tier, announceEvent, now + interval );
1465            tier->manualAnnounceAllowedAt = now + tier->announceMinIntervalSec;
1466        }
1467        else if( ( responseCode == 404 ) || ( 500 <= responseCode && responseCode <= 599 ) )
1468        {
1469            /* 404: The requested resource could not be found but may be
1470             * available again in the future.  Subsequent requests by
1471             * the client are permissible. */
1472
1473            /* 5xx: indicate cases in which the server is aware that it
1474             * has erred or is incapable of performing the request.
1475             * So we pause a bit and try again. */
1476
1477            const int interval = getRetryInterval( tier->currentTracker->host );
1478            tier->manualAnnounceAllowedAt = ~(time_t)0;
1479            tierAddAnnounce( tier, announceEvent, now + interval );
1480        }
1481        else if( 400 <= responseCode && responseCode <= 499 )
1482        {
1483            /* The request could not be understood by the server due to
1484             * malformed syntax. The client SHOULD NOT repeat the
1485             * request without modifications. */
1486            if( tr_torrentIsPrivate( tier->tor ) || ( tier->tor->info.trackerCount < 2 ) )
1487                publishErrorMessageAndStop( tier, _( "Tracker returned a 4xx message" ) );
1488            tier->announceAt = 0;
1489            tier->manualAnnounceAllowedAt = ~(time_t)0;
1490        }
1491        else
1492        {
1493            /* WTF did we get?? */
1494            const int interval = 120;
1495            dbgmsg( tier, "Invalid response from tracker... retrying in two minutes." );
1496            tier->manualAnnounceAllowedAt = ~(time_t)0;
1497            tierAddAnnounce( tier, announceEvent, now + interval );
1498        }
1499
1500        tier->lastAnnounceSucceeded = success;
1501        tier->lastAnnounceTimedOut = responseCode == 0;
1502
1503        if( success )
1504        {
1505            tier->isRunning = data->isRunningOnSuccess;
1506
1507            if( tier->currentTracker->host )
1508                tier->currentTracker->host->lastSuccessfulRequest = now;
1509        }
1510        else if( responseCode != HTTP_OK )
1511        {
1512            tierIncrementTracker( tier );
1513
1514            tr_ptrArrayInsert( &tier->announceEvents, (void*)announceEvent, 0 );
1515        }
1516    }
1517
1518    if( announcer != NULL )
1519    {
1520        ++announcer->slotsAvailable;
1521    }
1522
1523    tr_free( data );
1524}
1525
1526static const char*
1527getNextAnnounceEvent( tr_tier * tier )
1528{
1529    int i, n;
1530    int pos = -1;
1531    tr_ptrArray tmp;
1532    const char ** events;
1533    const char * str = NULL;
1534
1535    assert( tier != NULL );
1536    assert( tr_isTorrent( tier->tor ) );
1537
1538    /* special case #1: if "stopped" is in the queue, ignore everything before it */
1539    events = (const char**) tr_ptrArrayPeek( &tier->announceEvents, &n );
1540    if( pos == -1 ) {
1541        for( i=0; i<n; ++i )
1542            if( !strcmp( events[i], "stopped" ) )
1543                break;
1544        if( i <  n )
1545            pos = i;
1546    }
1547
1548    /* special case #2: don't use empty strings if something follows them */
1549    if( pos == -1 ) {
1550        for( i = 0; i < n; ++i )
1551            if( *events[i] )
1552                break;
1553        if( i < n )
1554            pos = i;
1555    }
1556
1557    /* default: use the next in the queue */
1558    if( ( pos == -1 ) && ( n > 0 ) )
1559        pos = 0;
1560
1561    /* special case #3: if there are duplicate requests in a row, skip to the last one */
1562    if( pos >= 0 ) {
1563        for( i=pos+1; i<n; ++i )
1564            if( strcmp( events[pos], events[i] ) )
1565                break;
1566        pos = i - 1;
1567    }
1568
1569    /* special case #4: BEP 21: "In order to tell the tracker that a peer is a
1570     * partial seed, it MUST send an event=paused parameter in every
1571     * announce while it is a partial seed." */
1572    str = pos>=0 ? events[pos] : NULL;
1573    if( tr_cpGetStatus( &tier->tor->completion ) == TR_PARTIAL_SEED )
1574        if( !str || strcmp( str, "stopped" ) )
1575            str = "paused";
1576
1577#if 0
1578for( i=0; i<n; ++i ) fprintf( stderr, "(%d)\"%s\" ", i, events[i] );
1579fprintf( stderr, "\n" );
1580fprintf( stderr, "using (%d)\"%s\"\n", pos, events[pos] );
1581if( strcmp( events[pos], str ) ) fprintf( stderr, "...but really using [%s]\n", str );
1582#endif
1583
1584    /* announceEvents array upkeep */
1585    tmp = TR_PTR_ARRAY_INIT;
1586    for( i=pos+1; i<n; ++i )
1587        tr_ptrArrayAppend( &tmp, (void*)events[i] );
1588    tr_ptrArrayDestruct( &tier->announceEvents, NULL );
1589    tier->announceEvents = tmp;
1590
1591    return str;
1592}
1593
1594static void
1595tierAnnounce( tr_announcer * announcer, tr_tier * tier )
1596{
1597    const char * announceEvent = getNextAnnounceEvent( tier );
1598
1599    assert( !tier->isAnnouncing );
1600
1601    if( announceEvent != NULL )
1602    {
1603        char * url;
1604        struct announce_data * data;
1605        const tr_torrent * tor = tier->tor;
1606        const time_t now = tr_time( );
1607
1608        data = tr_new0( struct announce_data, 1 );
1609        data->torrentId = tr_torrentId( tor );
1610        data->tierId = tier->key;
1611        data->isRunningOnSuccess = tor->isRunning;
1612        data->timeSent = now;
1613        data->event = announceEvent;
1614        url = createAnnounceURL( announcer, tor, tier, data->event );
1615
1616        tier->isAnnouncing = TRUE;
1617        tier->lastAnnounceStartTime = now;
1618        --announcer->slotsAvailable;
1619        tr_webRun( announcer->session, url, NULL, onAnnounceDone, data );
1620
1621        tr_free( url );
1622    }
1623}
1624
1625static tr_bool
1626parseScrapeResponse( tr_tier     * tier,
1627                     const char  * response,
1628                     size_t        responseLen,
1629                     char        * result,
1630                     size_t        resultlen )
1631{
1632    tr_bool success = FALSE;
1633    tr_benc benc, *files;
1634    const int bencLoaded = !tr_bencLoad( response, responseLen, &benc, NULL );
1635    if( bencLoaded && tr_bencDictFindDict( &benc, "files", &files ) )
1636    {
1637        const char * key;
1638        tr_benc * val;
1639        int i = 0;
1640        while( tr_bencDictChild( files, i++, &key, &val ))
1641        {
1642            int64_t intVal;
1643            tr_benc * flags;
1644
1645            if( memcmp( tier->tor->info.hash, key, SHA_DIGEST_LENGTH ) )
1646                continue;
1647
1648            success = TRUE;
1649            publishErrorClear( tier );
1650
1651            if( ( tr_bencDictFindInt( val, "complete", &intVal ) ) )
1652                tier->currentTracker->seederCount = intVal;
1653
1654            if( ( tr_bencDictFindInt( val, "incomplete", &intVal ) ) )
1655                tier->currentTracker->leecherCount = intVal;
1656
1657            if( ( tr_bencDictFindInt( val, "downloaded", &intVal ) ) )
1658                tier->currentTracker->downloadCount = intVal;
1659
1660            if( ( tr_bencDictFindInt( val, "downloaders", &intVal ) ) )
1661                tier->currentTracker->downloaderCount = intVal;
1662
1663            if( tr_bencDictFindDict( val, "flags", &flags ) )
1664                if( ( tr_bencDictFindInt( flags, "min_request_interval", &intVal ) ) )
1665                    tier->scrapeIntervalSec = MAX( DEFAULT_SCRAPE_INTERVAL_SEC, (int)intVal );
1666
1667            tr_tordbg( tier->tor,
1668                       "Scrape successful. Rescraping in %d seconds.",
1669                       tier->scrapeIntervalSec );
1670        }
1671    }
1672
1673    if( bencLoaded )
1674        tr_bencFree( &benc );
1675
1676    if( success )
1677        tr_strlcpy( result, _( "Success" ), resultlen );
1678    else
1679        tr_strlcpy( result, _( "Error parsing response" ), resultlen );
1680
1681    return success;
1682}
1683
1684static void
1685onScrapeDone( tr_session   * session,
1686              long           responseCode,
1687              const void   * response,
1688              size_t         responseLen,
1689              void         * vdata )
1690{
1691    tr_bool success = FALSE;
1692    tr_announcer * announcer = session->announcer;
1693    struct announce_data * data = vdata;
1694    tr_tier * tier = getTier( announcer, data->torrentId, data->tierId );
1695    const time_t now = tr_time( );
1696
1697    if( announcer )
1698        ++announcer->slotsAvailable;
1699
1700    if( announcer && tier )
1701    {
1702        tier->isScraping = FALSE;
1703        tier->lastScrapeTime = now;
1704
1705        if( tier->currentTracker->host )
1706        {
1707            tr_host * host = tier->currentTracker->host;
1708            host->lastRequestTime = data->timeSent;
1709            host->lastResponseInterval = now - data->timeSent;
1710        }
1711
1712        if( 200 <= responseCode && responseCode <= 299 )
1713        {
1714            const int interval = tier->scrapeIntervalSec;
1715            tier->scrapeAt = now + interval;
1716
1717            if( responseCode == HTTP_OK )
1718                success = parseScrapeResponse( tier, response, responseLen,
1719                                               tier->lastScrapeStr, sizeof( tier->lastScrapeStr ) );
1720            else
1721                tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1722                             _( "tracker gave HTTP Response Code %1$ld (%2$s)" ),
1723                             responseCode, tr_webGetResponseStr( responseCode ) );
1724            tr_tordbg( tier->tor, "%s", tier->lastScrapeStr );
1725        }
1726        else if( 300 <= responseCode && responseCode <= 399 )
1727        {
1728            /* this shouldn't happen; libcurl should handle this */
1729            const int interval = 5;
1730            tier->scrapeAt = now + interval;
1731            tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1732                         "Got a redirect. Retrying in %d seconds", interval );
1733            tr_tordbg( tier->tor, "%s", tier->lastScrapeStr );
1734        }
1735        else
1736        {
1737            const int interval = getRetryInterval( tier->currentTracker->host );
1738
1739            /* Don't retry on a 4xx.
1740             * Retry at growing intervals on a 5xx */
1741            if( 400 <= responseCode && responseCode <= 499 )
1742                tier->scrapeAt = 0;
1743            else
1744                tier->scrapeAt = now + interval;
1745
1746            /* %1$ld - http status code, such as 404
1747             * %2$s - human-readable explanation of the http status code */
1748            if( !responseCode )
1749                tr_strlcpy( tier->lastScrapeStr, _( "tracker did not respond" ),
1750                            sizeof( tier->lastScrapeStr ) );
1751            else
1752                tr_snprintf( tier->lastScrapeStr, sizeof( tier->lastScrapeStr ),
1753                             _( "tracker gave HTTP Response Code %1$ld (%2$s)" ),
1754                             responseCode, tr_webGetResponseStr( responseCode ) );
1755        }
1756
1757        tier->lastScrapeSucceeded = success;
1758        tier->lastScrapeTimedOut = responseCode == 0;
1759
1760        if( success && tier->currentTracker->host )
1761            tier->currentTracker->host->lastSuccessfulRequest = now;
1762    }
1763
1764    tr_free( data );
1765}
1766
1767static void
1768tierScrape( tr_announcer * announcer, tr_tier * tier )
1769{
1770    char * url;
1771    const char * scrape;
1772    struct announce_data * data;
1773    const time_t now = tr_time( );
1774
1775    assert( tier );
1776    assert( !tier->isScraping );
1777    assert( tier->currentTracker != NULL );
1778    assert( tr_isTorrent( tier->tor ) );
1779
1780    data = tr_new0( struct announce_data, 1 );
1781    data->torrentId = tr_torrentId( tier->tor );
1782    data->tierId = tier->key;
1783
1784    scrape = tier->currentTracker->scrape;
1785
1786    url = tr_strdup_printf( "%s%cinfo_hash=%s",
1787                            scrape,
1788                            strchr( scrape, '?' ) ? '&' : '?',
1789                            tier->tor->info.hashEscaped );
1790
1791    tier->isScraping = TRUE;
1792    tier->lastScrapeStartTime = now;
1793    --announcer->slotsAvailable;
1794    dbgmsg( tier, "scraping \"%s\"", url );
1795    tr_webRun( announcer->session, url, NULL, onScrapeDone, data );
1796
1797    tr_free( url );
1798}
1799
1800static void
1801flushCloseMessages( tr_announcer * announcer )
1802{
1803    int i;
1804    const int n = tr_ptrArraySize( &announcer->stops );
1805
1806    for( i=0; i<n; ++i )
1807    {
1808        struct stop_message * stop = tr_ptrArrayNth( &announcer->stops, i );
1809        tr_webRun( announcer->session, stop->url, NULL, NULL, NULL );
1810        stopFree( stop );
1811    }
1812
1813    tr_ptrArrayClear( &announcer->stops );
1814}
1815
1816static tr_bool
1817tierNeedsToAnnounce( const tr_tier * tier, const time_t now )
1818{
1819    return !tier->isAnnouncing
1820        && !tier->isScraping
1821        && ( tier->announceAt != 0 )
1822        && ( tier->announceAt <= now )
1823        && ( tr_ptrArraySize( &tier->announceEvents ) != 0 );
1824}
1825
1826static tr_bool
1827tierNeedsToScrape( const tr_tier * tier, const time_t now )
1828{
1829    return ( !tier->isScraping )
1830        && ( tier->scrapeAt != 0 )
1831        && ( tier->scrapeAt <= now )
1832        && ( tier->currentTracker != NULL )
1833        && ( tier->currentTracker->scrape != NULL );
1834}
1835
1836static void
1837announceMore( tr_announcer * announcer )
1838{
1839    tr_torrent * tor = NULL;
1840    const time_t now = tr_time( );
1841
1842    if( announcer->slotsAvailable > 0 )
1843    {
1844        int i;
1845        int n;
1846        tr_ptrArray announceMe = TR_PTR_ARRAY_INIT;
1847        tr_ptrArray scrapeMe = TR_PTR_ARRAY_INIT;
1848
1849        /* build a list of tiers that need to be announced */
1850        while(( tor = tr_torrentNext( announcer->session, tor ))) {
1851            if( tor->tiers ) {
1852                n = tr_ptrArraySize( &tor->tiers->tiers );
1853                for( i=0; i<n; ++i ) {
1854                    tr_tier * tier = tr_ptrArrayNth( &tor->tiers->tiers, i );
1855                    if( tierNeedsToAnnounce( tier, now ) )
1856                        tr_ptrArrayAppend( &announceMe, tier );
1857                    else if( tierNeedsToScrape( tier, now ) )
1858                        tr_ptrArrayAppend( &scrapeMe, tier );
1859                }
1860            }
1861        }
1862
1863        /* if there are more tiers than slots available, prioritize */
1864        n = tr_ptrArraySize( &announceMe );
1865        if( n > announcer->slotsAvailable )
1866            qsort( tr_ptrArrayBase( &announceMe ), n, sizeof( tr_tier * ), compareTiers );
1867
1868        /* announce some */
1869        n = MIN( tr_ptrArraySize( &announceMe ), announcer->slotsAvailable );
1870        for( i=0; i<n; ++i ) {
1871            tr_tier * tier = tr_ptrArrayNth( &announceMe, i );
1872            dbgmsg( tier, "announcing tier %d of %d", i, n );
1873            tierAnnounce( announcer, tier );
1874        }
1875
1876        /* scrape some */
1877        n = MIN( tr_ptrArraySize( &scrapeMe ), announcer->slotsAvailable );
1878        for( i=0; i<n; ++i ) {
1879            tr_tier * tier = tr_ptrArrayNth( &scrapeMe, i );
1880            dbgmsg( tier, "scraping tier %d of %d", (i+1), n );
1881            tierScrape( announcer, tier );
1882        }
1883
1884#if 0
1885char timebuf[64];
1886tr_getLogTimeStr( timebuf, 64 );
1887fprintf( 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) );
1888#endif
1889
1890        /* cleanup */
1891        tr_ptrArrayDestruct( &scrapeMe, NULL );
1892        tr_ptrArrayDestruct( &announceMe, NULL );
1893    }
1894
1895    tor = NULL;
1896    while(( tor = tr_torrentNext( announcer->session, tor ))) {
1897        if( tor->dhtAnnounceAt <= now ) {
1898            if( tor->isRunning && tr_torrentAllowsDHT(tor) ) {
1899                int rc;
1900                rc = tr_dhtAnnounce(tor, AF_INET, 1);
1901                if(rc == 0)
1902                    /* The DHT is not ready yet.  Try again soon. */
1903                    tor->dhtAnnounceAt = now + 5 + tr_cryptoWeakRandInt( 5 );
1904                else
1905                    /* We should announce at least once every 30 minutes. */
1906                    tor->dhtAnnounceAt =
1907                        now + 25 * 60 + tr_cryptoWeakRandInt( 3 * 60 );
1908            }
1909        }
1910
1911        if( tor->dhtAnnounce6At <= now ) {
1912            if( tor->isRunning && tr_torrentAllowsDHT(tor) ) {
1913                int rc;
1914                rc = tr_dhtAnnounce(tor, AF_INET6, 1);
1915                if(rc == 0)
1916                    tor->dhtAnnounce6At = now + 5 + tr_cryptoWeakRandInt( 5 );
1917                else
1918                    tor->dhtAnnounce6At =
1919                        now + 25 * 60 + tr_cryptoWeakRandInt( 3 * 60 );
1920            }
1921        }
1922    }
1923
1924    /* Local Peer Discovery */
1925    if( announcer->lpdHouseKeepingAt <= now )
1926    {
1927        tr_lpdAnnounceMore( now, LPD_HOUSEKEEPING_INTERVAL_SECS );
1928
1929        /* reschedule more LDS announces for ( the future + jitter ) */
1930        announcer->lpdHouseKeepingAt =
1931            calcRescheduleWithJitter( LPD_HOUSEKEEPING_INTERVAL_SECS );
1932    }
1933}
1934
1935static void
1936onUpkeepTimer( int foo UNUSED, short bar UNUSED, void * vannouncer )
1937{
1938    tr_announcer * announcer = vannouncer;
1939    tr_sessionLock( announcer->session );
1940
1941    /* maybe send out some "stopped" messages for closed torrents */
1942    flushCloseMessages( announcer );
1943
1944    /* maybe send out some announcements to trackers */
1945    announceMore( announcer );
1946
1947    /* set up the next timer */
1948    tr_timerAdd( announcer->upkeepTimer, UPKEEP_INTERVAL_SECS, 0 );
1949
1950    tr_sessionUnlock( announcer->session );
1951}
1952
1953/***
1954****
1955***/
1956
1957tr_tracker_stat *
1958tr_announcerStats( const tr_torrent * torrent,
1959                   int              * setmeTrackerCount )
1960{
1961    int i;
1962    int n;
1963    int out = 0;
1964    int tierCount;
1965    tr_tracker_stat * ret;
1966    const time_t now = tr_time( );
1967
1968    assert( tr_isTorrent( torrent ) );
1969
1970    /* count the trackers... */
1971    for( i=n=0, tierCount=tr_ptrArraySize( &torrent->tiers->tiers ); i<tierCount; ++i ) {
1972        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1973        n += tr_ptrArraySize( &tier->trackers );
1974    }
1975
1976    /* alloc the stats */
1977    *setmeTrackerCount = n;
1978    ret = tr_new0( tr_tracker_stat, n );
1979
1980    /* populate the stats */
1981    for( i=0, tierCount=tr_ptrArraySize( &torrent->tiers->tiers ); i<tierCount; ++i )
1982    {
1983        int j;
1984        const tr_tier * tier = tr_ptrArrayNth( &torrent->tiers->tiers, i );
1985        n = tr_ptrArraySize( &tier->trackers );
1986        for( j=0; j<n; ++j )
1987        {
1988            const tr_tracker_item * tracker = tr_ptrArrayNth( (tr_ptrArray*)&tier->trackers, j );
1989            tr_tracker_stat * st = ret + out++;
1990
1991            st->id = tracker->id;
1992            tr_strlcpy( st->host, tracker->host->name, sizeof( st->host ) );
1993            tr_strlcpy( st->announce, tracker->announce, sizeof( st->announce ) );
1994            st->tier = i;
1995            st->isBackup = tracker != tier->currentTracker;
1996            st->lastScrapeStartTime = tier->lastScrapeStartTime;
1997
1998            st->seederCount = tracker->seederCount;
1999            st->leecherCount = tracker->leecherCount;
2000            st->downloadCount = tracker->downloadCount;
2001
2002            if( st->isBackup )
2003            {
2004                st->scrapeState = TR_TRACKER_INACTIVE;
2005                st->announceState = TR_TRACKER_INACTIVE;
2006                st->nextScrapeTime = 0;
2007                st->nextAnnounceTime = 0;
2008            }
2009            else
2010            {
2011                if(( st->hasScraped = tier->lastScrapeTime != 0 )) {
2012                    st->lastScrapeTime = tier->lastScrapeTime;
2013                    st->lastScrapeSucceeded = tier->lastScrapeSucceeded;
2014                    st->lastScrapeTimedOut = tier->lastScrapeTimedOut;
2015                    tr_strlcpy( st->lastScrapeResult, tier->lastScrapeStr, sizeof( st->lastScrapeResult ) );
2016                }
2017
2018                if( tier->isScraping )
2019                    st->scrapeState = TR_TRACKER_ACTIVE;
2020                else if( !tier->scrapeAt )
2021                    st->scrapeState = TR_TRACKER_INACTIVE;
2022                else if( tier->scrapeAt > now )
2023                {
2024                    st->scrapeState = TR_TRACKER_WAITING;
2025                    st->nextScrapeTime = tier->scrapeAt;
2026                }
2027                else
2028                    st->scrapeState = TR_TRACKER_QUEUED;
2029
2030                st->lastAnnounceStartTime = tier->lastAnnounceStartTime;
2031
2032                if(( st->hasAnnounced = tier->lastAnnounceTime != 0 )) {
2033                    st->lastAnnounceTime = tier->lastAnnounceTime;
2034                    tr_strlcpy( st->lastAnnounceResult, tier->lastAnnounceStr, sizeof( st->lastAnnounceResult ) );
2035                    st->lastAnnounceSucceeded = tier->lastAnnounceSucceeded;
2036                    st->lastAnnounceTimedOut = tier->lastAnnounceTimedOut;
2037                    st->lastAnnouncePeerCount = tier->lastAnnouncePeerCount;
2038                }
2039
2040                if( tier->isAnnouncing )
2041                    st->announceState = TR_TRACKER_ACTIVE;
2042                else if( !torrent->isRunning || !tier->announceAt )
2043                    st->announceState = TR_TRACKER_INACTIVE;
2044                else if( tier->announceAt > now )
2045                {
2046                    st->announceState = TR_TRACKER_WAITING;
2047                    st->nextAnnounceTime = tier->announceAt;
2048                }
2049                else
2050                    st->announceState = TR_TRACKER_QUEUED;
2051            }
2052        }
2053    }
2054
2055    return ret;
2056}
2057
2058void
2059tr_announcerStatsFree( tr_tracker_stat * trackers,
2060                       int trackerCount UNUSED )
2061{
2062    tr_free( trackers );
2063}
Note: See TracBrowser for help on using the repository browser.