ice_transport.cpp 47.3 KB
Newer Older
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
 *
4 5 6 7 8 9
 *  Author: Guillaume Roguez <guillaume.roguez@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.
Guillaume Roguez's avatar
Guillaume Roguez committed
10
 *
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *  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.
 */

#include "ice_transport.h"
#include "ice_socket.h"
#include "logger.h"
#include "sip/sip_utils.h"
#include "manager.h"
Stepan Salenikovich's avatar
Stepan Salenikovich committed
26
#include "upnp/upnp_control.h"
27 28

#include <pjlib.h>
Guillaume Roguez's avatar
Guillaume Roguez committed
29
#include <msgpack.hpp>
30

31 32 33 34 35 36
#include <map>
#include <atomic>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
37
#include <utility>
Guillaume Roguez's avatar
Guillaume Roguez committed
38
#include <tuple>
39 40
#include <algorithm>
#include <sstream>
41 42
#include <chrono>
#include <thread>
43
#include <cerrno>
44

45
#define TRY(ret) do {                                        \
46
        if ((ret) != PJ_SUCCESS)                             \
47
            throw std::runtime_error(#ret " failed");        \
48 49
    } while (0)

Adrien Béraud's avatar
Adrien Béraud committed
50
namespace jami {
51

Guillaume Roguez's avatar
Guillaume Roguez committed
52
static constexpr unsigned STUN_MAX_PACKET_SIZE {8192};
53 54 55
static constexpr uint16_t IPV6_HEADER_SIZE = 40; ///< Size in bytes of IPV6 packet header
static constexpr uint16_t IPV4_HEADER_SIZE = 20; ///< Size in bytes of IPV4 packet header
static constexpr int MAX_CANDIDATES {32};
Guillaume Roguez's avatar
Guillaume Roguez committed
56

57 58
//==============================================================================

59 60 61
using MutexGuard = std::lock_guard<std::mutex>;
using MutexLock = std::unique_lock<std::mutex>;

62 63 64 65 66 67 68 69 70 71 72
namespace
{

struct IceSTransDeleter
{
    void operator ()(pj_ice_strans* ptr) {
        pj_ice_strans_stop_ice(ptr);
        pj_ice_strans_destroy(ptr);
    }
};

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
class PeerChannel {
public:
  PeerChannel() {}
  ~PeerChannel() { stop(); }

  PeerChannel(PeerChannel &&o) {
    MutexGuard lk{o.mutex_};
    stream_ = std::move(o.stream_);
  }

  PeerChannel &operator=(PeerChannel &&o) {
    std::lock(mutex_, o.mutex_);
    MutexGuard lk1{mutex_, std::adopt_lock};
    MutexGuard lk2{o.mutex_, std::adopt_lock};
    stream_ = std::move(o.stream_);
    return *this;
  }

  void operator<<(const std::string &data) {
    MutexGuard lk{mutex_};
    stream_.clear();
    stream_ << data;

    notified_ = true;
    cv_.notify_one();
  }

  ssize_t isDataAvailable() {
    MutexGuard lk{mutex_};
    auto pos = stream_.tellg();
    stream_.seekg(0, std::ios_base::end);
    auto available = (stream_.tellg() - pos);
    stream_.seekg(pos);
    return available;
  }

  template <typename Duration> bool wait(Duration timeout) {
    std::lock(apiMutex_, mutex_);
    MutexGuard lk_api{apiMutex_, std::adopt_lock};
    MutexLock lk{mutex_, std::adopt_lock};
    auto a = cv_.wait_for(lk, timeout,
                        [this] { return stop_ or /*(data.size() != 0)*/ !stream_.eof(); });
    return a;
  }

  std::size_t read(char *output, std::size_t size) {
    std::lock(apiMutex_, mutex_);
    MutexGuard lk_api{apiMutex_, std::adopt_lock};
    MutexLock lk{mutex_, std::adopt_lock};
    cv_.wait(lk, [&, this] {
      if (stop_)
        return true;
      stream_.read(&output[0], size);
      return stream_.gcount() > 0;
    });
    return stop_ ? 0 : stream_.gcount();
  }

  void stop() noexcept {
    {
      MutexGuard lk{mutex_};
      if (stop_)
        return;
      stop_ = true;
    }
    cv_.notify_all();

    // Make sure that no thread is blocked into read() or wait() methods
    MutexGuard lk_api{apiMutex_};
  }

private:
  PeerChannel(const PeerChannel &o) = delete;
  PeerChannel &operator=(const PeerChannel &o) = delete;
  std::mutex apiMutex_{};
  std::mutex mutex_{};
  std::condition_variable cv_{};
  std::stringstream stream_{};
  bool stop_{false};
  bool notified_{false};

  std::vector<char> data;

  friend void operator<<(std::vector<char> &, PeerChannel &);
};

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
} // namespace <anonymous>

//==============================================================================

class IceTransport::Impl
{
public:
    Impl(const char* name, int component_count, bool master, const IceTransportOptions& options);
    ~Impl();

    void onComplete(pj_ice_strans* ice_st, pj_ice_strans_op op,
                    pj_status_t status);

    void onReceiveData(unsigned comp_id, void *pkt, pj_size_t size);

    /**
     * Set/change transport role as initiator.
     * Should be called before start method.
     */
    bool setInitiatorSession();

    /**
     * Set/change transport role as slave.
     * Should be called before start method.
     */
    bool setSlaveSession();

    bool createIceSession(pj_ice_sess_role role);

    void getUFragPwd();

    void getDefaultCanditates();

    // Non-mutex protected of public versions
    bool _isInitialized() const;
    bool _isStarted() const;
    bool _isRunning() const;
    bool _isFailed() const;

    IpAddr getLocalAddress(unsigned comp_id) const;
    IpAddr getRemoteAddress(unsigned comp_id) const;

201
    std::unique_ptr<pj_pool_t, std::function<void(pj_pool_t*)>> pool_;
202 203
    IceTransportCompleteCb on_initdone_cb_;
    IceTransportCompleteCb on_negodone_cb_;
204
    IceRecvInfo on_recv_cb_;
205 206 207 208 209 210 211 212 213 214 215 216
    std::unique_ptr<pj_ice_strans, IceSTransDeleter> icest_;
    unsigned component_count_;
    pj_ice_sess_cand cand_[MAX_CANDIDATES] {};
    std::string local_ufrag_;
    std::string local_pwd_;
    pj_sockaddr remoteAddr_;
    std::condition_variable iceCV_ {};
    mutable std::mutex iceMutex_ {};
    pj_ice_strans_cfg config_;
    std::string last_errmsg_;

