turn_transport.cpp 15.5 KB
Newer Older
1
/*
2
 *  Copyright (C) 2017-2019 Savoir-faire Linux Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 *  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.
 *
 *  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 "turn_transport.h"

#include "logger.h"
#include "ip_utils.h"
#include "sip/sip_utils.h"
26
#include "map_utils.h"
27 28 29 30 31 32 33 34 35 36 37

#include <pjnath.h>
#include <pjlib-util.h>
#include <pjlib.h>

#include <future>
#include <atomic>
#include <thread>
#include <vector>
#include <iterator>
#include <mutex>
38 39 40 41
#include <sstream>
#include <limits>
#include <map>
#include <condition_variable>
42

Adrien Béraud's avatar
Adrien Béraud committed
43
namespace jami {
44

45 46 47
using MutexGuard = std::lock_guard<std::mutex>;
using MutexLock = std::unique_lock<std::mutex>;

48 49 50
inline
namespace {

51 52
enum class RelayState
{
53 54 55 56 57
    NONE,
    READY,
    DOWN,
};

58 59 60 61 62
class PeerChannel
{
public:
    PeerChannel() {}
    ~PeerChannel() {
63
        stop();
64 65 66 67 68 69
    }

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

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    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;
        cv_.notify_one();
    }

86 87
    template <typename Duration>
    bool wait(Duration timeout) {
88 89 90 91
        std::lock(apiMutex_, mutex_);
        MutexGuard lk_api {apiMutex_, std::adopt_lock};
        MutexLock lk {mutex_, std::adopt_lock};
        return cv_.wait_for(lk, timeout, [this]{ return stop_ or !stream_.eof(); });
92 93
    }

94
    std::size_t read(char* output, std::size_t size) {
95 96 97
        std::lock(apiMutex_, mutex_);
        MutexGuard lk_api {apiMutex_, std::adopt_lock};
        MutexLock lk {mutex_, std::adopt_lock};
98
        cv_.wait(lk, [&, this]{
99 100
                if (stop_)
                    return true;
101
                stream_.read(&output[0], size);
102
                return stream_.gcount() > 0;
103
            });
104
        return stop_ ? 0 : stream_.gcount();
105 106
    }

107 108 109 110 111 112 113 114 115 116 117 118 119
    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_};
    }

120 121 122
private:
    PeerChannel(const PeerChannel&o) = delete;
    PeerChannel& operator =(const PeerChannel& o) = delete;
123
    std::mutex apiMutex_ {};
124 125 126 127 128 129 130 131
    std::mutex mutex_ {};
    std::condition_variable cv_ {};
    std::stringstream stream_ {};
    bool stop_ {false};

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

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
}

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

template <class Callable, class... Args>
inline void
PjsipCall(Callable& func, Args... args)
{
    auto status = func(args...);
    if (status != PJ_SUCCESS)
        throw sip_utils::PjsipFailure(status);
}

template <class Callable, class... Args>
inline auto
PjsipCallReturn(const Callable& func, Args... args) -> decltype(func(args...))
{
    auto res = func(args...);
    if (!res)
        throw sip_utils::PjsipFailure();
    return res;
}

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

157 158
class TurnTransportPimpl
{
159 160 161 162 163
public:
    TurnTransportPimpl() = default;
    ~TurnTransportPimpl();

    void onTurnState(pj_turn_state_t old_state, pj_turn_state_t new_state);
164
    void onRxData(const uint8_t* pkt, unsigned pkt_len, const pj_sockaddr_t* peer_addr, unsigned addr_len);
165
    void onPeerConnection(pj_uint32_t conn_id, const pj_sockaddr_t* peer_addr, unsigned addr_len, pj_status_t status);
166 167
    void ioJob();

168 169 170 171
    std::mutex apiMutex_;

    std::map<IpAddr, PeerChannel> peerChannels_;

172
    GenericSocket<uint8_t>::RecvCb onRxDataCb;
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    TurnTransportParams settings;
    pj_caching_pool poolCache {};
    pj_pool_t* pool {nullptr};
    pj_stun_config stunConfig {};
    pj_turn_sock* relay {nullptr};
    pj_str_t relayAddr {};
    IpAddr peerRelayAddr; // address where peers should connect to
    IpAddr mappedAddr;

    std::atomic<RelayState> state {RelayState::NONE};
    std::atomic_bool ioJobQuit {false};
    std::thread ioWorker;
};

TurnTransportPimpl::~TurnTransportPimpl()
{
189
    if (relay && state.load() != RelayState::DOWN) {
190 191 192
        try {
            pj_turn_sock_destroy(relay);
        } catch (...) {
Adrien Béraud's avatar
Adrien Béraud committed
193
            JAMI_ERR() << "exception during pj_turn_sock_destroy() call (ignored)";
194 195
        }
    }
196 197 198 199
    ioJobQuit = true;
    if (ioWorker.joinable())
        ioWorker.join();
    pj_caching_pool_destroy(&poolCache);
200

201 202 203 204 205 206 207 208 209 210
}

void
TurnTransportPimpl::onTurnState(pj_turn_state_t old_state, pj_turn_state_t new_state)
{
    if (new_state == PJ_TURN_STATE_READY) {
        pj_turn_session_info info;
        pj_turn_sock_get_info(relay, &info);
        peerRelayAddr = IpAddr {info.relay_addr};
        mappedAddr = IpAddr {info.mapped_addr};
Adrien Béraud's avatar
Adrien Béraud committed
211
        JAMI_DBG("TURN server ready, peer relay address: %s", peerRelayAddr.toString(true, true).c_str());
212 213
        state = RelayState::READY;
    } else if (old_state <= PJ_TURN_STATE_READY and new_state > PJ_TURN_STATE_READY) {
Adrien Béraud's avatar
Adrien Béraud committed
214
        JAMI_WARN("TURN server disconnected (%s)", pj_turn_state_name(new_state));
215
        state = RelayState::DOWN;
216 217
        MutexGuard lk {apiMutex_};
        peerChannels_.clear();
218 219 220 221
    }
}

void
222
TurnTransportPimpl::onRxData(const uint8_t* pkt, unsigned pkt_len,
223 224
                             const pj_sockaddr_t* addr, unsigned addr_len)
{
225 226 227 228 229 230 231 232 233
    IpAddr peer_addr (*static_cast<const pj_sockaddr*>(addr), addr_len);

    decltype(peerChannels_)::iterator channel_it;
    {
        MutexGuard lk {apiMutex_};
        channel_it = peerChannels_.find(peer_addr);
        if (channel_it == std::end(peerChannels_))
            return;
    }
234

235 236 237 238
    if (onRxDataCb)
        onRxDataCb(pkt, pkt_len);
    else
        (channel_it->second) << std::string(reinterpret_cast<const char*>(pkt), pkt_len);
239 240
}

241
void
242
TurnTransportPimpl::onPeerConnection(pj_uint32_t conn_id,
243 244
                                     const pj_sockaddr_t* addr, unsigned addr_len,
                                     pj_status_t status)
245
{
246
    IpAddr peer_addr (*static_cast<const pj_sockaddr*>(addr), addr_len);
247 248 249 250 251 252 253 254
    if (status == PJ_SUCCESS) {
        JAMI_DBG() << "Received connection attempt from "
                    << peer_addr.toString(true, true) << ", id=" << std::hex
                    << conn_id;
        {
            MutexGuard lk {apiMutex_};
            peerChannels_.emplace(peer_addr, PeerChannel {});
        }
255
    }
256

257
    if (settings.onPeerConnection)
258
        settings.onPeerConnection(conn_id, peer_addr, status == PJ_SUCCESS);
259 260 261 262 263 264 265 266 267 268 269 270 271 272
}

void
TurnTransportPimpl::ioJob()
{
    sip_utils::register_thread();

    while (!ioJobQuit.load()) {
        const pj_time_val delay = {0, 10};
        pj_ioqueue_poll(stunConfig.ioqueue, &delay);
        pj_timer_heap_poll(stunConfig.timer_heap, nullptr);
    }
}

273
//==============================================================================
274 275 276 277

TurnTransport::TurnTransport(const TurnTransportParams& params)
    : pimpl_ {new TurnTransportPimpl}
{
278 279
    sip_utils::register_thread();

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    auto server = params.server;
    if (!server.getPort())
        server.setPort(PJ_STUN_PORT);

    if (server.isUnspecified())
        throw std::invalid_argument("invalid turn server address");

    pimpl_->settings = params;

    // PJSIP memory pool
    pj_caching_pool_init(&pimpl_->poolCache, &pj_pool_factory_default_policy, 0);
    pimpl_->pool = PjsipCallReturn(pj_pool_create, &pimpl_->poolCache.factory,
                                   "RgTurnTr", 512, 512, nullptr);

    // STUN config
    pj_stun_config_init(&pimpl_->stunConfig, &pimpl_->poolCache.factory, 0, nullptr, nullptr);

    // create global timer heap
    PjsipCall(pj_timer_heap_create, pimpl_->pool, 1000, &pimpl_->stunConfig.timer_heap);

    // create global ioqueue
    PjsipCall(pj_ioqueue_create, pimpl_->pool, 16, &pimpl_->stunConfig.ioqueue);

    // run a thread to handles timer/ioqueue events
    pimpl_->ioWorker = std::thread([this]{ pimpl_->ioJob(); });

    // TURN callbacks
    pj_turn_sock_cb relay_cb;
    pj_bzero(&relay_cb, sizeof(relay_cb));
    relay_cb.on_rx_data = [](pj_turn_sock* relay, void* pkt, unsigned pkt_len,
                             const pj_sockaddr_t* peer_addr, unsigned addr_len) {
311 312
        auto pimpl = static_cast<TurnTransportPimpl*>(pj_turn_sock_get_user_data(relay));
        pimpl->onRxData(reinterpret_cast<uint8_t*>(pkt), pkt_len, peer_addr, addr_len);
313 314 315
    };
    relay_cb.on_state = [](pj_turn_sock* relay, pj_turn_state_t old_state,
                           pj_turn_state_t new_state) {
316 317
        auto pimpl = static_cast<TurnTransportPimpl*>(pj_turn_sock_get_user_data(relay));
        pimpl->onTurnState(old_state, new_state);
318
    };
319 320
    relay_cb.on_connection_status = [](pj_turn_sock *relay,
                                        pj_status_t status,
321 322 323 324
                                        pj_uint32_t conn_id,
                                        const pj_sockaddr_t *peer_addr,
                                        unsigned addr_len) {
      auto pimpl = static_cast<TurnTransportPimpl *>(pj_turn_sock_get_user_data(relay));
325
      pimpl->onPeerConnection(conn_id, peer_addr, addr_len, status);
326 327 328 329 330 331 332 333 334 335
    };

    // TURN socket config
    pj_turn_sock_cfg turn_sock_cfg;
    pj_turn_sock_cfg_default(&turn_sock_cfg);
    turn_sock_cfg.max_pkt_size = params.maxPacketSize;

    // TURN socket creation
    PjsipCall(pj_turn_sock_create,
              &pimpl_->stunConfig, server.getFamily(), PJ_TURN_TP_TCP,
336
              &relay_cb, &turn_sock_cfg, &*this->pimpl_, &pimpl_->relay);
337 338 339

    // TURN allocation setup
    pj_turn_alloc_param turn_alloc_param;
340
    pj_turn_alloc_param_default(&turn_alloc_param);
341 342
    if (params.authorized_family != 0)
        turn_alloc_param.af = params.authorized_family; // RFC 6156!!!
343 344 345 346 347 348 349

    if (params.isPeerConnection)
        turn_alloc_param.peer_conn_type = PJ_TURN_TP_TCP; // RFC 6062!!!

    pj_stun_auth_cred cred;
    pj_bzero(&cred, sizeof(cred));
    cred.type = PJ_STUN_AUTH_CRED_STATIC;
350 351
    pj_strset(&cred.data.static_cred.realm, (char*)pimpl_->settings.realm.c_str(), pimpl_->settings.realm.size());
    pj_strset(&cred.data.static_cred.username, (char*)pimpl_->settings.username.c_str(), pimpl_->settings.username.size());
352
    cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
353
    pj_strset(&cred.data.static_cred.data, (char*)pimpl_->settings.password.c_str(), pimpl_->settings.password.size());
354 355 356 357

    pimpl_->relayAddr = pj_strdup3(pimpl_->pool, server.toString().c_str());

    // TURN connection/allocation
Adrien Béraud's avatar
Adrien Béraud committed
358
    JAMI_DBG() << "Connecting to TURN " << server.toString(true, true);
359 360 361 362 363
    PjsipCall(pj_turn_sock_alloc,
              pimpl_->relay, &pimpl_->relayAddr, server.getPort(),
              nullptr, &cred, &turn_alloc_param);
}

364 365 366 367 368 369 370 371 372 373
TurnTransport::~TurnTransport() = default;

void
TurnTransport::shutdown(const IpAddr& addr)
{
    MutexLock lk {pimpl_->apiMutex_};
    auto& channel = pimpl_->peerChannels_.at(addr);
    lk.unlock();
    channel.stop();
}
374

375 376 377 378 379 380
bool
TurnTransport::isInitiator() const
{
    return !pimpl_->settings.server;
}

381 382 383 384 385 386
void
TurnTransport::permitPeer(const IpAddr& addr)
{
    if (addr.isUnspecified())
        throw std::invalid_argument("invalid peer address");

387 388 389
    if (addr.getFamily() != pimpl_->peerRelayAddr.getFamily())
        throw std::invalid_argument("mismatching peer address family");

390
    sip_utils::register_thread();
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    PjsipCall(pj_turn_sock_set_perm, pimpl_->relay, 1, addr.pjPtr(), 1);
}

bool
TurnTransport::isReady() const
{
    return pimpl_->state.load() == RelayState::READY;
}

void
TurnTransport::waitServerReady()
{
    while (pimpl_->state.load() != RelayState::READY) {
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
    }
}

const IpAddr&
TurnTransport::peerRelayAddr() const
{
    return pimpl_->peerRelayAddr;
}

const IpAddr&
TurnTransport::mappedAddr() const
{
    return pimpl_->mappedAddr;
}

bool
421
TurnTransport::sendto(const IpAddr& peer, const char* const buffer, std::size_t length)
422
{
423
    sip_utils::register_thread();
424
    auto status = pj_turn_sock_sendto(pimpl_->relay,
425
                                      reinterpret_cast<const pj_uint8_t*>(buffer), length,
426
                                      peer.pjPtr(), peer.getLength());
427
    if (status != PJ_SUCCESS && status != PJ_EPENDING && status != PJ_EBUSY)
428
        throw sip_utils::PjsipFailure(PJ_STATUS_TO_OS(status));
429

430
    return status != PJ_EBUSY;
431 432
}

433 434 435 436 437 438
bool
TurnTransport::sendto(const IpAddr& peer, const std::vector<char>& buffer)
{
    return sendto(peer, &buffer[0], buffer.size());
}

439 440
std::size_t
TurnTransport::recvfrom(const IpAddr& peer, char* buffer, std::size_t size)
441
{
442 443 444 445
    MutexLock lk {pimpl_->apiMutex_};
    auto& channel = pimpl_->peerChannels_.at(peer);
    lk.unlock();
    return channel.read(buffer, size);
446 447 448 449 450
}

void
TurnTransport::recvfrom(const IpAddr& peer, std::vector<char>& result)
{
451 452 453
    auto res = recvfrom(peer, result.data(), result.size());
    result.resize(res);
}
454

455 456 457
std::vector<IpAddr>
TurnTransport::peerAddresses() const
{
458
    MutexLock lk {pimpl_->apiMutex_};
459
    return map_utils::extractKeys(pimpl_->peerChannels_);
460 461
}

462
int
463
TurnTransport::waitForData(const IpAddr& peer, std::chrono::milliseconds timeout, std::error_code& ec) const
464
{
465
    (void)ec; ///< \todo handle errors
466 467 468
    MutexLock lk {pimpl_->apiMutex_};
    auto& channel = pimpl_->peerChannels_.at(peer);
    lk.unlock();
469
    return channel.wait(timeout);
470 471
}

472 473 474 475 476 477 478
//==============================================================================

ConnectedTurnTransport::ConnectedTurnTransport(TurnTransport& turn, const IpAddr& peer)
    : turn_ {turn}
    , peer_ {peer}
{}

479 480 481 482 483 484
void
ConnectedTurnTransport::shutdown()
{
    turn_.shutdown(peer_);
}

485
int
486
ConnectedTurnTransport::waitForData(std::chrono::milliseconds timeout, std::error_code& ec) const
487
{
488
    return turn_.waitForData(peer_, timeout, ec);
489 490 491 492 493 494
}

std::size_t
ConnectedTurnTransport::write(const ValueType* buf, std::size_t size, std::error_code& ec)
{
    try {
495 496 497 498 499 500 501
        auto success = turn_.sendto(peer_, reinterpret_cast<const char*>(buf), size);
        if (!success) {
            // if !success, pj_turn_sock_sendto returned EBUSY
            // So, we should retry to send this later
            ec.assign(EAGAIN, std::generic_category());
            return 0;
        }
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    } catch (const sip_utils::PjsipFailure& ex) {
        ec = ex.code();
        return 0;
    }

    ec.clear();
    return size;
}

std::size_t
ConnectedTurnTransport::read(ValueType* buf, std::size_t size, std::error_code& ec)
{
    if (size > 0) {
        try {
            size = turn_.recvfrom(peer_, reinterpret_cast<char*>(buf), size);
        } catch (const sip_utils::PjsipFailure& ex) {
            ec = ex.code();
            return 0;
        }

        if (size == 0) {
            ec = std::make_error_code(std::errc::broken_pipe);
            return 0;
        }
    }

    ec.clear();
    return size;
530 531
}

Adrien Béraud's avatar
Adrien Béraud committed
532
} // namespace jami