upnp_context.cpp 49.5 KB
Newer Older
Stepan Salenikovich's avatar
Stepan Salenikovich committed
1
/*
Sébastien Blin's avatar
Sébastien Blin committed
2
 *  Copyright (C) 2004-2019 Savoir-faire Linux Inc.
Guillaume Roguez's avatar
Guillaume Roguez committed
3
 *
Stepan Salenikovich's avatar
Stepan Salenikovich committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 *  Author: Stepan Salenikovich <stepan.salenikovich@savoirfairelinux.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

Adrien Béraud's avatar
Adrien Béraud committed
25
26
27
28
#if HAVE_LIBNATPMP
#include <natpmp.h>
#endif

Stepan Salenikovich's avatar
Stepan Salenikovich committed
29
30
31
#include "logger.h"
#include "ip_utils.h"
#include "upnp_igd.h"
32
#include "compiler_intrinsics.h"
Stepan Salenikovich's avatar
Stepan Salenikovich committed
33

34
35
36
#include <opendht/rng.h>
using random_device = dht::crypto::random_device;

Adrien Béraud's avatar
Adrien Béraud committed
37
38
39
40
41
42
43
44
45
#include <string>
#include <set>
#include <mutex>
#include <memory>
#include <condition_variable>
#include <random>
#include <chrono>
#include <cstdlib> // for std::free

46
47
#include "upnp_context.h"

Adrien Béraud's avatar
Adrien Béraud committed
48
namespace jami { namespace upnp {
Stepan Salenikovich's avatar
Stepan Salenikovich committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62

/**
 * This should be used to get a UPnPContext.
 * It only makes sense to have one unless you have separate
 * contexts for multiple internet interfaces, which is not currently
 * supported.
 */
std::shared_ptr<UPnPContext>
getUPnPContext()
{
    static auto context = std::make_shared<UPnPContext>();
    return context;
}

Adrien Béraud's avatar
Adrien Béraud committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* UPnP error codes */
constexpr static int INVALID_ARGS = 402;
constexpr static int ARRAY_IDX_INVALID = 713;
constexpr static int CONFLICT_IN_MAPPING = 718;

/* max number of times to retry mapping if it fails due to conflict;
 * there isn't much logic in picking this number... ideally not many ports should
 * be mapped in a system, so a few number of random port retries should work;
 * a high number of retries would indicate there might be some kind of bug or else
 * incompatibility with the router; we use it to prevent an infinite loop of
 * retrying to map the entry
 */
constexpr static unsigned MAX_RETRIES = 20;

Stepan Salenikovich's avatar
Stepan Salenikovich committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#if HAVE_LIBUPNP

/* UPnP IGD definitions */
constexpr static const char * UPNP_ROOT_DEVICE = "upnp:rootdevice";
constexpr static const char * UPNP_IGD_DEVICE = "urn:schemas-upnp-org:device:InternetGatewayDevice:1";
constexpr static const char * UPNP_WAN_DEVICE = "urn:schemas-upnp-org:device:WANDevice:1";
constexpr static const char * UPNP_WANCON_DEVICE = "urn:schemas-upnp-org:device:WANConnectionDevice:1";
constexpr static const char * UPNP_WANIP_SERVICE = "urn:schemas-upnp-org:service:WANIPConnection:1";
constexpr static const char * UPNP_WANPPP_SERVICE = "urn:schemas-upnp-org:service:WANPPPConnection:1";

constexpr static const char * INVALID_ARGS_STR = "402";
constexpr static const char * ARRAY_IDX_INVALID_STR = "713";
constexpr static const char * CONFLICT_IN_MAPPING_STR = "718";

/*
 * Local prototypes
 */
static std::string get_element_text(IXML_Node*);
static std::string get_first_doc_item(IXML_Document*, const char*);
static std::string get_first_element_item(IXML_Element*, const char*);
static void checkResponseError(IXML_Document*);

Adrien Béraud's avatar
Adrien Béraud committed
99
#else
Adrien Béraud's avatar
Adrien Béraud committed
100

Adrien Béraud's avatar
Adrien Béraud committed
101
102
103
constexpr static int UPNP_E_SUCCESS = 0;

#endif // HAVE_LIBUPNP
104

Stepan Salenikovich's avatar
Stepan Salenikovich committed
105
UPnPContext::UPnPContext()
Adrien Béraud's avatar
Adrien Béraud committed
106
#if HAVE_LIBNATPMP
107
    : pmpThread_([this]() {
Adrien Béraud's avatar
Adrien Béraud committed
108
109
110
111
112
        auto pmp_igd = std::make_shared<PMPIGD>();
        natpmp_t natpmp;

        while (pmpRun_) {
            if (initnatpmp(&natpmp, 0, 0) < 0) {
Adrien Béraud's avatar
Adrien Béraud committed
113
                JAMI_ERR("NAT-PMP: can't initialize libnatpmp");
Adrien Béraud's avatar
Adrien Béraud committed
114
115
116
                std::unique_lock<std::mutex> lk(pmpMutex_);
                pmpCv_.wait_for(lk, std::chrono::minutes(1));
            } else {
Adrien Béraud's avatar
Adrien Béraud committed
117
                JAMI_DBG("NAT-PMP: initialized");
Adrien Béraud's avatar
Adrien Béraud committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
                break;
            }
        }

        while (pmpRun_) {
            std::unique_lock<std::mutex> lk(pmpMutex_);
            pmpCv_.wait_until(lk, pmp_igd->getRenewalTime(), [&] {
                return not pmpRun_ or pmp_igd->getRenewalTime() <= clock::now();
            });
            if (not pmpRun_) break;

            auto now = clock::now();

            if (pmp_igd->renewal_ < now) {
                PMPsearchForIGD(pmp_igd, natpmp);
            }
            if (pmpIGD_) {
                if (pmp_igd->clearAll_) {
                    PMPdeleteAllPortMapping(*pmp_igd, natpmp, NATPMP_PROTOCOL_UDP);
                    PMPdeleteAllPortMapping(*pmp_igd, natpmp, NATPMP_PROTOCOL_TCP);
                    pmp_igd->clearAll_ = false;
                    pmp_igd->toRemove_.clear();
                } else if (not pmp_igd->toRemove_.empty()) {
141
                    decltype(pmp_igd->toRemove_) removed = std::move(pmp_igd->toRemove_);
Adrien Béraud's avatar
Adrien Béraud committed
142
                    pmp_igd->toRemove_.clear();
143
144
145
146
147
                    lk.unlock();
                    for (auto& m : removed) {
                        PMPaddPortMapping(*pmp_igd, natpmp, m, true);
                    }
                    lk.lock();
Adrien Béraud's avatar
Adrien Béraud committed
148
149
150
151
152
153
154
                }
                auto mapping = pmp_igd->getNextMappingToRenew();
                if (mapping and mapping->renewal_ < now)
                    PMPaddPortMapping(*pmp_igd, natpmp, *mapping);
            }
        }
        closenatpmp(&natpmp);
Adrien Béraud's avatar
Adrien Béraud committed
155
        JAMI_DBG("NAT-PMP: ended");
156
    })
