source: branches/1.3x/libtransmission/tracker.c @ 6489

Last change on this file since 6489 was 6489, checked in by charles, 14 years ago

(1.3x) lots of C correctness tweaks suggested by sparse/cgcc

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