source: branches/1.0x/libtransmission/tracker.c @ 5029

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

(1.0x) #690: get multitracker torrents working with the evhttp code

  • Property svn:keywords set to Date Rev Author Id
File size: 33.7 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 5029 2008-02-13 17:18:29Z 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, int * tryAgain )
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    *tryAgain = moveToNextAddress;
340
341    if( moveToNextAddress )
342    {
343        if ( ++t->addressIndex >= t->addressCount ) /* we've tried them all */
344        {
345            *tryAgain = FALSE;
346            t->addressIndex = 0;
347            ret = "Tracker hasn't responded yet.  Retrying...";
348            tr_inf( ret );
349        }
350    }
351
352
353    return ret;
354}
355
356/* Convert to compact form */
357static uint8_t *
358parseOldPeers( benc_val_t * bePeers, int * setmePeerCount )
359{
360    int i;
361    uint8_t *compact, *walk;
362    const int peerCount = bePeers->val.l.count;
363
364    assert( bePeers->type == TYPE_LIST );
365
366    compact = tr_new( uint8_t, peerCount*6 );
367
368    for( i=0, walk=compact; i<peerCount; ++i )
369    {
370        struct in_addr addr;
371        tr_port_t port;
372        benc_val_t * val;
373        benc_val_t * peer = &bePeers->val.l.vals[i];
374
375        val = tr_bencDictFind( peer, "ip" );
376        if( !val || val->type!=TYPE_STR || tr_netResolve(val->val.s.s, &addr) )
377            continue;
378
379        memcpy( walk, &addr, 4 );
380        walk += 4;
381
382        val = tr_bencDictFind( peer, "port" );
383        if( !val || val->type!=TYPE_INT || val->val.i<0 || val->val.i>0xffff )
384            continue;
385
386        port = htons( val->val.i );
387        memcpy( walk, &port, 2 );
388        walk += 2;
389    }
390
391    *setmePeerCount = peerCount;
392    return compact;
393}
394
395static void
396onTrackerResponse( struct evhttp_request * req, void * vhash )
397{
398    const char * warning;
399    int tryAgain;
400    int responseCode;
401    struct torrent_hash * torrent_hash = (struct torrent_hash*) vhash;
402    tr_tracker * t = findTrackerFromHash( torrent_hash );
403
404    onReqDone( torrent_hash->handle );
405    tr_free( torrent_hash );
406
407    if( t == NULL ) /* tracker has been closed */
408        return;
409
410    dbgmsg( t, "got response from tracker: \"%s\"",
411            ( req && req->response_code_line ) ?  req->response_code_line
412                                               : "(null)" );
413
414    tr_inf( "Torrent \"%s\" tracker response: %s",
415            t->name,
416            ( req ? req->response_code_line : "(null)") );
417
418    if( req && ( req->response_code == HTTP_OK ) )
419    {
420        benc_val_t benc;
421        const int bencLoaded = !parseBencResponse( req, &benc );
422
423        publishErrorClear( t );
424
425        if( bencLoaded && benc.type==TYPE_DICT )
426        {
427            benc_val_t * tmp;
428
429            if(( tmp = tr_bencDictFind( &benc, "failure reason" ))) {
430                dbgmsg( t, "got failure message [%s]", tmp->val.s.s );
431                publishErrorMessageAndStop( t, tmp->val.s.s );
432            }
433
434            if(( tmp = tr_bencDictFind( &benc, "warning message" ))) {
435                dbgmsg( t, "got warning message [%s]", tmp->val.s.s );
436                publishWarning( t, tmp->val.s.s );
437            }
438
439            if(( tmp = tr_bencDictFind( &benc, "interval" ))) {
440                dbgmsg( t, "setting interval to %d", tmp->val.i );
441                t->announceIntervalSec = tmp->val.i;
442            }
443
444            if(( tmp = tr_bencDictFind( &benc, "min interval" ))) {
445                dbgmsg( t, "setting min interval to %d", tmp->val.i );
446                t->announceMinIntervalSec = tmp->val.i;
447            }
448
449            if(( tmp = tr_bencDictFind( &benc, "tracker id" )))
450                t->trackerID = tr_strndup( tmp->val.s.s, tmp->val.s.i );
451
452            if(( tmp = tr_bencDictFind( &benc, "complete" )))
453                t->seederCount = tmp->val.i;
454
455            if(( tmp = tr_bencDictFind( &benc, "incomplete" )))
456                t->leecherCount = tmp->val.i;
457
458            if(( tmp = tr_bencDictFind( &benc, "peers" )))
459            {
460                int peerCount = 0;
461                uint8_t * peerCompact = NULL;
462
463                if( tmp->type == TYPE_LIST ) /* original protocol */
464                {
465                    if( tmp->val.l.count > 0 )
466                        peerCompact = parseOldPeers( tmp, &peerCount );
467                }
468                else if( tmp->type == TYPE_STR ) /* "compact" extension */
469                {
470                    if( tmp->val.s.i >= 6 )
471                    {
472                        peerCount = tmp->val.s.i / 6;
473                        peerCompact = tr_new( uint8_t, tmp->val.s.i );
474                        memcpy( peerCompact, tmp->val.s.s, tmp->val.s.i );
475                    }
476                }
477
478                publishNewPeers( t, peerCount, peerCompact );
479                tr_free( peerCompact );
480            }
481        }
482
483        if( bencLoaded )
484            tr_bencFree( &benc );
485    }
486
487    if (( warning = updateAddresses( t, req, &tryAgain ) )) {
488        publishWarning( t, warning );
489        tr_err( warning );
490    }
491
492    /**
493    ***
494    **/
495
496    if( tryAgain )
497        responseCode = 300;
498    else if( req )
499        responseCode = req->response_code;
500    else
501        responseCode = 503;
502
503    if( 200<=responseCode && responseCode<=299 )
504    {
505        dbgmsg( t, "request succeeded. reannouncing in %d seconds",
506                   t->announceIntervalSec );
507        t->reannounceAt = time( NULL ) + t->randOffset + t->announceIntervalSec;
508        t->manualAnnounceAllowedAt = time( NULL ) + t->announceMinIntervalSec;
509    }
510    else if( 300<=responseCode && responseCode<=399 )
511    {
512        dbgmsg( t, "got a redirect; retrying immediately" );
513
514        /* it's a redirect... updateAddresses() has already
515         * parsed the redirect, all that's left is to retry */
516        t->reannounceAt = time( NULL );
517        t->manualAnnounceAllowedAt = time( NULL ) + t->announceMinIntervalSec;
518    }
519    else if( 400<=responseCode && responseCode<=499 )
520    {
521        const char * err = req && req->response_code_line
522            ? req->response_code_line
523            : "Unspecified 4xx error from tracker.";
524        dbgmsg( t, err );
525
526        /* The request could not be understood by the server due to
527         * malformed syntax. The client SHOULD NOT repeat the
528         * request without modifications. */
529        publishErrorMessageAndStop( t, err );
530        t->manualAnnounceAllowedAt = ~(time_t)0;
531        t->reannounceAt = 0;
532    }
533    else if( 500<=responseCode && responseCode<=599 )
534    {
535        dbgmsg( t, "Got a 5xx error... retrying in one minute." );
536
537        /* Response status codes beginning with the digit "5" indicate
538         * cases in which the server is aware that it has erred or is
539         * incapable of performing the request.  So we pause a bit and
540         * try again. */
541        if( req && req->response_code_line )
542            publishWarning( t, req->response_code_line );
543        t->manualAnnounceAllowedAt = ~(time_t)0;
544        t->reannounceAt = time( NULL ) + 60;
545    }
546    else
547    {
548        dbgmsg( t, "Invalid response from tracker... retrying in two minutes." );
549
550        /* WTF did we get?? */
551        if( req && req->response_code_line )
552            publishWarning( t, req->response_code_line );
553        t->manualAnnounceAllowedAt = ~(time_t)0;
554        t->reannounceAt = time( NULL ) + t->randOffset + 120;
555    }
556}
557
558static void
559onScrapeResponse( struct evhttp_request * req, void * vhash )
560{
561    const char * warning;
562    int tryAgain;
563    time_t nextScrapeSec = 60;
564    struct torrent_hash * torrent_hash = (struct torrent_hash*) vhash;
565    tr_tracker * t = findTrackerFromHash( torrent_hash );
566
567    onReqDone( torrent_hash->handle );
568    tr_free( torrent_hash );
569
570    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) );
571
572    if( t == NULL ) /* tracker's been closed... */
573        return;
574
575    tr_inf( "Got scrape response for  '%s': %s",
576            t->name,
577            ( ( req && req->response_code_line ) ? req->response_code_line
578                                                 : "(null)") );
579
580    if( req && ( req->response_code == HTTP_OK ) )
581    {
582        benc_val_t 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                benc_val_t *tmp, *flags;
595                benc_val_t *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_dbg( "Torrent '%s' scrape successful."
615                        "  Rescraping in %d seconds",
616                        t->name, t->scrapeIntervalSec );
617
618                nextScrapeSec = t->scrapeIntervalSec;
619            }
620        }
621
622        if( bencLoaded )
623            tr_bencFree( &benc );
624    }
625
626    if (( warning = updateAddresses( t, req, &tryAgain ) ))
627    {
628        tr_err( warning );
629        publishWarning( t, warning );
630    }
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    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    struct evhttp_connection * evcon = getConnection( handle, req->address, req->port );
871    tr_tracker * t = findTracker( handle, req->torrent_hash );
872    dbgmsg( t, "sending '%s' to tracker %s:%d, timeout is %d", req->uri, req->address, req->port, (int)req->timeout );
873    evhttp_connection_set_timeout( evcon, req->timeout );
874    ++handle->tracker->socketCount;
875    if( evhttp_make_request( evcon, req->req, EVHTTP_REQ_GET, req->uri ))
876        (*req->req->cb)(req->req, req->req->cb_arg);
877    else
878        dbgmsg( t, "incremented socket count to %d", handle->tracker->socketCount );
879}
880
881static void
882invokeNextInQueue( tr_handle * handle, tr_list ** list )
883{
884    struct tr_tracker_request * req = tr_list_pop_front( list );
885    invokeRequest( handle, req );
886    freeRequest( req );
887}
888
889static int
890socketIsAvailable( tr_handle * handle )
891{
892    const int max = handle->tracker->isShuttingDown
893                      ? MAX_TRACKER_SOCKETS_DURING_SHUTDOWN
894                      : MAX_TRACKER_SOCKETS;
895    return handle->tracker->socketCount < max;
896}
897
898static void ensureGlobalsExist( tr_handle * );
899
900static void
901enqueueScrape( tr_handle * handle, const tr_tracker * tracker )
902{
903    struct tr_tracker_request * req;
904    ensureGlobalsExist( handle );
905    req = createScrape( handle, tracker );
906    tr_list_append( &handle->tracker->scrapeQueue, req );
907}
908
909static void
910enqueueRequest( tr_handle * handle, const tr_tracker * tracker, int reqtype )
911{
912    struct tr_tracker_request * req;
913    ensureGlobalsExist( handle );
914    req = createRequest( handle, tracker, reqtype );
915    tr_list_append( &handle->tracker->requestQueue, req );
916}
917
918static void
919scrapeSoon( tr_tracker * t )
920{
921    if( trackerSupportsScrape( t ) )
922        t->scrapeAt = time( NULL ) + t->randOffset;
923}
924
925static int
926pulse( void * vhandle )
927{
928    tr_handle * handle = vhandle;
929    struct tr_tracker_handle * th = handle->tracker;
930    tr_torrent * tor;
931    const time_t now = time( NULL );
932
933    if( handle->tracker == NULL )
934        return FALSE;
935
936    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
937        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) );
938
939    /* upkeep: queue periodic rescrape / reannounce */
940    for( tor=handle->torrentList; tor; tor=tor->next )
941    {
942        tr_tracker * t = tor->tracker;
943
944        if( t->scrapeAt && trackerSupportsScrape( t ) && ( now >= t->scrapeAt ) ) {
945            t->scrapeAt = 0;
946            enqueueScrape( handle, t );
947        }
948
949        if( t->reannounceAt && t->isRunning && ( now >= t->reannounceAt ) ) {
950            t->reannounceAt = 0;
951            enqueueRequest( handle, t, TR_REQ_REANNOUNCE );
952        }
953    }
954
955    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
956        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) );
957
958    /* look for things to do... process all the requests, then process all the scrapes */
959    while( th->requestQueue && socketIsAvailable( handle ) )
960        invokeNextInQueue( handle, &th->requestQueue );
961    while( th->scrapeQueue && socketIsAvailable( handle ) )
962        invokeNextInQueue( handle, &th->scrapeQueue );
963
964    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
965        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) );
966
967    return maybeFreeGlobals( handle );
968}
969
970static void
971onReqDone( tr_handle * handle )
972{
973    if( handle->tracker )
974    {
975        pulse( handle );
976        --handle->tracker->socketCount;
977        dbgmsg( NULL, "decrementing socket count to %d", handle->tracker->socketCount );
978    }
979}
980
981/***
982****  LIFE CYCLE
983***/
984
985static void
986generateKeyParam( char * msg, int len )
987{
988    int i;
989    const char * pool = "abcdefghijklmnopqrstuvwxyz0123456789";
990    const int poolSize = strlen( pool );
991    for( i=0; i<len; ++i )
992        *msg++ = pool[tr_rand(poolSize)];
993    *msg = '\0';
994}
995
996static int
997is_rfc2396_alnum( char ch )
998{
999    return ( (ch >= 'a' && ch <= 'z' )
1000            || (ch >= 'A' && ch <= 'Z' )
1001            || (ch >= '0' && ch <= '9' ) );
1002}
1003
1004static void
1005escape( char * out, const uint8_t * in, int in_len ) /* rfc2396 */
1006{
1007    const uint8_t *end = in + in_len;
1008    while( in != end )
1009        if( is_rfc2396_alnum(*in) )
1010            *out++ = (char) *in++;
1011        else 
1012            out += snprintf( out, 4, "%%%02X", (unsigned int)*in++ );
1013    *out = '\0';
1014}
1015
1016tr_tracker *
1017tr_trackerNew( const tr_torrent * torrent )
1018{
1019    const tr_info * info = &torrent->info;
1020    int i, j, sum, *iwalk;
1021    tr_tracker_info * nwalk;
1022    tr_tracker * t;
1023
1024    t = tr_new0( tr_tracker, 1 );
1025    t->handle = torrent->handle;
1026    t->scrapeIntervalSec       = DEFAULT_SCRAPE_INTERVAL_SEC;
1027    t->announceIntervalSec     = DEFAULT_ANNOUNCE_INTERVAL_SEC;
1028    t->announceMinIntervalSec  = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
1029    generateKeyParam( t->key_param, KEYLEN );
1030
1031    t->publisher = tr_publisherNew( );
1032    t->timesDownloaded = -1;
1033    t->seederCount = -1;
1034    t->leecherCount = -1;
1035    t->manualAnnounceAllowedAt = ~(time_t)0;
1036    t->name = tr_strdup( info->name );
1037    t->randOffset = tr_rand( 60 );
1038    memcpy( t->hash, info->hash, SHA_DIGEST_LENGTH );
1039    escape( t->escaped, info->hash, SHA_DIGEST_LENGTH );
1040
1041    for( sum=i=0; i<info->trackerTiers; ++i )
1042         sum += info->trackerList[i].count;
1043    t->addresses = nwalk = tr_new0( tr_tracker_info, sum );
1044    t->addressIndex = 0;
1045    t->addressCount = sum;
1046    t->tierFronts = iwalk = tr_new0( int, sum );
1047
1048    for( i=0; i<info->trackerTiers; ++i )
1049    {
1050        const int tierFront = nwalk - t->addresses;
1051
1052        for( j=0; j<info->trackerList[i].count; ++j )
1053        {
1054            const tr_tracker_info * src = &info->trackerList[i].list[j];
1055            nwalk->address = tr_strdup( src->address );
1056            nwalk->port = src->port;
1057            nwalk->announce = tr_strdup( src->announce );
1058            nwalk->scrape = tr_strdup( src->scrape );
1059            ++nwalk;
1060
1061            *iwalk++ = tierFront;
1062        }
1063    }
1064
1065    assert( nwalk - t->addresses == sum );
1066    assert( iwalk - t->tierFronts == sum );
1067
1068    scrapeSoon( t );
1069
1070    return t;
1071}
1072
1073static void
1074onTrackerFreeNow( void * vt )
1075{
1076    int i;
1077    tr_tracker * t = vt;
1078
1079    tr_publisherFree( &t->publisher );
1080    tr_free( t->name );
1081    tr_free( t->trackerID );
1082    tr_free( t->peer_id );
1083
1084    /* addresses... */
1085    for( i=0; i<t->addressCount; ++i )
1086        tr_trackerInfoClear( &t->addresses[i] );
1087    tr_free( t->addresses );
1088    tr_free( t->tierFronts );
1089
1090    /* redirect... */
1091    if( t->redirect ) {
1092        tr_trackerInfoClear( t->redirect );
1093        tr_free( t->redirect );
1094    }
1095
1096    tr_free( t );
1097}
1098
1099void
1100tr_trackerFree( tr_tracker * t )
1101{
1102    tr_runInEventThread( t->handle, onTrackerFreeNow, t );
1103}
1104
1105
1106/***
1107****  PUBLIC
1108***/
1109
1110tr_publisher_tag
1111tr_trackerSubscribe( tr_tracker          * t,
1112                     tr_delivery_func      func,
1113                     void                * user_data )
1114{
1115    return tr_publisherSubscribe( t->publisher, func, user_data );
1116}
1117
1118void
1119tr_trackerUnsubscribe( tr_tracker        * t,
1120                       tr_publisher_tag    tag )
1121{
1122    tr_publisherUnsubscribe( t->publisher, tag );
1123}
1124
1125const tr_tracker_info *
1126tr_trackerGetAddress( const tr_tracker   * t )
1127{
1128    return getCurrentAddress( t );
1129}
1130
1131int
1132tr_trackerCanManualAnnounce ( const tr_tracker * t)
1133{
1134    return t->isRunning
1135            && ( time(NULL) >= t->manualAnnounceAllowedAt );
1136}
1137
1138void
1139tr_trackerGetCounts( const tr_tracker  * t,
1140                     int               * setme_completedCount,
1141                     int               * setme_leecherCount,
1142                     int               * setme_seederCount )
1143{
1144    if( setme_completedCount )
1145       *setme_completedCount = t->timesDownloaded;
1146
1147    if( setme_leecherCount )
1148       *setme_leecherCount = t->leecherCount;
1149
1150    if( setme_seederCount )
1151       *setme_seederCount = t->seederCount;
1152}
1153
1154
1155void
1156tr_trackerStart( tr_tracker * t )
1157{
1158    tr_free( t->peer_id );
1159    t->peer_id = tr_peerIdNew( );
1160
1161    if( t->isRunning == 0 ) {
1162        t->isRunning = 1;
1163        enqueueRequest( t->handle, t, TR_REQ_STARTED );
1164    }
1165}
1166
1167void
1168tr_trackerReannounce( tr_tracker * t )
1169{
1170    enqueueRequest( t->handle, t, TR_REQ_REANNOUNCE );
1171}
1172
1173void
1174tr_trackerCompleted( tr_tracker * t )
1175{
1176    enqueueRequest( t->handle, t, TR_REQ_COMPLETED );
1177}
1178
1179void
1180tr_trackerStop( tr_tracker * t )
1181{
1182    if( t->isRunning ) {
1183        t->isRunning = 0;
1184        enqueueRequest( t->handle, t, TR_REQ_STOPPED );
1185    }
1186}
1187
1188void
1189tr_trackerChangeMyPort( tr_tracker * t )
1190{
1191    if( t->isRunning )
1192        tr_trackerReannounce( t );
1193}
Note: See TracBrowser for help on using the repository browser.