Adrien Béraud's avatar
Adrien Béraud committed
157
#endif
158
{
Adrien Béraud's avatar
Adrien Béraud committed
159
#if HAVE_LIBUPNP
Stepan Salenikovich's avatar
Stepan Salenikovich committed
160
161
162
163
164
165
166
167
    int upnp_err;
    char* ip_address = nullptr;
    unsigned short port = 0;

    /* TODO: allow user to specify interface to be used
     *       by selecting the IP
     */

Stepan Salenikovich's avatar
Stepan Salenikovich committed
168
 #ifdef UPNP_ENABLE_IPV6
Adrien Béraud's avatar
Adrien Béraud committed
169
     JAMI_DBG("UPnP: IPv6 support enabled, but we will use IPv4");
Stepan Salenikovich's avatar
Stepan Salenikovich committed
170
171
172
173
174
     /* IPv6 version seems to fail on some systems with:
      * UPNP_E_SOCKET_BIND: An error occurred binding a socket. */
     /* TODO: figure out why ipv6 version doesn't work  */
     // upnp_err = UpnpInit2(0, 0);
 #endif
Stepan Salenikovich's avatar
Stepan Salenikovich committed
175
176
    upnp_err = UpnpInit(0, 0);
    if ( upnp_err != UPNP_E_SUCCESS ) {
Adrien Béraud's avatar
Adrien Béraud committed
177
        JAMI_ERR("UPnP: can't initialize libupnp: %s", UpnpGetErrorMessage(upnp_err));
Stepan Salenikovich's avatar
Stepan Salenikovich committed
178
        UpnpFinish();
179
    } else {
Adrien Béraud's avatar
Adrien Béraud committed
180
        JAMI_DBG("UPnP: using IPv4");
181
182
183
        ip_address = UpnpGetServerIpAddress(); // do not free, it is freed by UpnpFinish()
        port = UpnpGetServerPort();

Adrien Béraud's avatar
Adrien Béraud committed
184
        JAMI_DBG("UPnP: initialiazed on %s:%u", ip_address, port);
185
186
187
188
189
190
191

        // relax the parser to allow malformed XML text
        ixmlRelaxParser( 1 );

        // Register a control point to start looking for devices right away
        upnp_err = UpnpRegisterClient( cp_callback, this, &ctrlptHandle_ );
        if ( upnp_err != UPNP_E_SUCCESS ) {
Adrien Béraud's avatar
Adrien Béraud committed
192
            JAMI_ERR("UPnP: can't register client: %s", UpnpGetErrorMessage(upnp_err));
193
194
195
196
197
198
            UpnpFinish();
        } else {
            clientRegistered_ = true;
            // start gathering a list of available devices
            searchForIGD();
        }
Stepan Salenikovich's avatar
Stepan Salenikovich committed
199
    }
Adrien Béraud's avatar
Adrien Béraud committed
200
#endif
Stepan Salenikovich's avatar
Stepan Salenikovich committed
201
202
203
204
}

UPnPContext::~UPnPContext()
{
205
206
207
208
    /* make sure everything is unregistered, freed, and UpnpFinish() is called */
    {
        std::lock_guard<std::mutex> lock(validIGDMutex_);
        for( auto const &it : validIGDs_) {
Adrien Béraud's avatar
Adrien Béraud committed
209
210
211
212
213
214
215
216
217
#if HAVE_LIBUPNP
            if (auto igd = dynamic_cast<UPnPIGD*>(it.second.get()))
                removeMappingsByLocalIPAndDescription(*igd, Mapping::UPNP_DEFAULT_MAPPING_DESCRIPTION);
#endif
        }
#if HAVE_LIBNATPMP
        if (pmpIGD_) {
            {
                std::lock_guard<std::mutex> lk(pmpMutex_);
218
                pmpIGD_->clearMappings();
Adrien Béraud's avatar
Adrien Béraud committed
219
220
            }
            pmpCv_.notify_all();
Stepan Salenikovich's avatar
Stepan Salenikovich committed
221
        }
Adrien Béraud's avatar
Adrien Béraud committed
222
#endif
223
    }
Stepan Salenikovich's avatar
Stepan Salenikovich committed
224

Adrien Béraud's avatar
Adrien Béraud committed
225
226
227
228
229
230
231
232
233
#if HAVE_LIBNATPMP
    pmpRun_ = false;
    pmpCv_.notify_all();
    if (pmpThread_.joinable())
        pmpThread_.join();
    pmpIGD_.reset();
#endif

#if HAVE_LIBUPNP
234
235
    if (clientRegistered_)
        UpnpUnRegisterClient( ctrlptHandle_ );
Stepan Salenikovich's avatar
Stepan Salenikovich committed
236

237
238
    if (deviceRegistered_)
        UpnpUnRegisterRootDevice( deviceHandle_ );
Edric Milaret's avatar
Edric Milaret committed
239
240
// FIXME : on windows thread have already been destroyed at this point resulting in a deadlock
#ifndef _WIN32
241
    UpnpFinish();
Edric Milaret's avatar
Edric Milaret committed
242
#endif
Adrien Béraud's avatar
Adrien Béraud committed
243
#endif
244
245
}

246
247
248
249
250
251
252
253
254
255
256
void
UPnPContext::connectivityChanged()
{
    {
        std::lock_guard<std::mutex> lock(validIGDMutex_);

        /* when the network changes, we're likely no longer connected to the same IGD, or if we are
         * we might now have a different IP, thus we clear the list of IGDs and notify the listeners
         * so that they can attempt to re-do the port mappings once we detect an IGD
         */
        validIGDs_.clear();
Adrien Béraud's avatar
Adrien Béraud committed
257
258
#if HAVE_LIBNATPMP
        if (pmpIGD_) {
259
260
            std::lock_guard<std::mutex> lk(pmpMutex_);
            pmpIGD_->clear();
Adrien Béraud's avatar
Adrien Béraud committed
261
262
263
264
265
            pmpIGD_->renewal_ = clock::now();
            pmpIGD_.reset();
        }
        pmpCv_.notify_all();
#endif
266
267
268
269
270
        validIGDCondVar_.notify_all();
        for (const auto& l : igdListeners_)
            l.second();
    }

Adrien Béraud's avatar
Adrien Béraud committed
271
#if HAVE_LIBUPNP
272
273
    // send out a new search request
    searchForIGD();
Adrien Béraud's avatar
Adrien Béraud committed
274
#endif
Stepan Salenikovich's avatar
Stepan Salenikovich committed
275
276
277
}

