source: trunk/libtransmission/tracker.c @ 4878

Last change on this file since 4878 was 4878, checked in by charles, 15 years ago

fix off-by-one that was uncovered by the new benc's stricter parsing.

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