blob: bfca535f324d2488064d0221f6a3a62cde50677d [file] [log] [blame]
Adrien BĂ©rauda1d294f2023-07-17 22:42:13 -04001/*
2 * Copyright (C) 2004-2023 Savoir-faire Linux Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17#include "turn_transport.h"
18#include "../sip_utils.h"
19
20#include <atomic>
21#include <thread>
22
23#include <pjnath.h>
24#include <pjlib-util.h>
25#include <pjlib.h>
26
27#define TRY(ret) \
28 do { \
29 if ((ret) != PJ_SUCCESS) \
30 throw std::runtime_error(#ret " failed"); \
31 } while (0)
32
33namespace dhtnet {
34
35class TurnLock
36{
37 pj_grp_lock_t* lk_;
38
39public:
40 TurnLock(pj_turn_sock* sock)
41 : lk_(pj_turn_sock_get_grp_lock(sock))
42 {
43 lock();
44 }
45
46 ~TurnLock() { unlock(); }
47
48 void lock() { pj_grp_lock_add_ref(lk_); }
49
50 void unlock() { pj_grp_lock_dec_ref(lk_); }
51};
52
53class TurnTransport::Impl
54{
55public:
56 Impl(std::function<void(bool)>&& cb, const std::shared_ptr<Logger>& logger)
57 : cb_(std::move(cb)), logger_(logger) {}
58 ~Impl();
59
60 /**
61 * Detect new TURN state
62 */
63 void onTurnState(pj_turn_state_t old_state, pj_turn_state_t new_state);
64
65 /**
66 * Pool events from pjsip
67 */
68 void ioJob();
69
70 void start()
71 {
72 ioWorker = std::thread([this] { ioJob(); });
73 }
74
75 void shutdown() {
76 std::lock_guard<std::mutex> lock(shutdownMtx_);
77 if (relay) {
78 pj_turn_sock_destroy(relay);
79 relay = nullptr;
80 }
81 turnLock.reset();
82 if (ioWorker.joinable())
83 ioWorker.join();
84 }
85
86 TurnTransportParams settings;
87
88 pj_caching_pool poolCache {};
89 pj_pool_t* pool {nullptr};
90 pj_stun_config stunConfig {};
91 pj_turn_sock* relay {nullptr};
92 std::unique_ptr<TurnLock> turnLock;
93 pj_str_t relayAddr {};
94 IpAddr peerRelayAddr; // address where peers should connect to
95 IpAddr mappedAddr;
96 std::function<void(bool)> cb_;
97
98 std::thread ioWorker;
99 std::atomic_bool stopped_ {false};
100 std::atomic_bool cbCalled_ {false};
101 std::mutex shutdownMtx_;
102 std::shared_ptr<Logger> logger_;
103};
104
105TurnTransport::Impl::~Impl()
106{
107 shutdown();
108 pj_caching_pool_destroy(&poolCache);
109}
110
111void
112TurnTransport::Impl::onTurnState(pj_turn_state_t old_state, pj_turn_state_t new_state)
113{
114 if (new_state == PJ_TURN_STATE_DESTROYING) {
115 stopped_ = true;
116 return;
117 }
118
119 if (new_state == PJ_TURN_STATE_READY) {
120 pj_turn_session_info info;
121 pj_turn_sock_get_info(relay, &info);
122 peerRelayAddr = IpAddr {info.relay_addr};
123 mappedAddr = IpAddr {info.mapped_addr};
124 if(logger_) logger_->debug("TURN server ready, peer relay address: {:s}",
125 peerRelayAddr.toString(true, true).c_str());
126 cbCalled_ = true;
127 cb_(true);
128 } else if (old_state <= PJ_TURN_STATE_READY and new_state > PJ_TURN_STATE_READY and not cbCalled_) {
129 if(logger_) logger_->debug("TURN server disconnected ({:s})", pj_turn_state_name(new_state));
130 cb_(false);
131 }
132}
133
134void
135TurnTransport::Impl::ioJob()
136{
137 const pj_time_val delay = {0, 10};
138 while (!stopped_) {
139 pj_ioqueue_poll(stunConfig.ioqueue, &delay);
140 pj_timer_heap_poll(stunConfig.timer_heap, nullptr);
141 }
142}
143
144TurnTransport::TurnTransport(const TurnTransportParams& params, std::function<void(bool)>&& cb, const std::shared_ptr<Logger>& logger)
145 : pimpl_ {new Impl(std::move(cb), logger)}
146{
147 auto server = params.server;
148 if (!server.getPort())
149 server.setPort(PJ_STUN_PORT);
150 if (server.isUnspecified())
151 throw std::invalid_argument("invalid turn server address");
152 pimpl_->settings = params;
153 // PJSIP memory pool
154 pj_caching_pool_init(&pimpl_->poolCache, &pj_pool_factory_default_policy, 0);
155 pimpl_->pool = pj_pool_create(&pimpl_->poolCache.factory, "TurnTransport", 512, 512, nullptr);
156 if (not pimpl_->pool)
157 throw std::runtime_error("pj_pool_create() failed");
158 // STUN config
159 pj_stun_config_init(&pimpl_->stunConfig, &pimpl_->poolCache.factory, 0, nullptr, nullptr);
160 // create global timer heap
161 TRY(pj_timer_heap_create(pimpl_->pool, 1000, &pimpl_->stunConfig.timer_heap));
162 // create global ioqueue
163 TRY(pj_ioqueue_create(pimpl_->pool, 16, &pimpl_->stunConfig.ioqueue));
164 // TURN callbacks
165 pj_turn_sock_cb relay_cb;
166 pj_bzero(&relay_cb, sizeof(relay_cb));
167 relay_cb.on_state =
168 [](pj_turn_sock* relay, pj_turn_state_t old_state, pj_turn_state_t new_state) {
169 auto pimpl = static_cast<Impl*>(pj_turn_sock_get_user_data(relay));
170 pimpl->onTurnState(old_state, new_state);
171 };
172 // TURN socket config
173 pj_turn_sock_cfg turn_sock_cfg;
174 pj_turn_sock_cfg_default(&turn_sock_cfg);
175 turn_sock_cfg.max_pkt_size = 4096;
176 // TURN socket creation
177 TRY(pj_turn_sock_create(&pimpl_->stunConfig,
178 server.getFamily(),
179 PJ_TURN_TP_TCP,
180 &relay_cb,
181 &turn_sock_cfg,
182 &*this->pimpl_,
183 &pimpl_->relay));
184 // TURN allocation setup
185 pj_turn_alloc_param turn_alloc_param;
186 pj_turn_alloc_param_default(&turn_alloc_param);
187 turn_alloc_param.peer_conn_type = PJ_TURN_TP_TCP;
188 pj_stun_auth_cred cred;
189 pj_bzero(&cred, sizeof(cred));
190 cred.type = PJ_STUN_AUTH_CRED_STATIC;
191 pj_cstr(&cred.data.static_cred.realm, pimpl_->settings.realm.c_str());
192 pj_cstr(&cred.data.static_cred.username, pimpl_->settings.username.c_str());
193 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
194 pj_cstr(&cred.data.static_cred.data, pimpl_->settings.password.c_str());
195 pimpl_->relayAddr = pj_strdup3(pimpl_->pool, server.toString().c_str());
196 // TURN connection/allocation
197 if (logger) logger->debug("Connecting to TURN {:s}", server.toString(true, true));
198 TRY(pj_turn_sock_alloc(pimpl_->relay,
199 &pimpl_->relayAddr,
200 server.getPort(),
201 nullptr,
202 &cred,
203 &turn_alloc_param));
204 pimpl_->turnLock = std::make_unique<TurnLock>(pimpl_->relay);
205 pimpl_->start();
206}
207
208TurnTransport::~TurnTransport() {}
209
210void
211TurnTransport::shutdown()
212{
213 pimpl_->shutdown();
214}
215
216} // namespace jami