bool
278
UPnPContext::hasValidIGD(std::chrono::seconds timeout)
Stepan Salenikovich's avatar
Stepan Salenikovich committed
279
{
280
    if (not clientRegistered_ and not pmpRun_) {
Adrien Béraud's avatar
Adrien Béraud committed
281
        JAMI_WARN("UPnP: Control Point not registered");
Stepan Salenikovich's avatar
Stepan Salenikovich committed
282
283
284
        return false;
    }

285
286
    std::unique_lock<std::mutex> lock(validIGDMutex_);
    if (!validIGDCondVar_.wait_for(lock, timeout,
287
                                   [this]{return hasValidIGD_unlocked();})) {
Adrien Béraud's avatar
Adrien Béraud committed
288
        JAMI_WARN("UPnP: check for valid IGD timeout");
289
        return false;
Stepan Salenikovich's avatar
Stepan Salenikovich committed
290
291
    }

292
    return hasValidIGD_unlocked();
Stepan Salenikovich's avatar
Stepan Salenikovich committed
293
294
}

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
size_t
UPnPContext::addIGDListener(IGDFoundCallback&& cb)
{
    std::lock_guard<std::mutex> lock(validIGDMutex_);
    auto token = ++listenerToken_;
    igdListeners_.emplace(token, std::move(cb));
    return token;
}

void
UPnPContext::removeIGDListener(size_t token)
{
    std::lock_guard<std::mutex> lock(validIGDMutex_);
    auto it = igdListeners_.find(token);
    if (it != igdListeners_.end())
        igdListeners_.erase(it);
}

313
314
315
316
317
318
319
320
321
322
bool
UPnPContext::hasValidIGD_unlocked() const
{
    return
#if HAVE_LIBNATPMP
    pmpIGD_ or
#endif
    not validIGDs_.empty();
}

Stepan Salenikovich's avatar
Stepan Salenikovich committed
323
324
325
326
327
/**
 * chooses the IGD to use,
 * assumes you already have a lock on validIGDMutex_
 */
IGD*
Eloi Bail's avatar
Eloi Bail committed
328
UPnPContext::chooseIGD_unlocked() const
Stepan Salenikovich's avatar
Stepan Salenikovich committed
329
{
Adrien Béraud's avatar
Adrien Béraud committed
330
331
332
333
#if HAVE_LIBNATPMP
    if (pmpIGD_)
        return pmpIGD_.get();
#endif
Stepan Salenikovich's avatar
Stepan Salenikovich committed
334
335
    if (validIGDs_.empty())
        return nullptr;
336
    return validIGDs_.begin()->second.get();
Stepan Salenikovich's avatar
Stepan Salenikovich committed
337
338
339
340
341
342
343
344
345
346
347
348
349
350
}

/**
 * tries to add mapping
 */
Mapping
UPnPContext::addMapping(IGD* igd,
                        uint16_t port_external,
                        uint16_t port_internal,
                        PortType type,
                        int *upnp_error)
{
    *upnp_error = -1;

Sébastien Blin's avatar
Sébastien Blin committed
351
    Mapping mapping{port_external, port_internal, type};
Stepan Salenikovich's avatar
Stepan Salenikovich committed
352
353
354
355
356
357
358
359
360
361
362

    /* check if this mapping already exists
     * if the mapping is the same, then we just need to increment the number of users globally
     * if the mapping is not the same, then we have to return fail, as the external port is used
     * for something else
     * if the mapping doesn't exist, then try to add it
     */
    auto globalMappings = type == PortType::UDP ? &igd->udpMappings : &igd->tcpMappings;
    auto iter = globalMappings->find(port_external);
    if (iter != globalMappings->end()) {
        /* mapping exists with same external port */
363
        GlobalMapping* mapping_ptr = &iter->second;
Stepan Salenikovich's avatar
Stepan Salenikovich committed
364
365
366
367
        if (*mapping_ptr == mapping) {
            /* the same mapping, so nothing needs to be done */
            *upnp_error = UPNP_E_SUCCESS;
            ++(mapping_ptr->users);
Adrien Béraud's avatar
Adrien Béraud committed
368
            JAMI_DBG("UPnp : mapping already exists, incrementing number of users: %d",
Stepan Salenikovich's avatar
Stepan Salenikovich committed
369
370
371
372
                     iter->second.users);
            return mapping;
        } else {
            /* this port is already used by a different mapping */
Adrien Béraud's avatar
Adrien Béraud committed
373
            JAMI_WARN("UPnP: cannot add a mapping with an external port which is already used by another:\n\tcurrent: %s\n\ttrying to add: %s",
Stepan Salenikovich's avatar
Stepan Salenikovich committed
374
375
376
377
378
379
380
                      mapping_ptr->toString().c_str(), mapping.toString().c_str());
            *upnp_error = CONFLICT_IN_MAPPING;
            return {};
        }
    }

    /* mapping doesn't exist, so try to add it */
Adrien Béraud's avatar
Adrien Béraud committed
381
    JAMI_DBG("adding port mapping : %s", mapping.toString().c_str());
Stepan Salenikovich's avatar
Stepan Salenikovich committed
382

Adrien Béraud's avatar
Adrien Béraud committed
383
384
385
386
387
#if HAVE_LIBUPNP
    auto upnp = dynamic_cast<const UPnPIGD*>(igd);
    if (not upnp or addPortMapping(*upnp, mapping, upnp_error))
#endif
    {
Stepan Salenikovich's avatar
Stepan Salenikovich committed
388
        /* success; add it to global list */
Philippe Gorley's avatar
Philippe Gorley committed
389
        globalMappings->emplace(port_external, GlobalMapping{mapping});
Adrien Béraud's avatar
Adrien Béraud committed
390
391
392
393
394
395
#if HAVE_LIBNATPMP
#if HAVE_LIBUPNP
        if (not upnp)
#endif
            pmpCv_.notify_all();
#endif
Stepan Salenikovich's avatar
Stepan Salenikovich committed
396
397
398
399
400
401
402
403
404
        return mapping;
    }
    return {};
}

