source: trunk/libtransmission/tr-lpd.c

Last change on this file was 14641, checked in by mikedld, 5 years ago

Get rid of some more warnings

  • Property svn:keywords set to Date Rev Author Id
File size: 20.8 KB
Line 
1/*
2Copyright (c) 2010 by Johannes Lieder
3
4Permission is hereby granted, free of charge, to any person obtaining a copy
5of this software and associated documentation files (the "Software"), to deal
6in the Software without restriction, including without limitation the rights
7to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8copies of the Software, and to permit persons to whom the Software is
9furnished to do so, subject to the following conditions:
10
11The above copyright notice and this permission notice shall be included in
12all copies or substantial portions of the Software.
13
14THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20THE SOFTWARE.
21*/
22
23/* ansi */
24#include <errno.h>
25#include <stdio.h>
26#include <string.h> /* strlen (), strncpy (), strstr (), memset () */
27
28/* posix */
29#include <signal.h> /* sig_atomic_t */
30#include <ctype.h> /* toupper () */
31
32#ifdef _WIN32
33  #include <inttypes.h>
34  #include <ws2tcpip.h>
35  typedef uint16_t in_port_t; /* all missing */
36#else
37  #include <sys/time.h>
38  #include <unistd.h> /* close () */
39  #include <sys/types.h>
40  #include <sys/socket.h> /* socket (), bind () */
41  #include <netinet/in.h> /* sockaddr_in */
42#endif
43
44/* third party */
45#include <event2/event.h>
46#include <event2/util.h>
47
48/* libT */
49#include "transmission.h"
50#include "log.h"
51#include "net.h"
52#include "peer-mgr.h" /* tr_peerMgrAddPex () */
53#include "session.h"
54#include "torrent.h" /* tr_torrentFindFromHash () */
55#include "tr-lpd.h"
56#include "utils.h"
57#include "version.h"
58
59/**
60* @brief Local Peer Discovery
61* @file tr-lpd.c
62*
63* This module implements the Local Peer Discovery (LPD) protocol as supported by the
64* uTorrent client application. A typical LPD datagram is 119 bytes long.
65*
66* $Id: tr-lpd.c 14641 2015-12-29 00:42:40Z mikedld $
67*/
68
69static void event_callback (evutil_socket_t, short, void*);
70
71enum {
72   UPKEEP_INTERVAL_SECS = 5
73};
74static struct event * upkeep_timer = NULL;
75
76static tr_socket_t lpd_socket; /**<separate multicast receive socket */
77static tr_socket_t lpd_socket2; /**<and multicast send socket */
78static struct event * lpd_event = NULL;
79static tr_port lpd_port;
80
81static tr_torrent* lpd_torStaticType UNUSED; /* just a helper for static type analysis */
82static tr_session* session;
83
84enum { lpd_maxDatagramLength = 200 }; /**<the size an LPD datagram must not exceed */
85const char lpd_mcastGroup[] = "239.192.152.143"; /**<LPD multicast group */
86const int lpd_mcastPort = 6771; /**<LPD source and destination UPD port */
87static struct sockaddr_in lpd_mcastAddr; /**<initialized from the above constants in tr_lpdInit */
88
89/**
90* @brief Protocol-related information carried by a Local Peer Discovery packet */
91struct lpd_protocolVersion
92{
93    int major, minor;
94};
95
96enum lpd_enumTimeToLive {
97    lpd_ttlSameSubnet = 1,
98    lpd_ttlSameSite = 32,
99    lpd_ttlSameRegion = 64,
100    lpd_ttlSameContinent = 128,
101    lpd_ttlUnrestricted = 255
102};
103
104enum {
105    lpd_announceInterval = 4 * 60, /**<4 min announce interval per torrent */
106    lpd_announceScope = lpd_ttlSameSubnet /**<the maximum scope for LPD datagrams */
107};
108
109
110/**
111* @defgroup DoS Message Flood Protection
112* @{
113* We want to have a means to protect the libtransmission backend against message
114* flooding: the strategy is to cap event processing once more than ten messages
115* per second (that is, taking the average over one of our housekeeping intervals)
116* got into our processing handler.
117* If we'd really hit the limit and start discarding events, we either joined an
118* extremely crowded multicast group or a malevolent host is sending bogus data to
119* our socket. In this situation, we rather miss some announcements than blocking
120* the actual task.
121* @}
122*/
123
124/**
125* @ingroup DoS
126* @brief allow at most ten messages per second (interval average)
127* @note this constraint is only enforced once per housekeeping interval */
128enum { lpd_announceCapFactor = 10 };
129
130/**
131* @ingroup DoS
132* @brief number of unsolicited messages during the last HK interval
133* @remark counts downwards */
134static int lpd_unsolicitedMsgCounter;
135
136/**
137* @def CRLF
138* @brief a line-feed, as understood by the LPD protocol */
139#define CRLF "\r\n"
140
141
142/**
143* @defgroup HttpReqProc HTTP-style request handling
144* @{
145*/
146
147/**
148* @brief Checks for BT-SEARCH method and separates the parameter section
149* @param[in] s The request string
150* @param[out] ver If non-NULL, gets filled with protocol info from the request
151* @return Returns a relative pointer to the beginning of the parameter section;
152*         if result is NULL, s was invalid and no information will be returned
153* @remark Note that the returned pointer is only usable as long as the given
154*         pointer s is valid; that is, return storage is temporary.
155*
156* Determines whether the given string checks out to be a valid BT-SEARCH message.
157* If so, the return value points to the beginning of the parameter section (note:
158* in this case the function returns a character sequence beginning with CRLF).
159* If parameter is not NULL, the declared protocol version is returned as part of
160* the lpd_protocolVersion structure.
161*/
162static const char* lpd_extractHeader (const char* s, struct lpd_protocolVersion* const ver)
163{
164    int major = -1, minor = -1;
165    size_t len;
166
167    assert (s != NULL);
168    len = strlen (s);
169
170    /* something might be rotten with this chunk of data */
171    if (len == 0 || len > lpd_maxDatagramLength)
172        return NULL;
173
174    /* now we can attempt to look up the BT-SEARCH header */
175    if (sscanf (s, "BT-SEARCH * HTTP/%d.%d" CRLF, &major, &minor) != 2)
176        return NULL;
177
178    if (major < 0 || minor < 0)
179        return NULL;
180
181    {
182        /* a pair of blank lines at the end of the string, no place else */
183        const char* const two_blank = CRLF CRLF CRLF;
184        const char* const end = strstr (s, two_blank);
185
186        if (end == NULL || strlen (end) > strlen (two_blank))
187            return NULL;
188    }
189
190    if (ver != NULL)
191    {
192        ver->major = major;
193        ver->minor = minor;
194    }
195
196    /* separate the header, begins with CRLF */
197    return strstr (s, CRLF);
198}
199
200/**
201* @brief Return the value of a named parameter
202*
203* @param[in] str Input string of "\r\nName: Value" pairs without HTTP-style method part
204* @param[in] name Name of parameter to extract
205* @param[in] n Maximum available storage for value to return
206* @param[out] val Output parameter for the actual value
207* @return Returns 1 if value could be copied successfully
208*
209* Extracts the associated value of a named parameter from a HTTP-style header by
210* performing the following steps:
211*   - assemble search string "\r\nName: " and locate position
212*   - copy back value from end to next "\r\n"
213*/
214static bool lpd_extractParam (const char* const str, const char* const name, int n, char* const val)
215{
216    /* configure maximum length of search string here */
217    enum { maxLength = 30 };
218    char sstr[maxLength] = { 0 };
219    const char* pos;
220
221    assert (str != NULL && name != NULL);
222    assert (val != NULL);
223
224    if (strlen (name) > maxLength - strlen (CRLF ": "))
225        return false;
226
227    /* compose the string token to search for */
228    tr_snprintf (sstr, maxLength, CRLF "%s: ", name);
229
230    pos = strstr (str, sstr);
231    if (pos == NULL)
232        return false; /* search was not successful */
233
234    {
235        const char* const beg = pos + strlen (sstr);
236        const char* const new_line = strstr (beg, CRLF);
237
238        /* the value is delimited by the next CRLF */
239        int len = new_line - beg;
240
241        /* if value string hits the length limit n,
242         * leave space for a trailing '\0' character */
243        if (len < n--)
244            n = len;
245
246        strncpy (val, beg, n);
247        val[n] = 0;
248    }
249
250    /* we successfully returned the value string */
251    return true;
252}
253
254/**
255* @} */
256
257static void on_upkeep_timer (evutil_socket_t, short, void *);
258
259/**
260* @brief Initializes Local Peer Discovery for this node
261*
262* For the most part, this means setting up an appropriately configured multicast socket
263* and event-based message handling.
264*
265* @remark Since the LPD service does not use another protocol family yet, this code is
266* IPv4 only for the time being.
267*/
268int tr_lpdInit (tr_session* ss, tr_address* tr_addr UNUSED)
269{
270    struct ip_mreq mcastReq;
271    const int opt_on = 1, opt_off = 0;
272
273    if (session) /* already initialized */
274        return -1;
275
276    assert (lpd_announceInterval > 0);
277    assert (lpd_announceScope > 0);
278
279    lpd_port = tr_sessionGetPeerPort (ss);
280    if (lpd_port <= 0)
281        return -1;
282
283    tr_logAddNamedDbg ("LPD", "Initialising Local Peer Discovery");
284
285    /* setup datagram socket (receive) */
286    {
287        lpd_socket = socket (PF_INET, SOCK_DGRAM, 0);
288        if (lpd_socket == TR_BAD_SOCKET)
289            goto fail;
290
291        if (evutil_make_socket_nonblocking (lpd_socket) < 0)
292            goto fail;
293
294        if (setsockopt (lpd_socket, SOL_SOCKET, SO_REUSEADDR,
295                (const void *) &opt_on, sizeof opt_on) < 0)
296            goto fail;
297
298        memset (&lpd_mcastAddr, 0, sizeof lpd_mcastAddr);
299        lpd_mcastAddr.sin_family = AF_INET;
300        lpd_mcastAddr.sin_port = htons (lpd_mcastPort);
301        if (evutil_inet_pton (lpd_mcastAddr.sin_family, lpd_mcastGroup,
302                &lpd_mcastAddr.sin_addr) < 0)
303            goto fail;
304
305        if (bind (lpd_socket, (struct sockaddr*) &lpd_mcastAddr,
306                sizeof lpd_mcastAddr) < 0)
307            goto fail;
308
309        /* we want to join that LPD multicast group */
310        memset (&mcastReq, 0, sizeof mcastReq);
311        mcastReq.imr_multiaddr = lpd_mcastAddr.sin_addr;
312        mcastReq.imr_interface.s_addr = htonl (INADDR_ANY);
313        if (setsockopt (lpd_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
314                (const void *) &mcastReq, sizeof mcastReq) < 0)
315            goto fail;
316
317        if (setsockopt (lpd_socket, IPPROTO_IP, IP_MULTICAST_LOOP,
318                (const void *) &opt_off, sizeof opt_off) < 0)
319            goto fail;
320    }
321
322    /* setup datagram socket (send) */
323    {
324        const unsigned char scope = lpd_announceScope;
325
326        lpd_socket2 = socket (PF_INET, SOCK_DGRAM, 0);
327        if (lpd_socket2 == TR_BAD_SOCKET)
328            goto fail;
329
330        if (evutil_make_socket_nonblocking (lpd_socket2) < 0)
331            goto fail;
332
333        /* configure outbound multicast TTL */
334        if (setsockopt (lpd_socket2, IPPROTO_IP, IP_MULTICAST_TTL,
335                (const void *) &scope, sizeof scope) < 0)
336            goto fail;
337
338        if (setsockopt (lpd_socket2, IPPROTO_IP, IP_MULTICAST_LOOP,
339                (const void *) &opt_off, sizeof opt_off) < 0)
340            goto fail;
341    }
342
343    session = ss;
344
345    /* Note: lpd_unsolicitedMsgCounter remains 0 until the first timeout event, thus
346     * any announcement received during the initial interval will be discarded. */
347
348    lpd_event = event_new (ss->event_base, lpd_socket, EV_READ | EV_PERSIST, event_callback, NULL);
349    event_add (lpd_event, NULL);
350
351    upkeep_timer = evtimer_new (ss->event_base, on_upkeep_timer, ss);
352    tr_timerAdd (upkeep_timer, UPKEEP_INTERVAL_SECS, 0);
353
354    tr_logAddNamedDbg ("LPD", "Local Peer Discovery initialised");
355
356    return 1;
357
358    fail:
359    {
360        const int save = errno;
361        evutil_closesocket (lpd_socket);
362        evutil_closesocket (lpd_socket2);
363        lpd_socket = lpd_socket2 = TR_BAD_SOCKET;
364        session = NULL;
365        tr_logAddNamedDbg ("LPD", "LPD initialisation failed (errno = %d)", save);
366        errno = save;
367    }
368
369
370    return -1;
371}
372
373void tr_lpdUninit (tr_session* ss)
374{
375    if (session != ss)
376        return;
377
378    tr_logAddNamedDbg ("LPD", "Uninitialising Local Peer Discovery");
379
380    event_free (lpd_event);
381    lpd_event = NULL;
382
383    evtimer_del (upkeep_timer);
384    upkeep_timer = NULL;
385
386    /* just shut down, we won't remember any former nodes */
387    evutil_closesocket (lpd_socket);
388    evutil_closesocket (lpd_socket2);
389    tr_logAddNamedDbg ("LPD", "Done uninitialising Local Peer Discovery");
390
391    session = NULL;
392}
393
394bool
395tr_lpdEnabled (const tr_session* ss)
396{
397    return ss && (ss == session);
398}
399
400
401/**
402* @cond
403* @brief Performs some (internal) software consistency checks at compile time.
404* @remark Declared inline for the compiler not to allege us of feeding unused
405* functions. In any other respect, lpd_consistencyCheck is an orphaned function.
406*/
407UNUSED static inline void
408lpd_consistencyCheck (void)
409{
410    /* if the following check fails, the definition of a hash string has changed
411     * without our knowledge; revise string handling in functions tr_lpdSendAnnounce
412     * and tr_lpdConsiderAnnounce. However, the code is designed to function as long
413     * as interfaces to the rest of the lib remain compatible with char* strings. */
414    TR_STATIC_ASSERT (sizeof (lpd_torStaticType->info.hashString[0]) == sizeof (char), "");
415}
416/**
417* @endcond */
418
419
420/**
421* @defgroup LdsProto LPD announcement processing
422* @{
423*/
424
425/**
426* @brief Announce the given torrent on the local network
427*
428* @param[in] t Torrent to announce
429* @return Returns true on success
430*
431* Send a query for torrent t out to the LPD multicast group (or the LAN, for that
432* matter). A listening client on the same network might react by adding us to his
433* peer pool for torrent t.
434*/
435bool
436tr_lpdSendAnnounce (const tr_torrent* t)
437{
438    size_t i;
439    const char fmt[] =
440        "BT-SEARCH * HTTP/%u.%u" CRLF
441        "Host: %s:%u" CRLF
442        "Port: %u" CRLF
443        "Infohash: %s" CRLF
444        CRLF
445        CRLF;
446
447    char hashString[lengthof (t->info.hashString)];
448    char query[lpd_maxDatagramLength + 1] = { 0 };
449
450    if (t == NULL)
451        return false;
452
453    /* make sure the hash string is normalized, just in case */
454    for (i = 0; i < sizeof hashString; i++)
455        hashString[i] = toupper (t->info.hashString[i]);
456
457    /* prepare a zero-terminated announce message */
458    tr_snprintf (query, lpd_maxDatagramLength + 1, fmt, 1, 1,
459                 lpd_mcastGroup, lpd_mcastPort, lpd_port, hashString);
460
461    /* actually send the query out using [lpd_socket2] */
462    {
463        const int len = strlen (query);
464
465        /* destination address info has already been set up in tr_lpdInit (),
466         * so we refrain from preparing another sockaddr_in here */
467        int res = sendto (lpd_socket2, (const void *) query, len, 0,
468          (const struct sockaddr*) &lpd_mcastAddr, sizeof lpd_mcastAddr);
469
470        if (res != len)
471            return false;
472    }
473
474    tr_logAddTorDbg (t, "LPD announce message away");
475
476    return true;
477}
478
479/**
480* @brief Process incoming unsolicited messages and add the peer to the announced
481* torrent if all checks are passed.
482*
483* @param[in,out] peer Adress information of the peer to add
484* @param[in] msg The announcement message to consider
485* @return Returns 0 if any input parameter or the announce was invalid, 1 if the peer
486* was successfully added, -1 if not; a non-null return value indicates a side-effect to
487* the peer in/out parameter.
488*
489* @note The port information gets added to the peer structure if tr_lpdConsiderAnnounce
490* is able to extract the necessary information from the announce message. That is, if
491* return != 0, the caller may retrieve the value from the passed structure.
492*/
493static int tr_lpdConsiderAnnounce (tr_pex* peer, const char* const msg)
494{
495    enum
496    {
497        maxValueLen = 25,
498        maxHashLen = lengthof (lpd_torStaticType->info.hashString)
499    };
500
501    struct lpd_protocolVersion ver = { -1, -1 };
502    char value[maxValueLen] = { 0 };
503    char hashString[maxHashLen] = { 0 };
504    int res = 0, peerPort = 0;
505
506    if (peer != NULL && msg != NULL)
507    {
508        tr_torrent* tor = NULL;
509
510        const char* params = lpd_extractHeader (msg, &ver);
511        if (params == NULL || ver.major != 1) /* allow messages of protocol v1 */
512            return 0;
513
514        /* save the effort to check Host, which seems to be optional anyway */
515
516        if (!lpd_extractParam (params, "Port", maxValueLen, value))
517            return 0;
518
519        /* determine announced peer port, refuse if value too large */
520        if (sscanf (value, "%d", &peerPort) != 1 || peerPort > (in_port_t)-1)
521            return 0;
522
523        peer->port = htons (peerPort);
524        res = -1; /* signal caller side-effect to peer->port via return != 0 */
525
526        if (!lpd_extractParam (params, "Infohash", maxHashLen, hashString))
527            return res;
528
529        tor = tr_torrentFindFromHashString (session, hashString);
530
531        if (tr_isTorrent (tor) && tr_torrentAllowsLPD (tor))
532        {
533            /* we found a suitable peer, add it to the torrent */
534            tr_peerMgrAddPex (tor, TR_PEER_FROM_LPD, peer, -1);
535            tr_logAddTorDbg (tor, "Learned %d local peer from LPD (%s:%u)",
536                1, tr_address_to_string (&peer->addr), peerPort);
537
538            /* periodic reconnectPulse () deals with the rest... */
539
540            return 1;
541        }
542        else
543            tr_logAddNamedDbg ("LPD", "Cannot serve torrent #%s", hashString);
544    }
545
546    return res;
547}
548
549/**
550* @} */
551
552/**
553* @note Since it possible for tr_lpdAnnounceMore to get called from outside the LPD module,
554* the function needs to be informed of the externally employed housekeeping interval.
555* Further, by setting interval to zero (or negative) the caller may actually disable LPD
556* announces on a per-interval basis.
557*
558* FIXME: since this function's been made private and is called by a periodic timer,
559* most of the previous paragraph isn't true anymore... we weren't using that functionality
560* before. are there cases where we should? if not, should we remove the bells & whistles?
561*/
562static int
563tr_lpdAnnounceMore (const time_t now, const int interval)
564{
565    tr_torrent* tor = NULL;
566    int announcesSent = 0;
567
568    if (!tr_isSession (session))
569        return -1;
570
571    while ((tor = tr_torrentNext (session, tor))
572          && tr_sessionAllowsLPD (session))
573    {
574        if (tr_isTorrent (tor))
575        {
576            int announcePrio = 0;
577
578            if (!tr_torrentAllowsLPD (tor))
579                continue;
580
581            /* issue #3208: prioritize downloads before seeds */
582            switch (tr_torrentGetActivity (tor))
583            {
584            case TR_STATUS_DOWNLOAD:
585                announcePrio = 1;
586                break;
587            case TR_STATUS_SEED:
588                announcePrio = 2;
589                break;
590            default: /* fall through */
591                break;
592            }
593
594            if (announcePrio > 0 && tor->lpdAnnounceAt <= now)
595            {
596                if (tr_lpdSendAnnounce (tor))
597                    announcesSent++;
598
599                tor->lpdAnnounceAt = now +
600                    lpd_announceInterval * announcePrio;
601
602                break; /* that's enough; for this interval */
603            }
604        }
605    }
606
607    /* perform housekeeping for the flood protection mechanism */
608    {
609        const int maxAnnounceCap = interval * lpd_announceCapFactor;
610
611        if (lpd_unsolicitedMsgCounter < 0)
612            tr_logAddNamedInfo ("LPD", "Dropped %d announces in the last interval (max. %d "
613                     "allowed)", -lpd_unsolicitedMsgCounter, maxAnnounceCap);
614
615        lpd_unsolicitedMsgCounter = maxAnnounceCap;
616    }
617
618    return announcesSent;
619}
620
621static void
622on_upkeep_timer (evutil_socket_t foo UNUSED, short bar UNUSED, void * vsession UNUSED)
623{
624    const time_t now = tr_time ();
625    tr_lpdAnnounceMore (now, UPKEEP_INTERVAL_SECS);
626    tr_timerAdd (upkeep_timer, UPKEEP_INTERVAL_SECS, 0);
627}
628
629/**
630* @brief Processing of timeout notifications and incoming data on the socket
631* @note maximum rate of read events is limited according to @a lpd_maxAnnounceCap
632* @see DoS */
633static void event_callback (evutil_socket_t s UNUSED, short type, void* ignore UNUSED)
634{
635    assert (tr_isSession (session));
636
637    /* do not allow announces to be processed if LPD is disabled */
638    if (!tr_sessionAllowsLPD (session))
639        return;
640
641    if ((type & EV_READ) != 0)
642    {
643        struct sockaddr_in foreignAddr;
644        int addrLen = sizeof foreignAddr;
645        char foreignMsg[lpd_maxDatagramLength + 1];
646
647        /* process local announcement from foreign peer */
648        int res = recvfrom (lpd_socket, (void *) foreignMsg, lpd_maxDatagramLength,
649            0, (struct sockaddr*) &foreignAddr, (socklen_t*) &addrLen);
650
651        /* besides, do we get flooded? then bail out! */
652        if (--lpd_unsolicitedMsgCounter < 0)
653            return;
654
655        if (res > 0 && res <= lpd_maxDatagramLength)
656        {
657            struct tr_pex foreignPeer =
658                {
659                    .port = 0, /* the peer-to-peer port is yet unknown */
660                    .flags = 0
661                };
662
663            /* be paranoid enough about zero terminating the foreign string */
664            foreignMsg[res] = '\0';
665
666            foreignPeer.addr.addr.addr4 = foreignAddr.sin_addr;
667            if (tr_lpdConsiderAnnounce (&foreignPeer, foreignMsg) != 0)
668                return; /* OK so far, no log message */
669        }
670
671        tr_logAddNamedDbg ("LPD", "Discarded invalid multicast message");
672    }
673}
674
Note: See TracBrowser for help on using the repository browser.