source: trunk/libtransmission/tracker.c @ 5244

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

don't let vraa have that many peers any more.

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