static uint16_t
generateRandomPort()
{
    /* obtain a random number from hardware */
405
    static random_device rd;
Stepan Salenikovich's avatar
Stepan Salenikovich committed
406
407
408
409
410
    /* seed the generator */
    static std::mt19937 gen(rd());
    /* define the range */
    static std::uniform_int_distribution<uint16_t> dist(Mapping::UPNP_PORT_MIN, Mapping::UPNP_PORT_MAX);

Adrien Béraud's avatar
Adrien Béraud committed
411
    return dist(gen);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
412
413
414
415
416
417
}

/**
 * chooses a random port that is not yet used by the daemon for UPnP
 */
uint16_t
Adrien Béraud's avatar
Adrien Béraud committed
418
UPnPContext::chooseRandomPort(const IGD& igd, PortType type)
Stepan Salenikovich's avatar
Stepan Salenikovich committed
419
420
{
    auto globalMappings = type == PortType::UDP ?
Adrien Béraud's avatar
Adrien Béraud committed
421
                          &igd.udpMappings : &igd.tcpMappings;
Stepan Salenikovich's avatar
Stepan Salenikovich committed
422
423
424
425
426
427
428
429

    uint16_t port = generateRandomPort();

    /* keep generating random ports until we find one which is not used */
    while(globalMappings->find(port) != globalMappings->end()) {
        port = generateRandomPort();
    }

Adrien Béraud's avatar
Adrien Béraud committed
430
    JAMI_DBG("UPnP: chose random port %u", port);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458

    return port;
}

/**
 * tries to add mapping from and to the port_desired
 * if unique == true, makes sure the client is not using this port already
 * if the mapping fails, tries other available ports until success
 *
 * tries to use a random port between 1024 < > 65535 if desired port fails
 *
 * maps port_desired to port_local; if use_same_port == true, makes sure that
 * that the external and internal ports are the same
 *
 * returns a valid mapping on success and an invalid mapping on failure
 */
Mapping
UPnPContext::addAnyMapping(uint16_t port_desired,
                           uint16_t port_local,
                           PortType type,
                           bool use_same_port,
                           bool unique)
{
    /* get a lock on the igd list because we don't want the igd to be modified
     * or removed from the list while using it */
    std::lock_guard<std::mutex> lock(validIGDMutex_);
    IGD* igd = chooseIGD_unlocked();
    if (not igd) {
Adrien Béraud's avatar
Adrien Béraud committed
459
        JAMI_WARN("UPnP: no valid IGD available");
Stepan Salenikovich's avatar
Stepan Salenikovich committed
460
461
462
463
464
465
466
467
468
469
        return {};
    }

    auto globalMappings = type == PortType::UDP ?
                          &igd->udpMappings : &igd->tcpMappings;
    if (unique) {
        /* check that port is not already used by the client */
        auto iter = globalMappings->find(port_desired);
        if (iter != globalMappings->end()) {
            /* port already used, we need a unique port */
Adrien Béraud's avatar
Adrien Béraud committed
470
            port_desired = chooseRandomPort(*igd, type);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
471
472
473
474
475
476
477
478
479
480
        }
    }

    if (use_same_port)
        port_local = port_desired;

    int upnp_error;
    Mapping mapping = addMapping(igd, port_desired, port_local, type, &upnp_error);
    /* keep trying to add the mapping as long as the upnp error is 718 == conflicting mapping
     * if adding the mapping fails for any other reason, give up
481
     * don't try more than MAX_RETRIES to prevent infinite loops
Stepan Salenikovich's avatar
Stepan Salenikovich committed
482
     */
483
484
485
486
487
    unsigned numberRetries = 0;

    while ( not mapping
            and (upnp_error == CONFLICT_IN_MAPPING or upnp_error == INVALID_ARGS)
            and numberRetries < MAX_RETRIES ) {
Stepan Salenikovich's avatar
Stepan Salenikovich committed
488
489
490
491
        /* acceptable errors to keep trying:
         * 718 : conflictin mapping
         * 402 : invalid args (due to router implementation)
         */
Adrien Béraud's avatar
Adrien Béraud committed
492
        JAMI_DBG("UPnP: mapping failed (conflicting entry? err = %d), trying with a different port.",
493
                 upnp_error);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
494
        /* TODO: make sure we don't try sellecting the same random port twice if it fails ? */
Adrien Béraud's avatar
Adrien Béraud committed
495
        port_desired = chooseRandomPort(*igd, type);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
496
497
498
        if (use_same_port)
            port_local = port_desired;
        mapping = addMapping(igd, port_desired, port_local, type, &upnp_error);
499
        ++numberRetries;
Stepan Salenikovich's avatar
Stepan Salenikovich committed
500
501
    }

502
    if (not mapping and numberRetries == MAX_RETRIES)
Adrien Béraud's avatar
Adrien Béraud committed
503
        JAMI_DBG("UPnP: could not add mapping after %u retries, giving up", MAX_RETRIES);
504

Stepan Salenikovich's avatar
Stepan Salenikovich committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
    return mapping;
}

/**
 * tries to remove the given mapping
 */
