source: trunk/libtransmission/tracker.c @ 5650

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

peer-msgs: faster upload speeds in situations with few peers. this patch needs wider testing for side-effects wrt speed limits.

  • Property svn:keywords set to Date Rev Author Id
File size: 36.0 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 5650 2008-04-19 19:37:05Z 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        tr_ndbg( t->name, "request succeeded. rescraping in %d seconds", interval );
643        t->scrapeAt = time( NULL ) + interval;
644    }
645    else if( 300<=responseCode && responseCode<=399 )
646    {
647        const int interval = 5;
648        dbgmsg( t, "got a redirect. retrying in %d seconds", interval );
649        t->scrapeAt = time( NULL ) + interval;
650    }
651    else
652    {
653        const int interval = t->retryScrapeIntervalSec + t->randOffset;
654        dbgmsg( t, "Tracker responded to scrape with %d.  Retrying in %d seconds.", responseCode,  interval );
655        t->retryScrapeIntervalSec *= 2;
656        t->scrapeAt = time( NULL ) + interval;
657    }
658}
659
660/***
661****
662***/
663
664enum
665{
666    TR_REQ_STARTED,
667    TR_REQ_COMPLETED,
668    TR_REQ_STOPPED,
669    TR_REQ_REANNOUNCE,
670    TR_REQ_SCRAPE,
671    TR_REQ_COUNT
672};
673
674struct tr_tracker_request
675{
676    int port;
677    int timeout;
678    int reqtype; /* TR_REQ_* */
679    char * address;
680    char * uri;
681    struct evhttp_request * req;
682    uint8_t torrent_hash[SHA_DIGEST_LENGTH];
683};
684
685static void
686freeRequest( struct tr_tracker_request * req )
687{
688    tr_free( req->address );
689    tr_free( req->uri );
690    tr_free( req );
691}
692
693static void
694addCommonHeaders( const tr_tracker * t,
695                  struct evhttp_request * req )
696{
697    char buf[1024];
698    const tr_tracker_info * address = getCurrentAddress( t );
699    snprintf( buf, sizeof(buf), "%s:%d", address->address, address->port );
700    evhttp_add_header( req->output_headers, "Host", buf );
701    evhttp_add_header( req->output_headers, "Connection", "close" );
702    evhttp_add_header( req->output_headers, "User-Agent",
703                                         TR_NAME "/" LONG_VERSION_STRING );
704}
705
706static char*
707buildTrackerRequestURI( const tr_tracker  * t,
708                        const tr_torrent  * torrent,
709                        const char        * eventName )
710{
711    const int isStopping = !strcmp( eventName, "stopped" );
712    const int numwant = isStopping ? 0 : NUMWANT;
713    struct evbuffer * buf = evbuffer_new( );
714    char * ret;
715
716    const char * ann = getCurrentAddress(t)->announce;
717   
718    evbuffer_add_printf( buf, "%s"
719                              "%cinfo_hash=%s"
720                              "&peer_id=%s"
721                              "&port=%d"
722                              "&uploaded=%"PRIu64
723                              "&downloaded=%"PRIu64
724                              "&corrupt=%"PRIu64
725                              "&left=%"PRIu64
726                              "&compact=1"
727                              "&numwant=%d"
728                              "&key=%s"
729                              "&supportcrypto=1"
730                              "&requirecrypto=%d"
731                              "%s%s"
732                              "%s%s",
733        ann,
734        strchr(ann, '?') ? '&' : '?',
735        t->escaped,
736        t->peer_id,
737        tr_sharedGetPublicPort( t->handle->shared ),
738        torrent->uploadedCur,
739        torrent->downloadedCur,
740        torrent->corruptCur,
741        tr_cpLeftUntilComplete( torrent->completion ),
742        numwant,
743        t->key_param,
744        ( t->handle->encryptionMode==TR_ENCRYPTION_REQUIRED ? 1 : 0 ),
745        ( ( eventName && *eventName ) ? "&event=" : "" ),
746        ( ( eventName && *eventName ) ? eventName : "" ),
747        ( ( t->trackerID && *t->trackerID ) ? "&trackerid=" : "" ),
748        ( ( t->trackerID && *t->trackerID ) ? t->trackerID : "" ) );
749
750    ret = tr_strdup( (char*) EVBUFFER_DATA( buf ) );
751    evbuffer_free( buf );
752    return ret;
753}
754
755static struct tr_tracker_request*
756createRequest( tr_handle * handle, const tr_tracker * tracker, int reqtype )
757{
758    static const char* strings[TR_REQ_COUNT] = { "started", "completed", "stopped", "", "err" };
759    const tr_torrent * torrent = tr_torrentFindFromHash( handle, tracker->hash );
760    const tr_tracker_info * address = getCurrentAddress( tracker );
761    const int isStopping = reqtype == TR_REQ_STOPPED;
762    const char * eventName = strings[reqtype];
763    struct tr_tracker_request * req;
764
765    req = tr_new0( struct tr_tracker_request, 1 );
766    req->address = tr_strdup( address->address );
767    req->port = address->port;
768    req->uri = buildTrackerRequestURI( tracker, torrent, eventName );
769    req->timeout = isStopping ? STOP_TIMEOUT_INTERVAL_SEC : TIMEOUT_INTERVAL_SEC;
770    req->reqtype = reqtype;
771    req->req = isStopping
772        ? evhttp_request_new( onStoppedResponse, handle )
773        : evhttp_request_new( onTrackerResponse, torrentHashNew(handle, tracker) );
774    memcpy( req->torrent_hash, tracker->hash, SHA_DIGEST_LENGTH );
775    addCommonHeaders( tracker, req->req );
776
777    return req;
778}
779
780static struct tr_tracker_request*
781createScrape( tr_handle * handle, const tr_tracker * tracker )
782{
783    const tr_tracker_info * a = getCurrentAddress( tracker );
784    struct tr_tracker_request * req;
785
786    req = tr_new0( struct tr_tracker_request, 1 );
787    req->address = tr_strdup( a->address );
788    req->port = a->port;
789    req->timeout = TIMEOUT_INTERVAL_SEC;
790    req->req = evhttp_request_new( onScrapeResponse, torrentHashNew( handle, tracker ) );
791    req->reqtype = TR_REQ_SCRAPE;
792    tr_asprintf( &req->uri, "%s%cinfo_hash=%s", a->scrape, strchr(a->scrape,'?')?'&':'?', tracker->escaped );
793    memcpy( req->torrent_hash, tracker->hash, SHA_DIGEST_LENGTH );
794    addCommonHeaders( tracker, req->req );
795
796    return req;
797}
798
799struct tr_tracker_handle
800{
801    int socketCount;
802    unsigned int isShuttingDown : 1;
803    tr_timer * pulseTimer;
804    tr_list * requestQueue;
805    tr_list * scrapeQueue;
806};
807
808static int pulse( void * vhandle );
809
810static void
811ensureGlobalsExist( tr_handle * handle )
812{
813    if( handle->tracker == NULL )
814    {
815        handle->tracker = tr_new0( struct tr_tracker_handle, 1 );
816        handle->tracker->pulseTimer = tr_timerNew( handle, pulse, handle, PULSE_INTERVAL_MSEC );
817        dbgmsg( NULL, "creating tracker timer" );
818    }
819}
820
821static void
822freeRequest2( void * req )
823{
824    freeRequest( req );
825}
826
827void
828tr_trackerShuttingDown( tr_handle * handle )
829{
830    if( handle->tracker )
831    {
832        /* since we're shutting down, we don't need to scrape anymore... */
833        tr_list_free( &handle->tracker->scrapeQueue, freeRequest2 );
834
835        handle->tracker->isShuttingDown = 1;
836    }
837}
838
839static int
840maybeFreeGlobals( tr_handle * handle )
841{
842    int globalsExist = handle->tracker != NULL;
843
844    if( globalsExist
845        && ( handle->tracker->socketCount < 1 )
846        && ( handle->tracker->requestQueue == NULL )
847        && ( handle->tracker->scrapeQueue == NULL )
848        && ( handle->torrentList== NULL ) )
849    {
850        dbgmsg( NULL, "freeing tracker timer" );
851        tr_timerFree( &handle->tracker->pulseTimer );
852        tr_free( handle->tracker );
853        handle->tracker = NULL;
854        globalsExist = FALSE;
855    }
856
857    return globalsExist;
858}
859
860/***
861****
862***/
863
864static int
865freeConnection( void * evcon )
866{
867    evhttp_connection_free( evcon );
868    return FALSE;
869}
870static void
871connectionClosedCB( struct evhttp_connection * evcon, void * vhandle )
872{
873    tr_handle * handle = vhandle;
874
875    /* libevent references evcon right after calling this function,
876       so we can't free it yet... defer it to after this call chain
877       has played out */
878    tr_timerNew( handle, freeConnection, evcon, 100 );
879}
880
881static struct evhttp_connection*
882getConnection( tr_handle * handle, const char * address, int port )
883{
884    struct evhttp_connection * c = evhttp_connection_new( address, port );
885    evhttp_connection_set_closecb( c, connectionClosedCB, handle );
886    return c;
887}
888
889static void
890invokeRequest( tr_handle * handle, const struct tr_tracker_request * req )
891{
892    const time_t now = time( NULL );
893    struct evhttp_connection * evcon = getConnection( handle, req->address, req->port );
894    tr_tracker * t = findTracker( handle, req->torrent_hash );
895    dbgmsg( t, "sending '%s' to tracker %s:%d, timeout is %d", req->uri, req->address, req->port, (int)req->timeout );
896    evhttp_connection_set_timeout( evcon, req->timeout );
897    ++handle->tracker->socketCount;
898
899    if( t != NULL )
900    {
901        if( req->reqtype == TR_REQ_SCRAPE )
902        {
903            t->lastScrapeTime = now;
904            t->scrapeAt = 0;
905        }
906        else
907        {
908            t->lastAnnounceTime = now;
909            t->reannounceAt = 0;
910            t->manualAnnounceAllowedAt = 0;
911        }
912    }
913
914    if( evhttp_make_request( evcon, req->req, EVHTTP_REQ_GET, req->uri ))
915        (*req->req->cb)(req->req, req->req->cb_arg);
916    else
917        dbgmsg( t, "incremented socket count to %d", handle->tracker->socketCount );
918}
919
920static void
921invokeNextInQueue( tr_handle * handle, tr_list ** list )
922{
923    struct tr_tracker_request * req = tr_list_pop_front( list );
924    invokeRequest( handle, req );
925    freeRequest( req );
926}
927
928static int
929socketIsAvailable( tr_handle * handle )
930{
931    const int max = handle->tracker->isShuttingDown
932                      ? MAX_TRACKER_SOCKETS_DURING_SHUTDOWN
933                      : MAX_TRACKER_SOCKETS;
934    return handle->tracker->socketCount < max;
935}
936
937static void ensureGlobalsExist( tr_handle * );
938
939static void
940enqueueScrape( tr_handle * handle, const tr_tracker * tracker )
941{
942    struct tr_tracker_request * req;
943    ensureGlobalsExist( handle );
944    req = createScrape( handle, tracker );
945    tr_list_append( &handle->tracker->scrapeQueue, req );
946}
947
948static void
949enqueueRequest( tr_handle * handle, const tr_tracker * tracker, int reqtype )
950{
951    struct tr_tracker_request * req;
952    ensureGlobalsExist( handle );
953    req = createRequest( handle, tracker, reqtype );
954    tr_list_append( &handle->tracker->requestQueue, req );
955}
956
957static void
958scrapeSoon( tr_tracker * t )
959{
960    if( trackerSupportsScrape( t ) )
961        t->scrapeAt = time( NULL ) + t->randOffset;
962}
963
964static int
965pulse( void * vhandle )
966{
967    tr_handle * handle = vhandle;
968    struct tr_tracker_handle * th = handle->tracker;
969    tr_torrent * tor;
970    const time_t now = time( NULL );
971
972    if( handle->tracker == NULL )
973        return FALSE;
974
975    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
976        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) );
977
978    /* upkeep: queue periodic rescrape / reannounce */
979    for( tor=handle->torrentList; tor; tor=tor->next )
980    {
981        tr_tracker * t = tor->tracker;
982
983        if( t->scrapeAt && trackerSupportsScrape( t ) && ( now >= t->scrapeAt ) ) {
984            t->scrapeAt = 0;
985            enqueueScrape( handle, t );
986        }
987
988        if( t->reannounceAt && t->isRunning && ( now >= t->reannounceAt ) ) {
989            t->reannounceAt = 0;
990            enqueueRequest( handle, t, TR_REQ_REANNOUNCE );
991        }
992    }
993
994    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
995        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) );
996
997    /* look for things to do... process all the requests, then process all the scrapes */
998    while( th->requestQueue && socketIsAvailable( handle ) )
999        invokeNextInQueue( handle, &th->requestQueue );
1000    while( th->scrapeQueue && socketIsAvailable( handle ) )
1001        invokeNextInQueue( handle, &th->scrapeQueue );
1002
1003    if( handle->tracker->socketCount || tr_list_size(th->requestQueue) || tr_list_size(th->scrapeQueue) )
1004        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) );
1005
1006    return maybeFreeGlobals( handle );
1007}
1008
1009static void
1010onReqDone( tr_handle * handle )
1011{
1012    if( handle->tracker )
1013    {
1014        pulse( handle );
1015        --handle->tracker->socketCount;
1016        dbgmsg( NULL, "decrementing socket count to %d", handle->tracker->socketCount );
1017    }
1018}
1019
1020/***
1021****  LIFE CYCLE
1022***/
1023
1024static void
1025generateKeyParam( char * msg, int len )
1026{
1027    int i;
1028    const char * pool = "abcdefghijklmnopqrstuvwxyz0123456789";
1029    const int poolSize = strlen( pool );
1030    for( i=0; i<len; ++i )
1031        *msg++ = pool[tr_rand(poolSize)];
1032    *msg = '\0';
1033}
1034
1035static int
1036is_rfc2396_alnum( char ch )
1037{
1038    return ( (ch >= 'a' && ch <= 'z' )
1039            || (ch >= 'A' && ch <= 'Z' )
1040            || (ch >= '0' && ch <= '9' ) );
1041}
1042
1043static void
1044escape( char * out, const uint8_t * in, int in_len ) /* rfc2396 */
1045{
1046    const uint8_t *end = in + in_len;
1047    while( in != end )
1048        if( is_rfc2396_alnum(*in) )
1049            *out++ = (char) *in++;
1050        else 
1051            out += snprintf( out, 4, "%%%02X", (unsigned int)*in++ );
1052    *out = '\0';
1053}
1054
1055tr_tracker *
1056tr_trackerNew( const tr_torrent * torrent )
1057{
1058    const tr_info * info = &torrent->info;
1059    int i, j, sum, *iwalk;
1060    tr_tracker_info * nwalk;
1061    tr_tracker * t;
1062
1063    t = tr_new0( tr_tracker, 1 );
1064    t->handle = torrent->handle;
1065    t->scrapeIntervalSec       = DEFAULT_SCRAPE_INTERVAL_SEC;
1066    t->retryScrapeIntervalSec  = 60;
1067    t->announceIntervalSec     = DEFAULT_ANNOUNCE_INTERVAL_SEC;
1068    t->announceMinIntervalSec  = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
1069    generateKeyParam( t->key_param, KEYLEN );
1070
1071    t->publisher = tr_publisherNew( );
1072    t->timesDownloaded = -1;
1073    t->seederCount = -1;
1074    t->leecherCount = -1;
1075    t->manualAnnounceAllowedAt = ~(time_t)0;
1076    t->name = tr_strdup( info->name );
1077    t->randOffset = tr_rand( 60 );
1078    memcpy( t->hash, info->hash, SHA_DIGEST_LENGTH );
1079    escape( t->escaped, info->hash, SHA_DIGEST_LENGTH );
1080
1081    for( sum=i=0; i<info->trackerTiers; ++i )
1082         sum += info->trackerList[i].count;
1083    t->addresses = nwalk = tr_new0( tr_tracker_info, sum );
1084    t->addressIndex = 0;
1085    t->addressCount = sum;
1086    t->tierFronts = iwalk = tr_new0( int, sum );
1087
1088    for( i=0; i<info->trackerTiers; ++i )
1089    {
1090        const int tierFront = nwalk - t->addresses;
1091
1092        for( j=0; j<info->trackerList[i].count; ++j )
1093        {
1094            const tr_tracker_info * src = &info->trackerList[i].list[j];
1095            nwalk->address = tr_strdup( src->address );
1096            nwalk->port = src->port;
1097            nwalk->announce = tr_strdup( src->announce );
1098            nwalk->scrape = tr_strdup( src->scrape );
1099            ++nwalk;
1100
1101            *iwalk++ = tierFront;
1102        }
1103    }
1104
1105    assert( nwalk - t->addresses == sum );
1106    assert( iwalk - t->tierFronts == sum );
1107
1108    scrapeSoon( t );
1109
1110    return t;
1111}
1112
1113static void
1114onTrackerFreeNow( void * vt )
1115{
1116    int i;
1117    tr_tracker * t = vt;
1118
1119    tr_publisherFree( &t->publisher );
1120    tr_free( t->name );
1121    tr_free( t->trackerID );
1122    tr_free( t->peer_id );
1123
1124    /* addresses... */
1125    for( i=0; i<t->addressCount; ++i )
1126        tr_trackerInfoClear( &t->addresses[i] );
1127    tr_free( t->addresses );
1128    tr_free( t->tierFronts );
1129
1130    /* redirect... */
1131    if( t->redirect ) {
1132        tr_trackerInfoClear( t->redirect );
1133        tr_free( t->redirect );
1134    }
1135
1136    tr_free( t );
1137}
1138
1139/***
1140****  PUBLIC
1141***/
1142
1143void
1144tr_trackerFree( tr_tracker * t )
1145{
1146    if( t )
1147        tr_runInEventThread( t->handle, onTrackerFreeNow, t );
1148}
1149
1150tr_publisher_tag
1151tr_trackerSubscribe( tr_tracker          * t,
1152                     tr_delivery_func      func,
1153                     void                * user_data )
1154{
1155    return tr_publisherSubscribe( t->publisher, func, user_data );
1156}
1157
1158void
1159tr_trackerUnsubscribe( tr_tracker        * t,
1160                       tr_publisher_tag    tag )
1161{
1162    if( t )
1163        tr_publisherUnsubscribe( t->publisher, tag );
1164}
1165
1166const tr_tracker_info *
1167tr_trackerGetAddress( const tr_tracker   * t )
1168{
1169    return getCurrentAddress( t );
1170}
1171
1172time_t
1173tr_trackerGetManualAnnounceTime( const struct tr_tracker * t )
1174{
1175    return t->isRunning ? t->manualAnnounceAllowedAt : 0;
1176}
1177
1178int
1179tr_trackerCanManualAnnounce ( const tr_tracker * t)
1180{
1181    const time_t allow = tr_trackerGetManualAnnounceTime( t );
1182    return allow && ( allow <= time( NULL ) );
1183}
1184
1185void
1186tr_trackerGetCounts( const tr_tracker  * t,
1187                     int               * setme_completedCount,
1188                     int               * setme_leecherCount,
1189                     int               * setme_seederCount )
1190{
1191    if( setme_completedCount )
1192       *setme_completedCount = t->timesDownloaded;
1193
1194    if( setme_leecherCount )
1195       *setme_leecherCount = t->leecherCount;
1196
1197    if( setme_seederCount )
1198       *setme_seederCount = t->seederCount;
1199}
1200
1201
1202void
1203tr_trackerStart( tr_tracker * t )
1204{
1205    if( t )
1206    {
1207        tr_free( t->peer_id );
1208        t->peer_id = tr_peerIdNew( );
1209
1210        if( t->isRunning == 0 ) {
1211            t->isRunning = 1;
1212            enqueueRequest( t->handle, t, TR_REQ_STARTED );
1213        }
1214    }
1215}
1216
1217void
1218tr_trackerReannounce( tr_tracker * t )
1219{
1220    enqueueRequest( t->handle, t, TR_REQ_REANNOUNCE );
1221}
1222
1223void
1224tr_trackerCompleted( tr_tracker * t )
1225{
1226    enqueueRequest( t->handle, t, TR_REQ_COMPLETED );
1227}
1228
1229void
1230tr_trackerStop( tr_tracker * t )
1231{
1232    if( t && t->isRunning ) {
1233        t->isRunning = 0;
1234        t->reannounceAt = t->manualAnnounceAllowedAt = 0;
1235        enqueueRequest( t->handle, t, TR_REQ_STOPPED );
1236    }
1237}
1238
1239void
1240tr_trackerChangeMyPort( tr_tracker * t )
1241{
1242    if( t->isRunning )
1243        tr_trackerReannounce( t );
1244}
1245
1246void
1247tr_trackerStat( const tr_tracker * t,
1248                struct tr_tracker_stat * setme)
1249{
1250    assert( t != NULL );
1251    assert( setme != NULL );
1252
1253    strlcpy( setme->scrapeResponse,
1254             t->lastScrapeResponse,
1255             sizeof( setme->scrapeResponse ) );
1256    setme->lastScrapeTime = t->lastScrapeTime;
1257    setme->nextScrapeTime = t->scrapeAt;
1258
1259    strlcpy( setme->announceResponse,
1260             t->lastAnnounceResponse,
1261             sizeof( setme->announceResponse ) );
1262    setme->lastAnnounceTime = t->lastAnnounceTime;
1263    setme->nextAnnounceTime = t->reannounceAt;
1264    setme->nextManualAnnounceTime = t->manualAnnounceAllowedAt;
1265}
Note: See TracBrowser for help on using the repository browser.