blob: 3cf78d26b9c05666b2489b97f358a986f4a0210d [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
80 void shutdown() {
81 std::lock_guard<std::mutex> lock(shutdownMtx_);
82 if (relay) {
83 pj_turn_sock_destroy(relay);
84 relay = nullptr;
85 }
86 turnLock.reset();
87 if (ioWorker.joinable())
88 ioWorker.join();
89 }
90
91 TurnTransportParams settings;
92
93 pj_caching_pool poolCache {};
94 pj_pool_t* pool {nullptr};
95 pj_stun_config stunConfig {};
96 pj_turn_sock* relay {nullptr};
97 std::unique_ptr<TurnLock> turnLock;
98 pj_str_t relayAddr {};
99 IpAddr peerRelayAddr; // address where peers should connect to
100 IpAddr mappedAddr;
101 std::function<void(bool)> cb_;
102
103 std::thread ioWorker;
104 std::atomic_bool stopped_ {false};
105 std::atomic_bool cbCalled_ {false};
106 std::mutex shutdownMtx_;
107 std::shared_ptr<Logger> logger_;
108};
109
110TurnTransport::Impl::~Impl()
111{
112 shutdown();
113 pj_caching_pool_destroy(&poolCache);
114}
115
116void
117TurnTransport::Impl::onTurnState(pj_turn_state_t old_state, pj_turn_state_t new_state)
118{
119 if (new_state == PJ_TURN_STATE_DESTROYING) {
120 stopped_ = true;
121 return;
122 }
123
124 if (new_state == PJ_TURN_STATE_READY) {
125 pj_turn_session_info info;
126 pj_turn_sock_get_info(relay, &info);
127 peerRelayAddr = IpAddr {info.relay_addr};
128 mappedAddr = IpAddr {info.mapped_addr};
129 if(logger_) logger_->debug("TURN server ready, peer relay address: {:s}",
130 peerRelayAddr.toString(true, true).c_str());
131 cbCalled_ = true;
132 cb_(true);
133 } else if (old_state <= PJ_TURN_STATE_READY and new_state > PJ_TURN_STATE_READY and not cbCalled_) {
134 if(logger_) logger_->debug("TURN server disconnected ({:s})", pj_turn_state_name(new_state));
135 cb_(false);
136 }
137}
138
139void
140TurnTransport::Impl::ioJob()
141{
142 const pj_time_val delay = {0, 10};
143 while (!stopped_) {
144 pj_ioqueue_poll(stunConfig.ioqueue, &delay);
145 pj_timer_heap_poll(stunConfig.timer_heap, nullptr);
146 }
147}
148
149TurnTransport::TurnTransport(const TurnTransportParams& params, std::function<void(bool)>&& cb, const std::shared_ptr<Logger>& logger)
150 : pimpl_ {new Impl(std::move(cb), logger)}
151{
152 auto server = params.server;
153 if (!server.getPort())
154 server.setPort(PJ_STUN_PORT);
155 if (server.isUnspecified())
156 throw std::invalid_argument("invalid turn server address");
157 pimpl_->settings = params;
158 // PJSIP memory pool
159 pj_caching_pool_init(&pimpl_->poolCache, &pj_pool_factory_default_policy, 0);
160 pimpl_->pool = pj_pool_create(&pimpl_->poolCache.factory, "TurnTransport", 512, 512, nullptr);
161 if (not pimpl_->pool)
162 throw std::runtime_error("pj_pool_create() failed");
163 // STUN config
164 pj_stun_config_init(&pimpl_->stunConfig, &pimpl_->poolCache.factory, 0, nullptr, nullptr);
165 // create global timer heap
166 TRY(pj_timer_heap_create(pimpl_->pool, 1000, &pimpl_->stunConfig.timer_heap));
167 // create global ioqueue
168 TRY(pj_ioqueue_create(pimpl_->pool, 16, &pimpl_->stunConfig.ioqueue));
169 // TURN callbacks
170 pj_turn_sock_cb relay_cb;
171 pj_bzero(&relay_cb, sizeof(relay_cb));
172 relay_cb.on_state =
173 [](pj_turn_sock* relay, pj_turn_state_t old_state, pj_turn_state_t new_state) {
174 auto pimpl = static_cast<Impl*>(pj_turn_sock_get_user_data(relay));
175 pimpl->onTurnState(old_state, new_state);
176 };
177 // TURN socket config
178 pj_turn_sock_cfg turn_sock_cfg;
179 pj_turn_sock_cfg_default(&turn_sock_cfg);
180 turn_sock_cfg.max_pkt_size = 4096;
181 // TURN socket creation
182 TRY(pj_turn_sock_create(&pimpl_->stunConfig,
183 server.getFamily(),
184 PJ_TURN_TP_TCP,
185 &relay_cb,
186 &turn_sock_cfg,
187 &*this->pimpl_,
188 &pimpl_->relay));
189 // TURN allocation setup
190 pj_turn_alloc_param turn_alloc_param;
191 pj_turn_alloc_param_default(&turn_alloc_param);
192 turn_alloc_param.peer_conn_type = PJ_TURN_TP_TCP;
193 pj_stun_auth_cred cred;
194 pj_bzero(&cred, sizeof(cred));
195 cred.type = PJ_STUN_AUTH_CRED_STATIC;
196 pj_cstr(&cred.data.static_cred.realm, pimpl_->settings.realm.c_str());
197 pj_cstr(&cred.data.static_cred.username, pimpl_->settings.username.c_str());
198 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
199 pj_cstr(&cred.data.static_cred.data, pimpl_->settings.password.c_str());
200 pimpl_->relayAddr = pj_strdup3(pimpl_->pool, server.toString().c_str());
201 // TURN connection/allocation
202 if (logger) logger->debug("Connecting to TURN {:s}", server.toString(true, true));
203 TRY(pj_turn_sock_alloc(pimpl_->relay,
204 &pimpl_->relayAddr,
205 server.getPort(),
206 nullptr,
207 &cred,
208 &turn_alloc_param));
209 pimpl_->turnLock = std::make_unique<TurnLock>(pimpl_->relay);
210 pimpl_->start();
211}
212
213TurnTransport::~TurnTransport() {}
214
215void
216TurnTransport::shutdown()
217{
218 pimpl_->shutdown();
219}
220
Sébastien Blin464bdff2023-07-19 08:02:53 -0400221} // namespace dhtnet