void
UPnPContext::removeMapping(const Mapping& mapping)
{
    /* get a lock on the igd list because we don't want the igd to be modified
     * or removed from the list while using it */
    std::lock_guard<std::mutex> lock(validIGDMutex_);
    IGD* igd = chooseIGD_unlocked();
    if (not igd) {
Adrien Béraud's avatar
Adrien Béraud committed
519
        JAMI_WARN("UPnP: no valid IGD available");
520
        return;
Stepan Salenikovich's avatar
Stepan Salenikovich committed
521
522
523
524
525
526
527
528
529
    }

    /* first make sure the mapping exists in the global list of the igd */
    auto globalMappings = mapping.getType() == PortType::UDP ?
                          &igd->udpMappings : &igd->tcpMappings;

    auto iter = globalMappings->find(mapping.getPortExternal());
    if ( iter != globalMappings->end() ) {
        /* make sure its the same mapping */
Adrien Béraud's avatar
Adrien Béraud committed
530
531
        GlobalMapping& global_mapping = iter->second;
        if (mapping == global_mapping ) {
Stepan Salenikovich's avatar
Stepan Salenikovich committed
532
            /* now check the users */
Adrien Béraud's avatar
Adrien Béraud committed
533
            if (global_mapping.users > 1) {
Stepan Salenikovich's avatar
Stepan Salenikovich committed
534
                /* more than one user, simply decrement the number */
Adrien Béraud's avatar
Adrien Béraud committed
535
                --(global_mapping.users);
Adrien Béraud's avatar
Adrien Béraud committed
536
                JAMI_DBG("UPnP: decrementing users of mapping: %s, %d users remaining",
Adrien Béraud's avatar
Adrien Béraud committed
537
                         mapping.toString().c_str(), global_mapping.users);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
538
539
            } else {
                /* no other users, can delete */
Adrien Béraud's avatar
Adrien Béraud committed
540
541
#if HAVE_LIBUPNP
                if (auto upnp = dynamic_cast<UPnPIGD*>(igd)) {
Adrien Béraud's avatar
Adrien Béraud committed
542
                    JAMI_DBG("UPnP: removing port mapping : %s",
Adrien Béraud's avatar
Adrien Béraud committed
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
                             mapping.toString().c_str());
                    deletePortMapping(*upnp,
                                      mapping.getPortExternalStr(),
                                      mapping.getTypeStr());
                }
#endif
#if HAVE_LIBNATPMP
                if (auto pmp = dynamic_cast<PMPIGD*>(igd)) {
                    {
                        std::lock_guard<std::mutex> lk(pmpMutex_);
                        pmp->toRemove_.emplace_back(std::move(global_mapping));
                    }
                    pmpCv_.notify_all();
                }
#endif
Stepan Salenikovich's avatar
Stepan Salenikovich committed
558
559
560
                globalMappings->erase(iter);
            }
        } else {
Adrien Béraud's avatar
Adrien Béraud committed
561
            JAMI_WARN("UPnP: cannot remove mapping which doesn't match the existing one in the IGD list");
Stepan Salenikovich's avatar
Stepan Salenikovich committed
562
563
        }
    } else {
Adrien Béraud's avatar
Adrien Béraud committed
564
        JAMI_WARN("UPnP: cannot remove mapping which is not in the list of existing mappings of the IGD");
Stepan Salenikovich's avatar
Stepan Salenikovich committed
565
566
567
568
    }
}

IpAddr
Eloi Bail's avatar
Eloi Bail committed
569
570
571
572
573
574
575
576
577
578
UPnPContext::getLocalIP() const
{
    /* get a lock on the igd list because we don't want the igd to be modified
     * or removed from the list while using it */
    std::lock_guard<std::mutex> lock(validIGDMutex_);

    /* if its a valid igd, we must have already gotten the local ip */
    if (auto igd = chooseIGD_unlocked())
        return igd->localIp;

Adrien Béraud's avatar
Adrien Béraud committed
579
    JAMI_WARN("UPnP: no valid IGD available");
Eloi Bail's avatar
Eloi Bail committed
580
581
582
583
584
    return {};
}

IpAddr
UPnPContext::getExternalIP() const
Stepan Salenikovich's avatar
Stepan Salenikovich committed
585
586
587
588
589
590
{
    /* get a lock on the igd list because we don't want the igd to be modified
     * or removed from the list while using it */
    std::lock_guard<std::mutex> lock(validIGDMutex_);

    /* if its a valid igd, we must have already gotten the external ip */
Eloi Bail's avatar
Eloi Bail committed
591
592
593
    if (auto igd = chooseIGD_unlocked())
        return igd->publicIp;

Adrien Béraud's avatar
Adrien Béraud committed
594
    JAMI_WARN("UPnP: no valid IGD available");
Eloi Bail's avatar
Eloi Bail committed
595
    return {};
Stepan Salenikovich's avatar
Stepan Salenikovich committed
596
597
}

Adrien Béraud's avatar
Adrien Béraud committed
598
599
600
601
602
603
#if HAVE_LIBNATPMP

void
UPnPContext::PMPsearchForIGD(const std::shared_ptr<PMPIGD>& pmp_igd, natpmp_t& natpmp)
{
    if (sendpublicaddressrequest(&natpmp) < 0) {
Adrien Béraud's avatar
Adrien Béraud committed
604
        JAMI_ERR("NAT-PMP: can't send request");
Adrien Béraud's avatar
Adrien Béraud committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
        pmp_igd->renewal_ = clock::now() + std::chrono::minutes(1);
        return;
    }

    while (pmpRun_) {
        natpmpresp_t response;
        std::this_thread::sleep_for(std::chrono::milliseconds(2));
        auto r = readnatpmpresponseorretry(&natpmp, &response);
        if (r < 0 && r != NATPMP_TRYAGAIN) {
            pmp_igd->renewal_ = clock::now() + std::chrono::minutes(5);
            break;
        }
        else if (r != NATPMP_TRYAGAIN) {
            pmp_igd->localIp = ip_utils::getLocalAddr(AF_INET);
            pmp_igd->publicIp = IpAddr(response.pnu.publicaddress.addr);
            if (not pmpIGD_) {
Adrien Béraud's avatar
Adrien Béraud committed
621
622
                JAMI_DBG("NAT-PMP: found new device");
                JAMI_DBG("NAT-PMP: got external IP: %s", pmp_igd->publicIp.toString().c_str());
Adrien Béraud's avatar
Adrien Béraud committed
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
                {
                    std::lock_guard<std::mutex> lock(validIGDMutex_);
                    pmpIGD_ = pmp_igd;
                    validIGDCondVar_.notify_all();
                    for (const auto& l : igdListeners_)
                        l.second();
                }
            }
            pmp_igd->renewal_ = clock::now() + std::chrono::minutes(1);
            break;
        }
    }
}

void
UPnPContext::PMPaddPortMapping(const PMPIGD& /*pmp_igd*/, natpmp_t& natpmp, GlobalMapping& mapping, bool remove) const
{
    if (sendnewportmappingrequest(&natpmp,
                                  mapping.getType() == PortType::UDP ? NATPMP_PROTOCOL_UDP : NATPMP_PROTOCOL_TCP,
                                  mapping.getPortInternal(),
                                  mapping.getPortExternal(), remove ? 0 : 3600) < 0) {
Adrien Béraud's avatar
Adrien Béraud committed
644
        JAMI_ERR("NAT-PMP: can't send port mapping request");
Adrien Béraud's avatar
Adrien Béraud committed
645
646
647
        mapping.renewal_ = clock::now() + std::chrono::minutes(1);
        return;
    }
Adrien Béraud's avatar
Adrien Béraud committed
648
    JAMI_DBG("NAT-PMP: sent port mapping %srequest", remove ? "removal " : "");
Adrien Béraud's avatar
Adrien Béraud committed
649
650
651
652
653
    while (pmpRun_) {
        natpmpresp_t response;
        std::this_thread::sleep_for(std::chrono::milliseconds(2));
        auto r = readnatpmpresponseorretry(&natpmp, &response);
        if (r < 0 && r != NATPMP_TRYAGAIN) {
Adrien Béraud's avatar
Adrien Béraud committed
654
            JAMI_ERR("NAT-PMP: can't %sregister port mapping", remove ? "un" : "");
Adrien Béraud's avatar
Adrien Béraud committed
655
656
657
658
659
660
661
662
663
664
665
666
667
668
            break;
        }
        else if (r != NATPMP_TRYAGAIN) {
            mapping.renewal_ = clock::now()
                             + std::chrono::seconds(response.pnu.newportmapping.lifetime/2);
            break;
        }
    }
}