    struct Packet {
217 218 219
      Packet(void *pkt, pj_size_t size)
          : data{reinterpret_cast<char *>(pkt), reinterpret_cast<char *>(pkt) + size} { }
        std::vector<char> data;
220 221
    };

222 223 224
    std::vector<PeerChannel> peerChannels_;
    std::mutex apiMutex_;

225 226 227 228 229 230 231 232 233 234 235 236 237 238
    struct ComponentIO {
        std::mutex mutex;
        std::condition_variable cv;
        std::deque<Packet> queue;
        IceRecvCb cb;
    };

    std::vector<ComponentIO> compIO_;

    std::atomic_bool initiatorSession_ {true};

    /**
     * Returns the IP of each candidate for a given component in the ICE session
     */
Sébastien Blin's avatar
Sébastien Blin committed
239 240 241 242 243
    struct LocalCandidate {
        IpAddr addr;
        pj_ice_cand_transport transport;
    };
    std::vector<LocalCandidate> getLocalICECandidates(unsigned comp_id) const;
244 245 246 247 248

    /**
     * Adds a reflective candidate to ICE session
     * Must be called before negotiation
     */
Sébastien Blin's avatar
Sébastien Blin committed
249 250 251
    void addReflectiveCandidate(int comp_id, const IpAddr &base,
                                const IpAddr &addr,
                                const pj_ice_cand_transport& transport);
252 253 254 255 256 257 258 259 260 261 262 263 264 265

    /**
     * Creates UPnP port mappings and adds ICE candidates based on those mappings
     */
    void selectUPnPIceCandidates();

    std::unique_ptr<upnp::Controller> upnp_;

    bool onlyIPv4Private_ {true};

    // IO/Timer events are handled by following thread
    std::thread thread_;
    std::atomic_bool threadTerminateFlags_ {false};
    void handleEvents(unsigned max_msec);
266 267 268 269

