source: trunk/libtransmission/tracker.c @ 5292

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

#798: 1.06's handling of tracker http 301 redirects can cause a huge strain on tracker

  • Property svn:keywords set to Date Rev Author Id
File size: 35.1 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 5292 2008-03-18 19:33:08Z charles $
11 */
12
13#include <assert.h>
14#include <stdio.h> /* snprintf */
15#include <stdlib.h>
16#include <string.h> /* strcmp, strchr */
17#include <libgen.h> /* basename */
18
19#include <event.h>
20#include <evhttp.h>
21
22#include "transmission.h"
23#include "bencode.h"
24#include "completion.h"
25#include "list.h"
26#include "net.h"
27#include "publish.h"
28#include "shared.h"
29#include "torrent.h"
30#include "tracker.h"
31#include "trcompat.h" /* strlcpy */
32#include "trevent.h"
33#include "utils.h"
34
35enum
36{
37    /* seconds between tracker pulses */
38    PULSE_INTERVAL_MSEC = 1000,
39
40    /* maximum number of concurrent tracker socket connections */
41    MAX_TRACKER_SOCKETS = 16,
42
43    /* maximum number of concurrent tracker socket connections during shutdown.
44     * all the peer connections should be gone by now, so we can hog more
45     * connections to send `stop' messages to the trackers */
46    MAX_TRACKER_SOCKETS_DURING_SHUTDOWN = 64,
47
48    /* unless the tracker says otherwise, rescrape this frequently */
49    DEFAULT_SCRAPE_INTERVAL_SEC = (60 * 15),
50
51    /* unless the tracker says otherwise, this is the announce interval */
52    DEFAULT_ANNOUNCE_INTERVAL_SEC = (60 * 4),
53
54    /* unless the tracker says otherwise, this is the announce min_interval */
55    DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC = (60 * 2),
56
57    /* this is how long we'll leave a request hanging before timeout */
58    TIMEOUT_INTERVAL_SEC = 30,
59
60    /* this is how long we'll leave a 'stop' request hanging before timeout.
61       we wait less time for this so it doesn't slow down shutdowns */
62    STOP_TIMEOUT_INTERVAL_SEC = 5,
63
64    /* the value of the 'numwant' argument passed in tracker requests. */
65    NUMWANT = 200,
66
67    /* the length of the 'key' argument passed in tracker requests */
68    KEYLEN = 10
69};
70
71/**
72***
73**/
74
75struct tr_tracker
76{
77    tr_handle * handle;
78
79    /* these are set from the latest scrape or tracker response */
80    int announceIntervalSec;
81    int announceMinIntervalSec;
82    int scrapeIntervalSec;
83
84    tr_tracker_info * redirect;
85    tr_tracker_info * addresses;
86    int addressIndex;
87    int addressCount;
88    int * tierFronts;
89
90    /* sent as the "key" argument in tracker requests
91       to verify us if our IP address changes.
92       This is immutable for the life of the tracker object. */
93    char key_param[KEYLEN+1];
94
95    tr_publisher_t * publisher;
96
97    /* torrent hash string */
98    uint8_t hash[SHA_DIGEST_LENGTH];
99    char escaped[SHA_DIGEST_LENGTH * 3 + 1];
100    char * name;
101
102    /* corresponds to the peer_id sent as a tracker request parameter.
103       one tracker admin says: "When the same torrent is opened and
104       closed and opened again without quitting Transmission ...
105       change the peerid. It would help sometimes if a stopped event
106       was missed to ensure that we didn't think someone was cheating. */
107    uint8_t * peer_id;
108
109    /* these are set from the latest tracker response... -1 is 'unknown' */
110    int timesDownloaded;
111    int seederCount;
112    int leecherCount;
113    char * trackerID;
114
115    time_t manualAnnounceAllowedAt;
116    time_t reannounceAt;
117    time_t scrapeAt;
118
119    time_t lastScrapeTime;
120    char lastScrapeResponse[512];
121
122    time_t lastAnnounceTime;
123    char lastAnnounceResponse[512];
124
125    int randOffset;
126
127    unsigned int isRunning     : 1;
128};
129
130/**
131***
132**/
133
134static void
135myDebug( const char * file, int line, const tr_tracker * t, const char * fmt, ... )
136{   
137    FILE * fp = tr_getLog( );
138    if( fp != NULL )
139    {
140        va_list args;
141        char timestr[64];
142        struct evbuffer * buf = evbuffer_new( );
143        char * myfile = tr_strdup( file );
144
145        evbuffer_add_printf( buf, "[%s] ", tr_getLogTimeStr( timestr, sizeof(timestr) ) );
146        if( t != NULL )
147            evbuffer_add_printf( buf, "%s ", t->name );
148        va_start( args, fmt );
149        evbuffer_add_vprintf( buf, fmt, args );
150        va_end( args );
151        evbuffer_add_printf( buf, " (%s:%d)\n", basename(myfile), line );
152        fwrite( EVBUFFER_DATA(buf), 1, EVBUFFER_LENGTH(buf), fp );
153
154        tr_free( myfile );
155        evbuffer_free( buf );
156    }
157}
158
159#define dbgmsg(t, fmt...) myDebug(__FILE__, __LINE__, t, ##fmt )
160
161/***
162****
163***/
164
165static const tr_tracker_info *
166getCurrentAddress( const tr_tracker * t )
167{
168    assert( t->addresses != NULL );
169    assert( t->addressIndex >= 0 );
170    assert( t->addressIndex < t->addressCount );
171
172    return t->redirect ? t->redirect
173                       : t->addresses + t->addressIndex;
174}
175
176static int
177trackerSupportsScrape( const tr_tracker * t )
178{
179    const tr_tracker_info * info = getCurrentAddress( t );
180
181    return ( info != NULL )
182        && ( info->scrape != NULL )
183        && ( info->scrape[0] != '\0' );
184}
185
186/***
187****
188***/
189
190struct torrent_hash
191{
192    tr_handle * handle;
193    uint8_t hash[SHA_DIGEST_LENGTH];
194};
195
196static struct torrent_hash*
197torrentHashNew( tr_handle * handle, const tr_tracker * t )
198{
199    struct torrent_hash * data = tr_new( struct torrent_hash, 1 );
200    data->handle = handle;
201    memcpy( data->hash, t->hash, SHA_DIGEST_LENGTH );
202    return data;
203}
204
205tr_tracker *
206findTrackerFromHash( struct torrent_hash * data )
207{
208    tr_torrent * torrent = tr_torrentFindFromHash( data->handle, data->hash );
209    return torrent ? torrent->tracker : NULL;
210}
211
212tr_tracker *
213findTracker( tr_handle * handle, const uint8_t * hash )
214{
215    tr_torrent * torrent = tr_torrentFindFromHash( handle, hash );
216    return torrent ? torrent->tracker : NULL;
217}
218
219/***
220****  PUBLISH
221***/
222
223static const tr_tracker_event emptyEvent = { 0, NULL, NULL, NULL, 0 };
224
225static void
226publishMessage( tr_tracker * t, const char * msg, int type )
227{
228    if( t != NULL )
229    {
230        tr_tracker_event event = emptyEvent;
231        event.hash = t->hash;
232        event.messageType = type;
233        event.text = msg;
234        tr_publisherPublish( t->publisher, t, &event );
235    }
236}
237
238static void
239publishErrorClear( tr_tracker * t )
240{
241    publishMessage( t, NULL, TR_TRACKER_ERROR_CLEAR );
242}
243
244static void
245publishErrorMessageAndStop( tr_tracker * t, const char * msg )
246{
247    t->isRunning = 0;
248    publishMessage( t, msg, TR_TRACKER_ERROR );
249}
250
251static void
252publishWarning( tr_tracker * t, const char * msg )
253{
254    publishMessage( t, msg, TR_TRACKER_WARNING );
255}
256
257static void
258publishNewPeers( tr_tracker * t, int count, uint8_t * peers )
259{
260    tr_tracker_event event = emptyEvent;
261    event.hash = t->hash;
262    event.messageType = TR_TRACKER_PEERS;
263    event.peerCount = count;
264    event.peerCompact = peers;
265    tr_ndbg( t->name, "Torrent got %d new peers", count );
266    if( count )
267        tr_publisherPublish( t->publisher, t, &event );
268}
269
270/***
271****
272***/
273
274static void onReqDone( tr_handle * handle );
275
276static void
277onStoppedResponse( struct evhttp_request * req UNUSED, void * handle )
278{
279    dbgmsg( NULL, "got a response to some `stop' message" );
280    onReqDone( handle );
281}
282
283static int
284parseBencResponse( struct evhttp_request * req, tr_benc * setme )
285{
286    const unsigned char * body = EVBUFFER_DATA( req->input_buffer );
287    const int bodylen = EVBUFFER_LENGTH( req->input_buffer );
288    return tr_bencLoad( body, bodylen, setme, NULL );
289}
290
291static void
292updateAddresses( tr_tracker * t, const struct evhttp_request * req, int * tryAgain )
293{
294    int moveToNextAddress = FALSE;
295
296    if( !req ) /* tracker didn't respond */
297    {
298        tr_ninf( t->name, _( "Tracker hasn't responded yet.  Retrying..." ) );
299        moveToNextAddress = TRUE;
300    }
301    else if( req->response_code == HTTP_OK )
302    {
303        if( t->redirect != NULL )
304        {
305            /* multitracker spec: "if a connection with a tracker is
306               successful, it will be moved to the front of the tier." */
307            const int i = t->addressIndex;
308            const int j = t->tierFronts[i];
309            const tr_tracker_info swap = t->addresses[i];
310            t->addresses[i] = t->addresses[j];
311            t->addresses[j] = swap;
312        }
313    }
314    else if(    ( req->response_code == HTTP_MOVEPERM )
315             || ( req->response_code == HTTP_MOVETEMP ) )
316    {
317        const char * loc = evhttp_find_header( req->input_headers, "Location" );
318        tr_tracker_info tmp;
319        if( tr_trackerInfoInit( &tmp, loc, -1 ) ) /* a bad redirect? */
320        {
321            moveToNextAddress = TRUE;
322        }
323        else if( req->response_code == HTTP_MOVEPERM )
324        {
325            tr_tracker_info * cur = &t->addresses[t->addressIndex];
326            tr_trackerInfoClear( cur );
327            *cur = tmp;
328        }
329        else if( req->response_code == HTTP_MOVETEMP )
330        {
331            if( t->redirect == NULL )
332                t->redirect = tr_new0( tr_tracker_info, 1 );
333            else
334                tr_trackerInfoClear( t->redirect );
335            *t->redirect = tmp;
336        }
337    }
338    else 
339    {
340        moveToNextAddress = TRUE;
341    }
342
343    *tryAgain = moveToNextAddress;
344
345    if( moveToNextAddress )
346    {
347        if ( ++t->addressIndex >= t->addressCount ) /* we've tried them all */
348        {
349            *tryAgain = FALSE;
350            t->addressIndex = 0;
351        }
352        else
353        {
354            const tr_tracker_info * n = getCurrentAddress( t );
355            tr_ninf( t->name, _( "Trying next tracker \"%s:%d\"" ), n->address, n->port );
356        }
357    }
358}
359
360/* Convert to compact form */
361static uint8_t *
362parseOldPeers( tr_benc * bePeers, int * setmePeerCount )
363{
364    int i;
365    uint8_t *compact, *walk;
366    const int peerCount = bePeers->val.l.count;
367
368    assert( bePeers->type == TYPE_LIST );
369
370    compact = tr_new( uint8_t, peerCount*6 );
371
372    for( i=0, walk=compact; i<peerCount; ++i )
373    {
374        struct in_addr addr;
375        tr_port_t port;
376        tr_benc * val;
377        tr_benc * peer = &bePeers->val.l.vals[i];
378
379        val = tr_bencDictFind( peer, "ip" );
380        if( !val || val->type!=TYPE_STR || tr_netResolve(val->val.s.s, &addr) )
381            continue;
382
383        memcpy( walk, &addr, 4 );
384        walk += 4;
385
386        val = tr_bencDictFind( peer, "port" );
387        if( !val || val->type!=TYPE_INT || val->val.i<0 || val->val.i>0xffff )
388            continue;
389
390        port = htons( val->val.i );
391        memcpy( walk, &port, 2 );
392        walk += 2;
393    }
394
395    *setmePeerCount = peerCount;
396    return compact;
397}
398
399static void
400onTrackerResponse( struct evhttp_request * req, void * vhash )
401{
402    int tryAgain;
403    int responseCode;
404    struct torrent_hash * torrent_hash = (struct torrent_hash*) vhash;
405    tr_tracker * t = findTrackerFromHash( torrent_hash );
406
407    onReqDone( torrent_hash->handle );
408    tr_free( torrent_hash );
409
410    if( t == NULL ) /* tracker has been closed */
411        return;
412
413    dbgmsg( t, "got response from tracker: \"%s\"",
414            ( req && req->response_code_line ) ?  req->response_code_line
415                                               : "(null)" );
416
417    *t->lastAnnounceResponse = '\0';
418    if( req && req->response_code_line )
419        strlcpy( t->lastAnnounceResponse, req->response_code_line, sizeof( t->lastAnnounceResponse ) );
420
421    tr_ndbg( t->name, "tracker response: %s",
422             ( req ? req->response_code_line : "(null)") );
423
424    if( req && ( req->response_code == HTTP_OK ) )
425    {
426        tr_benc benc;
427        const int bencLoaded = !parseBencResponse( req, &benc );
428
429        publishErrorClear( t );
430
431        if( bencLoaded && benc.type==TYPE_DICT )
432        {
433            tr_benc * tmp;
434
435            if(( tmp = tr_bencDictFind( &benc, "failure reason" ))) {
436                dbgmsg( t, "got failure message [%s]", tmp->val.s.s );
437                publishErrorMessageAndStop( t, tmp->val.s.s );
438            }
439
440            if(( tmp = tr_bencDictFind( &benc, "warning message" ))) {
441                dbgmsg( t, "got warning message [%s]", tmp->val.s.s );
442                publishWarning( t, tmp->val.s.s );
443            }
444
445            if(( tmp = tr_bencDictFind( &benc, "interval" ))) {
446                dbgmsg( t, "setting interval to %d", tmp->val.i );
447                t->announceIntervalSec = tmp->val.i;
448            }
449
450            if(( tmp = tr_bencDictFind( &benc, "min interval" ))) {
451                dbgmsg( t, "setting min interval to %d", tmp->val.i );
452                t->announceMinIntervalSec = tmp->val.i;
453            }
454
455            if(( tmp = tr_bencDictFind( &benc, "tracker id" )))
456                t->trackerID = tr_strndup( tmp->val.s.s, tmp->val.s.i );
457
458            if(( tmp = tr_bencDictFind( &benc, "complete" )))
459                t->seederCount = tmp->val.i;
460
461            if(( tmp = tr_bencDictFind( &benc, "incomplete" )))
462                t->leecherCount = tmp->val.i;
463
464            if(( tmp = tr_bencDictFind( &benc, "peers" )))
465            {
466                int peerCount = 0;
467                uint8_t * peerCompact = NULL;
468
469                if( tmp->type == TYPE_LIST ) /* original protocol */
470                {
471                    if( tmp->val.l.count > 0 )
472                        peerCompact = parseOldPeers( tmp, &peerCount );
473                }
474                else if( tmp->type == TYPE_STR ) /* "compact" extension */
475                {
476                    if( tmp->val.s.i >= 6 )
477                    {
478                        peerCount = tmp->val.s.i / 6;
479                        peerCompact = tr_new( uint8_t, tmp->val.s.i );
480                        memcpy( peerCompact, tmp->val.s.s, tmp->val.s.i );
481                    }
482                }
483
484                publishNewPeers( t, peerCount, peerCompact );
485                tr_free( peerCompact );
486            }
487        }
488
489        if( bencLoaded )
490            tr_bencFree( &benc );
491    }
492
493    updateAddresses( t, req, &tryAgain );
494
495    /**
496    ***
497    **/
498
499    if( tryAgain )
500        responseCode = 300;
501    else if( req )
502        responseCode = req->response_code;
503    else
504        responseCode = 503;
505
506    if( 200<=responseCode && responseCode<=299 )
507    {
508        dbgmsg( t, "request succeeded. reannouncing in %d seconds",
509                   t->announceIntervalSec );
510        t->reannounceAt = time( NULL ) + t->randOffset + t->announceIntervalSec;
511        t->manualAnnounceAllowedAt = time( NULL ) + t->announceMinIntervalSec;
512    }
513    else if( 300<=responseCode && responseCode<=399 )
514    {
515        const int interval = 20;
516        dbgmsg( t, "got a redirect. retrying in %d seconds", interval );
517
518        /* it's a redirect... updateAddresses() has already
519         * parsed the redirect, all that's left is to retry */
520        t->reannounceAt = time( NULL ) + interval;
521        t->manualAnnounceAllowedAt = time( NULL ) + t->announceMinIntervalSec;
522    }
523    else if( 400<=responseCode && responseCode<=499 )
524    {
525        const char * err = req && req->response_code_line
526            ? req->response_code_line
527            : "Unspecified 4xx error from tracker.";
528        dbgmsg( t, err );
529
530        /* The request could not be understood by the server due to
531         * malformed syntax. The client SHOULD NOT repeat the
532         * request without modifications. */
533        publishErrorMessageAndStop( t, err );
534        t->manualAnnounceAllowedAt = ~(time_t)0;
535        t->reannounceAt = 0;
536    }
537    else if( 500<=responseCode && responseCode<=599 )
538    {
539        dbgmsg( t, "Got a 5xx error... retrying in one minute." );
540
541        /* Response status codes beginning with the digit "5" indicate
542         * cases in which the server is aware that it has erred or is
543         * incapable of performing the request.  So we pause a bit and
544         * try again. */
545        if( req && req->response_code_line )
546            publishWarning( t, req->response_code_line );
547        t->manualAnnounceAllowedAt = ~(time_t)0;
548        t->reannounceAt = time( NULL ) + 60;
549    }
550    else
551    {
552        dbgmsg( t, "Invalid response from tracker... retrying in two minutes." );
553
554        /* WTF did we get?? */
555        if( req && req->response_code_line )
556            publishWarning( t, req->response_code_line );
557        t->manualAnnounceAllowedAt = ~(time_t)0;
558        t->reannounceAt = time( NULL ) + t->randOffset + 120;
559    }
560}
561
562static void
563onScrapeResponse( struct evhttp_request * req, void * vhash )
564{
565    int tryAgain;
566    time_t nextScrapeSec = 60;
567    struct torrent_hash * torrent_hash = (struct torrent_hash*) vhash;
568    tr_tracker * t = findTrackerFromHash( torrent_hash );
569
570    onReqDone( torrent_hash->handle );
571    tr_free( torrent_hash );
572
573    dbgmsg( t, "Got scrape response for '%s': %s (%d)", (t ? t->name : "(null)"), (req ? req->response_code_line : "(no line)"), (req ? req->response_code : -1) );
574
575    if( t == NULL ) /* tracker's been closed... */
576        return;
577
578    *t->lastScrapeResponse = '\0';
579    if( req && req->response_code_line )
580        strlcpy( t->lastScrapeResponse, req->response_code_line, sizeof( t->lastScrapeResponse ) );
581
582    tr_ndbg( t->name, "Got scrape response: \"%s\"",
583            ( ( req && req->response_code_line ) ? req->response_code_line : "(null)") );
584
585    if( req && ( req->response_code == HTTP_OK ) )
586    {
587        tr_benc benc, *files;
588        const int bencLoaded = !parseBencResponse( req, &benc );
589
590        if( bencLoaded
591            && (( files = tr_bencDictFind( &benc, "files" ) ))
592            && ( files->type == TYPE_DICT ) )
593        {
594            int i;
595            for( i=0; i<files->val.l.count; i+=2 )
596            {
597                const uint8_t* hash =
598                        (const uint8_t*) files->val.l.vals[i].val.s.s;
599                tr_benc *tmp, *flags;
600                tr_benc *tordict = &files->val.l.vals[i+1];
601                if( memcmp( t->hash, hash, SHA_DIGEST_LENGTH ) )
602                    continue;
603
604                publishErrorClear( t );
605
606                if(( tmp = tr_bencDictFind( tordict, "complete" )))
607                    t->seederCount = tmp->val.i;
608
609                if(( tmp = tr_bencDictFind( tordict, "incomplete" )))
610                    t->leecherCount = tmp->val.i;
611
612                if(( tmp = tr_bencDictFind( tordict, "downloaded" )))
613                    t->timesDownloaded = tmp->val.i;
614
615                if(( flags = tr_bencDictFind( tordict, "flags" )))
616                    if(( tmp = tr_bencDictFind( flags, "min_request_interval")))
617                        t->scrapeIntervalSec = tmp->val.i;
618
619                tr_ndbg( t->name, "Scrape successful.  Rescraping in %d seconds.",
620                         t->scrapeIntervalSec );
621
622                nextScrapeSec = t->scrapeIntervalSec;
623            }
624        }
625
626        if( bencLoaded )
627            tr_bencFree( &benc );
628    }
629
630    updateAddresses( t, req, &tryAgain );
631
632    if( tryAgain ) 
633        t->scrapeAt = time( NULL );
634    else
635        t->scrapeAt = time( NULL ) + t->randOffset + nextScrapeSec;
636}
637
638/***
639****
640***/
641
642enum
643{
644    TR_REQ_STARTED,
645    TR_REQ_COMPLETED,
646    TR_REQ_STOPPED,
647    TR_REQ_REANNOUNCE,
648    TR_REQ_SCRAPE,
649    TR_REQ_COUNT
650};
651
652struct tr_tracker_request
653{
654    int port;
655    int timeout;
656    int reqtype; /* TR_REQ_* */
657    char * address;
658    char * uri;
659    struct evhttp_request * req;
660    uint8_t torrent_hash[SHA_DIGEST_LENGTH];
661};
662
663static void
664freeRequest( struct tr_tracker_request * req )
665{
666    tr_free( req->address );
667    tr_free( req->uri );
668    tr_free( req );
669}
670
671static void
672addCommonHeaders( const tr_tracker * t,
673                  struct evhttp_request * req )
674{
675    char buf[1024];
676    const tr_tracker_info * address = getCurrentAddress( t );
677    snprintf( buf, sizeof(buf), "%s:%d", address->address, address->port );
678    evhttp_add_header( req->output_headers, "Host", buf );
679    evhttp_add_header( req->output_headers, "Connection", "close" );
680    evhttp_add_header( req->output_headers, "User-Agent",
681                                         TR_NAME "/" LONG_VERSION_STRING );
682}
683
684static char*
685buildTrackerRequestURI( const tr_tracker  * t,
686                        const tr_torrent  * torrent,
687                        const char        * eventName )
688{
689    const int isStopping = !strcmp( eventName, "stopped" );
690    const int numwant = isStopping ? 0 : NUMWANT;
691    struct evbuffer * buf = evbuffer_new( );
692    char * ret;
693
694    const char * ann = getCurrentAddress(t)->announce;
695   
696    evbuffer_add_printf( buf, "%s"
697                              "%cinfo_hash=%s"
698                              "&peer_id=%s"
699                              "&port=%d"
700                              "&uploaded=%"PRIu64
701                              "&downloaded=%"PRIu64
702                              "&corrupt=%"PRIu64
703                              "&left=%"PRIu64
704                              "&compact=1"
705                              "&numwant=%d"
706                              "&key=%s"
707                              "&supportcrypto=1"
708                              "&requirecrypto=%d"
709                              "%s%s"
710                              "%s%s",
711        ann,
712        strchr(ann, '?') ? '&' : '?',
713        t->escaped,
714        t->peer_id,
715        tr_sharedGetPublicPort( t->handle->shared ),
716        torrent->uploadedCur,
717        torrent->downloadedCur,
718        torrent->corruptCur,
719        tr_cpLeftUntilComplete( torrent->completion ),
720        numwant,
721        t->key_param,
722        ( t->handle->encryptionMode==TR_ENCRYPTION_REQUIRED ? 1 : 0 ),
723        ( ( eventName && *eventName ) ? "&event=" : "" ),
724        ( ( eventName && *eventName ) ? eventName : "" ),
725        ( ( t->trackerID && *t->trackerID ) ? "&trackerid=" : "" ),
726        ( ( t->trackerID && *t->trackerID ) ? t->trackerID : "" ) );
727
728    ret = tr_strdup( (char*) EVBUFFER_DATA( buf ) );
729    evbuffer_free( buf );
730    return ret;
731}
732
733static struct tr_tracker_request*
734createRequest( tr_handle * handle, const tr_tracker * tracker, int reqtype )
735{
736    static const char* strings[TR_REQ_COUNT] = { "started", "completed", "stopped", "", "err" };
737    const tr_torrent * torrent = tr_torrentFindFromHash( handle, tracker->hash );
738    const tr_tracker_info * address = getCurrentAddress( tracker );
739    const int isStopping = reqtype == TR_REQ_STOPPED;
740    const char * eventName = strings[reqtype];
741    struct tr_tracker_request * req;
742
743    req = tr_new0( struct tr_tracker_request, 1 );
744    req->address = tr_strdup( address->address );
745    req->port = address->port;
746    req->uri = buildTrackerRequestURI( tracker, torrent, eventName );
747    req->timeout = isStopping ? STOP_TIMEOUT_INTERVAL_SEC : TIMEOUT_INTERVAL_SEC;
748    req->reqtype = reqtype;
749    req->req = isStopping
750        ? evhttp_request_new( onStoppedResponse, handle )
751        : evhttp_request_new( onTrackerResponse, torrentHashNew(handle, tracker) );
752    memcpy( req->torrent_hash, tracker->hash, SHA_DIGEST_LENGTH );
753    addCommonHeaders( tracker, req->req );
754
755    return req;
756}
757
758static struct tr_tracker_request*
759createScrape( tr_handle * handle, const tr_tracker * tracker )
760{
761    const tr_tracker_info * a = getCurrentAddress( tracker );
762    struct tr_tracker_request * req;
763
764    req = tr_new0( struct tr_tracker_request, 1 );
765    req->address = tr_strdup( a->address );
766    req->port = a->port;
767    req->timeout = TIMEOUT_INTERVAL_SEC;
768    req->req = evhttp_request_new( onScrapeResponse, torrentHashNew( handle, tracker ) );
769    req->reqtype = TR_REQ_SCRAPE;
770    tr_asprintf( &req->uri, "%s%cinfo_hash=%s", a->scrape, strchr(a->scrape,'?')?'&':'?', tracker->escaped );
771    memcpy( req->torrent_hash, tracker->hash, SHA_DIGEST_LENGTH );
772    addCommonHeaders( tracker, req->req );
773
774    return req;
775}
776
777struct tr_tracker_handle
778{
779    int socketCount;
780    unsigned int isShuttingDown : 1;
781    tr_timer * pulseTimer;
782    tr_list * requestQueue;
783    tr_list * scrapeQueue;
784};
785
786static int pulse( void * vhandle );
787
788static void
789ensureGlobalsExist( tr_handle * handle )
790{
791    if( handle->tracker == NULL )
792    {
793        handle->tracker = tr_new0( struct tr_tracker_handle, 1 );
794        handle->tracker->pulseTimer = tr_timerNew( handle, pulse, handle, PULSE_INTERVAL_MSEC );
795        dbgmsg( NULL, "creating tracker timer" );
796    }
797}
798
799static void
800freeRequest2( void * req )
801{
802    freeRequest( req );
803}
804
805void
806tr_trackerShuttingDown( tr_handle * handle )
807{
808    if( handle->tracker )
809    {
810        /* since we're shutting down, we don't need to scrape anymore... */
811        tr_list_free( &handle->tracker->scrapeQueue, freeRequest2 );
812
813        handle->tracker->isShuttingDown = 1;
814    }
815}
816
817static int
818maybeFreeGlobals( tr_handle * handle )
819{
820    int globalsExist = handle->tracker != NULL;
821
822    if( globalsExist
823        && ( handle->tracker->socketCount < 1 )
824        && ( handle->tracker->requestQueue == NULL )
825        && ( handle->tracker->scrapeQueue == NULL )
826        && ( handle->torrentList== NULL ) )
827    {
828        dbgmsg( NULL, "freeing tracker timer" );
829        tr_timerFree( &handle->tracker->pulseTimer );
830        tr_free( handle->tracker );
831        handle->tracker = NULL;
832        globalsExist = FALSE;
833    }
834
835    return globalsExist;
836}
837
838/***
839****
840***/
841
842static int
843freeConnection( void * evcon )
844{
845    evhttp_connection_free( evcon );
846    return FALSE;
847}
848static void
849connectionClosedCB( struct evhttp_connection * evcon, void * vhandle )
850{
851    tr_handle * handle = vhandle;
852
853    /* libevent references evcon right after calling this function,
854       so we can't free it yet... defer it to after this call chain
855       has played out */
856    tr_timerNew( handle, freeConnection, evcon, 100 );
857}
858
859static struct evhttp_connection*
860getConnection( tr_handle * handle, const char * address, int port )
861{
862    struct evhttp_connection * c = evhttp_connection_new( address, port );
863    evhttp_connection_set_closecb( c, connectionClosedCB, handle );
864    return c;
865}
866
867static void
868invokeRequest( tr_handle * handle, const struct tr_tracker_request * req )
869{
870    const time_t now = time( NULL );
871    struct evhttp_connection * evcon = getConnection( handle, req->address, req->port );
872    tr_tracker * t = findTracker( handle, req->torrent_hash );
873    dbgmsg( t, "sending '%s' to tracker %s:%d, timeout is %d", req->uri, req->address, req->port, (int)req->timeout );
874    evhttp_connection_set_timeout( evcon, req->timeout );
875    ++handle->tracker->socketCount;
876
877    if( t != NULL )
878    {
879        if( req->reqtype == TR_REQ_SCRAPE )
880        {
881            t->lastScrapeTime = now;
882            t->scrapeAt = 0;
883        }
884        else
885        {
886            t->lastAnnounceTime = now;
887            t->reannounceAt = 0;
888            t->manualAnnounceAllowedAt = 0;
889        }
890    }
891
892    if( evhttp_make_request( evcon, req->req, EVHTTP_REQ_GET, req->uri ))
893        (*req->req->cb)(req->req, req->req->cb_arg);
894    else
895        dbgmsg( t, "incremented socket count to %d", handle->tracker->socketCount );
896}
897
898static void
899invokeNextInQueue( tr_handle * handle, tr_list ** list )
900{
901    struct tr_tracker_request * req = tr_list_pop_front( list );
902    invokeRequest( handle, req );
903    freeRequest( req );
904}
905
906static int
907socketIsAvailable( tr_handle * handle )
908{
909    const int max = handle->tracker->isShuttingDown
910                      ? MAX_TRACKER_SOCKETS_DURING_SHUTDOWN
911                      : MAX_TRACKER_SOCKETS;
912    return handle->tracker->socketCount < max;
913}
914
915static void ensureGlobalsExist( tr_handle * );
916
917static void
918enqueueScrape( tr_handle * handle, const tr_tracker * tracker )
919{
920    struct tr_tracker_request * req;
921    ensureGlobalsExist( handle );
922    req = createScrape( handle, tracker );
923    tr_list_append( &handle->tracker->scrapeQueue, req );
924}
925
926static void
927enqueueRequest( tr_handle * handle, const tr_tracker * tracker, int reqtype )
928{
929    struct tr_tracker_request * req;
930    ensureGlobalsExist( handle );
931    req = createRequest( handle, tracker, reqtype );
932    tr_list_append( &handle->tracker->requestQueue, req );
933}
934
935static void
936scrapeSoon( tr_tracker * t )
937{
938    if( trackerSupportsScrape( t ) )
939        t->scrapeAt = time( NULL ) + t->randOffset;
940}
941
942static int
943pulse( void * vhandle )
944{
945    tr_handle * handle = vhandle;
946    struct tr_tracker_handle * th = handle->tracker;
947    tr_torrent * tor;
948    const time_t now = time( NULL );
949
950    if( handle->tracker == NULL )
951        return FALSE;
952
953    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
954        dbgmsg( NULL, "tracker pulse... %d sockets, %d reqs left, %d scrapes left", handle->tracker->socketCount, tr_list_size(th->requestQueue), tr_list_size(th->scrapeQueue) );
955
956    /* upkeep: queue periodic rescrape / reannounce */
957    for( tor=handle->torrentList; tor; tor=tor->next )
958    {
959        tr_tracker * t = tor->tracker;
960
961        if( t->scrapeAt && trackerSupportsScrape( t ) && ( now >= t->scrapeAt ) ) {
962            t->scrapeAt = 0;
963            enqueueScrape( handle, t );
964        }
965
966        if( t->reannounceAt && t->isRunning && ( now >= t->reannounceAt ) ) {
967            t->reannounceAt = 0;
968            enqueueRequest( handle, t, TR_REQ_REANNOUNCE );
969        }
970    }
971
972    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
973        dbgmsg( NULL, "tracker pulse after upkeep... %d sockets, %d reqs left, %d scrapes left", handle->tracker->socketCount, tr_list_size(th->requestQueue), tr_list_size(th->scrapeQueue) );
974
975    /* look for things to do... process all the requests, then process all the scrapes */
976    while( th->requestQueue && socketIsAvailable( handle ) )
977        invokeNextInQueue( handle, &th->requestQueue );
978    while( th->scrapeQueue && socketIsAvailable( handle ) )
979        invokeNextInQueue( handle, &th->scrapeQueue );
980
981    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
982        dbgmsg( NULL, "tracker pulse done... %d sockets, %d reqs left, %d scrapes left", handle->tracker->socketCount, tr_list_size(th->requestQueue), tr_list_size(th->scrapeQueue) );
983
984    return maybeFreeGlobals( handle );
985}
986
987static void
988onReqDone( tr_handle * handle )
989{
990    if( handle->tracker )
991    {
992        pulse( handle );
993        --handle->tracker->socketCount;
994        dbgmsg( NULL, "decrementing socket count to %d", handle->tracker->socketCount );
995    }
996}
997
998/***
999****  LIFE CYCLE
1000***/
1001
1002static void
1003generateKeyParam( char * msg, int len )
1004{
1005    int i;
1006    const char * pool = "abcdefghijklmnopqrstuvwxyz0123456789";
1007    const int poolSize = strlen( pool );
1008    for( i=0; i<len; ++i )
1009        *msg++ = pool[tr_rand(poolSize)];
1010    *msg = '\0';
1011}
1012
1013static int
1014is_rfc2396_alnum( char ch )
1015{
1016    return ( (ch >= 'a' && ch <= 'z' )
1017            || (ch >= 'A' && ch <= 'Z' )
1018            || (ch >= '0' && ch <= '9' ) );
1019}
1020
1021static void
1022escape( char * out, const uint8_t * in, int in_len ) /* rfc2396 */
1023{
1024    const uint8_t *end = in + in_len;
1025    while( in != end )
1026        if( is_rfc2396_alnum(*in) )
1027            *out++ = (char) *in++;
1028        else 
1029            out += snprintf( out, 4, "%%%02X", (unsigned int)*in++ );
1030    *out = '\0';
1031}
1032
1033tr_tracker *
1034tr_trackerNew( const tr_torrent * torrent )
1035{
1036    const tr_info * info = &torrent->info;
1037    int i, j, sum, *iwalk;
1038    tr_tracker_info * nwalk;
1039    tr_tracker * t;
1040
1041    t = tr_new0( tr_tracker, 1 );
1042    t->handle = torrent->handle;
1043    t->scrapeIntervalSec       = DEFAULT_SCRAPE_INTERVAL_SEC;
1044    t->announceIntervalSec     = DEFAULT_ANNOUNCE_INTERVAL_SEC;
1045    t->announceMinIntervalSec  = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
1046    generateKeyParam( t->key_param, KEYLEN );
1047
1048    t->publisher = tr_publisherNew( );
1049    t->timesDownloaded = -1;
1050    t->seederCount = -1;
1051    t->leecherCount = -1;
1052    t->manualAnnounceAllowedAt = ~(time_t)0;
1053    t->name = tr_strdup( info->name );
1054    t->randOffset = tr_rand( 60 );
1055    memcpy( t->hash, info->hash, SHA_DIGEST_LENGTH );
1056    escape( t->escaped, info->hash, SHA_DIGEST_LENGTH );
1057
1058    for( sum=i=0; i<info->trackerTiers; ++i )
1059         sum += info->trackerList[i].count;
1060    t->addresses = nwalk = tr_new0( tr_tracker_info, sum );
1061    t->addressIndex = 0;
1062    t->addressCount = sum;
1063    t->tierFronts = iwalk = tr_new0( int, sum );
1064
1065    for( i=0; i<info->trackerTiers; ++i )
1066    {
1067        const int tierFront = nwalk - t->addresses;
1068
1069        for( j=0; j<info->trackerList[i].count; ++j )
1070        {
1071            const tr_tracker_info * src = &info->trackerList[i].list[j];
1072            nwalk->address = tr_strdup( src->address );
1073            nwalk->port = src->port;
1074            nwalk->announce = tr_strdup( src->announce );
1075            nwalk->scrape = tr_strdup( src->scrape );
1076            ++nwalk;
1077
1078            *iwalk++ = tierFront;
1079        }
1080    }
1081
1082    assert( nwalk - t->addresses == sum );
1083    assert( iwalk - t->tierFronts == sum );
1084
1085    scrapeSoon( t );
1086
1087    return t;
1088}
1089
1090static void
1091onTrackerFreeNow( void * vt )
1092{
1093    int i;
1094    tr_tracker * t = vt;
1095
1096    tr_publisherFree( &t->publisher );
1097    tr_free( t->name );
1098    tr_free( t->trackerID );
1099    tr_free( t->peer_id );
1100
1101    /* addresses... */
1102    for( i=0; i<t->addressCount; ++i )
1103        tr_trackerInfoClear( &t->addresses[i] );
1104    tr_free( t->addresses );
1105    tr_free( t->tierFronts );
1106
1107    /* redirect... */
1108    if( t->redirect ) {
1109        tr_trackerInfoClear( t->redirect );
1110        tr_free( t->redirect );
1111    }
1112
1113    tr_free( t );
1114}
1115
1116void
1117tr_trackerFree( tr_tracker * t )
1118{
1119    tr_runInEventThread( t->handle, onTrackerFreeNow, t );
1120}
1121
1122
1123/***
1124****  PUBLIC
1125***/
1126
1127tr_publisher_tag
1128tr_trackerSubscribe( tr_tracker          * t,
1129                     tr_delivery_func      func,
1130                     void                * user_data )
1131{
1132    return tr_publisherSubscribe( t->publisher, func, user_data );
1133}
1134
1135void
1136tr_trackerUnsubscribe( tr_tracker        * t,
1137                       tr_publisher_tag    tag )
1138{
1139    tr_publisherUnsubscribe( t->publisher, tag );
1140}
1141
1142const tr_tracker_info *
1143tr_trackerGetAddress( const tr_tracker   * t )
1144{
1145    return getCurrentAddress( t );
1146}
1147
1148time_t
1149tr_trackerGetManualAnnounceTime( const struct tr_tracker * t )
1150{
1151    return t->isRunning ? t->manualAnnounceAllowedAt : 0;
1152}
1153
1154int
1155tr_trackerCanManualAnnounce ( const tr_tracker * t)
1156{
1157    const time_t allow = tr_trackerGetManualAnnounceTime( t );
1158    return allow && ( allow <= time( NULL ) );
1159}
1160
1161void
1162tr_trackerGetCounts( const tr_tracker  * t,
1163                     int               * setme_completedCount,
1164                     int               * setme_leecherCount,
1165                     int               * setme_seederCount )
1166{
1167    if( setme_completedCount )
1168       *setme_completedCount = t->timesDownloaded;
1169
1170    if( setme_leecherCount )
1171       *setme_leecherCount = t->leecherCount;
1172
1173    if( setme_seederCount )
1174       *setme_seederCount = t->seederCount;
1175}
1176
1177
1178void
1179tr_trackerStart( tr_tracker * t )
1180{
1181    tr_free( t->peer_id );
1182    t->peer_id = tr_peerIdNew( );
1183
1184    if( t->isRunning == 0 ) {
1185        t->isRunning = 1;
1186        enqueueRequest( t->handle, t, TR_REQ_STARTED );
1187    }
1188}
1189
1190void
1191tr_trackerReannounce( tr_tracker * t )
1192{
1193    enqueueRequest( t->handle, t, TR_REQ_REANNOUNCE );
1194}
1195
1196void
1197tr_trackerCompleted( tr_tracker * t )
1198{
1199    enqueueRequest( t->handle, t, TR_REQ_COMPLETED );
1200}
1201
1202void
1203tr_trackerStop( tr_tracker * t )
1204{
1205    if( t->isRunning ) {
1206        t->isRunning = 0;
1207        t->reannounceAt = t->manualAnnounceAllowedAt = 0;
1208        enqueueRequest( t->handle, t, TR_REQ_STOPPED );
1209    }
1210}
1211
1212void
1213tr_trackerChangeMyPort( tr_tracker * t )
1214{
1215    if( t->isRunning )
1216        tr_trackerReannounce( t );
1217}
1218
1219void
1220tr_trackerStat( const tr_tracker * t,
1221                struct tr_tracker_stat * setme)
1222{
1223    assert( t != NULL );
1224    assert( setme != NULL );
1225
1226    strlcpy( setme->scrapeResponse,
1227             t->lastScrapeResponse,
1228             sizeof( setme->scrapeResponse ) );
1229    setme->lastScrapeTime = t->lastScrapeTime;
1230    setme->nextScrapeTime = t->scrapeAt;
1231
1232    strlcpy( setme->announceResponse,
1233             t->lastAnnounceResponse,
1234             sizeof( setme->announceResponse ) );
1235    setme->lastAnnounceTime = t->lastAnnounceTime;
1236    setme->nextAnnounceTime = t->reannounceAt;
1237    setme->nextManualAnnounceTime = t->manualAnnounceAllowedAt;
1238}
Note: See TracBrowser for help on using the repository browser.