void
UPnPContext::PMPdeleteAllPortMapping(const PMPIGD& /*pmp_igd*/, natpmp_t& natpmp, int proto) const
{
    if (sendnewportmappingrequest(&natpmp, proto, 0, 0, 0) < 0) {
Adrien Béraud's avatar
Adrien Béraud committed
669
        JAMI_ERR("NAT-PMP: can't send all port mapping removal request");
Adrien Béraud's avatar
Adrien Béraud committed
670
671
        return;
    }
Adrien Béraud's avatar
Adrien Béraud committed
672
    JAMI_DBG("NAT-PMP: sent all port mapping removal request");
Adrien Béraud's avatar
Adrien Béraud committed
673
674
675
676
677
    while (pmpRun_) {
        natpmpresp_t response;
        std::this_thread::sleep_for(std::chrono::milliseconds(2));
        auto r = readnatpmpresponseorretry(&natpmp, &response);
        if (r < 0 && r != NATPMP_TRYAGAIN) {
Adrien Béraud's avatar
Adrien Béraud committed
678
            JAMI_ERR("NAT-PMP: can't remove all port mappings");
Adrien Béraud's avatar
Adrien Béraud committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
            break;
        }
        else if (r != NATPMP_TRYAGAIN) {
            break;
        }
    }
}

#endif /* HAVE_LIBNATPMP */


#if HAVE_LIBUPNP

void
UPnPContext::searchForIGD()
{
    if (not clientRegistered_) {
Adrien Béraud's avatar
Adrien Béraud committed
696
        JAMI_WARN("UPnP: Control Point not registered");
Adrien Béraud's avatar
Adrien Béraud committed
697
698
699
700
701
702
703
704
705
706
        return;
    }

    /* send out search for both types, as some routers may possibly only reply to one */
    UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_ROOT_DEVICE, this);
    UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_IGD_DEVICE, this);
    UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANIP_SERVICE, this);
    UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANPPP_SERVICE, this);
}

Stepan Salenikovich's avatar
Stepan Salenikovich committed
707
708
709
710
711
/**
 * Parses the device description and adds desired devices to
 * relevant lists
 */
void
Alexandre Viau's avatar
Alexandre Viau committed
712
UPnPContext::parseDevice(IXML_Document* doc, const UpnpDiscovery* d_event)
Stepan Salenikovich's avatar
Stepan Salenikovich committed
713
714
715
716
717
718
719
{
    if (not doc or not d_event)
        return;

    /* check to see the device type */
    std::string deviceType = get_first_doc_item(doc, "deviceType");
    if (deviceType.empty()) {
Adrien Béraud's avatar
Adrien Béraud committed
720
        /* JAMI_DBG("UPnP: could not find deviceType in the description document of the device"); */
Stepan Salenikovich's avatar
Stepan Salenikovich committed
721
722
723
724
725
726
727
728
729
730
731
        return;
    }

    if (deviceType.compare(UPNP_IGD_DEVICE) == 0) {
        parseIGD(doc, d_event);
    }

    /* TODO: check if its a ring device */
}

