blob: 49fdf5918f0ef5534cce11b6fa563f9a9c776131 [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>
Adrien Béraud1b7081a2023-07-18 10:31:45 -040022#include <mutex>
23#include <functional>
24#include <stdexcept>
Adrien Bérauda1d294f2023-07-17 22:42:13 -040025
Adrien Béraud9e0f84f2023-07-27 16:02:21 -040026extern "C" {
Adrien Bérauda1d294f2023-07-17 22:42:13 -040027#include <pjnath.h>
28#include <pjlib-util.h>
29#include <pjlib.h>
Adrien Béraud9e0f84f2023-07-27 16:02:21 -040030}
Adrien Bérauda1d294f2023-07-17 22:42:13 -040031
32#define TRY(ret) \
33 do { \
34 if ((ret) != PJ_SUCCESS) \
35 throw std::runtime_error(#ret " failed"); \
36 } while (0)
37
38namespace dhtnet {
39
40class TurnLock
41{
42 pj_grp_lock_t* lk_;
43
44public:
45 TurnLock(pj_turn_sock* sock)
46 : lk_(pj_turn_sock_get_grp_lock(sock))
47 {
48 lock();
49 }
50
51 ~TurnLock() { unlock(); }
52
53 void lock() { pj_grp_lock_add_ref(lk_); }
54
55 void unlock() { pj_grp_lock_dec_ref(lk_); }
56};
57
58class TurnTransport::Impl
59{
60public:
61 Impl(std::function<void(bool)>&& cb, const std::shared_ptr<Logger>& logger)
62 : cb_(std::move(cb)), logger_(logger) {}
63 ~Impl();
64
65 /**
66 * Detect new TURN state
67 */
68 void onTurnState(pj_turn_state_t old_state, pj_turn_state_t new_state);
69
70 /**
71 * Pool events from pjsip
72 */
73 void ioJob();
74
75 void start()
76 {
77 ioWorker = std::thread([this] { ioJob(); });
78 }
79
François-Simon Fauteux-Chapleau25693412024-04-10 11:49:18 -040080 void shutdown()
81 {
Adrien Béraud024c46f2024-03-02 23:53:18 -050082 std::lock_guard lock(shutdownMtx_);
François-Simon Fauteux-Chapleau25693412024-04-10 11:49:18 -040083 // The ioWorker thread must be stopped before caling pj_turn_sock_destroy,
84 // otherwise there's a potential race condition where pj_turn_sock_destroy
85 // sets the state of the TURN session to PJ_TURN_STATE_DESTROYING, and then
86 // ioWorker tries to execute a callback which expects the session to be in
87 // an earlier state. (This causes a crash if PJSIP was compiled with asserts
88 // enabled, see https://git.jami.net/savoirfairelinux/jami-daemon/-/issues/974)
89 if (ioWorker.joinable()) {
90 stopped_ = true;
91 ioWorker.join();
92 }
Adrien Bérauda1d294f2023-07-17 22:42:13 -040093 if (relay) {
94 pj_turn_sock_destroy(relay);
95 relay = nullptr;
96 }
97 turnLock.reset();
François-Simon Fauteux-Chapleau25693412024-04-10 11:49:18 -040098 }
Adrien Bérauda1d294f2023-07-17 22:42:13 -040099
100 TurnTransportParams settings;
101
102 pj_caching_pool poolCache {};
103 pj_pool_t* pool {nullptr};
104 pj_stun_config stunConfig {};
105 pj_turn_sock* relay {nullptr};
106 std::unique_ptr<TurnLock> turnLock;
107 pj_str_t relayAddr {};
108 IpAddr peerRelayAddr; // address where peers should connect to
109 IpAddr mappedAddr;
110 std::function<void(bool)> cb_;
111
112 std::thread ioWorker;
113 std::atomic_bool stopped_ {false};
114 std::atomic_bool cbCalled_ {false};
115 std::mutex shutdownMtx_;
116 std::shared_ptr<Logger> logger_;
117};
118
119TurnTransport::Impl::~Impl()
120{
121 shutdown();
122 pj_caching_pool_destroy(&poolCache);
123}
124
125void
126TurnTransport::Impl::onTurnState(pj_turn_state_t old_state, pj_turn_state_t new_state)
127{
128 if (new_state == PJ_TURN_STATE_DESTROYING) {
129 stopped_ = true;
130 return;
131 }
132
133 if (new_state == PJ_TURN_STATE_READY) {
134 pj_turn_session_info info;
135 pj_turn_sock_get_info(relay, &info);
136 peerRelayAddr = IpAddr {info.relay_addr};
137 mappedAddr = IpAddr {info.mapped_addr};
138 if(logger_) logger_->debug("TURN server ready, peer relay address: {:s}",
139 peerRelayAddr.toString(true, true).c_str());
140 cbCalled_ = true;
141 cb_(true);
142 } else if (old_state <= PJ_TURN_STATE_READY and new_state > PJ_TURN_STATE_READY and not cbCalled_) {
143 if(logger_) logger_->debug("TURN server disconnected ({:s})", pj_turn_state_name(new_state));
144 cb_(false);
145 }
146}
147
148void
149TurnTransport::Impl::ioJob()
150{
151 const pj_time_val delay = {0, 10};
152 while (!stopped_) {
153 pj_ioqueue_poll(stunConfig.ioqueue, &delay);
154 pj_timer_heap_poll(stunConfig.timer_heap, nullptr);
155 }
156}
157
158TurnTransport::TurnTransport(const TurnTransportParams& params, std::function<void(bool)>&& cb, const std::shared_ptr<Logger>& logger)
François-Simon Fauteux-Chapleau2ef5b662024-03-27 12:30:26 -0400159 : pjInitLock_()
160 , pimpl_ {new Impl(std::move(cb), logger)}
Adrien Bérauda1d294f2023-07-17 22:42:13 -0400161{
162 auto server = params.server;
163 if (!server.getPort())
164 server.setPort(PJ_STUN_PORT);
165 if (server.isUnspecified())
166 throw std::invalid_argument("invalid turn server address");
167 pimpl_->settings = params;
168 // PJSIP memory pool
169 pj_caching_pool_init(&pimpl_->poolCache, &pj_pool_factory_default_policy, 0);
170 pimpl_->pool = pj_pool_create(&pimpl_->poolCache.factory, "TurnTransport", 512, 512, nullptr);
171 if (not pimpl_->pool)
172 throw std::runtime_error("pj_pool_create() failed");
173 // STUN config
174 pj_stun_config_init(&pimpl_->stunConfig, &pimpl_->poolCache.factory, 0, nullptr, nullptr);
175 // create global timer heap
176 TRY(pj_timer_heap_create(pimpl_->pool, 1000, &pimpl_->stunConfig.timer_heap));
177 // create global ioqueue
178 TRY(pj_ioqueue_create(pimpl_->pool, 16, &pimpl_->stunConfig.ioqueue));
179 // TURN callbacks
180 pj_turn_sock_cb relay_cb;
181 pj_bzero(&relay_cb, sizeof(relay_cb));
182 relay_cb.on_state =
183 [](pj_turn_sock* relay, pj_turn_state_t old_state, pj_turn_state_t new_state) {
184 auto pimpl = static_cast<Impl*>(pj_turn_sock_get_user_data(relay));
185 pimpl->onTurnState(old_state, new_state);
186 };
187 // TURN socket config
188 pj_turn_sock_cfg turn_sock_cfg;
189 pj_turn_sock_cfg_default(&turn_sock_cfg);
190 turn_sock_cfg.max_pkt_size = 4096;
191 // TURN socket creation
192 TRY(pj_turn_sock_create(&pimpl_->stunConfig,
193 server.getFamily(),
194 PJ_TURN_TP_TCP,
195 &relay_cb,
196 &turn_sock_cfg,
197 &*this->pimpl_,
198 &pimpl_->relay));
199 // TURN allocation setup
200 pj_turn_alloc_param turn_alloc_param;
201 pj_turn_alloc_param_default(&turn_alloc_param);
202 turn_alloc_param.peer_conn_type = PJ_TURN_TP_TCP;
203 pj_stun_auth_cred cred;
204 pj_bzero(&cred, sizeof(cred));
205 cred.type = PJ_STUN_AUTH_CRED_STATIC;
206 pj_cstr(&cred.data.static_cred.realm, pimpl_->settings.realm.c_str());
207 pj_cstr(&cred.data.static_cred.username, pimpl_->settings.username.c_str());
208 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
209 pj_cstr(&cred.data.static_cred.data, pimpl_->settings.password.c_str());
210 pimpl_->relayAddr = pj_strdup3(pimpl_->pool, server.toString().c_str());
211 // TURN connection/allocation
212 if (logger) logger->debug("Connecting to TURN {:s}", server.toString(true, true));
213 TRY(pj_turn_sock_alloc(pimpl_->relay,
214 &pimpl_->relayAddr,
215 server.getPort(),
216 nullptr,
217 &cred,
218 &turn_alloc_param));
219 pimpl_->turnLock = std::make_unique<TurnLock>(pimpl_->relay);
220 pimpl_->start();
221}
222
223TurnTransport::~TurnTransport() {}
224
225void
226TurnTransport::shutdown()
227{
228 pimpl_->shutdown();
229}
230
Sébastien Blin464bdff2023-07-19 08:02:53 -0400231} // namespace dhtnet