turn_transport.cpp 15.3 KB
Newer Older
1
/*
2
 *  Copyright (C) 2017-2018 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 43 44

namespace ring {

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 190 191 192 193 194 195
    if (relay) {
        try {
            pj_turn_sock_destroy(relay);
        } catch (...) {
            RING_ERR() << "exception during pj_turn_sock_destroy() call (ignored)";
        }
    }
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 211 212 213 214 215
}

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};
        RING_DBG("TURN server ready, peer relay address: %s", peerRelayAddr.toString(true, true).c_str());
        state = RelayState::READY;
    } else if (old_state <= PJ_TURN_STATE_READY and new_state > PJ_TURN_STATE_READY) {
        RING_WARN("TURN server disconnected (%s)", pj_turn_state_name(new_state));
        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 242
}

void
TurnTransportPimpl::onPeerConnection(pj_uint32_t conn_id,
243 244
                                     const pj_sockaddr_t* addr, unsigned addr_len,
                                     pj_status_t status)
245
{
246 247 248 249 250
    IpAddr peer_addr (*static_cast<const pj_sockaddr*>(addr), addr_len);
    if (status == PJ_SUCCESS) {
        RING_DBG() << "Received connection attempt from " << peer_addr.toString(true, true)
                   << ", id=" << std::hex << conn_id;
        pj_turn_connect_peer(relay, conn_id, addr, addr_len);
251 252 253 254 255

        {
            MutexGuard lk {apiMutex_};
            peerChannels_.emplace(peer_addr, PeerChannel {});
        }
256
    }
257

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

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);
    }
}

274
//==============================================================================
275 276 277 278

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

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 311
    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) {
312 313
        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);
314 315 316
    };
    relay_cb.on_state = [](pj_turn_sock* relay, pj_turn_state_t old_state,
                           pj_turn_state_t new_state) {
317 318
        auto pimpl = static_cast<TurnTransportPimpl*>(pj_turn_sock_get_user_data(relay));
        pimpl->onTurnState(old_state, new_state);
319 320
    };
    relay_cb.on_peer_connection = [](pj_turn_sock* relay, pj_uint32_t conn_id,
321 322
                                     const pj_sockaddr_t* peer_addr, unsigned addr_len,
                                     pj_status_t status) {
323 324
        auto pimpl = static_cast<TurnTransportPimpl*>(pj_turn_sock_get_user_data(relay));
        pimpl->onPeerConnection(conn_id, peer_addr, addr_len, status);
325 326 327 328 329 330 331 332 333 334
    };

    // 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,
335
              &relay_cb, &turn_sock_cfg, &*this->pimpl_, &pimpl_->relay);
336 337 338

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

    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;
349 350
    pj_cstr(&cred.data.static_cred.realm, pimpl_->settings.realm.c_str());
    pj_cstr(&cred.data.static_cred.username, pimpl_->settings.username.c_str());
351
    cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
352
    pj_cstr(&cred.data.static_cred.data, pimpl_->settings.password.c_str());
353 354 355 356 357 358 359 360 361 362

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

    // TURN connection/allocation
    RING_DBG() << "Connecting to TURN " << server.toString(true, true);
    PjsipCall(pj_turn_sock_alloc,
              pimpl_->relay, &pimpl_->relayAddr, server.getPort(),
              nullptr, &cred, &turn_alloc_param);
}

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

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

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

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

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

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

429
    return status != PJ_EBUSY;
430 431
}

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

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

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

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

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

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

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

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

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

std::size_t
ConnectedTurnTransport::write(const ValueType* buf, std::size_t size, std::error_code& ec)
{
    try {
494 495 496 497 498 499 500
        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;
        }
501 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
    } 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;
529 530 531
}

} // namespace ring