-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathpeer_connection.cpp
422 lines (373 loc) · 12.6 KB
/
peer_connection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
420
421
422
/*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Guillaume Roguez <guillaume.roguez@savoirfairelinux.com>
* Author: Sébastien Blin <sebastien.blin@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 "peer_connection.h"
#include "data_transfer.h"
#include "manager.h"
#include "jamidht/jamiaccount.h"
#include "string_utils.h"
#include "security/tls_session.h"
#include <algorithm>
#include <chrono>
#include <future>
#include <vector>
#include <atomic>
#include <stdexcept>
#include <istream>
#include <ostream>
#include <unistd.h>
#include <cstdio>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/select.h>
#endif
#ifndef _MSC_VER
#include <sys/time.h>
#endif
namespace jami {
int
init_crt(gnutls_session_t session, dht::crypto::Certificate& crt)
{
// Support only x509 format
if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509) {
return GNUTLS_E_CERTIFICATE_ERROR;
}
// Store verification status
unsigned int status = 0;
auto ret = gnutls_certificate_verify_peers2(session, &status);
if (ret < 0 or (status & GNUTLS_CERT_SIGNATURE_FAILURE) != 0) {
return GNUTLS_E_CERTIFICATE_ERROR;
}
unsigned int cert_list_size = 0;
auto cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
if (cert_list == nullptr) {
return GNUTLS_E_CERTIFICATE_ERROR;
}
// Check if received peer certificate is awaited
std::vector<std::pair<uint8_t*, uint8_t*>> crt_data;
crt_data.reserve(cert_list_size);
for (unsigned i = 0; i < cert_list_size; i++)
crt_data.emplace_back(cert_list[i].data, cert_list[i].data + cert_list[i].size);
crt = dht::crypto::Certificate {crt_data};
return GNUTLS_E_SUCCESS;
}
using lock = std::lock_guard<std::mutex>;
static constexpr std::size_t IO_BUFFER_SIZE {8192}; ///< Size of char buffer used by IO operations
//==============================================================================
IceSocketEndpoint::IceSocketEndpoint(std::shared_ptr<IceTransport> ice, bool isSender)
: ice_(std::move(ice))
, iceIsSender(isSender)
{}
IceSocketEndpoint::~IceSocketEndpoint()
{
shutdown();
}
void
IceSocketEndpoint::shutdown()
{
if (ice_) {
// Sometimes the other peer never send any packet
// So, we cancel pending read to avoid to have
// any blocking operation.
ice_->cancelOperations();
ice_->stop();
}
}
int
IceSocketEndpoint::waitForData(std::chrono::milliseconds timeout, std::error_code& ec) const
{
if (ice_) {
if (!ice_->isRunning())
return -1;
return ice_->waitForData(compId_, timeout, ec);
}
return -1;
}
std::size_t
IceSocketEndpoint::read(ValueType* buf, std::size_t len, std::error_code& ec)
{
if (ice_) {
if (!ice_->isRunning())
return 0;
try {
auto res = ice_->recvfrom(compId_, reinterpret_cast<char*>(buf), len, ec);
if (res < 0)
shutdown();
return res;
} catch (const std::exception& e) {
JAMI_ERR("IceSocketEndpoint::read exception: %s", e.what());
}
return 0;
}
return -1;
}
std::size_t
IceSocketEndpoint::write(const ValueType* buf, std::size_t len, std::error_code& ec)
{
if (ice_) {
if (!ice_->isRunning())
return 0;
auto res = 0;
res = ice_->send(compId_, reinterpret_cast<const unsigned char*>(buf), len);
if (res < 0) {
ec.assign(errno, std::generic_category());
shutdown();
} else {
ec.clear();
}
return res;
}
return -1;
}
//==============================================================================
class TlsSocketEndpoint::Impl
{
public:
static constexpr auto TLS_TIMEOUT = std::chrono::seconds(40);
Impl(std::unique_ptr<IceSocketEndpoint>&& ep,
const dht::crypto::Certificate& peer_cert,
const Identity& local_identity,
const std::shared_future<tls::DhParams>& dh_params)
: peerCertificate {peer_cert}
, ep_ {ep.get()}
{
tls::TlsSession::TlsSessionCallbacks tls_cbs
= {/*.onStateChange = */ [this](tls::TlsSessionState state) { onTlsStateChange(state); },
/*.onRxData = */ [this](std::vector<uint8_t>&& buf) { onTlsRxData(std::move(buf)); },
/*.onCertificatesUpdate = */
[this](const gnutls_datum_t* l, const gnutls_datum_t* r, unsigned int n) {
onTlsCertificatesUpdate(l, r, n);
},
/*.verifyCertificate = */
[this](gnutls_session_t session) {
return verifyCertificate(session);
}};
tls::TlsParams tls_param = {
/*.ca_list = */ "",
/*.peer_ca = */ nullptr,
/*.cert = */ local_identity.second,
/*.cert_key = */ local_identity.first,
/*.dh_params = */ dh_params,
/*.timeout = */ TLS_TIMEOUT,
/*.cert_check = */ nullptr,
};
tls = std::make_unique<tls::TlsSession>(std::move(ep), tls_param, tls_cbs);
ep_->underlyingICE()->setOnShutdown([this]() { tls->shutdown(); });
}
Impl(std::unique_ptr<IceSocketEndpoint>&& ep,
std::function<bool(const dht::crypto::Certificate&)>&& cert_check,
const Identity& local_identity,
const std::shared_future<tls::DhParams>& dh_params)
: peerCertificateCheckFunc {std::move(cert_check)}
, peerCertificate {null_cert}
, ep_ {ep.get()}
{
tls::TlsSession::TlsSessionCallbacks tls_cbs
= {/*.onStateChange = */ [this](tls::TlsSessionState state) { onTlsStateChange(state); },
/*.onRxData = */ [this](std::vector<uint8_t>&& buf) { onTlsRxData(std::move(buf)); },
/*.onCertificatesUpdate = */
[this](const gnutls_datum_t* l, const gnutls_datum_t* r, unsigned int n) {
onTlsCertificatesUpdate(l, r, n);
},
/*.verifyCertificate = */
[this](gnutls_session_t session) {
return verifyCertificate(session);
}};
tls::TlsParams tls_param = {
/*.ca_list = */ "",
/*.peer_ca = */ nullptr,
/*.cert = */ local_identity.second,
/*.cert_key = */ local_identity.first,
/*.dh_params = */ dh_params,
/*.timeout = */ std::chrono::duration_cast<decltype(tls::TlsParams::timeout)>(TLS_TIMEOUT),
/*.cert_check = */ nullptr,
};
tls = std::make_unique<tls::TlsSession>(std::move(ep), tls_param, tls_cbs);
ep_->underlyingICE()->setOnShutdown([this]() {
if (tls)
tls->shutdown();
});
}
~Impl()
{
ep_->underlyingICE()->setOnShutdown({});
{
std::lock_guard<std::mutex> lk(cbMtx_);
onStateChangeCb_ = {};
onReadyCb_ = {};
}
tls.reset();
}
// TLS callbacks
int verifyCertificate(gnutls_session_t);
void onTlsStateChange(tls::TlsSessionState);
void onTlsRxData(std::vector<uint8_t>&&);
void onTlsCertificatesUpdate(const gnutls_datum_t*, const gnutls_datum_t*, unsigned int);
std::mutex cbMtx_ {};
OnStateChangeCb onStateChangeCb_;
dht::crypto::Certificate null_cert;
std::function<bool(const dht::crypto::Certificate&)> peerCertificateCheckFunc;
const dht::crypto::Certificate& peerCertificate;
std::atomic_bool isReady_ {false};
OnReadyCb onReadyCb_;
std::unique_ptr<tls::TlsSession> tls;
const IceSocketEndpoint* ep_;
};
int
TlsSocketEndpoint::Impl::verifyCertificate(gnutls_session_t session)
{
dht::crypto::Certificate crt;
auto verified = init_crt(session, crt);
if (verified != GNUTLS_E_SUCCESS)
return verified;
if (peerCertificateCheckFunc) {
if (!peerCertificateCheckFunc(crt)) {
JAMI_ERR() << "[TLS-SOCKET] Unexpected peer certificate";
return GNUTLS_E_CERTIFICATE_ERROR;
}
null_cert = std::move(crt);
} else {
if (crt.getPacked() != peerCertificate.getPacked()) {
JAMI_ERR() << "[TLS-SOCKET] Unexpected peer certificate";
return GNUTLS_E_CERTIFICATE_ERROR;
}
}
return GNUTLS_E_SUCCESS;
}
void
TlsSocketEndpoint::Impl::onTlsStateChange(tls::TlsSessionState state)
{
std::lock_guard<std::mutex> lk(cbMtx_);
if ((state == tls::TlsSessionState::SHUTDOWN || state == tls::TlsSessionState::ESTABLISHED)
&& !isReady_) {
isReady_ = true;
if (onReadyCb_)
onReadyCb_(state == tls::TlsSessionState::ESTABLISHED);
}
if (onStateChangeCb_ && !onStateChangeCb_(state))
onStateChangeCb_ = {};
}
void
TlsSocketEndpoint::Impl::onTlsRxData(UNUSED std::vector<uint8_t>&& buf)
{}
void
TlsSocketEndpoint::Impl::onTlsCertificatesUpdate(UNUSED const gnutls_datum_t* local_raw,
UNUSED const gnutls_datum_t* remote_raw,
UNUSED unsigned int remote_count)
{}
TlsSocketEndpoint::TlsSocketEndpoint(std::unique_ptr<IceSocketEndpoint>&& tr,
const Identity& local_identity,
const std::shared_future<tls::DhParams>& dh_params,
const dht::crypto::Certificate& peer_cert)
: pimpl_ {std::make_unique<Impl>(std::move(tr), peer_cert, local_identity, dh_params)}
{}
TlsSocketEndpoint::TlsSocketEndpoint(
std::unique_ptr<IceSocketEndpoint>&& tr,
const Identity& local_identity,
const std::shared_future<tls::DhParams>& dh_params,
std::function<bool(const dht::crypto::Certificate&)>&& cert_check)
: pimpl_ {
std::make_unique<Impl>(std::move(tr), std::move(cert_check), local_identity, dh_params)}
{}
TlsSocketEndpoint::~TlsSocketEndpoint() {}
bool
TlsSocketEndpoint::isInitiator() const
{
if (!pimpl_->tls) {
return false;
}
return pimpl_->tls->isInitiator();
}
int
TlsSocketEndpoint::maxPayload() const
{
if (!pimpl_->tls) {
return -1;
}
return pimpl_->tls->maxPayload();
}
std::size_t
TlsSocketEndpoint::read(ValueType* buf, std::size_t len, std::error_code& ec)
{
if (!pimpl_->tls) {
ec = std::make_error_code(std::errc::broken_pipe);
return -1;
}
return pimpl_->tls->read(buf, len, ec);
}
std::size_t
TlsSocketEndpoint::write(const ValueType* buf, std::size_t len, std::error_code& ec)
{
if (!pimpl_->tls) {
ec = std::make_error_code(std::errc::broken_pipe);
return -1;
}
return pimpl_->tls->write(buf, len, ec);
}
void
TlsSocketEndpoint::waitForReady(const std::chrono::milliseconds& timeout)
{
if (!pimpl_->tls) {
return;
}
pimpl_->tls->waitForReady(timeout);
}
int
TlsSocketEndpoint::waitForData(std::chrono::milliseconds timeout, std::error_code& ec) const
{
if (!pimpl_->tls) {
ec = std::make_error_code(std::errc::broken_pipe);
return -1;
}
return pimpl_->tls->waitForData(timeout, ec);
}
void
TlsSocketEndpoint::setOnStateChange(std::function<bool(tls::TlsSessionState state)>&& cb)
{
std::lock_guard<std::mutex> lk(pimpl_->cbMtx_);
pimpl_->onStateChangeCb_ = std::move(cb);
}
void
TlsSocketEndpoint::setOnReady(std::function<void(bool ok)>&& cb)
{
std::lock_guard<std::mutex> lk(pimpl_->cbMtx_);
pimpl_->onReadyCb_ = std::move(cb);
}
void
TlsSocketEndpoint::shutdown()
{
if (pimpl_->ep_) {
const auto* iceSocket = reinterpret_cast<const IceSocketEndpoint*>(pimpl_->ep_);
if (iceSocket && iceSocket->underlyingICE())
iceSocket->underlyingICE()->cancelOperations();
}
pimpl_->tls->shutdown();
}
std::shared_ptr<IceTransport>
TlsSocketEndpoint::underlyingICE() const
{
if (pimpl_->ep_)
if (const auto* iceSocket = reinterpret_cast<const IceSocketEndpoint*>(pimpl_->ep_))
return iceSocket->underlyingICE();
return {};
}
} // namespace jami