source: trunk/libtransmission/tracker.c @ 6412

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

rename `pulse' as peerPulse() and trackerPulse() to make backtraces easier to read

  • Property svn:keywords set to Date Rev Author Id
File size: 28.8 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 6412 2008-07-28 19:47:16Z 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
157tr_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, &benc, 0 );
326        publishErrorClear( t );
327        if( bencLoaded && tr_bencIsDict( &benc ) )
328        {
329            tr_benc * tmp;
330            int64_t i;
331            int incomplete = -1;
332            const char * str;
333
334            success = TRUE;
335            t->retryAnnounceIntervalSec = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
336
337            if(( tr_bencDictFindStr( &benc, "failure reason", &str ))) {
338                publishMessage( t, str, TR_TRACKER_ERROR );
339                success = FALSE;
340            }
341
342            if(( tr_bencDictFindStr( &benc, "warning message", &str )))
343                publishWarning( t, str );
344
345            if(( tr_bencDictFindInt( &benc, "interval", &i ))) {
346                dbgmsg( t->name, "setting interval to %d", (int)i );
347                t->announceIntervalSec = i;
348            }
349
350            if(( tr_bencDictFindInt( &benc, "min interval", &i ))) {
351                dbgmsg( t->name, "setting min interval to %d", (int)i );
352                t->announceMinIntervalSec = i;
353            }
354
355            if(( tr_bencDictFindStr( &benc, "tracker id", &str )))
356                t->trackerID = tr_strdup( str );
357
358            if(( tr_bencDictFindInt( &benc, "complete", &i )))
359                t->seederCount = i;
360
361            if(( tr_bencDictFindInt( &benc, "incomplete", &i )))
362                t->leecherCount = incomplete = i;
363
364            if(( tmp = tr_bencDictFind( &benc, "peers" )))
365            {
366                const int allAreSeeds = incomplete == 0;
367
368                if( tmp->type == TYPE_STR ) /* "compact" extension */
369                {
370                    publishNewPeers( t, allAreSeeds, tmp->val.s.s, tmp->val.s.i );
371                }
372                else if( tmp->type == TYPE_LIST ) /* original protocol */
373                {
374                    size_t byteCount = 0;
375                    uint8_t * compact = parseOldPeers( tmp, &byteCount );
376                    publishNewPeers( t, allAreSeeds, compact, byteCount );
377                    tr_free( compact );
378                }
379            }
380        }
381
382        if( bencLoaded )
383            tr_bencFree( &benc );
384    }
385
386    retry = updateAddresses( t, success );
387
388    /**
389    ***
390    **/
391
392    if( retry )
393        responseCode = 300;
394
395    if( 200<=responseCode && responseCode<=299 )
396    {
397        const int interval = t->announceIntervalSec + t->randOffset;
398        const time_t now = time ( NULL );
399        dbgmsg( t->name, "request succeeded. reannouncing in %d seconds", interval );
400        t->scrapeAt = now + t->scrapeIntervalSec + t->randOffset;
401        t->reannounceAt = now + interval;
402        t->manualAnnounceAllowedAt = now + t->announceMinIntervalSec;
403
404        /* #319: save the .resume file after an announce so that, in case
405         * of a crash, our stats still match up with the tracker's stats */
406        tr_torrentSaveResume( tr_torrentFindFromHash( t->session, t->hash ) );
407    }
408    else if( 300<=responseCode && responseCode<=399 )
409    {
410        /* it's a redirect... updateAddresses() has already
411         * parsed the redirect, all that's left is to retry */
412        const int interval = 5;
413        dbgmsg( t->name, "got a redirect. retrying in %d seconds", interval );
414        t->reannounceAt = time( NULL ) + interval;
415        t->manualAnnounceAllowedAt = time( NULL ) + t->announceMinIntervalSec;
416    }
417    else if( 400<=responseCode && responseCode<=499 )
418    {
419        /* The request could not be understood by the server due to
420         * malformed syntax. The client SHOULD NOT repeat the
421         * request without modifications. */
422        publishErrorMessageAndStop( t, _( "Tracker returned a 4xx message" ) );
423        t->manualAnnounceAllowedAt = ~(time_t)0;
424        t->reannounceAt = 0;
425    }
426    else if( 500<=responseCode && responseCode<=599 )
427    {
428        /* Response status codes beginning with the digit "5" indicate
429         * cases in which the server is aware that it has erred or is
430         * incapable of performing the request.  So we pause a bit and
431         * try again. */
432        t->manualAnnounceAllowedAt = ~(time_t)0;
433        t->reannounceAt = time( NULL ) + t->retryAnnounceIntervalSec;
434        t->retryAnnounceIntervalSec *= 2;
435    }
436    else
437    {
438        /* WTF did we get?? */
439        dbgmsg( t->name, "Invalid response from tracker... retrying in two minutes." );
440        t->manualAnnounceAllowedAt = ~(time_t)0;
441        t->reannounceAt = time( NULL ) + t->randOffset + 120;
442    }
443}
444
445static void
446onScrapeResponse( tr_session   * session,
447                  long           responseCode,
448                  const void   * response,
449                  size_t         responseLen,
450                  void         * torrent_hash )
451{
452    int success = FALSE;
453    int retry;
454    tr_tracker * t;
455
456    onReqDone( session );
457    t = findTracker( session, torrent_hash );
458    tr_free( torrent_hash );
459    if( !t ) /* tracker's been closed... */
460        return;
461
462    dbgmsg( t->name, "scrape response: %ld\n", responseCode );
463    tr_ndbg( t->name, "scrape response: %ld", responseCode );
464    t->lastScrapeResponse = responseCode;
465
466    if( responseCode == HTTP_OK )
467    {
468        tr_benc benc, *files;
469        const int bencLoaded = !tr_bencLoad( response, responseLen, &benc, 0 );
470        if( bencLoaded && tr_bencDictFindDict( &benc, "files", &files ) )
471        {
472            int i;
473            for( i=0; i<files->val.l.count; i+=2 )
474            {
475                int64_t itmp;
476                const uint8_t* hash =
477                    (const uint8_t*) files->val.l.vals[i].val.s.s;
478                tr_benc * flags;
479                tr_benc * tordict = &files->val.l.vals[i+1];
480                if( memcmp( t->hash, hash, SHA_DIGEST_LENGTH ) )
481                    continue;
482
483                publishErrorClear( t );
484
485                if(( tr_bencDictFindInt( tordict, "complete", &itmp )))
486                    t->seederCount = itmp;
487
488                if(( tr_bencDictFindInt( tordict, "incomplete", &itmp )))
489                    t->leecherCount = itmp;
490
491                if(( tr_bencDictFindInt( tordict, "downloaded", &itmp )))
492                    t->timesDownloaded = itmp;
493
494                if( tr_bencDictFindDict( tordict, "flags", &flags ))
495                    if(( tr_bencDictFindInt( flags, "min_request_interval", &itmp )))
496                        t->scrapeIntervalSec = i;
497
498                /* as per ticket #1045, safeguard against trackers returning
499                 * a very low min_request_interval... */
500                if( t->scrapeIntervalSec < DEFAULT_SCRAPE_INTERVAL_SEC )
501                    t->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
502
503                tr_ndbg( t->name, "Scrape successful.  Rescraping in %d seconds.",
504                         t->scrapeIntervalSec );
505
506                success = TRUE;
507                t->retryScrapeIntervalSec = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
508            }
509        }
510
511        if( bencLoaded )
512            tr_bencFree( &benc );
513    }
514
515    retry = updateAddresses( t, success );
516
517    /**
518    ***
519    **/
520
521    if( retry )
522        responseCode = 300;
523
524    if( 200<=responseCode && responseCode<=299 )
525    {
526        const int interval = t->scrapeIntervalSec + t->randOffset;
527        dbgmsg( t->name, "request succeeded. rescraping in %d seconds", interval );
528        tr_ndbg( t->name, "request succeeded. rescraping in %d seconds", interval );
529        t->scrapeAt = time( NULL ) + interval;
530    }
531    else if( 300<=responseCode && responseCode<=399 )
532    {
533        const int interval = 5;
534        dbgmsg( t->name, "got a redirect. retrying in %d seconds", interval );
535        t->scrapeAt = time( NULL ) + interval;
536    }
537    else
538    {
539        const int interval = t->retryScrapeIntervalSec + t->randOffset;
540        dbgmsg( t->name, "Tracker responded to scrape with %ld.  Retrying in %d seconds.",
541                   responseCode,  interval );
542        t->retryScrapeIntervalSec *= 2;
543        t->scrapeAt = time( NULL ) + interval;
544    }
545}
546
547/***
548****
549***/
550
551enum
552{
553    TR_REQ_STARTED,
554    TR_REQ_COMPLETED,
555    TR_REQ_STOPPED,
556    TR_REQ_REANNOUNCE,
557    TR_REQ_SCRAPE,
558    TR_REQ_COUNT
559};
560
561struct tr_tracker_request
562{
563    uint8_t torrent_hash[SHA_DIGEST_LENGTH];
564    int reqtype; /* TR_REQ_* */
565    char * url;
566    tr_web_done_func * done_func;
567    tr_session * session;
568};
569
570static void
571freeRequest( struct tr_tracker_request * req )
572{
573    tr_free( req->url );
574    tr_free( req );
575}
576
577static void
578buildTrackerRequestURI( tr_tracker        * t,
579                        const tr_torrent  * torrent,
580                        const char        * eventName,
581                        struct evbuffer   * buf )
582{
583    const int isStopping = !strcmp( eventName, "stopped" );
584    const int numwant = isStopping ? 0 : NUMWANT;
585    const char * ann = getCurrentAddressFromTorrent(t,torrent)->announce;
586   
587    evbuffer_add_printf( buf, "%cinfo_hash=%s"
588                              "&peer_id=%s"
589                              "&port=%d"
590                              "&uploaded=%"PRIu64
591                              "&downloaded=%"PRIu64
592                              "&corrupt=%"PRIu64
593                              "&left=%"PRIu64
594                              "&compact=1"
595                              "&numwant=%d"
596                              "&key=%s"
597                              "%s%s"
598                              "%s%s",
599        strchr(ann, '?') ? '&' : '?',
600        t->escaped,
601        t->peer_id,
602        tr_sessionGetPeerPort( t->session ),
603        torrent->uploadedCur,
604        torrent->downloadedCur,
605        torrent->corruptCur,
606        tr_cpLeftUntilComplete( torrent->completion ),
607        numwant,
608        t->key_param,
609        ( ( eventName && *eventName ) ? "&event=" : "" ),
610        ( ( eventName && *eventName ) ? eventName : "" ),
611        ( ( t->trackerID && *t->trackerID ) ? "&trackerid=" : "" ),
612        ( ( t->trackerID && *t->trackerID ) ? t->trackerID : "" ) );
613}
614
615static struct tr_tracker_request*
616createRequest( tr_session * session, tr_tracker * tracker, int reqtype )
617{
618    static const char* strings[] = { "started", "completed", "stopped", "", "err" };
619    const tr_torrent * torrent = tr_torrentFindFromHash( session, tracker->hash );
620    const tr_tracker_info * address = getCurrentAddressFromTorrent( tracker, torrent );
621    const int isStopping = reqtype == TR_REQ_STOPPED;
622    struct tr_tracker_request * req;
623    struct evbuffer * url;
624
625    url = evbuffer_new( );
626    evbuffer_add_printf( url, "%s", address->announce );
627    buildTrackerRequestURI( tracker, torrent, strings[reqtype], url );
628
629    req = tr_new0( struct tr_tracker_request, 1 );
630    req->session = session;
631    req->reqtype = reqtype;
632    req->done_func =  isStopping ? onStoppedResponse : onTrackerResponse;
633    req->url = tr_strdup( ( char * ) EVBUFFER_DATA( url ) );
634    memcpy( req->torrent_hash, tracker->hash, SHA_DIGEST_LENGTH );
635
636    evbuffer_free( url );
637    return req;
638}
639
640static struct tr_tracker_request*
641createScrape( tr_session * session, tr_tracker * tracker )
642{
643    const tr_tracker_info * a = getCurrentAddress( tracker );
644    struct tr_tracker_request * req;
645    struct evbuffer * url = evbuffer_new( );
646
647    evbuffer_add_printf( url, "%s%cinfo_hash=%s",
648                         a->scrape, strchr(a->scrape,'?')?'&':'?',
649                         tracker->escaped ); 
650
651    req = tr_new0( struct tr_tracker_request, 1 );
652    req->session = session;
653    req->reqtype = TR_REQ_SCRAPE;
654    req->url = tr_strdup( ( char * ) EVBUFFER_DATA( url ) );
655    req->done_func = onScrapeResponse;
656    memcpy( req->torrent_hash, tracker->hash, SHA_DIGEST_LENGTH );
657
658    evbuffer_free( url );
659    return req;
660}
661
662struct tr_tracker_handle
663{
664    unsigned int isShuttingDown : 1;
665    int runningCount;
666    tr_timer * pulseTimer;
667};
668
669static int trackerPulse( void * vsession );
670
671static void
672ensureGlobalsExist( tr_session * session )
673{
674    if( session->tracker == NULL )
675    {
676        session->tracker = tr_new0( struct tr_tracker_handle, 1 );
677        session->tracker->pulseTimer = tr_timerNew( session, trackerPulse, session, PULSE_INTERVAL_MSEC );
678        dbgmsg( NULL, "creating tracker timer" );
679    }
680}
681
682void
683tr_trackerShuttingDown( tr_session * session )
684{
685    if( session->tracker )
686        session->tracker->isShuttingDown = 1;
687}
688
689static int
690maybeFreeGlobals( tr_session * session )
691{
692    int globalsExist = session->tracker != NULL;
693
694    if( globalsExist
695        && ( session->tracker->runningCount < 1 )
696        && ( session->torrentList== NULL ) )
697    {
698        dbgmsg( NULL, "freeing tracker timer" );
699        tr_timerFree( &session->tracker->pulseTimer );
700        tr_free( session->tracker );
701        session->tracker = NULL;
702        globalsExist = FALSE;
703    }
704
705    return globalsExist;
706}
707
708/***
709****
710***/
711
712static void
713invokeRequest( void * vreq )
714{
715    struct tr_tracker_request * req = vreq;
716    tr_tracker * t = findTracker( req->session, req->torrent_hash );
717
718    if( t )
719    {
720        const time_t now = time( NULL );
721
722        if( req->reqtype == TR_REQ_SCRAPE )
723        {
724            t->lastScrapeTime = now;
725            t->scrapeAt = 1;
726        }
727        else
728        {
729            t->lastAnnounceTime = now;
730            t->reannounceAt = 1;
731            t->manualAnnounceAllowedAt = 1;
732            t->scrapeAt = req->reqtype == TR_REQ_STOPPED
733                        ? now + t->scrapeIntervalSec + t->randOffset
734                        : 0;
735        }
736    }
737
738    ++req->session->tracker->runningCount;
739
740    tr_webRun( req->session, req->url, NULL, req->done_func,
741               tr_memdup( req->torrent_hash, SHA_DIGEST_LENGTH ) );
742
743    freeRequest( req );
744}
745
746static void ensureGlobalsExist( tr_session * );
747
748static void
749enqueueScrape( tr_session * session, tr_tracker * tracker )
750{
751    struct tr_tracker_request * req;
752    ensureGlobalsExist( session );
753    req = createScrape( session, tracker );
754    tr_runInEventThread( session, invokeRequest, req );
755}
756
757static void
758enqueueRequest( tr_session * session, tr_tracker * tracker, int reqtype )
759{
760    struct tr_tracker_request * req;
761    ensureGlobalsExist( session );
762    req = createRequest( session, tracker, reqtype );
763    tr_runInEventThread( session, invokeRequest, req );
764}
765
766static int
767trackerPulse( void * vsession )
768{
769    tr_session * session = vsession;
770    struct tr_tracker_handle * th = session->tracker;
771    tr_torrent * tor;
772    const time_t now = time( NULL );
773
774    if( !session->tracker )
775        return FALSE;
776
777    if( th->runningCount )
778        dbgmsg( NULL, "tracker pulse... %d running", th->runningCount );
779
780    /* upkeep: queue periodic rescrape / reannounce */
781    for( tor=session->torrentList; tor; tor=tor->next )
782    {
783        tr_tracker * t = tor->tracker;
784
785        if( ( t->scrapeAt > 1 ) &&
786            ( t->scrapeAt <= now ) &&
787            ( trackerSupportsScrape( t, tor ) ) )
788        {
789            t->scrapeAt = 1;
790            enqueueScrape( session, t );
791        }
792
793        if( ( t->reannounceAt > 1 ) && 
794            ( t->reannounceAt <= now ) &&
795            ( t->isRunning ) )
796        {
797            t->reannounceAt = 1;
798            t->manualAnnounceAllowedAt = 1;
799            enqueueRequest( session, t, TR_REQ_REANNOUNCE );
800        }
801    }
802
803    if( th->runningCount )
804        dbgmsg( NULL, "tracker pulse after upkeep... %d running", th->runningCount );
805
806    return maybeFreeGlobals( session );
807}
808
809static void
810onReqDone( tr_session * session )
811{
812    if( session->tracker )
813    {
814        --session->tracker->runningCount;
815        dbgmsg( NULL, "decrementing runningCount to %d", session->tracker->runningCount );
816        trackerPulse( session );
817    }
818}
819
820/***
821****  LIFE CYCLE
822***/
823
824static void
825generateKeyParam( char * msg, int len )
826{
827    int i;
828    const char * pool = "abcdefghijklmnopqrstuvwxyz0123456789";
829    const int poolSize = strlen( pool );
830    for( i=0; i<len; ++i )
831        *msg++ = pool[tr_rand(poolSize)];
832    *msg = '\0';
833}
834
835static int
836is_rfc2396_alnum( char ch )
837{
838    return     ( '0' <= ch && ch <= '9' )
839            || ( 'A' <= ch && ch <= 'Z' )
840            || ( 'a' <= ch && ch <= 'z' );
841}
842
843static void
844escape( char * out, const uint8_t * in, int in_len ) /* rfc2396 */
845{
846    const uint8_t *end = in + in_len;
847    while( in != end )
848        if( is_rfc2396_alnum(*in) )
849            *out++ = (char) *in++;
850        else 
851            out += tr_snprintf( out, 4, "%%%02X", (unsigned int)*in++ );
852    *out = '\0';
853}
854
855tr_tracker *
856tr_trackerNew( const tr_torrent * torrent )
857{
858    const tr_info * info = &torrent->info;
859    tr_tracker * t;
860
861    t = tr_new0( tr_tracker, 1 );
862    t->publisher = tr_publisherNew( );
863    t->session                  = torrent->handle;
864    t->scrapeIntervalSec        = DEFAULT_SCRAPE_INTERVAL_SEC;
865    t->retryScrapeIntervalSec   = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
866    t->retryAnnounceIntervalSec = FIRST_ANNOUNCE_RETRY_INTERVAL_SEC;
867    t->announceIntervalSec      = DEFAULT_ANNOUNCE_INTERVAL_SEC;
868    t->announceMinIntervalSec   = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
869    t->timesDownloaded          = -1;
870    t->seederCount              = -1;
871    t->leecherCount             = -1;
872    t->lastAnnounceResponse     = -1;
873    t->lastScrapeResponse       = -1;
874    t->manualAnnounceAllowedAt  = ~(time_t)0;
875    t->name = tr_strdup( info->name );
876    t->randOffset = tr_rand( 30 );
877    memcpy( t->hash, info->hash, SHA_DIGEST_LENGTH );
878    escape( t->escaped, info->hash, SHA_DIGEST_LENGTH );
879    generateKeyParam( t->key_param, KEYLEN );
880
881    t->trackerIndex = 0;
882
883    if( trackerSupportsScrape( t, torrent ) )
884        t->scrapeAt = time( NULL ) + t->randOffset;
885
886    return t;
887}
888
889static void
890onTrackerFreeNow( void * vt )
891{
892    tr_tracker * t = vt;
893
894    tr_publisherFree( &t->publisher );
895    tr_free( t->name );
896    tr_free( t->trackerID );
897    tr_free( t->peer_id );
898
899    tr_free( t );
900}
901
902/***
903****  PUBLIC
904***/
905
906void
907tr_trackerFree( tr_tracker * t )
908{
909    if( t )
910        tr_runInEventThread( t->session, onTrackerFreeNow, t );
911}
912
913tr_publisher_tag
914tr_trackerSubscribe( tr_tracker          * t,
915                     tr_delivery_func      func,
916                     void                * user_data )
917{
918    return tr_publisherSubscribe( t->publisher, func, user_data );
919}
920
921void
922tr_trackerUnsubscribe( tr_tracker        * t,
923                       tr_publisher_tag    tag )
924{
925    if( t )
926        tr_publisherUnsubscribe( t->publisher, tag );
927}
928
929const tr_tracker_info *
930tr_trackerGetAddress( tr_tracker   * t )
931{
932    return getCurrentAddress( t );
933}
934
935time_t
936tr_trackerGetManualAnnounceTime( const struct tr_tracker * t )
937{
938    return t->isRunning ? t->manualAnnounceAllowedAt : 0;
939}
940
941int
942tr_trackerCanManualAnnounce ( const tr_tracker * t)
943{
944    const time_t allow = tr_trackerGetManualAnnounceTime( t );
945    return allow && ( allow <= time( NULL ) );
946}
947
948void
949tr_trackerGetCounts( const tr_tracker  * t,
950                     int               * setme_completedCount,
951                     int               * setme_leecherCount,
952                     int               * setme_seederCount )
953{
954    if( setme_completedCount )
955       *setme_completedCount = t->timesDownloaded;
956
957    if( setme_leecherCount )
958       *setme_leecherCount = t->leecherCount;
959
960    if( setme_seederCount )
961       *setme_seederCount = t->seederCount;
962}
963
964
965void
966tr_trackerStart( tr_tracker * t )
967{
968    if( t && !t->isRunning )
969    {
970        tr_free( t->peer_id );
971        t->peer_id = tr_peerIdNew( );
972
973        t->isRunning = 1;
974        enqueueRequest( t->session, t, TR_REQ_STARTED );
975    }
976}
977
978void
979tr_trackerReannounce( tr_tracker * t )
980{
981    enqueueRequest( t->session, t, TR_REQ_REANNOUNCE );
982}
983
984void
985tr_trackerCompleted( tr_tracker * t )
986{
987    enqueueRequest( t->session, t, TR_REQ_COMPLETED );
988}
989
990void
991tr_trackerStop( tr_tracker * t )
992{
993    if( t && t->isRunning ) {
994        t->isRunning = 0;
995        t->reannounceAt = t->manualAnnounceAllowedAt = 0;
996        enqueueRequest( t->session, t, TR_REQ_STOPPED );
997    }
998}
999
1000void
1001tr_trackerChangeMyPort( tr_tracker * t )
1002{
1003    if( t->isRunning )
1004        tr_trackerReannounce( t );
1005}
1006
1007void
1008tr_trackerStat( const tr_tracker * t,
1009                struct tr_stat   * setme)
1010{
1011    assert( t );
1012    assert( setme );
1013
1014    setme->lastScrapeTime = t->lastScrapeTime;
1015    setme->nextScrapeTime = t->scrapeAt;
1016    setme->lastAnnounceTime = t->lastAnnounceTime;
1017    setme->nextAnnounceTime = t->reannounceAt;
1018    setme->manualAnnounceTime = t->manualAnnounceAllowedAt;
1019
1020    if( t->lastScrapeResponse == -1 ) /* never been scraped */
1021        *setme->scrapeResponse = '\0';
1022    else
1023        tr_snprintf( setme->scrapeResponse,
1024                     sizeof( setme->scrapeResponse ),
1025                     "%s (%ld)",
1026                     tr_webGetResponseStr( t->lastScrapeResponse ),
1027                     t->lastScrapeResponse );
1028
1029    if( t->lastAnnounceResponse == -1 ) /* never been announced */
1030        *setme->announceResponse = '\0';
1031    else
1032        tr_snprintf( setme->announceResponse,
1033                     sizeof( setme->announceResponse ),
1034                     "%s (%ld)",
1035                     tr_webGetResponseStr( t->lastAnnounceResponse ),
1036                     t->lastAnnounceResponse );
1037}
Note: See TracBrowser for help on using the repository browser.