void
Alexandre Viau's avatar
Alexandre Viau committed
732
UPnPContext::parseIGD(IXML_Document* doc, const UpnpDiscovery* d_event)
Stepan Salenikovich's avatar
Stepan Salenikovich committed
733
734
735
736
737
738
739
740
741
{
    if (not doc or not d_event)
        return;

    /* check the UDN to see if its already in our device list(s)
     * if it is, then update the device advertisement timeout (expiration)
     */
    std::string UDN = get_first_doc_item(doc, "UDN");
    if (UDN.empty()) {
Adrien Béraud's avatar
Adrien Béraud committed
742
        JAMI_DBG("UPnP: could not find UDN in description document of device");
Stepan Salenikovich's avatar
Stepan Salenikovich committed
743
744
745
746
747
748
749
750
751
752
753
754
755
756
        return;
    }

    {
        std::lock_guard<std::mutex> lock(validIGDMutex_);
        auto it = validIGDs_.find(UDN);

        if (it != validIGDs_.end()) {
            /* we already have this device in our list */
            /* TODO: update expiration */
            return;
        }
    }

Adrien Béraud's avatar
Adrien Béraud committed
757
    std::unique_ptr<UPnPIGD> new_igd;
Stepan Salenikovich's avatar
Stepan Salenikovich committed
758
759
760
761
    int upnp_err;

    std::string friendlyName = get_first_doc_item(doc, "friendlyName");
    if (not friendlyName.empty() )
Adrien Béraud's avatar
Adrien Béraud committed
762
        JAMI_DBG("UPnP: checking new device of type IGD: '%s'",
Stepan Salenikovich's avatar
Stepan Salenikovich committed
763
764
765
766
767
768
                 friendlyName.c_str());

    /* determine baseURL */
    std::string baseURL = get_first_doc_item(doc, "URLBase");
    if (baseURL.empty()) {
        /* get it from the discovery event location */
Alexandre Viau's avatar
Alexandre Viau committed
769
        baseURL = std::string(UpnpDiscovery_get_Location_cstr(d_event));
Stepan Salenikovich's avatar
Stepan Salenikovich committed
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
    }

    /* check if its a valid IGD:
     *      1. check for IGD device... already done if this function is called
     *      2. check for WAN device... skip checking for this and check for the services directly
     *      3. check for WANIPConnection service or WANPPPConnection service
     *      4. check if connected to Internet (if not, no point in port forwarding)
     *      5. check that we can get the external IP
     */

    /* get list of services defined by serviceType */
    std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&> serviceList(nullptr, ixmlNodeList_free);
    serviceList.reset(ixmlDocument_getElementsByTagName(doc, "serviceType"));

    /* get list of all 'serviceType' elements */
    bool found_connected_IGD = false;
    unsigned long list_length = ixmlNodeList_length(serviceList.get());

    /* go through the 'serviceType' nodes until we find the first service of type
     * WANIPConnection or WANPPPConnection which is connected to an external network */
    for (unsigned long node_idx = 0; node_idx < list_length and not found_connected_IGD; node_idx++) {
        IXML_Node* serviceType_node = ixmlNodeList_item(serviceList.get(), node_idx);
        std::string serviceType = get_element_text(serviceType_node);

        /* only check serviceType of WANIPConnection or WANPPPConnection */
        if (serviceType.compare(UPNP_WANIP_SERVICE) == 0
            or serviceType.compare(UPNP_WANPPP_SERVICE) == 0) {

            /* we found a correct 'serviceType', now get the parent node because
             * the rest of the service definitions are siblings of 'serviceType' */
            IXML_Node* service_node = ixmlNode_getParentNode(serviceType_node);
            if (service_node) {
                /* perform sanity check; the parent node should be called "service" */
                if( strcmp(ixmlNode_getNodeName(service_node), "service") == 0) {
                    /* get the rest of the service definitions */

                    /* serviceId */
                    IXML_Element* service_element = (IXML_Element*)service_node;
                    std::string serviceId = get_first_element_item(service_element, "serviceId");

                    /* get the relative controlURL and turn it into absolute address using the URLBase */
                    std::string controlURL = get_first_element_item(service_element, "controlURL");
                    if (not controlURL.empty()) {
Guillaume Roguez's avatar
Guillaume Roguez committed
813
814
815
816
817
818
819
                        char* absolute_url = nullptr;
                        upnp_err = UpnpResolveURL2(baseURL.c_str(),
                                                   controlURL.c_str(),
                                                   &absolute_url);
                        if (upnp_err == UPNP_E_SUCCESS)
                            controlURL = absolute_url;
                        else
Adrien Béraud's avatar
Adrien Béraud committed
820
                            JAMI_WARN("UPnP: error resolving absolute controlURL: %s",
Guillaume Roguez's avatar
Guillaume Roguez committed
821
822
                                      UpnpGetErrorMessage(upnp_err));
                        std::free(absolute_url);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
823
824
825
826
827
                    }

                    /* get the relative eventSubURL and turn it into absolute address using the URLBase */
                    std::string eventSubURL = get_first_element_item(service_element, "eventSubURL");
                    if (not eventSubURL.empty()) {
Guillaume Roguez's avatar
Guillaume Roguez committed
828
829
830
831
832
833
834
                        char* absolute_url = nullptr;
                        upnp_err = UpnpResolveURL2(baseURL.c_str(),
                                                   eventSubURL.c_str(),
                                                   &absolute_url);
                        if (upnp_err == UPNP_E_SUCCESS)
                            eventSubURL = absolute_url;
                        else
Adrien Béraud's avatar
Adrien Béraud committed
835
                            JAMI_WARN("UPnP: error resolving absolute eventSubURL: %s",
Guillaume Roguez's avatar
Guillaume Roguez committed
836
837
                                      UpnpGetErrorMessage(upnp_err));
                        std::free(absolute_url);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
838
839
840
841
842
                    }

                    /* make sure all of the services are defined
                     * and check if the IGD is connected to an external network */
                    if (not (serviceId.empty() and controlURL.empty() and eventSubURL.empty()) ) {
Adrien Béraud's avatar
Adrien Béraud committed
843
                        /* JAMI_DBG("UPnP: got service info from device:\n\tserviceType: %s\n\tserviceID: %s\n\tcontrolURL: %s\n\teventSubURL: %s",
Stepan Salenikovich's avatar
Stepan Salenikovich committed
844
                                 serviceType.c_str(), serviceId.c_str(), controlURL.c_str(), eventSubURL.c_str()); */
845
846
847
848
849
850
851
852
                        new_igd.reset(new UPnPIGD(
                            std::move(UDN),
                            std::move(baseURL),
                            std::move(friendlyName),
                            std::move(serviceType),
                            std::move(serviceId),
                            std::move(controlURL),
                            std::move(eventSubURL)));
Adrien Béraud's avatar
Adrien Béraud committed
853
854
                        if (isIGDConnected(*new_igd)) {
                            new_igd->publicIp = getExternalIP(*new_igd);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
855
                            if (new_igd->publicIp) {
Adrien Béraud's avatar
Adrien Béraud committed
856
                                JAMI_DBG("UPnP: got external IP: %s", new_igd->publicIp.toString().c_str());
Eloi Bail's avatar
Eloi Bail committed
857
858
859
860
                                new_igd->localIp = ip_utils::getLocalAddr(pj_AF_INET());
                                if (new_igd->localIp)
                                    found_connected_IGD = true;

Stepan Salenikovich's avatar
Stepan Salenikovich committed
861
862
863
864
865
                            }
                        }
                    }
                    /* TODO: subscribe to the service to get events, eg: when IP changes */
                } else
Adrien Béraud's avatar
Adrien Béraud committed
866
                     JAMI_WARN("UPnP: IGD \"serviceType\" parent node is not called \"service\"!");
Stepan Salenikovich's avatar
Stepan Salenikovich committed
867
            } else
Adrien Béraud's avatar
Adrien Béraud committed
868
                JAMI_WARN("UPnP: IGD \"serviceType\" has no parent node!");
Stepan Salenikovich's avatar
Stepan Salenikovich committed
869
870
871
872
873
874
875
876
        }
    }

    /* if its a valid IGD, add to list of IGDs (ideally there is only one at a time)
     * subscribe to the WANIPConnection or WANPPPConnection service to receive
     * updates about state changes, eg: new external IP
     */
    if (found_connected_IGD) {
Adrien Béraud's avatar
Adrien Béraud committed
877
        JAMI_DBG("UPnP: found a valid IGD: %s", new_igd->getBaseURL().c_str());
Stepan Salenikovich's avatar
Stepan Salenikovich committed
878
879
880
881

        {
            std::lock_guard<std::mutex> lock(validIGDMutex_);
            /* delete all RING mappings first */
Adrien Béraud's avatar
Adrien Béraud committed
882
            removeMappingsByLocalIPAndDescription(*new_igd, Mapping::UPNP_DEFAULT_MAPPING_DESCRIPTION);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
883
            validIGDs_.emplace(UDN, std::move(new_igd));
884
            validIGDCondVar_.notify_all();
885
886
            for (const auto& l : igdListeners_)
                l.second();
Stepan Salenikovich's avatar
Stepan Salenikovich committed
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
        }
    }
}

