source: trunk/libtransmission/tracker.c @ 6421

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

#1126: crash on quit

  • 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 6421 2008-07-31 13:06:59Z 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    int runningCount;
665    tr_timer * pulseTimer;
666};
667
668static int trackerPulse( void * vsession );
669
670static void
671ensureGlobalsExist( tr_session * session )
672{
673    if( session->tracker == NULL )
674    {
675        session->tracker = tr_new0( struct tr_tracker_handle, 1 );
676        session->tracker->pulseTimer = tr_timerNew( session, trackerPulse, session, PULSE_INTERVAL_MSEC );
677        dbgmsg( NULL, "creating tracker timer" );
678    }
679}
680
681void
682tr_trackerSessionClose( tr_session * session )
683{
684    if( session && session->tracker )
685    {
686        dbgmsg( NULL, "freeing tracker timer" );
687        tr_timerFree( &session->tracker->pulseTimer );
688        tr_free( session->tracker );
689        session->tracker = NULL;
690    }
691}
692
693/***
694****
695***/
696
697static void
698invokeRequest( void * vreq )
699{
700    struct tr_tracker_request * req = vreq;
701    tr_tracker * t = findTracker( req->session, req->torrent_hash );
702
703    if( t )
704    {
705        const time_t now = time( NULL );
706
707        if( req->reqtype == TR_REQ_SCRAPE )
708        {
709            t->lastScrapeTime = now;
710            t->scrapeAt = 1;
711        }
712        else
713        {
714            t->lastAnnounceTime = now;
715            t->reannounceAt = 1;
716            t->manualAnnounceAllowedAt = 1;
717            t->scrapeAt = req->reqtype == TR_REQ_STOPPED
718                        ? now + t->scrapeIntervalSec + t->randOffset
719                        : 0;
720        }
721    }
722
723    ++req->session->tracker->runningCount;
724
725    tr_webRun( req->session, req->url, NULL, req->done_func,
726               tr_memdup( req->torrent_hash, SHA_DIGEST_LENGTH ) );
727
728    freeRequest( req );
729}
730
731static void ensureGlobalsExist( tr_session * );
732
733static void
734enqueueScrape( tr_session * session, tr_tracker * tracker )
735{
736    struct tr_tracker_request * req;
737    ensureGlobalsExist( session );
738    req = createScrape( session, tracker );
739    tr_runInEventThread( session, invokeRequest, req );
740}
741
742static void
743enqueueRequest( tr_session * session, tr_tracker * tracker, int reqtype )
744{
745    struct tr_tracker_request * req;
746    ensureGlobalsExist( session );
747    req = createRequest( session, tracker, reqtype );
748    tr_runInEventThread( session, invokeRequest, req );
749}
750
751static int
752trackerPulse( void * vsession )
753{
754    tr_session * session = vsession;
755    struct tr_tracker_handle * th = session->tracker;
756    tr_torrent * tor;
757    const time_t now = time( NULL );
758
759    if( !session->tracker )
760        return FALSE;
761
762    if( th->runningCount )
763        dbgmsg( NULL, "tracker pulse... %d running", th->runningCount );
764
765    /* upkeep: queue periodic rescrape / reannounce */
766    for( tor=session->torrentList; tor; tor=tor->next )
767    {
768        tr_tracker * t = tor->tracker;
769
770        if( ( t->scrapeAt > 1 ) &&
771            ( t->scrapeAt <= now ) &&
772            ( trackerSupportsScrape( t, tor ) ) )
773        {
774            t->scrapeAt = 1;
775            enqueueScrape( session, t );
776        }
777
778        if( ( t->reannounceAt > 1 ) && 
779            ( t->reannounceAt <= now ) &&
780            ( t->isRunning ) )
781        {
782            t->reannounceAt = 1;
783            t->manualAnnounceAllowedAt = 1;
784            enqueueRequest( session, t, TR_REQ_REANNOUNCE );
785        }
786    }
787
788    if( th->runningCount )
789        dbgmsg( NULL, "tracker pulse after upkeep... %d running", th->runningCount );
790
791    /* free the tracker manager if no torrents are left */
792    if(    ( session->tracker )
793        && ( session->tracker->runningCount < 1 )
794        && ( session->torrentList == NULL ) )
795    {
796        tr_trackerSessionClose( session );
797    }
798
799    /* if there are still running torrents (as indicated by
800     * the existence of the tracker manager) then keep the
801     * trackerPulse() timer alive */
802    return session->tracker != NULL;
803}
804
805static void
806onReqDone( tr_session * session )
807{
808    if( session->tracker )
809    {
810        --session->tracker->runningCount;
811        dbgmsg( NULL, "decrementing runningCount to %d", session->tracker->runningCount );
812        trackerPulse( session );
813    }
814}
815
816/***
817****  LIFE CYCLE
818***/
819
820static void
821generateKeyParam( char * msg, int len )
822{
823    int i;
824    const char * pool = "abcdefghijklmnopqrstuvwxyz0123456789";
825    const int poolSize = strlen( pool );
826    for( i=0; i<len; ++i )
827        *msg++ = pool[tr_rand(poolSize)];
828    *msg = '\0';
829}
830
831static int
832is_rfc2396_alnum( char ch )
833{
834    return     ( '0' <= ch && ch <= '9' )
835            || ( 'A' <= ch && ch <= 'Z' )
836            || ( 'a' <= ch && ch <= 'z' );
837}
838
839static void
840escape( char * out, const uint8_t * in, int in_len ) /* rfc2396 */
841{
842    const uint8_t *end = in + in_len;
843    while( in != end )
844        if( is_rfc2396_alnum(*in) )
845            *out++ = (char) *in++;
846        else 
847            out += tr_snprintf( out, 4, "%%%02X", (unsigned int)*in++ );
848    *out = '\0';
849}
850
851tr_tracker *
852tr_trackerNew( const tr_torrent * torrent )
853{
854    const tr_info * info = &torrent->info;
855    tr_tracker * t;
856
857    t = tr_new0( tr_tracker, 1 );
858    t->publisher = tr_publisherNew( );
859    t->session                  = torrent->handle;
860    t->scrapeIntervalSec        = DEFAULT_SCRAPE_INTERVAL_SEC;
861    t->retryScrapeIntervalSec   = FIRST_SCRAPE_RETRY_INTERVAL_SEC;
862    t->retryAnnounceIntervalSec = FIRST_ANNOUNCE_RETRY_INTERVAL_SEC;
863    t->announceIntervalSec      = DEFAULT_ANNOUNCE_INTERVAL_SEC;
864    t->announceMinIntervalSec   = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
865    t->timesDownloaded          = -1;
866    t->seederCount              = -1;
867    t->leecherCount             = -1;
868    t->lastAnnounceResponse     = -1;
869    t->lastScrapeResponse       = -1;
870    t->manualAnnounceAllowedAt  = ~(time_t)0;
871    t->name = tr_strdup( info->name );
872    t->randOffset = tr_rand( 30 );
873    memcpy( t->hash, info->hash, SHA_DIGEST_LENGTH );
874    escape( t->escaped, info->hash, SHA_DIGEST_LENGTH );
875    generateKeyParam( t->key_param, KEYLEN );
876
877    t->trackerIndex = 0;
878
879    if( trackerSupportsScrape( t, torrent ) )
880        t->scrapeAt = time( NULL ) + t->randOffset;
881
882    return t;
883}
884
885static void
886onTrackerFreeNow( void * vt )
887{
888    tr_tracker * t = vt;
889
890    tr_publisherFree( &t->publisher );
891    tr_free( t->name );
892    tr_free( t->trackerID );
893    tr_free( t->peer_id );
894
895    tr_free( t );
896}
897
898/***
899****  PUBLIC
900***/
901
902void
903tr_trackerFree( tr_tracker * t )
904{
905    if( t )
906        tr_runInEventThread( t->session, onTrackerFreeNow, t );
907}
908
909tr_publisher_tag
910tr_trackerSubscribe( tr_tracker          * t,
911                     tr_delivery_func      func,
912                     void                * user_data )
913{
914    return tr_publisherSubscribe( t->publisher, func, user_data );
915}
916
917void
918tr_trackerUnsubscribe( tr_tracker        * t,
919                       tr_publisher_tag    tag )
920{
921    if( t )
922        tr_publisherUnsubscribe( t->publisher, tag );
923}
924
925const tr_tracker_info *
926tr_trackerGetAddress( tr_tracker   * t )
927{
928    return getCurrentAddress( t );
929}
930
931time_t
932tr_trackerGetManualAnnounceTime( const struct tr_tracker * t )
933{
934    return t->isRunning ? t->manualAnnounceAllowedAt : 0;
935}
936
937int
938tr_trackerCanManualAnnounce ( const tr_tracker * t)
939{
940    const time_t allow = tr_trackerGetManualAnnounceTime( t );
941    return allow && ( allow <= time( NULL ) );
942}
943
944void
945tr_trackerGetCounts( const tr_tracker  * t,
946                     int               * setme_completedCount,
947                     int               * setme_leecherCount,
948                     int               * setme_seederCount )
949{
950    if( setme_completedCount )
951       *setme_completedCount = t->timesDownloaded;
952
953    if( setme_leecherCount )
954       *setme_leecherCount = t->leecherCount;
955
956    if( setme_seederCount )
957       *setme_seederCount = t->seederCount;
958}
959
960
961void
962tr_trackerStart( tr_tracker * t )
963{
964    if( t && !t->isRunning )
965    {
966        tr_free( t->peer_id );
967        t->peer_id = tr_peerIdNew( );
968
969        t->isRunning = 1;
970        enqueueRequest( t->session, t, TR_REQ_STARTED );
971    }
972}
973
974void
975tr_trackerReannounce( tr_tracker * t )
976{
977    enqueueRequest( t->session, t, TR_REQ_REANNOUNCE );
978}
979
980void
981tr_trackerCompleted( tr_tracker * t )
982{
983    enqueueRequest( t->session, t, TR_REQ_COMPLETED );
984}
985
986void
987tr_trackerStop( tr_tracker * t )
988{
989    if( t && t->isRunning ) {
990        t->isRunning = 0;
991        t->reannounceAt = t->manualAnnounceAllowedAt = 0;
992        enqueueRequest( t->session, t, TR_REQ_STOPPED );
993    }
994}
995
996void
997tr_trackerChangeMyPort( tr_tracker * t )
998{
999    if( t->isRunning )
1000        tr_trackerReannounce( t );
1001}
1002
1003void
1004tr_trackerStat( const tr_tracker * t,
1005                struct tr_stat   * setme)
1006{
1007    assert( t );
1008    assert( setme );
1009
1010    setme->lastScrapeTime = t->lastScrapeTime;
1011    setme->nextScrapeTime = t->scrapeAt;
1012    setme->lastAnnounceTime = t->lastAnnounceTime;
1013    setme->nextAnnounceTime = t->reannounceAt;
1014    setme->manualAnnounceTime = t->manualAnnounceAllowedAt;
1015
1016    if( t->lastScrapeResponse == -1 ) /* never been scraped */
1017        *setme->scrapeResponse = '\0';
1018    else
1019        tr_snprintf( setme->scrapeResponse,
1020                     sizeof( setme->scrapeResponse ),
1021                     "%s (%ld)",
1022                     tr_webGetResponseStr( t->lastScrapeResponse ),
1023                     t->lastScrapeResponse );
1024
1025    if( t->lastAnnounceResponse == -1 ) /* never been announced */
1026        *setme->announceResponse = '\0';
1027    else
1028        tr_snprintf( setme->announceResponse,
1029                     sizeof( setme->announceResponse ),
1030                     "%s (%ld)",
1031                     tr_webGetResponseStr( t->lastAnnounceResponse ),
1032                     t->lastAnnounceResponse );
1033}
Note: See TracBrowser for help on using the repository browser.