Repository navigation
Expand file tree
/
Copy pathsocket_utils.cpp
More file actions
391 lines (374 loc) · 12.3 KB
/
Copy pathsocket_utils.cpp
File metadata and controls
391 lines (374 loc) · 12.3 KB
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
#include "socket_utils.h"
#include "api_config.h"
#include "common.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <locale.h>
#include <loguru.hpp>
#ifdef __APPLE__
#include <mach/mach_time.h>
#include <sys/socket.h>
#include <xlocale.h>
#elif defined(__linux__)
#include <cerrno>
#include <ctime>
#include <linux/errqueue.h>
#include <linux/net_tstamp.h>
#include <netinet/in.h>
#include <sys/socket.h>
#elif defined(_WIN32)
#include <locale.h>
#endif
template <typename Socket, typename Protocol>
uint16_t bind_port_in_range_(Socket &sock, Protocol protocol) {
const auto *cfg = lsl::api_config::get_instance();
asio::error_code ec;
for (uint16_t port = cfg->base_port(), e = port + cfg->port_range(); port < e; port++) {
sock.bind(typename Protocol::endpoint(protocol, port), ec);
if (ec == asio::error::address_in_use) continue;
if (!ec) return port;
}
if (cfg->allow_random_ports()) {
// bind to port 0, i.e. let the operating system select a free port
sock.bind(typename Protocol::endpoint(protocol, 0), ec);
// query and return the port the socket was bound to
if (!ec) return sock.local_endpoint().port();
}
throw std::runtime_error(
"All local ports were found occupied. You may have more open outlets on this machine "
"than your PortRange setting allows (see "
"https://labstreaminglayer.readthedocs.io/info/network-connectivity.html"
") or you have a problem with your network configuration.");
}
uint16_t lsl::bind_port_in_range(udp_socket &sock, asio::ip::udp protocol) {
return bind_port_in_range_(sock, protocol);
}
uint16_t lsl::bind_and_listen_to_port_in_range(
tcp_acceptor &acc, asio::ip::tcp protocol, int backlog) {
uint16_t port = bind_port_in_range_(acc, protocol);
acc.listen(backlog);
return port;
}
namespace {
inline double ns_to_lsl_clock(int64_t ns) {
constexpr int64_t kNsPerSec = 1000000000LL;
const auto q = std::lldiv(ns, kNsPerSec);
return static_cast<double>(q.quot) + static_cast<double>(q.rem) / static_cast<double>(kNsPerSec);
}
#ifdef __linux__
/// Convert a CLOCK_REALTIME kernel timestamp to lsl_clock() seconds using the narrowest of 3
/// bracketed (CLOCK_REALTIME, steady_clock, CLOCK_REALTIME) reads so preemption cannot corrupt it.
bool realtime_to_lsl_clock(const timespec &stamp, double &out) {
int64_t best_span = std::numeric_limits<int64_t>::max();
int64_t best_rt_ns = 0;
int64_t best_steady_ns = 0;
for (int i = 0; i < 3; ++i) {
timespec rt0{}, rt1{};
if (clock_gettime(CLOCK_REALTIME, &rt0) != 0) return false;
const int64_t st_ns = lsl::lsl_local_clock_ns();
if (clock_gettime(CLOCK_REALTIME, &rt1) != 0) return false;
const int64_t ns0 = static_cast<int64_t>(rt0.tv_sec) * 1000000000LL + rt0.tv_nsec;
const int64_t ns1 = static_cast<int64_t>(rt1.tv_sec) * 1000000000LL + rt1.tv_nsec;
const int64_t span = ns1 - ns0;
if (span >= 0 && span < best_span) {
best_span = span;
best_rt_ns = ns0 + span / 2;
best_steady_ns = st_ns;
}
}
if (best_span == std::numeric_limits<int64_t>::max()) return false;
const int64_t stamp_ns = static_cast<int64_t>(stamp.tv_sec) * 1000000000LL + stamp.tv_nsec;
const int64_t age_ns = best_rt_ns - stamp_ns;
// Reject CLOCK_REALTIME jumps between the kernel stamp and now.
if (age_ns < -1000000LL || age_ns > 1000000000LL) return false;
out = ns_to_lsl_clock(best_steady_ns - age_ns);
return true;
}
#elif defined(__APPLE__)
/// Convert a mach_absolute_time() kernel stamp to lsl_clock() seconds via a bracketed age read.
/// Converting by age automatically cancels the sleep-time offset between mach_absolute_time()
/// and libc++'s steady_clock (CLOCK_MONOTONIC_RAW / mach_continuous_time()).
bool mach_to_lsl_clock(uint64_t stamp, double &out) {
static const mach_timebase_info_data_t tb = [] {
mach_timebase_info_data_t t{};
mach_timebase_info(&t);
return t;
}();
uint64_t best_span = std::numeric_limits<uint64_t>::max();
uint64_t best_mach = 0;
int64_t best_steady_ns = 0;
for (int i = 0; i < 3; ++i) {
const uint64_t m0 = mach_absolute_time();
const int64_t st_ns = lsl::lsl_local_clock_ns();
const uint64_t m1 = mach_absolute_time();
if (m1 >= m0 && (m1 - m0) < best_span) {
best_span = m1 - m0;
best_mach = m0 + best_span / 2;
best_steady_ns = st_ns;
}
}
if (best_span == std::numeric_limits<uint64_t>::max()) return false;
const int64_t age_ticks = static_cast<int64_t>(best_mach) - static_cast<int64_t>(stamp);
const int64_t age_ns = static_cast<int64_t>(
(static_cast<__int128>(age_ticks) * tb.numer) / tb.denom);
if (age_ns < -1000000LL || age_ns > 1000000000LL) return false;
out = ns_to_lsl_clock(best_steady_ns - age_ns);
return true;
}
#endif
inline bool is_ascii_space(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; }
#if defined(__linux__) || defined(__APPLE__)
locale_t get_c_locale() {
static locale_t loc = newlocale(LC_NUMERIC_MASK, "C", nullptr);
return loc;
}
#elif defined(_WIN32)
_locale_t get_c_locale() {
static _locale_t loc = _create_locale(LC_NUMERIC, "C");
return loc;
}
#endif
} // namespace
lsl::socket_timestamp_caps lsl::enable_socket_timestamps(udp_socket &sock) {
socket_timestamp_caps caps{};
#ifdef __linux__
int ts_flags = SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE |
SOF_TIMESTAMPING_OPT_TSONLY | SOF_TIMESTAMPING_OPT_ID;
if (setsockopt(sock.native_handle(), SOL_SOCKET, SO_TIMESTAMPING, &ts_flags, sizeof(ts_flags)) ==
0) {
caps.rx_kernel = true;
caps.tx_kernel = true;
return caps;
}
int one = 1;
if (setsockopt(sock.native_handle(), SOL_SOCKET, SO_TIMESTAMPNS, &one, sizeof(one)) == 0) {
caps.rx_kernel = true;
}
#elif defined(__APPLE__)
int one = 1;
if (setsockopt(sock.native_handle(), SOL_SOCKET, SO_TIMESTAMP_MONOTONIC, &one, sizeof(one)) ==
0) {
caps.rx_kernel = true;
}
#else
(void)sock;
#endif
return caps;
}
std::size_t lsl::receive_with_rx_timestamp(udp_socket &sock, char *buf, std::size_t len,
asio::ip::udp::endpoint &sender, rx_timestamps &rx, asio::error_code &ec) {
rx = rx_timestamps{};
#if defined(__linux__) || defined(__APPLE__)
if (!sock.is_open()) {
ec = asio::error::bad_descriptor;
return 0;
}
alignas(cmsghdr) char ctrl[256];
iovec iov{buf, len};
msghdr msg{};
msg.msg_name = sender.data();
msg.msg_namelen = static_cast<socklen_t>(sender.capacity());
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = ctrl;
msg.msg_controllen = sizeof(ctrl);
const ssize_t n = ::recvmsg(sock.native_handle(), &msg, MSG_DONTWAIT);
rx.user = lsl_clock();
if (n < 0) {
ec = asio::error_code(errno, asio::error::get_system_category());
return 0;
}
ec = asio::error_code();
sender.resize(msg.msg_namelen);
for (cmsghdr *c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) {
if (c->cmsg_level != SOL_SOCKET) continue;
#ifdef __linux__
if (c->cmsg_type == SCM_TIMESTAMPING) {
scm_timestamping ts{};
std::memcpy(&ts, CMSG_DATA(c), sizeof(ts));
if ((ts.ts[0].tv_sec != 0 || ts.ts[0].tv_nsec != 0) &&
realtime_to_lsl_clock(ts.ts[0], rx.kernel)) {
rx.has_kernel = true;
break;
}
} else if (c->cmsg_type == SCM_TIMESTAMPNS) {
timespec ts{};
std::memcpy(&ts, CMSG_DATA(c), sizeof(ts));
if (realtime_to_lsl_clock(ts, rx.kernel)) {
rx.has_kernel = true;
break;
}
}
#elif defined(__APPLE__)
if (c->cmsg_type == SCM_TIMESTAMP_MONOTONIC) {
uint64_t stamp = 0;
std::memcpy(&stamp, CMSG_DATA(c), sizeof(stamp));
if (mach_to_lsl_clock(stamp, rx.kernel)) {
rx.has_kernel = true;
break;
}
}
#endif
}
return static_cast<std::size_t>(n);
#else
(void)sock;
(void)buf;
(void)len;
(void)sender;
ec = asio::error::operation_not_supported;
return 0;
#endif
}
std::size_t lsl::send_with_tx_timestamp(udp_socket &sock, const char *data, std::size_t len,
const asio::ip::udp::endpoint &dest, bool want_tx_kernel, uint32_t &tx_ts_counter,
tx_timestamps &tx, asio::error_code &ec) {
tx = tx_timestamps{};
#ifdef __linux__
if (want_tx_kernel && sock.is_open()) {
iovec iov{const_cast<char *>(data), len};
alignas(cmsghdr) char ctrl[CMSG_SPACE(sizeof(uint32_t))] = {};
msghdr msg{};
msg.msg_name = const_cast<void *>(static_cast<const void *>(dest.data()));
msg.msg_namelen = static_cast<socklen_t>(dest.size());
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = ctrl;
msg.msg_controllen = sizeof(ctrl);
cmsghdr *cm = CMSG_FIRSTHDR(&msg);
cm->cmsg_level = SOL_SOCKET;
cm->cmsg_type = SO_TIMESTAMPING;
cm->cmsg_len = CMSG_LEN(sizeof(uint32_t));
const uint32_t tx_flags = SOF_TIMESTAMPING_TX_SOFTWARE;
std::memcpy(CMSG_DATA(cm), &tx_flags, sizeof(tx_flags));
tx.before = lsl_clock();
const ssize_t sent = ::sendmsg(sock.native_handle(), &msg, 0);
tx.after = lsl_clock();
if (sent < 0) {
ec = asio::error_code(errno, asio::error::get_system_category());
return 0;
}
ec = asio::error_code();
tx.ts_id = tx_ts_counter++;
tx.has_ts_id = true;
return static_cast<std::size_t>(sent);
}
#else
(void)want_tx_kernel;
(void)tx_ts_counter;
#endif
tx.before = lsl_clock();
const std::size_t sent = sock.send_to(asio::buffer(data, len), dest, 0, ec);
tx.after = lsl_clock();
return sent;
}
void lsl::drain_tx_timestamps(udp_socket &sock, std::vector<std::pair<uint32_t, double>> &out) {
#ifdef __linux__
if (!sock.is_open()) return;
for (;;) {
char err_data[64];
alignas(cmsghdr) char err_ctrl[256];
iovec err_iov{err_data, sizeof(err_data)};
msghdr err_msg{};
err_msg.msg_iov = &err_iov;
err_msg.msg_iovlen = 1;
err_msg.msg_control = err_ctrl;
err_msg.msg_controllen = sizeof(err_ctrl);
if (::recvmsg(sock.native_handle(), &err_msg, MSG_ERRQUEUE | MSG_DONTWAIT) < 0) break;
timespec tx_sw{};
bool has_id = false;
uint32_t err_id = 0;
for (cmsghdr *c = CMSG_FIRSTHDR(&err_msg); c; c = CMSG_NXTHDR(&err_msg, c)) {
if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SCM_TIMESTAMPING) {
scm_timestamping st{};
std::memcpy(&st, CMSG_DATA(c), sizeof(st));
tx_sw = st.ts[0];
} else if ((c->cmsg_level == SOL_IP && c->cmsg_type == IP_RECVERR) ||
(c->cmsg_level == SOL_IPV6 && c->cmsg_type == IPV6_RECVERR)) {
sock_extended_err serr{};
std::memcpy(&serr, CMSG_DATA(c), sizeof(serr));
if (serr.ee_origin == SO_EE_ORIGIN_TIMESTAMPING) {
has_id = true;
err_id = serr.ee_data;
}
}
}
double tx_sec = 0.0;
if (has_id && (tx_sw.tv_sec != 0 || tx_sw.tv_nsec != 0) &&
realtime_to_lsl_clock(tx_sw, tx_sec)) {
out.emplace_back(err_id, tx_sec);
}
}
#else
(void)sock;
(void)out;
#endif
}
int lsl::format_c_double(char *buf, std::size_t cap, double val) {
if (cap == 0) return 0;
const int n = std::snprintf(buf, cap, "%.16g", val);
if (n <= 0) return 0;
const std::size_t written = std::min(static_cast<std::size_t>(n), cap - 1);
for (std::size_t i = 0; i < written; ++i)
if (buf[i] == ',') buf[i] = '.';
return static_cast<int>(written);
}
bool lsl::parse_c_int(const char *&p, const char *end, int &out) {
while (p < end && is_ascii_space(*p)) ++p;
if (p >= end) return false;
bool neg = false;
const char *start = p;
if (*p == '-') {
neg = true;
++p;
} else if (*p == '+') {
++p;
}
if (p >= end || *p < '0' || *p > '9') {
p = start;
return false;
}
int64_t val = 0;
while (p < end && *p >= '0' && *p <= '9') {
val = val * 10 + (*p - '0');
if (val > static_cast<int64_t>(std::numeric_limits<int>::max()) + 1LL) {
p = start;
return false;
}
++p;
}
val = neg ? -val : val;
if (val < std::numeric_limits<int>::min() || val > std::numeric_limits<int>::max()) {
p = start;
return false;
}
out = static_cast<int>(val);
return true;
}
bool lsl::parse_c_double(const char *&p, const char *end, double &out) {
while (p < end && is_ascii_space(*p)) ++p;
if (p >= end) return false;
// Copy token to a small NUL-terminated stack buffer so strtod_l never reads past `end`.
char tmp[64];
const char *q = p;
std::size_t len = 0;
while (q < end && !is_ascii_space(*q) && *q != ',' && len + 1 < sizeof(tmp)) tmp[len++] = *q++;
if (len == 0) return false;
tmp[len] = '\0';
char *parsed_end = nullptr;
#if defined(__linux__) || defined(__APPLE__)
const double val = strtod_l(tmp, &parsed_end, get_c_locale());
#elif defined(_WIN32)
const double val = _strtod_l(tmp, &parsed_end, get_c_locale());
#else
const double val = std::strtod(tmp, &parsed_end);
#endif
if (parsed_end == tmp || parsed_end != tmp + len || !std::isfinite(val)) return false;
p = q;
out = val;
return true;
}