static std::string
get_element_text(IXML_Node* node)
{
    std::string ret;
    if (node) {
        IXML_Node *textNode = ixmlNode_getFirstChild(node);
        if (textNode) {
            const char* value = ixmlNode_getNodeValue(textNode);
            if (value)
                ret = std::string(value);
        }
    }
    return ret;
}

static std::string
get_first_doc_item(IXML_Document* doc, const char* item)
{
    std::string ret;

    std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&>
        nodeList(ixmlDocument_getElementsByTagName(doc, item), ixmlNodeList_free);
    if (nodeList) {
        /* if there are several nodes which match the tag, we only want the first one */
        ret = get_element_text( ixmlNodeList_item(nodeList.get(), 0) );
    }
    return ret;
}

static std::string
get_first_element_item(IXML_Element* element, const char* item)
{
    std::string ret;

    std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&>
        nodeList(ixmlElement_getElementsByTagName(element, item), ixmlNodeList_free);
    if (nodeList) {
        /* if there are several nodes which match the tag, we only want the first one */
        ret = get_element_text( ixmlNodeList_item(nodeList.get(), 0) );
    }
    return ret;
}
Adrien Béraud's avatar
Adrien Béraud committed
933
934

int
Alexandre Viau's avatar
Alexandre Viau committed
935
UPnPContext::cp_callback(Upnp_EventType event_type, const void* event, void* user_data)
Adrien Béraud's avatar
Adrien Béraud committed
936
937
938
939
{
    if (auto upnpContext = static_cast<UPnPContext*>(user_data))
        return upnpContext->handleUPnPEvents(event_type, event);

Adrien Béraud's avatar
Adrien Béraud committed
940
    JAMI_WARN("UPnP callback without UPnPContext");
Adrien Béraud's avatar
Adrien Béraud committed
941
942
943
    return 0;
}

Stepan Salenikovich's avatar
Stepan Salenikovich committed
944
int
Alexandre Viau's avatar
Alexandre Viau committed
945
UPnPContext::handleUPnPEvents(Upnp_EventType event_type, const void* event)
Stepan Salenikovich's avatar
Stepan Salenikovich committed
946
947
948
949
{
    switch( event_type )
    {
    case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
Adrien Béraud's avatar
Adrien Béraud committed
950
        /* JAMI_DBG("UPnP: CP received a discovery advertisement"); */
Stepan Salenikovich's avatar
Stepan Salenikovich committed
951
952
    case UPNP_DISCOVERY_SEARCH_RESULT:
    {
Alexandre Viau's avatar
Alexandre Viau committed
953
        const UpnpDiscovery* d_event = ( const UpnpDiscovery* )event;
Stepan Salenikovich's avatar
Stepan Salenikovich committed
954
955
956
957
        std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&> desc_doc(nullptr, ixmlDocument_free);
        int upnp_err;

        /* if (event_type != UPNP_DISCOVERY_ADVERTISEMENT_ALIVE)
Adrien Béraud's avatar
Adrien Béraud committed
958
             JAMI_DBG("UPnP: CP received a discovery search result"); */
Stepan Salenikovich's avatar
Stepan Salenikovich committed
959
960

        /* check if we are already in the process of checking this device */
961
        std::unique_lock<std::mutex> lock(cpDeviceMutex_);
Alexandre Viau's avatar
Alexandre Viau committed
962
        auto it = cpDevices_.find(std::string(UpnpDiscovery_get_Location_cstr(d_event)));
Stepan Salenikovich's avatar
Stepan Salenikovich committed
963

964
        if (it == cpDevices_.end()) {
Alexandre Viau's avatar
Alexandre Viau committed
965
            cpDevices_.emplace(std::string(UpnpDiscovery_get_Location_cstr(d_event)));
Stepan Salenikovich's avatar
Stepan Salenikovich committed
966
967
            lock.unlock();

Alexandre Viau's avatar
Alexandre Viau committed
968
            if (UpnpDiscovery_get_ErrCode(d_event) != UPNP_E_SUCCESS)
Adrien Béraud's avatar
Adrien Béraud committed
969
                JAMI_WARN("UPnP: Error in discovery event received by the CP: %s",
Alexandre Viau's avatar
Alexandre Viau committed
970
                          UpnpGetErrorMessage(UpnpDiscovery_get_ErrCode(d_event)));
Stepan Salenikovich's avatar
Stepan Salenikovich committed
971

Adrien Béraud's avatar
Adrien Béraud committed
972
            /* JAMI_DBG("UPnP: Control Point received discovery event from device:\n\tid: %s\n\ttype: %s\n\tservice: %s\n\tversion: %s\n\tlocation: %s\n\tOS: %s",
Alexandre Viau's avatar
Alexandre Viau committed
973
                     d_event->DeviceId, d_event->DeviceType, d_event->ServiceType, d_event->ServiceVer, UpnpDiscovery_get_Location_cstr(d_event), d_event->Os);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
974
975
976
977
978
979
980
            */

            /* note: this thing will block until success for the system socket timeout
             *       unless libupnp is compile with '-disable-blocking-tcp-connections'
             *       in which case it will block for the libupnp specified timeout
             */
            IXML_Document* desc_doc_ptr = nullptr;
Alexandre Viau's avatar
Alexandre Viau committed
981
            upnp_err = UpnpDownloadXmlDoc( UpnpDiscovery_get_Location_cstr(d_event), &desc_doc_ptr);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
982
983
            desc_doc.reset(desc_doc_ptr);
            if ( upnp_err != UPNP_E_SUCCESS ) {
984
985
986
987
                /* the download of the xml doc has failed; this probably happened
                 * because the router has UPnP disabled, but is still sending
                 * UPnP discovery packets
                 *
Adrien Béraud's avatar
Adrien Béraud committed
988
                 * JAMI_WARN("UPnP: Error downloading device description: %s",
989
990
                 *         UpnpGetErrorMessage(upnp_err));
                 */
Stepan Salenikovich's avatar
Stepan Salenikovich committed
991
            } else {
992
                parseDevice(desc_doc.get(), d_event);
Stepan Salenikovich's avatar
Stepan Salenikovich committed
993
994
995
996
997
998
999
            }

            /* finished parsing device; remove it from know devices list,
             * since next time it could be a new device with same URL
             * eg: if we switch routers or if a new device with the same IP appears
             */
            lock.lock();
Alexandre Viau's avatar
Alexandre Viau committed
1000
            cpDevices_.erase(UpnpDiscovery_get_Location_cstr(d_event));
For faster browsing, not all history is shown. View entire blame