source: trunk/libtransmission/tracker.c @ 6971

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

janitorial.
(1) re-enable `deflate' in transmission-remote iff libz is installed
(2) change c++-style comments to c-style comments
(3) add positional arguments to a couple of libT strings marked for translation

  • Property svn:keywords set to Date Rev Author Id
File size: 32.6 KB
Line 
1/*
2 * This file Copyright (C) 2007-2008 Charles Kerr <charles@rebelbase.com>
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: tracker.c 6971 2008-10-27 18:09:15Z charles $
11 */
12
13#include <assert.h>
14#include <stdlib.h>
15#include <string.h> /* strcmp, strchr */
16
17#include <event.h>
18
19#include "transmission.h"
20#include "bencode.h"
21#include "crypto.h"
22#include "completion.h"
23#include "net.h"
24#include "publish.h"
25#include "resume.h"
26#include "torrent.h"
27#include "tracker.h"
28#include "trevent.h"
29#include "utils.h"
30#include "web.h"
31
32enum
33{
34    /* the announceAt fields are set to this when the action is disabled */
35    TR_TRACKER_STOPPED = 0,
36
37    /* the announceAt fields are set to this when the action is in progress */
38    TR_TRACKER_BUSY = 1,
39
40    HTTP_OK = 200,
41
42    /* seconds between tracker pulses */
43    PULSE_INTERVAL_MSEC = 1000,
44
45    /* unless the tracker says otherwise, rescrape this frequently */
46    DEFAULT_SCRAPE_INTERVAL_SEC = ( 60 * 15 ),
47
48    /* unless the tracker says otherwise, this is the announce interval */
49    DEFAULT_ANNOUNCE_INTERVAL_SEC = ( 60 * 4 ),
50
51    /* unless the tracker says otherwise, this is the announce min_interval */
52    DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC = ( 60 * 2 ),
53
54    /* how long to wait before a rescrape the first time we get an error */
55    FIRST_SCRAPE_RETRY_INTERVAL_SEC = 30,
56
57    /* how long to wait before a reannounce the first time we get an error */
58    FIRST_ANNOUNCE_RETRY_INTERVAL_SEC = 30,
59
60    /* the value of the 'numwant' argument passed in tracker requests. */
61    NUMWANT = 80,
62
63    /* the length of the 'key' argument passed in tracker requests */
64    KEYLEN = 10
65};
66
67/**
68***
69**/
70
71struct tr_tracker
72{
73    unsigned int    isRunning : 1;
74
75    uint8_t         randOffset;
76
77    /* sent as the "key" argument in tracker requests
78       to verify us if our IP address changes.
79       This is immutable for the life of the tracker object. */
80    char    key_param[KEYLEN + 1];
81
82    /* these are set from the latest scrape or tracker response */
83    int    announceIntervalSec;
84    int    announceMinIntervalSec;
85    int    scrapeIntervalSec;
86    int    retryScrapeIntervalSec;
87    int    retryAnnounceIntervalSec;
88
89    /* index into the torrent's tr_info.trackers array */
90    int               trackerIndex;
91
92    tr_session *      session;
93
94    tr_publisher_t *  publisher;
95
96    /* torrent hash string */
97    uint8_t    hash[SHA_DIGEST_LENGTH];
98    char       escaped[SHA_DIGEST_LENGTH * 3 + 1];
99    char *     name;
100
101    /* corresponds to the peer_id sent as a tracker request parameter.
102       one tracker admin says: "When the same torrent is opened and
103       closed and opened again without quitting Transmission ...
104       change the peerid. It would help sometimes if a stopped event
105       was missed to ensure that we didn't think someone was cheating. */
106    uint8_t *  peer_id;
107
108    /* these are set from the latest tracker response... -1 is 'unknown' */
109    int       timesDownloaded;
110    int       seederCount;
111    int       leecherCount;
112    char *    trackerID;
113
114    time_t    manualAnnounceAllowedAt;
115    time_t    reannounceAt;
116
117    /* 0==never, 1==in progress, other values==when to scrape */
118    time_t    scrapeAt;
119
120    time_t    lastScrapeTime;
121    long      lastScrapeResponse;
122
123    time_t    lastAnnounceTime;
124    long      lastAnnounceResponse;
125};
126
127#define dbgmsg( name, ... ) \
128    do { \
129        if( tr_deepLoggingIsActive( ) ) \
130            tr_deepLog( __FILE__, __LINE__, name, __VA_ARGS__ ); \
131    } while( 0 )
132
133/***
134****
135***/
136
137static const tr_tracker_info *
138getCurrentAddressFromTorrent( tr_tracker *       t,
139                              const tr_torrent * tor )
140{
141    /* user might have removed trackers,
142     * so check to make sure our current index is in-bounds */
143    if( t->trackerIndex >= tor->info.trackerCount )
144        t->trackerIndex = 0;
145
146    assert( t->trackerIndex >= 0 );
147    assert( t->trackerIndex < tor->info.trackerCount );
148    return tor->info.trackers + t->trackerIndex;
149}
150
151static const tr_tracker_info *
152getCurrentAddress( tr_tracker * t )
153{
154    const tr_torrent * torrent;
155
156    if( ( torrent = tr_torrentFindFromHash( t->session, t->hash ) ) )
157        return getCurrentAddressFromTorrent( t, torrent );
158    return NULL;
159}
160
161static int
162trackerSupportsScrape( tr_tracker *       t,
163                       const tr_torrent * tor )
164{
165    const tr_tracker_info * info = getCurrentAddressFromTorrent( t, tor );
166
167    return info && info->scrape;
168}
169
170/***
171****
172***/
173
174static tr_tracker *
175findTracker( tr_session *    session,
176             const uint8_t * hash )
177{
178    tr_torrent * torrent = tr_torrentFindFromHash( session, hash );
179
180    return torrent ? torrent->tracker : NULL;
181}
182
183/***
184****  PUBLISH
185***/
186
187static const tr_tracker_event emptyEvent = { 0, NULL, NULL, NULL, 0, 0 };
188
189static void
190publishMessage( tr_tracker * t,
191                const char * msg,
192                int          type )
193{
194    if( t )
195    {
196        tr_tracker_event event = emptyEvent;
197        event.hash = t->hash;
198        event.messageType = type;
199        event.text = msg;
200        tr_publisherPublish( t->publisher, t, &event );
201    }
202}
203
204static void
205publishErrorClear( tr_tracker * t )
206{
207    publishMessage( t, NULL, TR_TRACKER_ERROR_CLEAR );
208}
209
210static void
211publishErrorMessageAndStop( tr_tracker * t,
212                            const char * msg )
213{
214    t->isRunning = 0;
215    publishMessage( t, msg, TR_TRACKER_ERROR );
216}
217
218static void
219publishWarning( tr_tracker * t,
220                const char * msg )
221{
222    publishMessage( t, msg, TR_TRACKER_WARNING );
223}
224
225static void
226publishNewPeers( tr_tracker * t,
227                 int          allAreSeeds,
228                 void *       compact,
229                 int          compactLen )
230{
231    tr_tracker_event event = emptyEvent;
232
233    event.hash = t->hash;
234    event.messageType = TR_TRACKER_PEERS;
235    event.allAreSeeds = allAreSeeds;
236    event.compact = compact;
237    event.compactLen = compactLen;
238    if( compactLen )
239        tr_publisherPublish( t->publisher, t, &event );
240}
241
242/***
243****
244***/
245
246static void onReqDone( tr_session * session );
247
248static int
249updateAddresses( tr_tracker * t,
250                 int          success )
251{
252    int          retry;
253
254    tr_torrent * torrent = tr_torrentFindFromHash( t->session, t->hash );
255
256    if( success )
257    {
258        /* multitracker spec: "if a connection with a tracker is
259           successful, it will be moved to the front of the tier." */
260        t->trackerIndex = tr_torrentPromoteTracker( torrent,
261                                                    t->trackerIndex );
262        retry = FALSE; /* we succeeded; no need to retry */
263    }
264    else if( ++t->trackerIndex >= torrent->info.trackerCount )
265    {
266        t->trackerIndex = 0;
267        retry = FALSE; /* we've tried them all */
268    }
269    else
270    {
271        const tr_tracker_info * n = getCurrentAddressFromTorrent( t,
272                                                                  torrent );
273        tr_ninf( t->name, _( "Trying tracker \"%s\"" ), n->announce );
274        retry = TRUE;
275    }
276
277    return retry;
278}
279
280/* Convert to compact form */
281static uint8_t *
282parseOldPeers( tr_benc * bePeers,
283               size_t *  byteCount )
284{
285    int       i;
286    uint8_t * compact, *walk;
287    const int peerCount = bePeers->val.l.count;
288
289    assert( bePeers->type == TYPE_LIST );
290
291    compact = tr_new( uint8_t, peerCount * 6 );
292
293    for( i = 0, walk = compact; i < peerCount; ++i )
294    {
295        const char *   s;
296        int64_t        itmp;
297        struct in_addr addr;
298        tr_port_t      port;
299        tr_benc *      peer = &bePeers->val.l.vals[i];
300
301        if( !tr_bencDictFindStr( peer, "ip",
302                                 &s ) || tr_netResolve( s, &addr ) )
303            continue;
304
305        memcpy( walk, &addr, 4 );
306        walk += 4;
307
308        if( !tr_bencDictFindInt( peer, "port",
309                                 &itmp ) || itmp < 0 || itmp > 0xffff )
310            continue;
311
312        port = htons( itmp );
313        memcpy( walk, &port, 2 );
314        walk += 2;
315    }
316
317    *byteCount = peerCount * 6;
318    return compact;
319}
320
321static void
322onStoppedResponse( tr_session *                 session,
323                   long            responseCode UNUSED,
324                   const void    * response     UNUSED,
325                   size_t          responseLen  UNUSED,
326                   void *                       torrent_hash  )
327{
328    tr_tracker * t = findTracker( session, torrent_hash );
329    if( t )
330    {
331        const time_t now = time( NULL );
332
333        t->reannounceAt = TR_TRACKER_STOPPED;
334        t->manualAnnounceAllowedAt = TR_TRACKER_STOPPED;
335
336        if( t->scrapeAt <= now )
337            t->scrapeAt = now + t->scrapeIntervalSec + t->randOffset;
338    }
339
340    dbgmsg( NULL, "got a response to some `stop' message" );
341    onReqDone( session );
342    tr_free( torrent_hash );
343}
344
345static void
346onTrackerResponse( tr_session * session,
347                   long         responseCode,
348                   const void * response,
349                   size_t       responseLen,
350                   void *       torrent_hash )
351{
352    int retry;
353    int success = FALSE;
354    int scrapeFields = 0;
355    tr_tracker * t;
356
357    onReqDone( session );
358    t = findTracker( session, torrent_hash );
359    tr_free( torrent_hash );
360    if( !t ) /* tracker's been closed */
361        return;
362
363    dbgmsg( t->name, "tracker response: %ld", responseCode );
364    tr_ndbg( t->name, "tracker response: %ld", responseCode );
365    t->lastAnnounceResponse = responseCode;
366
367    if( responseCode == HTTP_OK )
368    {
369        tr_benc   benc;
370        const int bencLoaded = !tr_bencLoad( response, responseLen,
371                                             &benc, NULL );
372        publishErrorClear( t );
373        if( bencLoaded && tr_bencIsDict( &benc ) )
374        {
375            tr_benc *    tmp;
376            int64_t      i;
377            int          incomplete = -1;
378            const char * str;
379
380            success = TRUE;
381            t->retryAnnounceIntervalSec = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
382
383            if( ( tr_bencDictFindStr( &benc, "failure reason", &str ) ) )
384            {
385                publishMessage( t, str, TR_TRACKER_ERROR );
386                success = FALSE;
387            }
388
389            if( ( tr_bencDictFindStr( &benc, "warning message", &str ) ) )
390                publishWarning( t, str );
391
392            if( ( tr_bencDictFindInt( &benc, "interval", &i ) ) )
393            {
394                dbgmsg( t->name, "setting interval to %d", (int)i );
395                t->announceIntervalSec = i;
396            }
397
398            if( ( tr_bencDictFindInt( &benc, "min interval", &i ) ) )
399            {
400                dbgmsg( t->name, "setting min interval to %d", (int)i );
401                t->announceMinIntervalSec = i;
402            }
403
404            if( ( tr_bencDictFindStr( &benc, "tracker id", &str ) ) )
405                t->trackerID = tr_strdup( str );
406
407            if( ( tr_bencDictFindInt( &benc, "complete", &i ) ) )
408            {
409                ++scrapeFields;
410                t->seederCount = i;
411            }
412
413            if( ( tr_bencDictFindInt( &benc, "incomplete", &i ) ) )
414            {
415                ++scrapeFields;
416                t->leecherCount = incomplete = i;
417            }
418
419            if( ( tr_bencDictFindInt( &benc, "downloaded", &i ) ) )
420            {
421                ++scrapeFields;
422                t->timesDownloaded = i;
423            }
424
425            if( ( tmp = tr_bencDictFind( &benc, "peers" ) ) )
426            {
427                const int allAreSeeds = incomplete == 0;
428
429                if( tmp->type == TYPE_STR ) /* "compact" extension */
430                {
431                    publishNewPeers( t, allAreSeeds, tmp->val.s.s,
432                                     tmp->val.s.i );
433                }
434                else if( tmp->type == TYPE_LIST ) /* original protocol */
435                {
436                    size_t    byteCount = 0;
437                    uint8_t * compact = parseOldPeers( tmp, &byteCount );
438                    publishNewPeers( t, allAreSeeds, compact, byteCount );
439                    tr_free( compact );
440                }
441            }
442        }
443
444        if( bencLoaded )
445            tr_bencFree( &benc );
446    }
447    else
448    {
449        /* %1$ld - http status code, such as 404
450         * %2$s - human-readable explanation of the http status code */
451        char * buf = tr_strdup_printf( _( "Tracker request failed.  Got HTTP Status Code %1$ld (%2$s)" ),
452                                      responseCode,
453                                      tr_webGetResponseStr( responseCode ) );
454        publishWarning( t, buf );
455        tr_free( buf );
456    }
457
458    retry = updateAddresses( t, success );
459
460    /**
461    ***
462    **/
463
464    if( retry )
465        responseCode = 300;
466
467    if( 200 <= responseCode && responseCode <= 299 )
468    {
469        const int    interval = t->announceIntervalSec + t->randOffset;
470        const time_t now = time ( NULL );
471        dbgmsg( t->name, "request succeeded. reannouncing in %d seconds",
472                interval );
473
474        /* if the announce response was a superset of the scrape response,
475           treat this as both a successful announce AND scrape. */
476        if( scrapeFields >= 3 ) {
477            t->lastScrapeResponse = responseCode;
478            t->lastScrapeTime = now;
479            t->scrapeAt = now + t->scrapeIntervalSec + t->randOffset;
480        }
481
482        /* most trackers don't provide all the scrape responses, but do
483           provide most of them, so don't scrape too soon anyway */
484        if( ( scrapeFields == 2 ) && ( t->scrapeAt <= ( now + 120 ) ) ) {
485            t->scrapeAt = now + t->scrapeIntervalSec + t->randOffset;
486        }
487
488        t->reannounceAt = now + interval;
489        t->manualAnnounceAllowedAt = now + t->announceMinIntervalSec;
490
491        /* #319: save the .resume file after an announce so that, in case
492         * of a crash, our stats still match up with the tracker's stats */
493        tr_torrentSaveResume( tr_torrentFindFromHash( t->session, t->hash ) );
494    }
495    else if( 300 <= responseCode && responseCode <= 399 )
496    {
497        /* it's a redirect... updateAddresses() has already
498         * parsed the redirect, all that's left is to retry */
499        const int interval = 5;
500        dbgmsg( t->name, "got a redirect. retrying in %d seconds", interval );
501        t->reannounceAt = time( NULL ) + interval;
502        t->manualAnnounceAllowedAt = time( NULL ) +
503                                     t->announceMinIntervalSec;
504    }
505    else if( 400 <= responseCode && responseCode <= 499 )
506    {
507        /* The request could not be understood by the server due to
508         * malformed syntax. The client SHOULD NOT repeat the
509         * request without modifications. */
510        publishErrorMessageAndStop( t, _( "Tracker returned a 4xx message" ) );
511        t->manualAnnounceAllowedAt = ~(time_t)0;
512        t->reannounceAt = TR_TRACKER_STOPPED;
513    }
514    else if( 500 <= responseCode && responseCode <= 599 )
515    {
516        /* Response status codes beginning with the digit "5" indicate
517         * cases in which the server is aware that it has erred or is
518         * incapable of performing the request.  So we pause a bit and
519         * try again. */
520        t->manualAnnounceAllowedAt = ~(time_t)0;
521        t->reannounceAt = time( NULL ) + t->retryAnnounceIntervalSec;
522        t->retryAnnounceIntervalSec *= 2;
523    }
524    else
525    {
526        /* WTF did we get?? */
527        dbgmsg(
528            t->name,
529            "Invalid response from tracker... retrying in two minutes." );
530        t->manualAnnounceAllowedAt = ~(time_t)0;
531        t->reannounceAt = time( NULL ) + t->randOffset + 120;
532    }
533}
534
535static void
536onScrapeResponse( tr_session * session,
537                  long         responseCode,
538                  const void * response,
539                  size_t       responseLen,
540                  void *       torrent_hash )
541{
542    int          success = FALSE;
543    int          retry;
544    tr_tracker * t;
545
546    onReqDone( session );
547    t = findTracker( session, torrent_hash );
548    tr_free( torrent_hash );
549    if( !t ) /* tracker's been closed... */
550        return;
551
552    dbgmsg( t->name, "scrape response: %ld\n", responseCode );
553    tr_ndbg( t->name, "scrape response: %ld", responseCode );
554    t->lastScrapeResponse = responseCode;
555
556    if( responseCode == HTTP_OK )
557    {
558        tr_benc   benc, *files;
559        const int bencLoaded = !tr_bencLoad( response, responseLen,
560                                             &benc, NULL );
561        if( bencLoaded && tr_bencDictFindDict( &benc, "files", &files ) )
562        {
563            size_t i;
564            for( i = 0; i < files->val.l.count; i += 2 )
565            {
566                int64_t        itmp;
567                const uint8_t* hash =
568                    (const uint8_t*) files->val.l.vals[i].val.s.s;
569                tr_benc *      flags;
570                tr_benc *      tordict = &files->val.l.vals[i + 1];
571                if( memcmp( t->hash, hash, SHA_DIGEST_LENGTH ) )
572                    continue;
573
574                publishErrorClear( t );
575
576                if( ( tr_bencDictFindInt( tordict, "complete", &itmp ) ) )
577                    t->seederCount = itmp;
578
579                if( ( tr_bencDictFindInt( tordict, "incomplete", &itmp ) ) )
580                    t->leecherCount = itmp;
581
582                if( ( tr_bencDictFindInt( tordict, "downloaded", &itmp ) ) )
583                    t->timesDownloaded = itmp;
584
585                if( tr_bencDictFindDict( tordict, "flags", &flags ) )
586                    if( ( tr_bencDictFindInt( flags, "min_request_interval",
587                                              &itmp ) ) )
588                        t->scrapeIntervalSec = i;
589
590                /* as per ticket #1045, safeguard against trackers returning
591                 * a very low min_request_interval... */
592                if( t->scrapeIntervalSec < DEFAULT_SCRAPE_INTERVAL_SEC )
593                    t->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
594
595                tr_ndbg( t->name,
596                         "Scrape successful.  Rescraping in %d seconds.",
597                         t->scrapeIntervalSec );
598
599                success = TRUE;
600                t->retryScrapeIntervalSec = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
601            }
602        }
603
604        if( bencLoaded )
605            tr_bencFree( &benc );
606    }
607
608    retry = updateAddresses( t, success );
609
610    /**
611    ***
612    **/
613
614    if( retry )
615        responseCode = 300;
616
617    if( 200 <= responseCode && responseCode <= 299 )
618    {
619        const int interval = t->scrapeIntervalSec + t->randOffset;
620        dbgmsg( t->name, "request succeeded. rescraping in %d seconds",
621                interval );
622        tr_ndbg( t->name, "request succeeded. rescraping in %d seconds",
623                 interval );
624        t->scrapeAt = time( NULL ) + interval;
625    }
626    else if( 300 <= responseCode && responseCode <= 399 )
627    {
628        const int interval = 5;
629        dbgmsg( t->name, "got a redirect. retrying in %d seconds", interval );
630        t->scrapeAt = time( NULL ) + interval;
631    }
632    else
633    {
634        const int interval = t->retryScrapeIntervalSec + t->randOffset;
635        dbgmsg(
636            t->name,
637            "Tracker responded to scrape with %ld.  Retrying in %d seconds.",
638            responseCode,  interval );
639        t->retryScrapeIntervalSec *= 2;
640        t->scrapeAt = time( NULL ) + interval;
641    }
642}
643
644/***
645****
646***/
647
648enum
649{
650    TR_REQ_STARTED,
651    TR_REQ_COMPLETED,
652    TR_REQ_STOPPED,
653    TR_REQ_REANNOUNCE,
654    TR_REQ_SCRAPE,
655    TR_REQ_COUNT
656};
657
658struct tr_tracker_request
659{
660    uint8_t             torrent_hash[SHA_DIGEST_LENGTH];
661    int                 reqtype; /* TR_REQ_* */
662    char *              url;
663    tr_web_done_func *  done_func;
664    tr_session *        session;
665};
666
667static void
668freeRequest( struct tr_tracker_request * req )
669{
670    tr_free( req->url );
671    tr_free( req );
672}
673
674static void
675buildTrackerRequestURI( tr_tracker *       t,
676                        const tr_torrent * torrent,
677                        const char *       eventName,
678                        struct evbuffer *  buf )
679{
680    const int    isStopping = !strcmp( eventName, "stopped" );
681    const int    numwant = isStopping ? 0 : NUMWANT;
682    const char * ann = getCurrentAddressFromTorrent( t, torrent )->announce;
683
684    evbuffer_add_printf( buf, "%cinfo_hash=%s"
685                              "&peer_id=%s"
686                              "&port=%d"
687                              "&uploaded=%" PRIu64
688                        "&downloaded=%" PRIu64
689                        "&corrupt=%" PRIu64
690                        "&left=%" PRIu64
691                        "&compact=1"
692                        "&numwant=%d"
693                        "&key=%s"
694                        "%s%s"
695                        "%s%s",
696                        strchr( ann, '?' ) ? '&' : '?',
697                        t->escaped,
698                        t->peer_id,
699                        tr_sessionGetPeerPort( t->session ),
700                        torrent->uploadedCur,
701                        torrent->downloadedCur,
702                        torrent->corruptCur,
703                        tr_cpLeftUntilComplete( torrent->completion ),
704                        numwant,
705                        t->key_param,
706                        ( ( eventName && *eventName ) ? "&event=" : "" ),
707                        ( ( eventName && *eventName ) ? eventName : "" ),
708                        ( ( t->trackerID
709                          && *t->trackerID ) ? "&trackerid=" : "" ),
710                        ( ( t->trackerID
711                          && *t->trackerID ) ? t->trackerID : "" ) );
712}
713
714static struct tr_tracker_request*
715createRequest(                 tr_session * session,
716                               tr_tracker * tracker,
717                           int reqtype )
718{
719    static const char*          strings[] =
720    { "started", "completed", "stopped", "", "err" };
721    const tr_torrent *          torrent = tr_torrentFindFromHash(
722        session, tracker->hash );
723    const tr_tracker_info *     address = getCurrentAddressFromTorrent(
724        tracker, torrent );
725    const int                   isStopping = reqtype == TR_REQ_STOPPED;
726    struct tr_tracker_request * req;
727    struct evbuffer *           url;
728
729    url = evbuffer_new( );
730    evbuffer_add_printf( url, "%s", address->announce );
731    buildTrackerRequestURI( tracker, torrent, strings[reqtype], url );
732
733    req = tr_new0( struct tr_tracker_request, 1 );
734    req->session = session;
735    req->reqtype = reqtype;
736    req->done_func =  isStopping ? onStoppedResponse : onTrackerResponse;
737    req->url = tr_strdup( EVBUFFER_DATA( url ) );
738    memcpy( req->torrent_hash, tracker->hash, SHA_DIGEST_LENGTH );
739
740    evbuffer_free( url );
741    return req;
742}
743
744static struct tr_tracker_request*
745createScrape( tr_session * session,
746              tr_tracker * tracker )
747{
748    const tr_tracker_info *     a = getCurrentAddress( tracker );
749    struct tr_tracker_request * req;
750    struct evbuffer *           url = evbuffer_new( );
751
752    evbuffer_add_printf( url, "%s%cinfo_hash=%s",
753                         a->scrape, strchr( a->scrape, '?' ) ? '&' : '?',
754                         tracker->escaped );
755
756    req = tr_new0( struct tr_tracker_request, 1 );
757    req->session = session;
758    req->reqtype = TR_REQ_SCRAPE;
759    req->url = tr_strdup( EVBUFFER_DATA( url ) );
760    req->done_func = onScrapeResponse;
761    memcpy( req->torrent_hash, tracker->hash, SHA_DIGEST_LENGTH );
762
763    evbuffer_free( url );
764    return req;
765}
766
767struct tr_tracker_handle
768{
769    int         runningCount;
770    tr_timer *  pulseTimer;
771};
772
773static int trackerPulse( void * vsession );
774
775static void
776ensureGlobalsExist( tr_session * session )
777{
778    if( session->tracker == NULL )
779    {
780        session->tracker = tr_new0( struct tr_tracker_handle, 1 );
781        session->tracker->pulseTimer =
782            tr_timerNew( session, trackerPulse, session,
783                         PULSE_INTERVAL_MSEC );
784        dbgmsg( NULL, "creating tracker timer" );
785    }
786}
787
788void
789tr_trackerSessionClose( tr_session * session )
790{
791    if( session && session->tracker )
792    {
793        dbgmsg( NULL, "freeing tracker timer" );
794        tr_timerFree( &session->tracker->pulseTimer );
795        tr_free( session->tracker );
796        session->tracker = NULL;
797    }
798}
799
800/***
801****
802***/
803
804static void
805invokeRequest( void * vreq )
806{
807    struct tr_tracker_request * req = vreq;
808    tr_tracker *                t = findTracker( req->session,
809                                                 req->torrent_hash );
810
811    if( t )
812    {
813        const time_t now = time( NULL );
814
815        if( req->reqtype == TR_REQ_SCRAPE )
816        {
817            t->lastScrapeTime = now;
818            t->scrapeAt = TR_TRACKER_BUSY;
819        }
820        else
821        {
822            t->lastAnnounceTime = now;
823            t->reannounceAt = TR_TRACKER_BUSY;
824            t->manualAnnounceAllowedAt = TR_TRACKER_BUSY;
825        }
826    }
827
828    ++req->session->tracker->runningCount;
829
830    tr_webRun( req->session, req->url, NULL, req->done_func,
831              tr_memdup( req->torrent_hash, SHA_DIGEST_LENGTH ) );
832
833    freeRequest( req );
834}
835
836static void
837enqueueScrape( tr_session * session,
838               tr_tracker * tracker )
839{
840    struct tr_tracker_request * req;
841
842    req = createScrape( session, tracker );
843    tr_runInEventThread( session, invokeRequest, req );
844}
845
846static void
847enqueueRequest( tr_session * session,
848                tr_tracker * tracker,
849                int          reqtype )
850{
851    struct tr_tracker_request * req;
852
853    req = createRequest( session, tracker, reqtype );
854    tr_runInEventThread( session, invokeRequest, req );
855}
856
857static int
858trackerPulse( void * vsession )
859{
860    tr_session *               session = vsession;
861    struct tr_tracker_handle * th = session->tracker;
862    tr_torrent *               tor;
863    const time_t               now = time( NULL );
864
865    if( !session->tracker )
866        return FALSE;
867
868    if( th->runningCount )
869        dbgmsg( NULL, "tracker pulse... %d running", th->runningCount );
870
871    /* upkeep: queue periodic rescrape / reannounce */
872    for( tor = session->torrentList; tor; tor = tor->next )
873    {
874        tr_tracker * t = tor->tracker;
875
876        if( ( t->scrapeAt > 1 )
877          && ( t->scrapeAt <= now )
878          && ( trackerSupportsScrape( t, tor ) ) )
879        {
880            t->scrapeAt = TR_TRACKER_BUSY;
881            enqueueScrape( session, t );
882        }
883
884        if( ( t->reannounceAt > 1 )
885          && ( t->reannounceAt <= now )
886          && ( t->isRunning ) )
887        {
888            t->reannounceAt = TR_TRACKER_BUSY;
889            t->manualAnnounceAllowedAt = TR_TRACKER_BUSY;
890            enqueueRequest( session, t, TR_REQ_REANNOUNCE );
891        }
892    }
893
894    if( th->runningCount )
895        dbgmsg( NULL, "tracker pulse after upkeep... %d running",
896                th->runningCount );
897
898    /* free the tracker manager if no torrents are left */
899    if( ( session->tracker )
900      && ( session->tracker->runningCount < 1 )
901      && ( session->torrentList == NULL ) )
902    {
903        tr_trackerSessionClose( session );
904    }
905
906    /* if there are still running torrents (as indicated by
907     * the existence of the tracker manager) then keep the
908     * trackerPulse() timer alive */
909    return session->tracker != NULL;
910}
911
912static void
913onReqDone( tr_session * session )
914{
915    if( session->tracker )
916    {
917        --session->tracker->runningCount;
918        dbgmsg( NULL, "decrementing runningCount to %d",
919                session->tracker->runningCount );
920        trackerPulse( session );
921    }
922}
923
924/***
925****  LIFE CYCLE
926***/
927
928static void
929generateKeyParam( char * msg,
930                  int    len )
931{
932    int          i;
933    const char * pool = "abcdefghijklmnopqrstuvwxyz0123456789";
934    const int    poolSize = strlen( pool );
935
936    for( i = 0; i < len; ++i )
937        *msg++ = pool[tr_cryptoRandInt( poolSize )];
938    *msg = '\0';
939}
940
941static int
942is_rfc2396_alnum( char ch )
943{
944    return ( '0' <= ch && ch <= '9' )
945           || ( 'A' <= ch && ch <= 'Z' )
946           || ( 'a' <= ch && ch <= 'z' );
947}
948
949static void
950escape( char *          out,
951        const uint8_t * in,
952        int             in_len )                     /* rfc2396 */
953{
954    const uint8_t *end = in + in_len;
955
956    while( in != end )
957        if( is_rfc2396_alnum( *in ) )
958            *out++ = (char) *in++;
959        else
960            out += tr_snprintf( out, 4, "%%%02X", (unsigned int)*in++ );
961
962    *out = '\0';
963}
964
965tr_tracker *
966tr_trackerNew( const tr_torrent * torrent )
967{
968    const tr_info * info = &torrent->info;
969    tr_tracker *    t;
970
971    ensureGlobalsExist( torrent->session );
972
973    t = tr_new0( tr_tracker, 1 );
974    t->publisher = tr_publisherNew( );
975    t->session                  = torrent->session;
976    t->scrapeIntervalSec        = DEFAULT_SCRAPE_INTERVAL_SEC;
977    t->retryScrapeIntervalSec   = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
978    t->retryAnnounceIntervalSec = FIRST_ANNOUNCE_RETRY_INTERVAL_SEC;
979    t->announceIntervalSec      = DEFAULT_ANNOUNCE_INTERVAL_SEC;
980    t->announceMinIntervalSec   = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
981    t->timesDownloaded          = -1;
982    t->seederCount              = -1;
983    t->leecherCount             = -1;
984    t->lastAnnounceResponse     = -1;
985    t->lastScrapeResponse       = -1;
986    t->manualAnnounceAllowedAt  = ~(time_t)0;
987    t->name = tr_strdup( info->name );
988    t->randOffset = tr_cryptoRandInt( 30 );
989    memcpy( t->hash, info->hash, SHA_DIGEST_LENGTH );
990    escape( t->escaped, info->hash, SHA_DIGEST_LENGTH );
991    generateKeyParam( t->key_param, KEYLEN );
992
993    t->trackerIndex = 0;
994
995    if( trackerSupportsScrape( t, torrent ) )
996        t->scrapeAt = time( NULL ) + t->randOffset;
997
998    return t;
999}
1000
1001static void
1002onTrackerFreeNow( void * vt )
1003{
1004    tr_tracker * t = vt;
1005
1006    tr_publisherFree( &t->publisher );
1007    tr_free( t->name );
1008    tr_free( t->trackerID );
1009    tr_free( t->peer_id );
1010
1011    tr_free( t );
1012}
1013
1014/***
1015****  PUBLIC
1016***/
1017
1018void
1019tr_trackerFree( tr_tracker * t )
1020{
1021    if( t )
1022        tr_runInEventThread( t->session, onTrackerFreeNow, t );
1023}
1024
1025tr_publisher_tag
1026tr_trackerSubscribe( tr_tracker *     t,
1027                     tr_delivery_func func,
1028                     void *           user_data )
1029{
1030    return tr_publisherSubscribe( t->publisher, func, user_data );
1031}
1032
1033void
1034tr_trackerUnsubscribe( tr_tracker *     t,
1035                       tr_publisher_tag tag )
1036{
1037    if( t )
1038        tr_publisherUnsubscribe( t->publisher, tag );
1039}
1040
1041const tr_tracker_info *
1042tr_trackerGetAddress( tr_tracker * t )
1043{
1044    return getCurrentAddress( t );
1045}
1046
1047time_t
1048tr_trackerGetManualAnnounceTime( const struct tr_tracker * t )
1049{
1050    return t->isRunning ? t->manualAnnounceAllowedAt : 0;
1051}
1052
1053int
1054tr_trackerCanManualAnnounce( const tr_tracker * t )
1055{
1056    const time_t allow = tr_trackerGetManualAnnounceTime( t );
1057
1058    return allow && ( allow <= time( NULL ) );
1059}
1060
1061void
1062tr_trackerGetCounts( const tr_tracker * t,
1063                     int *              setme_completedCount,
1064                     int *              setme_leecherCount,
1065                     int *              setme_seederCount )
1066{
1067    if( setme_completedCount )
1068        *setme_completedCount = t->timesDownloaded;
1069
1070    if( setme_leecherCount )
1071        *setme_leecherCount = t->leecherCount;
1072
1073    if( setme_seederCount )
1074        *setme_seederCount = t->seederCount;
1075}
1076
1077void
1078tr_trackerStart( tr_tracker * t )
1079{
1080    if( t && !t->isRunning )
1081    {
1082        tr_free( t->peer_id );
1083        t->peer_id = tr_peerIdNew( );
1084
1085        t->isRunning = 1;
1086        enqueueRequest( t->session, t, TR_REQ_STARTED );
1087    }
1088}
1089
1090void
1091tr_trackerReannounce( tr_tracker * t )
1092{
1093    enqueueRequest( t->session, t, TR_REQ_REANNOUNCE );
1094}
1095
1096void
1097tr_trackerCompleted( tr_tracker * t )
1098{
1099    enqueueRequest( t->session, t, TR_REQ_COMPLETED );
1100}
1101
1102void
1103tr_trackerStop( tr_tracker * t )
1104{
1105    if( t && t->isRunning )
1106    {
1107        t->isRunning = 0;
1108        t->reannounceAt = TR_TRACKER_STOPPED;
1109        t->manualAnnounceAllowedAt = TR_TRACKER_STOPPED;
1110        enqueueRequest( t->session, t, TR_REQ_STOPPED );
1111    }
1112}
1113
1114void
1115tr_trackerChangeMyPort( tr_tracker * t )
1116{
1117    if( t->isRunning )
1118        tr_trackerReannounce( t );
1119}
1120
1121void
1122tr_trackerStat( const tr_tracker * t,
1123                struct tr_stat *   setme )
1124{
1125    assert( t );
1126    assert( setme );
1127
1128    setme->lastScrapeTime = t->lastScrapeTime;
1129    setme->nextScrapeTime = t->scrapeAt;
1130    setme->lastAnnounceTime = t->lastAnnounceTime;
1131    setme->nextAnnounceTime = t->reannounceAt;
1132    setme->manualAnnounceTime = t->manualAnnounceAllowedAt;
1133
1134    if( t->lastScrapeResponse == -1 ) /* never been scraped */
1135        *setme->scrapeResponse = '\0';
1136    else
1137        tr_snprintf( setme->scrapeResponse,
1138                     sizeof( setme->scrapeResponse ),
1139                     "%s (%ld)",
1140                     tr_webGetResponseStr( t->lastScrapeResponse ),
1141                     t->lastScrapeResponse );
1142
1143    if( t->lastAnnounceResponse == -1 ) /* never been announced */
1144        *setme->announceResponse = '\0';
1145    else
1146        tr_snprintf( setme->announceResponse,
1147                     sizeof( setme->announceResponse ),
1148                     "%s (%ld)",
1149                     tr_webGetResponseStr( t->lastAnnounceResponse ),
1150                     t->lastAnnounceResponse );
1151}
1152
Note: See TracBrowser for help on using the repository browser.