    // Wait data on components
    std::vector<pj_ssize_t> lastReadLen_;
    std::condition_variable waitDataCv_ = {};
270 271 272
};

//==============================================================================
273

Guillaume Roguez's avatar
Guillaume Roguez committed
274 275 276 277 278 279 280 281 282 283 284 285 286
/**
 * Add stun/turn servers or default host as candidates
 */
static void
add_stun_server(pj_ice_strans_cfg& cfg, int af)
{
    if (cfg.stun_tp_cnt >= PJ_ICE_MAX_STUN)
        throw std::runtime_error("Too many STUN servers");
    auto& stun = cfg.stun_tp[cfg.stun_tp_cnt++];

    pj_ice_strans_stun_cfg_default(&stun);
    stun.cfg.max_pkt_size = STUN_MAX_PACKET_SIZE;
    stun.af = af;
287
    stun.conn_type = cfg.stun.conn_type;
Guillaume Roguez's avatar
Guillaume Roguez committed
288

Adrien Béraud's avatar
Adrien Béraud committed
289
    JAMI_DBG("[ice] added host stun server");
Guillaume Roguez's avatar
Guillaume Roguez committed
290 291 292
}

static void
293
add_stun_server(pj_pool_t& pool, pj_ice_strans_cfg& cfg, const StunServerInfo& info)
Guillaume Roguez's avatar
Guillaume Roguez committed
294 295 296 297
{
    if (cfg.stun_tp_cnt >= PJ_ICE_MAX_STUN)
        throw std::runtime_error("Too many STUN servers");

298
    IpAddr ip {info.uri};
Guillaume Roguez's avatar
Guillaume Roguez committed
299 300 301 302

    // Given URI cannot be DNS resolved or not IPv4 or IPv6?
    // This prevents a crash into PJSIP when ip.toString() is called.
    if (ip.getFamily() == AF_UNSPEC) {
Adrien Béraud's avatar
Adrien Béraud committed
303
        JAMI_WARN("[ice] STUN server '%s' not used, unresolvable address", info.uri.c_str());
Guillaume Roguez's avatar
Guillaume Roguez committed
304 305 306 307 308 309 310 311 312
        return;
    }

    auto& stun = cfg.stun_tp[cfg.stun_tp_cnt++];
    pj_ice_strans_stun_cfg_default(&stun);
    pj_strdup2_with_null(&pool, &stun.server, ip.toString().c_str());
    stun.af = ip.getFamily();
    stun.port = PJ_STUN_PORT;
    stun.cfg.max_pkt_size = STUN_MAX_PACKET_SIZE;
313
    stun.conn_type = cfg.stun.conn_type;
Guillaume Roguez's avatar
Guillaume Roguez committed
314

Adrien Béraud's avatar
Adrien Béraud committed
315
    JAMI_DBG("[ice] added stun server '%s', port %d", pj_strbuf(&stun.server), stun.port);
Guillaume Roguez's avatar
Guillaume Roguez committed
316 317 318
}

static void
319
add_turn_server(pj_pool_t& pool, pj_ice_strans_cfg& cfg, const TurnServerInfo& info)
Guillaume Roguez's avatar
Guillaume Roguez committed
320 321 322
{
    if (cfg.turn_tp_cnt >= PJ_ICE_MAX_TURN)
        throw std::runtime_error("Too many TURN servers");
323 324

    IpAddr ip {info.uri};
Guillaume Roguez's avatar
Guillaume Roguez committed
325 326 327

    // Same comment as add_stun_server()
    if (ip.getFamily() == AF_UNSPEC) {
Adrien Béraud's avatar
Adrien Béraud committed
328
        JAMI_WARN("[ice] TURN server '%s' not used, unresolvable address", info.uri.c_str());
Guillaume Roguez's avatar
Guillaume Roguez committed
329 330 331 332 333 334 335 336 337
        return;
    }

    auto& turn = cfg.turn_tp[cfg.turn_tp_cnt++];
    pj_ice_strans_turn_cfg_default(&turn);
    pj_strdup2_with_null(&pool, &turn.server, ip.toString().c_str());
    turn.af = ip.getFamily();
    turn.port = PJ_STUN_PORT;
    turn.cfg.max_pkt_size = STUN_MAX_PACKET_SIZE;
338
    turn.conn_type = cfg.turn.conn_type;
Guillaume Roguez's avatar
Guillaume Roguez committed
339 340

    // Authorization (only static plain password supported yet)
341
    if (not info.password.empty()) {
Guillaume Roguez's avatar
Guillaume Roguez committed
342 343
        turn.auth_cred.type = PJ_STUN_AUTH_CRED_STATIC;
        turn.auth_cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
344 345 346
        pj_strset(&turn.auth_cred.data.static_cred.realm, (char*)info.realm.c_str(), info.realm.size());
        pj_strset(&turn.auth_cred.data.static_cred.username, (char*)info.username.c_str(), info.username.size());
        pj_strset(&turn.auth_cred.data.static_cred.data, (char*)info.password.c_str(), info.password.size());
Guillaume Roguez's avatar
Guillaume Roguez committed
347 348
    }

Adrien Béraud's avatar
Adrien Béraud committed
349
    JAMI_DBG("[ice] added turn server '%s', port %d", pj_strbuf(&turn.server), turn.port);
Guillaume Roguez's avatar
Guillaume Roguez committed
350 351
}

352
//==============================================================================
353

354 355
IceTransport::Impl::Impl(const char* name, int component_count, bool master,
                         const IceTransportOptions& options)
356
    : pool_(nullptr, [](pj_pool_t* pool) { sip_utils::register_thread(); pj_pool_release(pool); })
357 358
    , on_initdone_cb_(options.onInitDone)
    , on_negodone_cb_(options.onNegoDone)
359
    , on_recv_cb_(options.onRecvReady)
360 361
    , component_count_(component_count)
    , compIO_(component_count)
Guillaume Roguez's avatar
Guillaume Roguez committed
362
    , initiatorSession_(master)
363
    , thread_()
364
{
365
    if (options.upnpEnable)
Stepan Salenikovich's avatar
Stepan Salenikovich committed
366 367
        upnp_.reset(new upnp::Controller());

368
    auto &iceTransportFactory = Manager::instance().getIceTransportFactory();
Guillaume Roguez's avatar
Guillaume Roguez committed
369
    config_ = iceTransportFactory.getIceCfg(); // config copy
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    if (options.tcpEnable) {
      config_.protocol = PJ_ICE_TP_TCP;
      config_.stun.conn_type = PJ_STUN_TP_TCP;
      config_.turn.conn_type = PJ_TURN_TP_TCP;
    } else {
      config_.protocol = PJ_ICE_TP_UDP;
      config_.stun.conn_type = PJ_STUN_TP_UDP;
      config_.turn.conn_type = PJ_TURN_TP_UDP;
    }

    if (options.aggressive) {
        config_.opt.aggressive = PJ_TRUE;
    } else {
        config_.opt.aggressive = PJ_FALSE;
    }

    peerChannels_.resize(component_count_ + 1);
    lastReadLen_.resize(component_count_);

    // Add local hosts (IPv4, IPv6) as stun candidates
    add_stun_server(config_, pj_AF_INET6());
    add_stun_server(config_, pj_AF_INET());
392

Adrien Béraud's avatar
Adrien Béraud committed
393
    sip_utils::register_thread();
394 395 396 397 398 399
    pool_.reset(pj_pool_create(iceTransportFactory.getPoolFactory(),
                               "IceTransport.pool", 512, 512, NULL));
    if (not pool_)
        throw std::runtime_error("pj_pool_create() failed");

    pj_ice_strans_cb icecb;
400
    pj_bzero(&icecb, sizeof(icecb));
401 402 403 404 405 406 407

    icecb.on_rx_data =                                                  \
        [] (pj_ice_strans* ice_st, unsigned comp_id, void *pkt, pj_size_t size,
            const pj_sockaddr_t* /*src_addr*/, unsigned /*src_addr_len*/) {
        if (auto* tr = static_cast<Impl*>(pj_ice_strans_get_user_data(ice_st)))
            tr->onReceiveData(comp_id, pkt, size);
        else
Adrien Béraud's avatar
Adrien Béraud committed
408
            JAMI_WARN("null IceTransport");
409 410 411 412 413 414 415
    };

    icecb.on_ice_complete = \
        [] (pj_ice_strans* ice_st, pj_ice_strans_op op, pj_status_t status) {
        if (auto* tr = static_cast<Impl*>(pj_ice_strans_get_user_data(ice_st)))
            tr->onComplete(ice_st, op, status);
        else
Adrien Béraud's avatar
Adrien Béraud committed
416
            JAMI_WARN("null IceTransport");
417
    };
418

419 420 421 422 423 424 425 426 427 428 429
    icecb.on_data_sent = [](pj_ice_strans* ice_st, unsigned comp_id,
                                pj_ssize_t size) {
        if (auto* tr = static_cast<Impl*>(pj_ice_strans_get_user_data(ice_st))) {
          if (comp_id > 0 && comp_id - 1 < tr->lastReadLen_.size()) {
            tr->lastReadLen_[comp_id - 1] = size;
            tr->waitDataCv_.notify_all();
          }
        } else
            JAMI_WARN("null IceTransport");
    };

430 431 432
    // Add STUN servers
    for (auto& server : options.stunServers)
        add_stun_server(*pool_, config_, server);
433

434 435 436
    // Add TURN servers
    for (auto& server : options.turnServers)
        add_turn_server(*pool_, config_, server);
437

438
    static constexpr auto IOQUEUE_MAX_HANDLES = std::min(PJ_IOQUEUE_MAX_HANDLES, 64);
439 440 441
    TRY( pj_timer_heap_create(pool_.get(), 100, &config_.stun_cfg.timer_heap) );
    TRY( pj_ioqueue_create(pool_.get(), IOQUEUE_MAX_HANDLES, &config_.stun_cfg.ioqueue) );

442 443 444 445 446 447 448 449 450
    pj_ice_strans* icest = nullptr;
    pj_status_t status = pj_ice_strans_create(name, &config_, component_count,
                                              this, &icecb, &icest);

    if (status != PJ_SUCCESS || icest == nullptr) {
        throw std::runtime_error("pj_ice_strans_create() failed");
    }

    // Must be created after any potential failure
451
    thread_ = std::thread([this]{
452
            sip_utils::register_thread();
453 454 455 456
            while (not threadTerminateFlags_) {
                handleEvents(500); // limit polling to 500ms
            }
        });
457 458
}

459
IceTransport::Impl::~Impl()
460
{
461
    sip_utils::register_thread();
462 463 464 465 466 467 468 469 470 471 472 473 474 475

    threadTerminateFlags_ = true;
    if (thread_.joinable())
        thread_.join();

    icest_.reset(); // must be done before ioqueue/timer destruction

    if (config_.stun_cfg.ioqueue)
        pj_ioqueue_destroy(config_.stun_cfg.ioqueue);

    if (config_.stun_cfg.timer_heap)
        pj_timer_heap_destroy(config_.stun_cfg.timer_heap);
}

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
bool
IceTransport::Impl::_isInitialized() const
{
    if (auto icest = icest_.get()) {
        auto state = pj_ice_strans_get_state(icest);
        return state >= PJ_ICE_STRANS_STATE_SESS_READY and state != PJ_ICE_STRANS_STATE_FAILED;
    }
    return false;
}

bool
IceTransport::Impl::_isStarted() const
{
    if (auto icest = icest_.get()) {
        auto state = pj_ice_strans_get_state(icest);
        return state >= PJ_ICE_STRANS_STATE_NEGO and state != PJ_ICE_STRANS_STATE_FAILED;
    }
    return false;
}

bool
IceTransport::Impl::_isRunning() const
{
    if (auto icest = icest_.get()) {
        auto state = pj_ice_strans_get_state(icest);
        return state >= PJ_ICE_STRANS_STATE_RUNNING and state != PJ_ICE_STRANS_STATE_FAILED;
    }
    return false;
}

bool
IceTransport::Impl::_isFailed() const
{
    if (auto icest = icest_.get())
        return pj_ice_strans_get_state(icest) == PJ_ICE_STRANS_STATE_FAILED;
    return false;
}

514
void
515
IceTransport::Impl::handleEvents(unsigned max_msec)
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
{
    // By tests, never seen more than two events per 500ms
    static constexpr auto MAX_NET_EVENTS = 2;

    pj_time_val max_timeout = {0, 0};
    pj_time_val timeout = {0, 0};
    unsigned net_event_count = 0;

    max_timeout.msec = max_msec;

    timeout.sec = timeout.msec = 0;
    pj_timer_heap_poll(config_.stun_cfg.timer_heap, &timeout);

    // timeout limitation
    if (timeout.msec >= 1000)
        timeout.msec = 999;
    if (PJ_TIME_VAL_GT(timeout, max_timeout))
        timeout = max_timeout;

    do {
        auto n_events = pj_ioqueue_poll(config_.stun_cfg.ioqueue, &timeout);

        // timeout
        if (not n_events)
            return;

        // error
        if (n_events < 0) {
            const auto err = pj_get_os_error();
            // Kept as debug as some errors are "normal" in regular context
546
            last_errmsg_ = sip_utils::sip_strerror(err);
Adrien Béraud's avatar
Adrien Béraud committed
547
            JAMI_DBG("[ice:%p] ioqueue error %d: %s", this, err, last_errmsg_.c_str());
548 549 550 551 552 553 554
            std::this_thread::sleep_for(std::chrono::milliseconds(PJ_TIME_VAL_MSEC(timeout)));
            return;
        }

        net_event_count += n_events;
        timeout.sec = timeout.msec = 0;
    } while (net_event_count < MAX_NET_EVENTS);
555
}
Stepan Salenikovich's avatar
Stepan Salenikovich committed
556

557
void
558
IceTransport::Impl::onComplete(pj_ice_strans* ice_st, pj_ice_strans_op op, pj_status_t status)
559 560
{
    const char *opname =
Guillaume Roguez's avatar
Guillaume Roguez committed
561
        op == PJ_ICE_STRANS_OP_INIT ? "initialization" :
562 563 564
        op == PJ_ICE_STRANS_OP_NEGOTIATION ? "negotiation" : "unknown_op";

    const bool done = status == PJ_SUCCESS;
565
    if (done) {
Adrien Béraud's avatar
Adrien Béraud committed
566
        JAMI_DBG("[ice:%p] %s success", this, opname);
567 568 569
    }
    else {
        last_errmsg_ = sip_utils::sip_strerror(status);
Adrien Béraud's avatar
Adrien Béraud committed
570
        JAMI_ERR("[ice:%p] %s failed: %s", this, opname, last_errmsg_.c_str());
571
    }
572

573
    {
574
        std::lock_guard<std::mutex> lk(iceMutex_);
Guillaume Roguez's avatar
Guillaume Roguez committed
575 576 577 578 579 580 581 582 583 584
        if (!icest_.get())
            icest_.reset(ice_st);
    }

    if (done and op == PJ_ICE_STRANS_OP_INIT) {
        if (initiatorSession_)
            setInitiatorSession();
        else
            setSlaveSession();
        selectUPnPIceCandidates();
585
    }
586 587

    if (op == PJ_ICE_STRANS_OP_INIT and on_initdone_cb_)
588
        on_initdone_cb_(done);
589 590 591 592 593 594 595
    else if (op == PJ_ICE_STRANS_OP_NEGOTIATION) {
        if (done) {
            // Dump of connection pairs
            std::stringstream out;
            for (unsigned i=0; i < component_count_; ++i) {
                auto laddr = getLocalAddress(i);
                auto raddr = getRemoteAddress(i);
596 597 598 599 600 601 602 603 604
                if (laddr and raddr) {
                    out << " [" << i << "] "
                        << laddr.toString(true, true)
                        << " <-> "
                        << raddr.toString(true, true)
                        << '\n';
                } else {
                    out << " [" << i << "] disabled\n";
                }
605
            }
Adrien Béraud's avatar
Adrien Béraud committed
606
            JAMI_DBG("[ice:%p] connection pairs (local <-> remote):\n%s", this, out.str().c_str());
607 608
        }
        if (on_negodone_cb_)
609
            on_negodone_cb_(done);
610
    }
611

Guillaume Roguez's avatar
Guillaume Roguez committed
612
    // Unlock waitForXXX APIs
613
    iceCV_.notify_all();
614 615
}

616 617 618
bool
IceTransport::Impl::setInitiatorSession()
{
Adrien Béraud's avatar
Adrien Béraud committed
619
    JAMI_DBG("ICE as master");
620 621 622 623 624
    initiatorSession_ = true;
    if (_isInitialized()) {
        auto status = pj_ice_strans_change_role(icest_.get(), PJ_ICE_SESS_ROLE_CONTROLLING);
        if (status != PJ_SUCCESS) {
            last_errmsg_ = sip_utils::sip_strerror(status);
Adrien Béraud's avatar
Adrien Béraud committed
625
            JAMI_ERR("[ice:%p] role change failed: %s", this, last_errmsg_.c_str());
626 627 628 629 630 631 632 633 634 635
            return false;
        }
        return true;
    }
    return createIceSession(PJ_ICE_SESS_ROLE_CONTROLLING);
}

bool
IceTransport::Impl::setSlaveSession()
{
Adrien Béraud's avatar
Adrien Béraud committed
636
    JAMI_DBG("ICE as slave");
637 638 639 640 641
    initiatorSession_ = false;
    if (_isInitialized()) {
        auto status = pj_ice_strans_change_role(icest_.get(), PJ_ICE_SESS_ROLE_CONTROLLED);
        if (status != PJ_SUCCESS) {
            last_errmsg_ = sip_utils::sip_strerror(status);
Adrien Béraud's avatar
Adrien Béraud committed
642
            JAMI_ERR("[ice:%p] role change failed: %s", this, last_errmsg_.c_str());
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
            return false;
        }
        return true;
    }
    return createIceSession(PJ_ICE_SESS_ROLE_CONTROLLED);
}

IpAddr
IceTransport::Impl::getLocalAddress(unsigned comp_id) const
{
    // Return the local IP of negotiated connection pair
    if (_isRunning()) {
        if (auto sess = pj_ice_strans_get_valid_pair(icest_.get(), comp_id+1))
            return sess->lcand->addr;
        else
            return {}; // disabled component
    } else
Adrien Béraud's avatar
Adrien Béraud committed
660
        JAMI_WARN("[ice:%p] bad call: non-negotiated transport", this);
661 662 663 664 665

    // Return the default IP (could be not nominated and valid after negotiation)
    if (_isInitialized())
        return cand_[comp_id].addr;

Adrien Béraud's avatar
Adrien Béraud committed
666
    JAMI_ERR("[ice:%p] bad call: non-initialized transport", this);
667 668 669 670 671 672 673 674 675 676 677 678 679
    return {};
}

IpAddr
IceTransport::Impl::getRemoteAddress(unsigned comp_id) const
{
    // Return the remote IP of negotiated connection pair
    if (_isRunning()) {
        if (auto sess = pj_ice_strans_get_valid_pair(icest_.get(), comp_id+1))
            return sess->rcand->addr;
        else
            return {}; // disabled component
    } else
Adrien Béraud's avatar
Adrien Béraud committed
680
        JAMI_WARN("[ice:%p] bad call: non-negotiated transport", this);
681

Adrien Béraud's avatar
Adrien Béraud committed
682
    JAMI_ERR("[ice:%p] bad call: non-negotiated transport", this);
683 684 685
    return {};
}

686
void
687
IceTransport::Impl::getUFragPwd()
688 689
{
    pj_str_t local_ufrag, local_pwd;
690
    pj_ice_strans_get_ufrag_pwd(icest_.get(), &local_ufrag, &local_pwd, nullptr, nullptr);
691 692 693 694
    local_ufrag_.assign(local_ufrag.ptr, local_ufrag.slen);
    local_pwd_.assign(local_pwd.ptr, local_pwd.slen);
}

695 696 697 698 699 700 701 702 703 704 705
void
IceTransport::Impl::getDefaultCanditates()
{
    for (unsigned i=0; i < component_count_; ++i)
        pj_ice_strans_get_def_cand(icest_.get(), i+1, &cand_[i]);
}

bool
IceTransport::Impl::createIceSession(pj_ice_sess_role role)
{
    if (pj_ice_strans_init_ice(icest_.get(), role, nullptr, nullptr) != PJ_SUCCESS) {
Adrien Béraud's avatar
Adrien Béraud committed
706
        JAMI_ERR("[ice:%p] pj_ice_strans_init_ice() failed", this);
707 708 709 710 711 712
        return false;
    }

    // Fetch some information on local configuration
    getUFragPwd();
    getDefaultCanditates();
Adrien Béraud's avatar
Adrien Béraud committed
713
    JAMI_DBG("[ice:%p] (local) ufrag=%s, pwd=%s", this, local_ufrag_.c_str(), local_pwd_.c_str());
714 715 716
    return true;
}

Sébastien Blin's avatar
Sébastien Blin committed
717 718
std::vector<IceTransport::Impl::LocalCandidate>
IceTransport::Impl::getLocalICECandidates(unsigned comp_id) const
719
{
Sébastien Blin's avatar
Sébastien Blin committed
720
    std::vector<LocalCandidate> cand_addrs;
721 722 723 724
    pj_ice_sess_cand cand[PJ_ARRAY_SIZE(cand_)];
    unsigned cand_cnt = PJ_ARRAY_SIZE(cand);

    if (pj_ice_strans_enum_cands(icest_.get(), comp_id, &cand_cnt, cand) != PJ_SUCCESS) {
Adrien Béraud's avatar
Adrien Béraud committed
725
        JAMI_ERR("[ice:%p] pj_ice_strans_enum_cands() failed", this);
726 727 728
        return cand_addrs;
    }

Sébastien Blin's avatar
Sébastien Blin committed
729 730 731
    for (unsigned i=0; i<cand_cnt; ++i) {
      cand_addrs.push_back({cand[i].addr, cand[i].transport});
    }
732 733 734 735

    return cand_addrs;
}

Sébastien Blin's avatar
Sébastien Blin committed
736 737 738
void IceTransport::Impl::addReflectiveCandidate(int comp_id, const IpAddr &base,
                                                const IpAddr &addr,
                                                const pj_ice_cand_transport& transport) {
739 740
    // HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK
    // WARNING: following implementation is a HACK of PJNATH !!
Sébastien Blin's avatar
Sébastien Blin committed
741 742 743 744 745 746 747 748 749
    // ice_strans doesn't have any API that permit to inject ICE any kind of
    // candidates. So, the hack consists in accessing hidden ICE session using a
    // patched PJPNATH library with a new API exposing this session
    // (pj_ice_strans_get_ice_sess). Then call pj_ice_sess_add_cand() with a
    // carfully forged candidate: the transport_id field uses an index in ICE
    // transport STUN servers array corresponding to a STUN server with the same
    // address familly. This implies we hope they'll not be modification of
    // transport_id meaning in future and no conflics with the borrowed STUN
    // config.
750
    // HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK-HACK
Adrien Béraud's avatar
Adrien Béraud committed
751
    sip_utils::register_thread();
752 753 754 755 756 757 758 759

    // borrowed from pjproject/pjnath/ice_strans.c, modified to be C++11'ized.
    static auto CREATE_TP_ID = [](pj_uint8_t type, pj_uint8_t idx) {
        return (pj_uint8_t)((type << 6) | idx);
    };
    static constexpr int SRFLX_PREF = 65535;
    static constexpr int TP_STUN = 1;

Sébastien Blin's avatar
Sébastien Blin committed
760 761 762
    // find a compatible STUN host with same address familly, normally all system
    // enabled host addresses are represented, so we expect to always found this
    // host
763 764 765
    int idx = -1;
    auto af = addr.getFamily();
    if (af == AF_UNSPEC) {
Sébastien Blin's avatar
Sébastien Blin committed
766 767
        JAMI_ERR("[ice:%p] Unable to add reflective IP %s: unknown addess familly",
                this, addr.toString().c_str());
768 769 770
        return;
    }

Sébastien Blin's avatar
Sébastien Blin committed
771
    for (unsigned i = 0; i < config_.stun_tp_cnt; ++i) {
772
        if (config_.stun_tp[i].af == af) {
Sébastien Blin's avatar
Sébastien Blin committed
773 774
        idx = i;
        break;
775 776 777
        }
    }
    if (idx < 0) {
Sébastien Blin's avatar
Sébastien Blin committed
778 779 780
        JAMI_ERR("[ice:%p] Unable to add reflective IP %s: no suitable local STUN "
                "host found",
                this, addr.toString().c_str());
781 782 783 784 785 786 787 788 789
        return;
    }

    pj_ice_sess_cand cand;

    cand.type = PJ_ICE_CAND_TYPE_SRFLX;
    cand.status = PJ_EPENDING; // not used
    cand.comp_id = comp_id;
    cand.transport_id = CREATE_TP_ID(TP_STUN, idx); // HACK!!
Sébastien Blin's avatar
Sébastien Blin committed
790 791
    cand.local_pref = SRFLX_PREF;                   // reflective
    cand.transport = transport;
792 793 794 795 796 797
    /* cand.foundation = ? */
    /* cand.prio = calculated by ice session */
    /* make base and addr the same since we're not going through a server */
    pj_sockaddr_cp(&cand.base_addr, base.pjPtr());
    pj_sockaddr_cp(&cand.addr, addr.pjPtr());
    pj_sockaddr_cp(&cand.rel_addr, &cand.base_addr);
Sébastien Blin's avatar
Sébastien Blin committed
798 799
    pj_ice_calc_foundation(pool_.get(), &cand.foundation, cand.type,
                            &cand.base_addr);
800

801
    auto ret = pj_ice_sess_add_cand(
Sébastien Blin's avatar
Sébastien Blin committed
802 803 804
        pj_ice_strans_get_ice_sess(icest_.get()), cand.comp_id, cand.transport_id,
        cand.type, cand.local_pref, &cand.foundation, &cand.addr, &cand.base_addr,
        &cand.rel_addr, pj_sockaddr_get_len(&cand.addr), NULL, cand.transport);
805 806 807

    if (ret != PJ_SUCCESS) {
        last_errmsg_ = sip_utils::sip_strerror(ret);
Sébastien Blin's avatar
Sébastien Blin committed
808 809 810 811
        JAMI_ERR("[ice:%p] pj_ice_sess_add_cand failed with error %d: %s", this,
                ret, last_errmsg_.c_str());
        JAMI_ERR("[ice:%p] failed to add candidate for comp_id=%d : %s : %s", this,
                comp_id, base.toString().c_str(), addr.toString().c_str());
812
    } else {
Sébastien Blin's avatar
Sébastien Blin committed
813 814
        JAMI_DBG("[ice:%p] succeed to add candidate for comp_id=%d : %s : %s", this,
                comp_id, base.toString().c_str(), addr.toString().c_str());
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
    }
}

void
IceTransport::Impl::selectUPnPIceCandidates()
{
    /* use upnp to open ports and add the proper candidates */
    if (upnp_) {
        /* for every component, get the candidate(s)
         * create a port mapping either with that port, or with an available port
         * add candidate with that port and public IP
         */
        if (auto publicIP = upnp_->getExternalIP()) {
            /* comp_id start at 1 */
            for (unsigned comp_id = 1; comp_id <= component_count_; ++comp_id) {
Adrien Béraud's avatar
Adrien Béraud committed
830
                JAMI_DBG("[ice:%p] UPnP: Opening port(s) for ICE comp %d and adding candidate with public IP",
831
                         this, comp_id);
Sébastien Blin's avatar
Sébastien Blin committed
832 833 834 835
                auto candidates = getLocalICECandidates(comp_id);
                for (const auto& candidate : candidates) {
                    if (candidate.transport == PJ_CAND_TCP_ACTIVE)
                        continue; // We don't need to map port 9.
836
                    auto localIP = upnp_->getLocalIP();
Sébastien Blin's avatar
Sébastien Blin committed
837 838
                    localIP.setPort(candidate.addr.getPort());
                    if (candidate.addr != localIP)
839
                        continue;
Sébastien Blin's avatar
Sébastien Blin committed
840
                    uint16_t port = candidate.addr.getPort();
841
                    uint16_t port_used;
Sébastien Blin's avatar
Sébastien Blin committed
842 843 844 845
                    auto portType = candidate.transport == PJ_CAND_UDP
                                        ? upnp::PortType::UDP
                                        : upnp::PortType::TCP;
                    if (upnp_->addAnyMapping(port, portType, true, &port_used)) {
846
                        publicIP.setPort(port_used);
Sébastien Blin's avatar
Sébastien Blin committed
847
                        addReflectiveCandidate(comp_id, candidate.addr, publicIP, candidate.transport);
848
                    } else
Adrien Béraud's avatar
Adrien Béraud committed
849
                        JAMI_WARN("[ice:%p] UPnP: Could not create a port mapping for the ICE candide", this);
850 851 852
                }
            }
        } else {
Adrien Béraud's avatar
Adrien Béraud committed
853
            JAMI_WARN("[ice:%p] UPnP: Could not determine public IP for ICE candidates", this);
854 855 856 857 858 859 860 861
        }
    }
}

void
IceTransport::Impl::onReceiveData(unsigned comp_id, void *pkt, pj_size_t size)
{
    if (!comp_id or comp_id > component_count_) {
Adrien Béraud's avatar
Adrien Béraud committed
862
        JAMI_ERR("rx: invalid comp_id (%u)", comp_id);
863 864 865 866 867
        return;
    }
    if (!size)
        return;
    auto& io = compIO_[comp_id-1];
868 869 870 871
    std::unique_lock<std::mutex> lk(io.mutex);
    if (on_recv_cb_) {
      on_recv_cb_();
    }
872 873 874
    if (io.cb) {
        io.cb((uint8_t*)pkt, size);
    } else {
875 876 877 878
        MutexLock lk{apiMutex_};
        auto &channel = peerChannels_.at(comp_id);
        lk.unlock();
        channel << std::string(reinterpret_cast<const char *>(pkt), size);
879 880 881 882 883 884 885 886 887 888 889 890
    }
}

//==============================================================================

IceTransport::IceTransport(const char* name, int component_count, bool master,
                           const IceTransportOptions& options)
    : pimpl_ {std::make_unique<Impl>(name, component_count, master, options)}
{}

bool
IceTransport::isInitialized() const
891
{
892 893
    std::lock_guard<std::mutex> lk(pimpl_->iceMutex_);
    return pimpl_->_isInitialized();
894 895
}

896 897
bool
IceTransport::isStarted() const
898
{
899 900
    std::lock_guard<std::mutex> lk {pimpl_->iceMutex_};
    return pimpl_->_isStarted();
901 902 903
}

bool
904
IceTransport::isRunning() const
905
{
906 907
    std::lock_guard<std::mutex> lk {pimpl_->iceMutex_};
    return pimpl_->_isRunning();
908 909 910
}

bool
911
IceTransport::isFailed() const
912
{
913 914
    std::lock_guard<std::mutex> lk {pimpl_->iceMutex_};
    return pimpl_->_isFailed();
915 916
}

917 918
unsigned
IceTransport::getComponentCount() const
919
{
920 921 922
    return pimpl_->component_count_;
}

923 924 925 926 927 928 929
bool
IceTransport::setSlaveSession()
{
    return pimpl_->setSlaveSession();
}
bool
IceTransport::setInitiatorSession()
930
{
931 932 933 934 935
    return pimpl_->setInitiatorSession();
}

std::string IceTransport::getLastErrMsg() const {
  return pimpl_->last_errmsg_;
936 937
}

938 939 940
bool
IceTransport::isInitiator() const
{
941 942 943 944
    if (isInitialized()) {
      return pj_ice_strans_get_role(pimpl_->icest_.get()) ==
             PJ_ICE_SESS_ROLE_CONTROLLING;
    }
945
    return pimpl_->initiatorSession_;
946 947
}

948
bool
949
IceTransport::start(const Attribute& rem_attrs, const std::vector<IceCandidate>& rem_candidates)
950
{
951
    if (not isInitialized()) {
Adrien Béraud's avatar
Adrien Béraud committed
952
        JAMI_ERR("[ice:%p] not initialized transport", this);
953 954 955
        return false;
    }

956 957
    // pj_ice_strans_start_ice crashes if remote candidates array is empty
    if (rem_candidates.empty()) {
Adrien Béraud's avatar
Adrien Béraud committed
958
        JAMI_ERR("[ice:%p] start failed: no remote candidates", this);
959 960 961
        return false;
    }

962
    pj_str_t ufrag, pwd;
Adrien Béraud's avatar
Adrien Béraud committed
963
    JAMI_DBG("[ice:%p] negotiation starting (%zu remote candidates)", this, rem_candidates.size());
964
    auto status = pj_ice_strans_start_ice(pimpl_->icest_.get(),
965 966
                                          pj_strset(&ufrag, (char*)rem_attrs.ufrag.c_str(), rem_attrs.ufrag.size()),
                                          pj_strset(&pwd, (char*)rem_attrs.pwd.c_str(), rem_attrs.pwd.size()),
967 968 969
                                          rem_candidates.size(),
                                          rem_candidates.data());
    if (status != PJ_SUCCESS) {
970
        pimpl_->last_errmsg_ = sip_utils::sip_strerror(status);
Adrien Béraud's avatar
Adrien Béraud committed
971
        JAMI_ERR("[ice:%p] start failed: %s", this, pimpl_->last_errmsg_.c_str());
972 973 974 975 976 977 978 979
        return false;
    }
    return true;
}

bool
IceTransport::start(const std::vector<uint8_t>& rem_data)
{
Guillaume Roguez's avatar
Guillaume Roguez committed
980 981
    std::string rem_ufrag;
    std::string rem_pwd;
982
    std::vector<IceCandidate> rem_candidates;
Guillaume Roguez's avatar
Guillaume Roguez committed
983 984 985 986

    auto data = reinterpret_cast<const char*>(rem_data.data());
    auto size = rem_data.size();

987
    try {
Guillaume Roguez's avatar
Guillaume Roguez committed
988 989 990
        std::size_t offset = 0;
        auto result = msgpack::unpack(data, size, offset);
        auto version = result.get().as<uint8_t>();
Adrien Béraud's avatar
Adrien Béraud committed
991
        JAMI_DBG("[ice:%p] rx msg v%u", this, version);
Guillaume Roguez's avatar
Guillaume Roguez committed
992 993 994 995 996 997 998 999 1000 1001
        if (version == 1) {
            result = msgpack::unpack(data, size, offset);
            std::tie(rem_ufrag, rem_pwd) = result.get().as<std::pair<std::string, std::string>>();
            result = msgpack::unpack(data, size, offset);
            auto comp_cnt = result.get().as<uint8_t>();
            while (comp_cnt-- > 0) {
                result = msgpack::unpack(data, size, offset);
                IceCandidate cand;
                for (const auto& line : result.get().as<std::vector<std::string>>()) {
                    if (getCandidateFromSDP(line, cand))
1002
                        rem_candidates.emplace_back(cand);
Guillaume Roguez's avatar
Guillaume Roguez committed
1003 1004 1005
                }
            }
        } else {
Adrien Béraud's avatar
Adrien Béraud committed
1006
            JAMI_ERR("[ice:%p] invalid msg version", this);
Guillaume Roguez's avatar
Guillaume Roguez committed
1007
            return false;
1008
        }
Guillaume Roguez's avatar
Guillaume Roguez committed
1009
    } catch (const msgpack::unpack_error& e) {
Adrien Béraud's avatar
Adrien Béraud committed
1010
        JAMI_ERR("[ice:%p] remote msg unpack error: %s", this, e.what());
1011 1012
        return false;
    }
Guillaume Roguez's avatar
Guillaume Roguez committed
1013

1014
    if (rem_ufrag.empty() or rem_pwd.empty() or rem_candidates.empty()) {
Adrien Béraud's avatar
Adrien Béraud committed
1015
        JAMI_ERR("[ice:%p] invalid remote attributes", this);
Guillaume Roguez's avatar
Guillaume Roguez committed
1016 1017 1018
        return false;
    }

1019
    if (pimpl_->onlyIPv4Private_)
Adrien Béraud's avatar
Adrien Béraud committed
1020
        JAMI_WARN("[ice:%p] no public IPv4 found, your connection may fail!", this);
1021

1022 1023 1024 1025 1026 1027
    return start({rem_ufrag, rem_pwd}, rem_candidates);
}

bool
IceTransport::stop()
{
Guillaume Roguez's avatar
Guillaume Roguez committed
1028
    if (isStarted()) {
1029
        auto status = pj_ice_strans_stop_ice(pimpl_->icest_.get());
Guillaume Roguez's avatar
Guillaume Roguez committed
1030
        if (status != PJ_SUCCESS) {
1031
            pimpl_->last_errmsg_ = sip_utils::sip_strerror(status);
Adrien Béraud's avatar
Adrien Béraud committed
1032
            JAMI_ERR("ICE stop failed: %s", pimpl_->last_errmsg_.c_str());
Guillaume Roguez's avatar
Guillaume Roguez committed
1033 1034
            return false;
        }
1035 1036 1037 1038 1039 1040 1041
    }
    return true;
}

IpAddr
IceTransport::getLocalAddress(unsigned comp_id) const
{
1042
    return pimpl_->getLocalAddress(comp_id);
1043 1044 1045 1046 1047
}

IpAddr
IceTransport::getRemoteAddress(unsigned comp_id) const
{
1048
    return pimpl_->getRemoteAddress(comp_id);
1049 1050 1051 1052 1053
}

const IceTransport::Attribute
IceTransport::getLocalAttributes() const
{
1054
    return {pimpl_->local_ufrag_, pimpl_->local_pwd_};
1055 1056 1057 1058 1059 1060
}

std::vector<std::string>
IceTransport::getLocalCandidates(unsigned comp_id) const
{
    std::vector<std::string> res;
1061
    pj_ice_sess_cand cand[PJ_ARRAY_SIZE(pimpl_->cand_)];
1062 1063
    unsigned cand_cnt = PJ_ARRAY_SIZE(cand);

1064
    if (pj_ice_strans_enum_cands(pimpl_->icest_.get(), comp_id+1, &cand_cnt, cand) != PJ_SUCCESS) {
Adrien Béraud's avatar
Adrien Béraud committed
1065
        JAMI_ERR("[ice:%p] pj_ice_strans_enum_cands() failed", this);
1066 1067 1068 1069 1070 1071 1072
        return res;
    }

    for (unsigned i=0; i<cand_cnt; ++i) {
        std::ostringstream val;
        char ipaddr[PJ_INET6_ADDRSTRLEN];

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
        /**   Section 4.5, RFC 6544 (https://tools.ietf.org/html/rfc6544)
         *    candidate-attribute   = "candidate" ":" foundation SP component-id
         * SP "TCP" SP priority SP connection-address SP port SP cand-type [SP
         * rel-addr] [SP rel-port] SP tcp-type-ext
         *                             *(SP extension-att-name SP
         *                                  extension-att-value)
         *
         *     tcp-type-ext          = "tcptype" SP tcp-type
         *     tcp-type              = "active" / "passive" / "so"
         */
1083
        val << std::string(cand[i].foundation.ptr, cand[i].foundation.slen);
1084 1085 1086
        val << " " << (unsigned)cand[i].comp_id;
        val << (cand[i].transport == PJ_CAND_UDP ? " UDP " : " TCP ");
        val << cand[i].prio;
1087 1088 1089 1090
        val << " " << pj_sockaddr_print(&cand[i].addr, ipaddr, sizeof(ipaddr), 0);
        val << " " << (unsigned)pj_sockaddr_get_port(&cand[i].addr);
        val << " typ " << pj_ice_get_cand_type_name(cand[i].type);

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
        if (cand[i].transport != PJ_CAND_UDP) {
            val << " tcptype";
            switch (cand[i].transport) {
            case PJ_CAND_TCP_ACTIVE:
                val << " active";
                break;
            case PJ_CAND_TCP_PASSIVE:
                val << " passive";
                break;
            case PJ_CAND_TCP_SO:
            default:
                val << " so";
                break;
            }
        }

1107 1108 1109 1110 1111 1112
        res.push_back(val.str());
    }

    return res;
}

1113 1114 1115
bool
IceTransport::registerPublicIP(unsigned compId, const IpAddr& publicIP)
{
1116
    if (not isInitialized()) {
Adrien Béraud's avatar
Adrien Béraud committed
1117
        JAMI_ERR("[ice:%p] registerPublicIP() called on non initialized transport", this);
Guillaume Roguez's avatar
Guillaume Roguez committed
1118
        return false;
1119
    }