source: trunk/libtransmission/tracker.c @ 5647

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

#890: be smarter about noticing seeds from tracker & pex

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