Debian Codegraph @

src/rist-common.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /* librist. Copyright © 2019-2020 SipRadius LLC. All right reserved.
2 * Author: Daniele Lacamera <[email protected]>
3 * Author: Antonio Cardace <[email protected]>
4 * Author: Kuldeep Singh Dhaka <[email protected]>
5 * Author: Sergio Ammirata, Ph.D. <[email protected]>
6 *
7 * SPDX-License-Identifier: BSD-2-Clause
8 */
9
10 #include "proto/gre.h"
11 #include "rist-private.h"
12 #include <limits.h>
13 #include "log-private.h"
14 #include "crypto/psk.h"
15 #include <lz4.h>
16 #include "crypto/random.h"
17 #include "udp-private.h"
18 #include "transport-private.h"
19 #include "udpsocket.h"
20 #include "endian-shim.h"
21 #include "time-shim.h"
22 #include "proto/rist_time.h"
23 #include "network.h"
24 #include "librist/tun.h"
25 #include "librist/tunnel.h"
26 #include <sys/types.h>
27 #include "proto/protocol_gre.h"
28 #if HAVE_SRP_SUPPORT
29 #include "proto/eap.h"
30 #endif
31 #include "mpegts.h"
32 #include "rist_ref.h"
33 #include "config.h"
34 #include "rist-thread.h"
35 #include "rist-nack-select.h"
36 #include "peer.h"
37 #include <stdbool.h>
38 #include "stdio-shim.h"
39 #include <assert.h>
40 #include "proto/gre.h"
41
42 static void rist_peer_recv(struct evsocket_ctx *evctx, int fd, short revents, void *arg, bool *again);
43 static void rist_peer_recv_wrap(struct evsocket_ctx *evctx, int fd, short revents, void *arg);
44 static void rist_peer_sockerr(struct evsocket_ctx *evctx, int fd, short revents, void *arg);
45 static PTHREAD_START_FUNC(receiver_pthread_dataout,arg);
46 static void store_peer_settings(const struct rist_peer_config *settings, struct rist_peer *peer);
47 static struct rist_peer *peer_initialize(const char *url, struct rist_sender *sender_ctx,
48 struct rist_receiver *receiver_ctx);
49 void remove_peer_from_flow(struct rist_peer *peer);
50
51 int parse_url_udp_options(const char* url, struct rist_udp_config *output_udp_config)
52 {
53 uint32_t clean_url_len = 0;
54 const char* query = NULL;
55 uint32_t prefix_len = 0;
56 struct udpsocket_url_param url_params[32];
57 int num_params = 0;
58 int i = 0;
59 int ret = 0;
60
61 if (!url || !url[0] || !output_udp_config)
62 return -1;
63
64 char *tmp_url = strdup( url );
65 if (!tmp_url)
66 return -1;
67
68 query = strchr( tmp_url, '/' );
69 if (query != NULL) {
70 prefix_len = (uint32_t)(query - tmp_url);
71 strncpy((void *)output_udp_config->prefix, tmp_url, prefix_len >= 16 ? 15 : prefix_len - 1);
72 output_udp_config->prefix[prefix_len] = '\0';
73 // Convert to lower
74 char *p =(char *)output_udp_config->prefix;
75 for(i = 0; i < 16; i++)
76 p[i] = p[i] > 0x40 && p[i] < 0x5b ? p[i] | 0x60 : p[i];
77 if (!strncmp(output_udp_config->prefix, "rtp", 3))
78 output_udp_config->rtp = true;
79 else
80 output_udp_config->rtp = false;
81 } else {
82 // default is udp
83 char src[] = "udp";
84 strcpy((void *)output_udp_config->prefix, src);
85 output_udp_config->rtp = false;
86 }
87
88 // Parse URL parameters
89 num_params = udpsocket_parse_url_parameters( tmp_url, url_params,
90 sizeof(url_params) / sizeof(struct udpsocket_url_param), &clean_url_len );
91 if (num_params > 0) {
92 for (i = 0; i < num_params; ++i) {
93 char* val = url_params[i].val;
94 if (!val)
95 continue;
96
97 if (strcmp( url_params[i].key, RIST_URL_PARAM_MIFACE ) == 0) {
98 strncpy((void *)output_udp_config->miface, val, RIST_MAX_STRING_SHORT - 1);
99 } else if (strcmp(url_params[i].key, RIST_URL_PARAM_MCAST_TTL) == 0) {
100 int temp = atoi(val);
101 if (temp > 0 && temp <= 255)
102 output_udp_config->multicast_ttl = (uint32_t)temp;
103 } else if (strcmp(url_params[i].key, RIST_URL_PARAM_MCAST_SOURCE) == 0) {
104 strncpy((void *)output_udp_config->multicast_source, val, RIST_MAX_STRING_LONG - 1);
105 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_STREAM_ID ) == 0) {
106 int temp = atoi( val );
107 if (temp > 0)
108 output_udp_config->stream_id = (uint16_t)temp;
109 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTP_TIMESTAMP ) == 0) {
110 int temp = atoi( val );
111 if (temp >= 0)
112 output_udp_config->rtp_timestamp = (uint16_t)temp;
113 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTP_SEQUENCE ) == 0) {
114 int temp = atoi( val );
115 if (temp >= 0)
116 output_udp_config->rtp_sequence = (uint16_t)temp;
117 } else if (output_udp_config->version == 1 && strcmp( url_params[i].key, RIST_URL_PARAM_RTP_OUTPUT_PTYPE) == 0) {
118 int temp = atoi( val );
119 if (temp >= 0)
120 output_udp_config->rtp_ptype = (uint8_t)temp;
121 } else if (output_udp_config->version == 1 && strcmp( url_params[i].key, RIST_URL_PARAM_MULTIPLEX_MODE) == 0) {
122 int temp = atoi( val );
123 if (temp >= 0)
124 output_udp_config->multiplex_mode = (uint8_t)temp;
125 /*UNUSED TODO} else if (output_udp_config->version == 1 && strcmp( url_params[i].key, RIST_URL_PARAM_MULTIPLEX_FILTER) == 0) {
126 strncpy((void *)output_udp_config->multiplex_filter, val, RIST_MAX_STRING_SHORT -1); */
127 } else {
128 ret = -1;
129 fprintf(stderr, "Unknown or invalid parameter %s\n", url_params[i].key);
130 }
131 }
132 }
133 strncpy((void *)output_udp_config->address, url, clean_url_len >= RIST_MAX_STRING_LONG ? RIST_MAX_STRING_LONG-1 : clean_url_len - 1);
134
135 free( tmp_url );
136
137 if (ret != 0)
138 return num_params;
139 else
140 return 0;
141 }
142
143 int parse_url_options(const char* url, struct rist_peer_config *output_peer_config)
144 {
145 uint32_t clean_url_len = 0;
146 struct udpsocket_url_param url_params[32];
147 int num_params = 0;
148 int i = 0;
149 int ret = 0;
150
151 if (!url || !url[0] || !output_peer_config)
152 return -1;
153
154 // Parse URL parameters
155 char *tmp_url = strdup( url );
156 if (!tmp_url)
157 return -1;
158
159 num_params = udpsocket_parse_url_parameters( tmp_url, url_params,
160 sizeof(url_params) / sizeof(struct udpsocket_url_param), &clean_url_len );
161 if (num_params > 0) {
162 for (i = 0; i < num_params; ++i) {
163 char* val = url_params[i].val;
164 if (!val)
165 continue;
166
167 if (strcmp( url_params[i].key, RIST_URL_PARAM_BUFFER_SIZE ) == 0) {
168 int temp = atoi( val );
169 if (temp >= 0) {
170 output_peer_config->recovery_length_min = temp;
171 output_peer_config->recovery_length_max = temp;
172 }
173 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_BUFFER_SIZE_MIN ) == 0) {
174 int temp = atoi( val );
175 if (temp >= 0)
176 output_peer_config->recovery_length_min = temp;
177 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_BUFFER_SIZE_MAX ) == 0) {
178 int temp = atoi( val );
179 if (temp >= 0)
180 output_peer_config->recovery_length_max = temp;
181 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_MIFACE ) == 0) {
182 strncpy((void *)output_peer_config->miface, val, 128-1);
183 } else if (output_peer_config->version >= 2 && strcmp(url_params[i].key, RIST_URL_PARAM_MCAST_TTL) == 0) {
184 int temp = atoi(val);
185 if (temp > 0 && temp <= 255)
186 output_peer_config->multicast_ttl = (uint32_t)temp;
187 } else if (output_peer_config->version >= 2 && strcmp(url_params[i].key, RIST_URL_PARAM_MCAST_SOURCE) == 0) {
188 strncpy((void *)output_peer_config->multicast_source, val, RIST_MAX_STRING_LONG - 1);
189 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_SECRET ) == 0) {
190 strncpy((void *)output_peer_config->secret, val, 128-1);
191 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_SRP_USERNAME) == 0) {
192 strncpy((void *)output_peer_config->srp_username, val, 256 -1);
193 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_SRP_PASSWORD) == 0) {
194 strncpy((void *)output_peer_config->srp_password, val, 256 -1);
195 } else if (output_peer_config->version >= 3 && strcmp( url_params[i].key, RIST_URL_PARAM_SRP_COMPAT) == 0) {
196 char *endp = NULL;
197 long temp = strtol(val, &endp, 10);
198 if (endp == val || *endp != '\0' || (temp != 0 && temp != 1)) {
199 ret = -1;
200 fprintf(stderr, "Invalid srp-compat '%s'; expected 0|1\n", val);
201 continue;
202 }
203 output_peer_config->srp_compat_legacy = (int)temp;
204 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_CNAME ) == 0) {
205 strncpy((void *)output_peer_config->cname, val, 128-1);
206 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_AES_TYPE ) == 0) {
207 int temp = atoi( val );
208 if (temp == 0 || temp == 128 || temp == 192 || temp == 256) {
209 output_peer_config->key_size = temp;
210 }
211 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_AES_KEY_ROTATION ) == 0) {
212 int temp = atoi( val );
213 if (temp > 0)
214 output_peer_config->key_rotation = temp;
215 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_BANDWIDTH ) == 0) {
216 int temp = atoi( val );
217 if (temp > 0)
218 output_peer_config->recovery_maxbitrate = temp;
219 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RET_BANDWIDTH ) == 0) {
220 int temp = atoi( val );
221 if (temp >= 0)
222 output_peer_config->recovery_maxbitrate_return = temp;
223 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT ) == 0) {
224 int temp = atoi( val );
225 if (temp >= 0) {
226 output_peer_config->recovery_rtt_min = temp;
227 output_peer_config->recovery_rtt_max = temp;
228 }
229 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT_MIN ) == 0) {
230 int temp = atoi( val );
231 if (temp >= 0)
232 output_peer_config->recovery_rtt_min = temp;
233 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT_MAX ) == 0) {
234 int temp = atoi( val );
235 if (temp >= 0)
236 output_peer_config->recovery_rtt_max = temp;
237 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_REORDER_BUFFER ) == 0) {
238 int temp = atoi( val );
239 if (temp >= 0)
240 output_peer_config->recovery_reorder_buffer = temp;
241 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_COMPRESSION ) == 0) {
242 int temp = atoi( val );
243 if (temp >= 0)
244 output_peer_config->compression = temp;
245 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_VIRT_DST_PORT ) == 0) {
246 int temp = atoi( val );
247 if (temp > 0)
248 output_peer_config->virt_dst_port = (uint16_t)temp;
249 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_WEIGHT ) == 0) {
250 int temp = atoi( val );
251 if (temp >= 0)
252 output_peer_config->weight = temp;
253 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RECOVERY_PRIORITY ) == 0) {
254 int temp = atoi( val );
255 if (temp >= 0)
256 output_peer_config->recovery_priority = (uint32_t)temp;
257 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_SESSION_TIMEOUT ) == 0) {
258 int temp = atoi( val );
259 if (temp > 0)
260 output_peer_config->session_timeout = temp;
261 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_KEEPALIVE_INT ) == 0) {
262 int temp = atoi( val );
263 if (temp > 0)
264 output_peer_config->keepalive_interval = temp;
265 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_CONGESTION_CONTROL ) == 0) {
266 int temp = atoi( val );
267 if (temp >= 0 && temp <= 2)
268 output_peer_config->congestion_control_mode = temp;
269 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_TIMING_MODE ) == 0) {
270 int temp = atoi( val );
271 if (temp >= 0 && temp <= 2)
272 output_peer_config->timing_mode = temp;
273 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_MIN_RETRIES ) == 0) {
274 int temp = atoi( val );
275 if (temp > 0)
276 output_peer_config->min_retries = temp;
277 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_MAX_RETRIES ) == 0) {
278 int temp = atoi( val );
279 if (temp > 0)
280 output_peer_config->max_retries = temp;
281 } else if (output_peer_config->version >= 1 &&
282 strcmp( url_params[i].key, RIST_URL_PARAM_SPLIT_MODE ) == 0) {
283 if (strcmp(val, "off") == 0)
284 output_peer_config->split_mode = LIBRIST_SPLIT_MODE_OFF;
285 else if (strcmp(val, "auto") == 0 || strcmp(val, "ts") == 0)
286 output_peer_config->split_mode = LIBRIST_SPLIT_MODE_AUTO;
287 else if (strcmp(val, "half") == 0)
288 output_peer_config->split_mode = LIBRIST_SPLIT_MODE_HALF;
289 else {
290 ret = -1;
291 fprintf(stderr, "Unknown split mode '%s'; expected off|auto|half\n", val);
292 }
293 } else if (output_peer_config->version >= 1 &&
294 strcmp( url_params[i].key, RIST_URL_PARAM_MERGE_MODE ) == 0) {
295 if (strcmp(val, "off") == 0)
296 output_peer_config->merge_mode = LIBRIST_MERGE_MODE_OFF;
297 else if (strcmp(val, "pairs") == 0)
298 output_peer_config->merge_mode = LIBRIST_MERGE_MODE_PAIRS;
299 else if (strcmp(val, "auto") == 0)
300 output_peer_config->merge_mode = LIBRIST_MERGE_MODE_AUTO;
301 else {
302 ret = -1;
303 fprintf(stderr, "Unknown merge mode '%s'; expected off|auto|pairs\n", val);
304 }
305 } else if (output_peer_config->version >= 2 && strcmp( url_params[i].key, RIST_URL_PARAM_REFLECTOR ) == 0) {
306 int temp = atoi( val );
307 if (temp >= 0 && temp <= 1)
308 output_peer_config->reflector = temp;
309 } else if (output_peer_config->version >= 2 && strcmp( url_params[i].key, RIST_URL_PARAM_LOCAL_PORT ) == 0) {
310 int temp = atoi( val );
311 if (temp > 0 && temp <= 65535)
312 output_peer_config->local_port = (uint16_t)temp;
313 } else if (output_peer_config->version >= 5 &&
314 strcmp( url_params[i].key, RIST_URL_PARAM_RECOVERY_DEPTH ) == 0) {
315 char *endp = NULL;
316 long temp = strtol(val, &endp, 10);
317 if (endp == val || *endp != '\0' ||
318 temp < RIST_RECOVERY_DEPTH_MIN || temp > RIST_RECOVERY_DEPTH_MAX) {
319 ret = -1;
320 fprintf(stderr, "Invalid recovery-depth '%s'; expected %d..%d "
321 "(ring = 65536 << depth packets; default %d)\n", val,
322 RIST_RECOVERY_DEPTH_MIN, RIST_RECOVERY_DEPTH_MAX,
323 RIST_RECOVERY_DEPTH_DEFAULT);
324 } else {
325 output_peer_config->recovery_depth = (uint8_t)temp;
326 }
327 } else if (output_peer_config->version >= 4 &&
328 strcmp( url_params[i].key, RIST_URL_PARAM_PROFILE ) == 0) {
329 /* version >= 4: writing profile fields on a
330 * struct sized for an older version would
331 * overflow the caller's allocation. */
332 char *endp = NULL;
333 long temp = strtol(val, &endp, 10);
334 if (endp == val || *endp != '\0' ||
335 temp < RIST_PROFILE_SIMPLE || temp > RIST_PROFILE_ADVANCED) {
336 ret = -1;
337 fprintf(stderr, "Invalid profile '%s'; expected 0|1|2\n", val);
338 continue;
339 }
340 output_peer_config->profile = (enum rist_profile)temp;
341 output_peer_config->profile_set = 1;
342 } else {
343 ret = -1;
344 fprintf(stderr, "Unknown or invalid parameter %s\n", url_params[i].key);
345 }
346 }
347 }
348 strncpy((void *)output_peer_config->address, url, clean_url_len >= RIST_MAX_STRING_LONG ? RIST_MAX_STRING_LONG-1 : clean_url_len - 1);
349
350 free( tmp_url );
351
352 if (ret != 0)
353 return num_params;
354 else
355 return 0;
356 }
357
358 struct rist_common_ctx *get_cctx(struct rist_peer *peer)
359 {
360 if (peer->sender_ctx) {
361 return &peer->sender_ctx->common;
362 } else {
363 return &peer->receiver_ctx->common;
364 }
365 }
366
367 int rist_max_jitter_set(struct rist_common_ctx *ctx, int t)
368 {
369 if (t > 0) {
370 ctx->rist_max_jitter = t * RIST_CLOCK;
371 return 0;
372 }
373
374 return -1;
375 }
376
377 int rist_recovery_rtt_multiplier_set_internal(struct rist_common_ctx *ctx, int multiplier)
378 {
379 if (multiplier >= 1) {
380 ctx->recovery_rtt_multiplier = multiplier;
381 return 0;
382 }
383 return -1;
384 }
385
386 /* Reference packet size for the config-time recovery-window sanity check.
387 * 7x188 MPEG-TS over RTP is the common RIST framing. Smaller packets put
388 * MORE packets in the buffer and make the window tighter, so this estimate
389 * is deliberately optimistic: it only warns when the configuration clearly
390 * overruns the window even with full-size packets. */
391 #define RIST_RECOVERY_REF_PKT_BYTES 1316
392
393 /* Warn (once, at peer-config time) if the configured recovery-maxbitrate and
394 * max buffer would queue more packets than the recovery window can address.
395 * Packets beyond the window cannot be retransmitted regardless of how many
396 * NACKs are sent. window is the addressable window in packets for this role
397 * (receiver NACK window or sender retransmit window). */
398 static void rist_warn_recovery_window(struct rist_peer *peer, size_t window, bool sender)
399 {
400 uint32_t maxbitrate = peer->config.recovery_maxbitrate; /* kbps */
401 uint32_t length_max = peer->config.recovery_length_max; /* ms */
402 if (maxbitrate == 0 || length_max == 0 || window == 0)
403 return;
404 uint64_t pkts_in_buffer =
405 (uint64_t)maxbitrate * length_max / (RIST_RECOVERY_REF_PKT_BYTES * 8);
406 if (pkts_in_buffer <= window)
407 return;
408 struct rist_common_ctx *cctx = get_cctx(peer);
409 bool advanced = (cctx->profile == RIST_PROFILE_ADVANCED);
410 rist_log_priv(cctx, RIST_LOG_WARN,
411 "Peer #%"PRIu32": recovery config exceeds the %s recovery window. "
412 "At %u kbps a %u ms buffer holds ~%"PRIu64" packets (assuming ~%d-byte "
413 "packets; smaller packets are worse), but the %s-profile %s window "
414 "addresses only %zu packets - packets beyond it cannot be retransmitted. %s\n",
415 peer->adv_peer_id,
416 sender ? "sender" : "receiver",
417 maxbitrate, length_max, pkts_in_buffer, RIST_RECOVERY_REF_PKT_BYTES,
418 advanced ? "Advanced" : (cctx->profile == RIST_PROFILE_MAIN ? "Main" : "Simple"),
419 sender ? "retransmit" : "NACK",
420 window,
421 advanced
422 ? "Lower recovery-maxbitrate/buffer, or enlarge the ring via ?recovery-depth= (or rist_recovery_depth_set()) before rist_start()."
423 : "Lower recovery-maxbitrate/buffer, or use the Advanced profile for a 32-bit sequence space.");
424 }
425
426 static void init_peer_settings(struct rist_peer *peer)
427 {
428 peer->eight_times_rtt = peer->config.recovery_rtt_min * 8;
429 if (peer->receiver_mode) {
430 assert(peer->receiver_ctx != NULL);
431 uint32_t recovery_maxbitrate_mbps = peer->config.recovery_maxbitrate < 1000 ? 1 : peer->config.recovery_maxbitrate / 1000;
432 // Initial value for some variables
433 peer->recovery_buffer_ticks =
434 (peer->config.recovery_length_max - peer->config.recovery_length_min) / 2 + peer->config.recovery_length_min;
435 peer->recovery_buffer_ticks = peer->recovery_buffer_ticks * RIST_CLOCK;
436 peer->missing_counter_max =
437 (uint32_t)(peer->recovery_buffer_ticks / RIST_CLOCK) * recovery_maxbitrate_mbps /
438 (sizeof(struct rist_gre_seq) + sizeof(struct rist_rtp_hdr) + sizeof(uint32_t));
439
440 {
441 struct rist_common_ctx *cctx = get_cctx(peer);
442 size_t rwin = ((cctx->profile == RIST_PROFILE_ADVANCED)
443 ? cctx->recovery_queue_max : UINT16_SIZE) / 2;
444 rist_warn_recovery_window(peer, rwin, false);
445 }
446
447 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
448 "New peer with id #%"PRIu32" was configured with maxrate=%d/%d bufmin=%d bufmax=%d reorder=%d rttmin=%d rttmax=%d congestion_control=%d min_retries=%d max_retries=%d\n",
449 peer->adv_peer_id, peer->config.recovery_maxbitrate, peer->config.recovery_maxbitrate_return, peer->config.recovery_length_min, peer->config.recovery_length_max, peer->config.recovery_reorder_buffer,
450 peer->config.recovery_rtt_min /RIST_CLOCK, peer->config.recovery_rtt_max /RIST_CLOCK, peer->config.congestion_control_mode, peer->config.min_retries, peer->config.max_retries);
451 if (peer->config.recovery_length_min != peer->config.recovery_length_max)
452 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Enabling automatic buffer scaling\n");
453 }
454 else {
455 assert(peer->sender_ctx != NULL);
456 struct rist_sender *ctx = peer->sender_ctx;
457 {
458 size_t swin = ((ctx->common.profile == RIST_PROFILE_ADVANCED)
459 ? ctx->sender_queue_max : UINT16_SIZE) / 2;
460 rist_warn_recovery_window(peer, swin, true);
461 }
462 /* Global context settings */
463 if (peer->config.recovery_maxbitrate > ctx->recovery_maxbitrate_max) {
464 ctx->recovery_maxbitrate_max = peer->config.recovery_maxbitrate;
465 int max_jitter_ms = ctx->common.rist_max_jitter / RIST_CLOCK;
466 // Asume MTU of 1400 for now
467 uint32_t max_nacksperloop = ctx->recovery_maxbitrate_max * max_jitter_ms / (8*1400);
468 // Normalize against the total buffer size
469 max_nacksperloop = max_nacksperloop * 1000 / peer->config.recovery_length_max;
470 // Anything less that 2240Kbps at 5ms will round down to zero (100Mbps is 44)
471 if (max_nacksperloop == 0)
472 max_nacksperloop = 1;
473 // The effective buffer is 50% the total buffer size
474 max_nacksperloop = max_nacksperloop * 2;
475 if (max_nacksperloop > ctx->max_nacksperloop) {
476 ctx->max_nacksperloop = (uint32_t)max_nacksperloop;
477 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Setting max nacks per cycle to %"PRIu32"\n",
478 max_nacksperloop);
479 }
480 }
481
482 if (!peer->listening && peer->config.weight != RIST_PEER_WEIGHT_DUPLICATE && !peer->parent) {
483 ctx->total_weight += peer->config.weight;
484 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Peer weight: %lu\n", peer->config.weight);
485 }
486
487 /* Set target recover size (buffer) */
488 if ((peer->config.recovery_length_max + (2 * peer->config.recovery_rtt_min)) > ctx->sender_recover_min_time) {
489 ctx->sender_recover_min_time = peer->config.recovery_length_max + (2 * peer->config.recovery_rtt_min / RIST_CLOCK);
490 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Setting buffer size to %zums (Max buffer size + 2 * Min RTT, %zu+2*%zu)\n", ctx->sender_recover_min_time,
491 peer->config.recovery_length_max,peer->config.recovery_rtt_min / RIST_CLOCK);
492 // TODO: adjust this size based on the dynamic RTT measurement
493 }
494
495 }
496 }
497
498 struct rist_buffer *rist_new_buffer(struct rist_common_ctx *ctx, const void *buf, size_t len, uint8_t type, uint32_t seq, uint64_t source_time, uint16_t src_port, uint16_t dst_port)
499 {
500 RIST_MARK_UNUSED(ctx);
501 // TODO: we will ran out of stack before heap and when that happens malloc will crash not just
502 // return NULL ... We need to find and remove all heap allocations
503 struct rist_buffer *b;
504 b = malloc(sizeof(*b));
505 if (!b) {
506 fprintf(stderr, "OOM\n");
507 return NULL;
508 }
509
510 b->data = malloc(len + RIST_MAX_PAYLOAD_OFFSET);
511 if (!b->data) {
512 free(b);
513 fprintf(stderr, "OOM\n");
514 return NULL;
515 }
516 b->alloc_size = len;
517 if (buf != NULL && len > 0)
518 {
519 memcpy((uint8_t *)b->data + RIST_MAX_PAYLOAD_OFFSET, buf, len);
520 }
521 b->alloc_size = len;
522 b->next_free = NULL;
523 b->free = false;
524 b->size = len;
525 b->source_time = source_time;
526 b->seq = seq;
527 b->time = timestampNTP_u64();
528 b->type = type;
529 b->src_port = src_port;
530 b->dst_port = dst_port;
531 b->last_retry_request = 0;
532 b->transmit_count = 0;
533 b->use_seq = 0;
534 b->retry_queued = false;
535 return b;
536 }
537
538 void free_rist_buffer(struct rist_common_ctx *ctx, struct rist_buffer *b)
539 {
540 RIST_MARK_UNUSED(ctx);
541 free(b->data);
542 free(b);
543
544 }
545
546 static uint64_t receiver_calculate_packet_time(struct rist_flow *f, const uint64_t source_time, uint64_t now, bool retry, uint8_t payload_type)
547 {
548 //Check and correct timing
549 uint64_t packet_time = source_time + f->time_offset;
550 if (RIST_UNLIKELY(!retry && source_time < f->max_source_time && ((f->max_source_time - source_time) > (UINT32_MAX /2)) && (now - f->time_offset_changed_ts) > 3 * f->recovery_buffer_ticks))
551 {
552 int64_t new_offset = (int64_t)now - (int64_t)source_time;
553 int64_t offset_diff = llabs(new_offset - f->time_offset);
554 //Make sure the new and old offsets differ at least by 10 hrs, otherwise something is wrong.
555 if (offset_diff > (int64_t)(10LL * 3600LL * 1000LL * RIST_CLOCK)) {
556 f->time_offset_old = f->time_offset;
557 //Calculate new offset by getting max time for payload type and adding it to old offset
558 //Fast path for mpegts payload type with clock of 90khz
559 if (RIST_UNLIKELY(payload_type != RTP_PTYPE_RIST))
560 f->time_offset += convertRTPtoNTP(payload_type, 0, UINT32_MAX);
561 else
562 f->time_offset += ((uint64_t)UINT32_MAX << 32) / RTP_PTYPE_MPEGTS_CLOCKHZ;
563 rist_log_priv(get_cctx(f->peer_lst[0]), RIST_LOG_INFO, "Clock wrapped, old offset: %" PRId64 " new offset %" PRId64 "\n", f->time_offset / RIST_CLOCK, f->time_offset_old / RIST_CLOCK);
564 f->offset_recalc_sample_count = 0;
565 f->max_source_time = 0;
566 f->time_offset_changed_ts = now;
567 }
568 packet_time = source_time + f->time_offset;
569 //Packets with old clock will be too big due to the wrong offset.
570 } else if (RIST_UNLIKELY(packet_time > f->last_packet_ts && ((packet_time - f->last_packet_ts) > UINT32_MAX / 2) && (now - f->time_offset_changed_ts) < 3 * f->recovery_buffer_ticks))
571 {
572 packet_time = source_time + f->time_offset_old;
573 } else if (source_time > f->max_source_time)
574 {
575 f->last_packet_ts = packet_time;
576 f->max_source_time = source_time;
577 }
578 return packet_time;
579 }
580
581 static int receiver_insert_queue_packet(struct rist_flow *f, struct rist_peer *peer, size_t idx, const void *buf, size_t len, uint32_t seq, uint64_t source_time, uint16_t src_port, uint16_t dst_port, uint64_t packet_time)
582 {
583 /*
584 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
585 "Inserting seq %"PRIu32" len %zu source_time %"PRIu32" at idx %zu\n",
586 seq, len, source_time, idx);
587 */
588 f->receiver_queue[idx] = rist_new_buffer(get_cctx(peer), buf, len, RIST_PAYLOAD_TYPE_DATA_RAW, seq, source_time, src_port, dst_port);
589 if (RIST_UNLIKELY(!f->receiver_queue[idx])) {
590 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Could not create packet buffer inside receiver buffer, OOM, decrease max bitrate or buffer time length\n");
591 return -1;
592 }
593 f->receiver_queue[idx]->peer = peer;
594 f->receiver_queue[idx]->packet_time = packet_time;
595 f->receiver_queue[idx]->target_output_time = packet_time + f->recovery_buffer_ticks;
596 atomic_fetch_add_explicit(&f->receiver_queue_size, len, memory_order_release);
597
598 return 0;
599 }
600
601 static inline void receiver_mark_missing(struct rist_flow *f, struct rist_peer *peer, uint32_t current_seq, uint64_t rtt) {
602 uint32_t counter = 1;
603 uint64_t packet_time_last = 0;
604 /* Index the ring exactly as receiver_enqueue() does. 16-bit flows had a
605 * sequence range equal to receiver_queue_max so a raw seq was always a
606 * valid index, but a 32-bit (Advanced) seq can exceed receiver_queue_max
607 * and run off the array -> OOB read of a stale/NULL slot, then a NULL
608 * deref. */
609 size_t last_idx = f->last_seq_found & (f->receiver_queue_max - 1);
610 size_t cur_idx = current_seq & (f->receiver_queue_max - 1);
611 if (RIST_UNLIKELY(!f->receiver_queue[last_idx]))
612 if (RIST_LIKELY(!f->rtc_timing_mode))
613 packet_time_last = timestampNTP_u64();
614 else
615 packet_time_last = timestampNTP_RTC_u64();
616 else
617 packet_time_last = f->receiver_queue[last_idx]->packet_time;
618 uint64_t packet_time_now;
619 if (RIST_UNLIKELY(!f->receiver_queue[cur_idx])) {
620 if (RIST_LIKELY(!f->rtc_timing_mode))
621 packet_time_now = timestampNTP_u64();
622 else
623 packet_time_now = timestampNTP_RTC_u64();
624 } else {
625 packet_time_now = f->receiver_queue[cur_idx]->packet_time;
626 }
627 /* short_seq (Simple/Main) flows wrap at 16 bits; 32-bit (Advanced) flows
628 * use the true gap so a real >64k loss is not truncated. Cap mirrors the
629 * recovery-walk hole cap (UINT16_SIZE/2 short, receiver_queue_max/2 else). */
630 uint32_t missing_count = rist_seq_gap(current_seq, f->last_seq_found,
631 f->short_seq);
632 uint32_t missing_count_cap = f->short_seq
633 ? (UINT16_SIZE / 2)
634 : (uint32_t)(f->receiver_queue_max / 2);
635 if (missing_count > missing_count_cap)
636 return;
637 uint64_t interpacket_time = (packet_time_now - packet_time_last) / (missing_count +1);
638 uint32_t missing_seq = (f->last_seq_found + counter);
639
640 if (f->short_seq)
641 missing_seq = (uint16_t)missing_seq;
642
643 uint64_t nack_time = packet_time_last;
644 while (missing_seq != current_seq)
645 {
646 nack_time += interpacket_time;
647 if (RIST_UNLIKELY(peer->buffer_bloat_active || f->missing_counter > peer->missing_counter_max))
648 {
649 if (f->missing_counter > peer->missing_counter_max)
650 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
651 "Retry buffer is already too large (%d) for the configured "
652 "bandwidth ... ignoring missing packet(s).\n",
653 f->missing_counter);
654 if (peer->buffer_bloat_active)
655 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
656 "Link has collapsed. Not queuing new retries until it recovers.\n");
657 break;
658 }
659 rist_receiver_missing(f, peer, nack_time, missing_seq, rtt);
660 if (RIST_UNLIKELY(counter == f->receiver_queue_max))
661 break;
662 counter++;
663 missing_seq = (f->last_seq_found + counter);
664 if (f->short_seq)
665 missing_seq = (uint16_t)missing_seq;
666 }
667 }
668
669 int compare(const void *a, const void *b)
670 {
671 uint64_t ua = *(const uint64_t *)a;
672 uint64_t ub = *(const uint64_t *)b;
673 return (ua > ub) - (ua < ub);
674 }
675
676 static void recalculate_clock_offset(struct rist_flow *flow)
677 {
678 //arbitrarily chosen minimal sample count
679 if (flow->offset_recalc_sample_count < 100)
680 return;
681
682 /* to counter clock drift we are recalculating our offset every 2048 inserted
683 packets. Every "correctly" (in-order, no-discontinuities) packet's clock offset
684 is inserted into an array. Of which we will take the median. */
685 qsort(flow->offset_recalc_samples, flow->offset_recalc_sample_count, sizeof(uint64_t), compare);
686 size_t middle = flow->offset_recalc_sample_count / 2;
687 uint64_t median_offset = flow->offset_recalc_samples[middle];
688 flow->offset_recalc_sample_count = 0;
689 uint64_t diff = 0;
690 uint64_t negative = (median_offset < (uint64_t)flow->time_offset);
691 if (negative)
692 diff = flow->time_offset - median_offset;
693 else
694 diff = median_offset - flow->time_offset;
695 rist_log_priv2(flow->logging_settings, RIST_LOG_DEBUG, "Recalculated clock offset, old offset: %lu, new offset: %lu difference: %c%lu usec\n",
696 flow->time_offset, median_offset, negative? '-': '+', (diff * 1000 / RIST_CLOCK));
697 flow->time_offset = median_offset;
698 }
699
700
701 static int receiver_enqueue(struct rist_peer *peer, uint64_t source_time, uint64_t packet_recv_time, const void *buf, size_t len, uint32_t seq, uint64_t rtt, bool retry, uint16_t src_port, uint16_t dst_port, uint8_t payload_type)
702 {
703 struct rist_flow *f = peer->flow;
704
705 // fprintf(stderr,"receiver enqueue seq is %"PRIu32", source_time %"PRIu64"\n",
706 // seq, source_time);
707 uint64_t now;
708 uint64_t now_monotonic = packet_recv_time;
709 if (RIST_LIKELY(!f->rtc_timing_mode))
710 now = now_monotonic;
711 else
712 now = timestampNTP_RTC_u64();
713 //fprintf(stderr, "Offset would've been: %llu\n", now - source_time);
714 if (RIST_UNLIKELY((!f->receiver_queue_has_items && retry) || (f->rtc_timing_mode && f->time_offset == 0)))
715 return -1;
716 if (RIST_UNLIKELY(!f->receiver_queue_has_items)) {
717 /* we just received our first packet for this flow */
718 pthread_mutex_lock(&f->mutex);
719 if (atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire) > 0)
720 {
721 /* Clear the queue if the queue had data */
722 /* f->receiver_queue_has_items can be reset to false when the output queue is emptied */
723 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
724 "Clearing up old %zu bytes of old buffer data\n", atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire));
725 /* Delete all buffer data (if any) */
726 empty_receiver_queue(f, get_cctx(peer));
727 }
728 rist_flush_missing_flow_queue(f);
729 /* Initialize flow session timeout and stats timers */
730 f->flag_flow_buffer_start = true;
731 f->last_recv_ts = now_monotonic;
732 f->checks_next_time = now_monotonic;
733 /* Calculate and store clock offset with respect to source */
734 if (!f->rtc_timing_mode)
735 f->time_offset = (int64_t)now_monotonic - (int64_t)source_time;
736 /* This ensures the next packet does not trigger nacks */
737 f->last_seq_output = seq - 1;
738 f->last_seq_found = seq;
739 f->max_source_time = source_time;
740 /* This will synchronize idx and seq so we can insert packets into receiver buffer based on seq number */
741 size_t idx_initial = seq & (f->receiver_queue_max -1);
742 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
743 "Storing first packet seq %" PRIu32 ", idx %zu, %" PRIu64 ", offset %" PRId64 " ms, output_idx %zu\n",
744 seq, idx_initial, source_time, peer->flow->time_offset / RIST_CLOCK, idx_initial);
745 uint64_t packet_time = source_time + f->time_offset;
746
747 f->last_packet_ts = packet_time;
748 f->time_offset_changed_ts = 0;
749 f->time_offset_old = f->time_offset;
•750 /* Discard clock-drift samples gathered against the previous
751 * baseline. A flow-id change or a Main<->Advanced wire-framing
752 * switch (the two framings carry source_time in different
753 * timestamp domains) lands here with stale samples still queued;
754 * blending them into the median yields a bogus multi-second
755 * offset correction that releases the whole buffer at once and
756 * overflows the data-out fifo. Matches the clock-wrap reset. */
757 f->offset_recalc_sample_count = 0;
758
759 receiver_insert_queue_packet(f, peer, idx_initial, buf, len, seq, source_time, src_port, dst_port, packet_time);
760 atomic_store_explicit(&f->receiver_queue_output_idx, idx_initial, memory_order_release);
761
762 /* reset stats and timing state */
763 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
764 memset(&f->stats_instant, 0, sizeof(f->stats_instant));
765 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
766 f->last_output_time = 0;
767 f->too_late_ctr = 0;
768 f->receiver_queue_has_items = true;
769 pthread_mutex_unlock(&f->mutex);
770 return 0; // not a dupe
771 }
772
773 uint64_t packet_time = receiver_calculate_packet_time(f, source_time, now, retry, payload_type);
774 size_t idx = seq & (f->receiver_queue_max - 1);
775 if (RIST_UNLIKELY(peer->config.timing_mode == RIST_TIMING_MODE_ARRIVAL && retry))
776 {
777 //arrival packet time would be incorrect for a retry packet, so instead we interpolate between packets.
778 //this does assume CBR
779 struct rist_buffer *previous = NULL;
780 size_t index = (idx -1)& (f->receiver_queue_max - 1);
781 while (previous == NULL && index != idx)
782 {
783 previous = f->receiver_queue[index];
784 index = (index -1)& (f->receiver_queue_max - 1);
785 }
786 struct rist_buffer *next = NULL;
787 index = (idx +1)& (f->receiver_queue_max -1);
788 while (next == NULL && index != idx)
789 {
790 next = f->receiver_queue[index];
791 index = (index +1)& (f->receiver_queue_max -1);
792 }
793 //interpolate the arrival time, assuming CBR
794 /* Neighbours can be non-monotonic under arrival-based timing;
795 * clamp the CBR estimate into the interval instead of asserting. */
796 if (next && previous && next->packet_time > previous->packet_time)
797 {
798 uint32_t steps = (next->seq - previous->seq);
799 if (f->short_seq)
800 steps = (uint16_t)steps;
801 uint32_t steps_since_previous = seq - previous->seq;
802 if (f->short_seq)
803 steps_since_previous = (uint16_t)steps_since_previous;
804 if (steps > 1 && steps_since_previous > 0 && steps_since_previous < steps) {
805 /* multiply before dividing so integer rounding cannot push
806 * the estimate up to or past next->packet_time */
807 uint64_t span = next->packet_time - previous->packet_time;
808 packet_time = previous->packet_time + (span * steps_since_previous) / steps;
809 } else {
810 /* seq is not strictly between the neighbours (gap, reorder
811 * or sequence-number wrap): place it next to next. */
812 packet_time = next->packet_time - 1;
813 }
814 if (packet_time < previous->packet_time)
815 packet_time = previous->packet_time;
816 else if (packet_time > next->packet_time)
817 packet_time = next->packet_time;
818 } else if (next)
819 {
820 /* No usable previous neighbour, or neighbours whose times are
821 * non-monotonic: use next's time. */
822 packet_time = next->packet_time;
823 }
824 }
825
826 // Now, get the new position and check what is there
827 /* We need to check if the reader queue has progressed passed this packet, if
828 this is the case we silently drop the packet as it would not be output in a
829 valid way anyway.
830 We only check this for packets that arrive out of order (i.e.: with a lower
831 output time than the highest known output time) */
832 size_t reader_idx;
833 bool out_of_order = false;
834 uint32_t expected_seq = rist_seq_next(f->last_seq_found, f->short_seq);
835 if (RIST_UNLIKELY(packet_time < f->last_packet_ts && seq != expected_seq)) {
836 if (now > (packet_time + (f->recovery_buffer_ticks *1.1)))
837 {
838 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Packet %"PRIu32" too late, dropping!\n", seq);
839 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
840 f->stats_instant.dropped_late++;
841 if (f->stats_instant.dropped_late > 5 * f->stats_instant.received)
842 f->receiver_queue_has_items = false;
843 if ((f->stats_instant.dropped_late > (f->stats_instant.received * 5) && f->stats_instant.received > 100) ||
844 (f->stats_instant.dropped_late > 100 && f->stats_instant.received == 0)) {
845 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Too many late packets received, resetting flow");
846 f->receiver_queue_has_items = false;
847 }
848 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
849 return -1;
850 }
851 if (!retry) {
852 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
853 "Out of order packet received, seq %" PRIu32 " / age %" PRIu64 " ms\n",
854 seq, (timestampNTP_u64() - packet_time) / RIST_CLOCK);
855 out_of_order = true;
856 }
857 }
858 reader_idx = atomic_load_explicit(&f->receiver_queue_output_idx, memory_order_acquire);
859 if (RIST_UNLIKELY(idx == ((reader_idx -1) &(f->receiver_queue_max -1))))
860 {
861 //Buffer full!
862 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Buffer is full, dropping packet %"PRIu32"/%zu\n", seq, idx);
863 if (packet_time > f->last_packet_ts)
864 f->last_seq_found = seq;
865 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
866 f->stats_instant.dropped_full++;
867 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
868 //Something is wrong, and we should reset
869 if (f->stats_instant.dropped_full > 100) {
870 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Buffer is full, resetting buffer\n");
871 f->receiver_queue_has_items = false;
872 }
873 return -1;
874 }
875 if (RIST_UNLIKELY(f->receiver_queue[idx])) {
876 // TODO: record stats
877 struct rist_buffer *b = f->receiver_queue[idx];
878 /* Match on seq: the slot index is derived from the sequence number,
879 * and source_time is the arrival time on the Advanced path, so it
880 * cannot identify a genuine duplicate. A different seq in this slot
881 * is a stale entry from an earlier ring cycle and is replaced below. */
882 if (b->seq == seq) {
883 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Dupe! %"PRIu32"/%zu\n", seq, idx);
884 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
885 f->stats_instant.dupe++;
886 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
887 return 1;
888 }
889 else {
890 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Invalid Dupe (possible seq discontinuity)! %"PRIu32", freeing buffer ...\n", seq);
891 free_rist_buffer(get_cctx(peer), b);
892 f->receiver_queue[idx] = NULL;
893 }
894 }
895
896
897 /* Now, we insert the packet into receiver queue */
898 if (receiver_insert_queue_packet(f, peer, idx, buf, len, seq, source_time, src_port, dst_port, packet_time)) {
899 // only error is OOM, safe to exit here ...
900 return 0;
901 }
902 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
903 if (out_of_order)
904 f->stats_instant.reordered++;
905 f->stats_instant.received++;
906 f->stats_instant.received_bytes += (uint64_t)len;
907 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
908 // Check for missing data and queue retries
909 if (!retry) {
910 /* check for missing packets */
911 // We start at the last known good packet, and look forwards till we hit this seq
912 uint32_t missing_seq = seq - 1;
913 if (f->short_seq)
914 missing_seq = (uint16_t)missing_seq;
915
916 if (!out_of_order && missing_seq != f->last_seq_found)
917 {
918 receiver_mark_missing(f, peer, seq, rtt);
919 } else if (RIST_LIKELY(!f->rtc_timing_mode && !out_of_order))
920 {
921 //packet received in order, use it's offset as a sample in calculation to
922 //correct clock drift
923 f->offset_recalc_samples[f->offset_recalc_sample_count] = (int64_t)now - (int64_t)source_time;
924 f->offset_recalc_sample_count++;
925 if (f->offset_recalc_sample_count == 2048)
926 recalculate_clock_offset(f);
927 }
928 //If we stopped due to bloat or missing count max this will be incorrect.
929 if (!out_of_order)
930 f->last_seq_found = seq;
931 }
932 return 0;
933 }
934
935 static int rist_process_nack(struct rist_flow *f, struct rist_missing_buffer *b)
936 {
937 uint64_t now;
938 if (RIST_LIKELY(!f->rtc_timing_mode))
939 now = timestampNTP_u64();
940 else
941 now = timestampNTP_RTC_u64();
942 struct rist_peer *peer = b->peer;
943
944 pthread_mutex_lock(&f->mutex);
945 uint64_t recovery_buffer_ticks = f->recovery_buffer_ticks;
946 pthread_mutex_unlock(&f->mutex);
947
948 if (b->nack_count >= peer->config.max_retries) {
949 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Datagram %"PRIu32
950 " is missing, but nack count is too large (%u), age is %"PRIu64"ms, retry #%lu, max_retries %d, congestion_control_mode %d, stats_receiver_total.recovered_average %d\n",
951 b->seq,
952 b->nack_count,
953 (now - b->insertion_time) / RIST_CLOCK,
954 b->nack_count,
955 peer->config.max_retries,
956 peer->config.congestion_control_mode,
957 f->stats_total.recovered_average);
958 return 8;
959 } else {
960 if ((uint64_t)(now - b->insertion_time) > (recovery_buffer_ticks *1.1)) {
961 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
962 "Datagram %" PRIu32 " is missing but it is too late (%" PRIu64
963 "ms) to send NACK!, retry #%lu, retry queue %d, max time %"PRIu64"\n",
964 b->seq, (now - b->insertion_time)/RIST_CLOCK, b->nack_count,
965 f->missing_counter, recovery_buffer_ticks / RIST_CLOCK);
966 return 9;
967 } else if (now >= b->next_nack) {
968 uint64_t rtt = (peer->eight_times_rtt / 8);
969 if (rtt < peer->config.recovery_rtt_min) {
970 rtt = peer->config.recovery_rtt_min;
971 } else if (rtt > peer->config.recovery_rtt_max) {
972 rtt = peer->config.recovery_rtt_max;
973 }
974 if (b->nack_count == 0) {
975 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
976 f->stats_instant.missing++;
977 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
978 }
979
980 // TODO: make this 10% overhead configurable?
981 // retry more when we are running out of time (proportional)
982 /* start with 1.1 * 1000 and go down from there */
983 //uint32_t ratio = 1100 - (b->nack_count * 1100)/(2*b->peer->config.max_retries);
984 //b->next_nack = now + (uint64_t)rtt * (uint64_t)ratio * (uint64_t)RIST_CLOCK;
985 b->next_nack = now + (uint64_t)(rtt * 1.1);
986 b->nack_count++;
987
988 if (get_cctx(peer)->debug)
989 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Datagram %" PRIu32 " is missing, sending NACK!, next retry in %" PRIu64 "ms, age is %" PRIu64 "ms, retry #%lu, max_size is %" PRIu64 "ms\n",
990 b->seq, (b->next_nack - now) / RIST_CLOCK,
991 (now - b->insertion_time) / RIST_CLOCK,
992 b->nack_count,
993 recovery_buffer_ticks / RIST_CLOCK);
994
995 // update peer information
996 f->nacks.array[f->nacks.counter] = b->seq;
997 f->nacks.counter++;
998 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
999 f->stats_instant.retries++;
1000 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
1001 }
1002 }
1003
1004 return 0;
1005 }
1006
1007 void free_data_block(struct rist_data_block **const block)
1008 {
1009 assert(block != NULL);
1010 struct rist_data_block *b = *block;
1011 if (!b)
1012 return;
1013
1014 if (atomic_fetch_sub(&b->ref->refcnt, 1) == 1)
1015 {
1016 assert(b->ref->ptr == b);
1017 uint8_t *payload = ((uint8_t*)b->payload - RIST_MAX_PAYLOAD_OFFSET);//this is extremely ugly, though these offsets will stop existing in next release
1018 free(payload);
1019 free((void *)b->ref);
1020 free(b);
1021 }
1022 *block = NULL;
1023 }
1024
1025 static struct rist_data_block *new_data_block(struct rist_data_block *output_buffer_current, struct rist_buffer *b, uint8_t *payload, uint32_t flow_id, uint32_t flags)
1026 {
1027 struct rist_data_block *output_buffer;
1028 if (output_buffer_current) {
1029 if (rist_ref_iswritable(output_buffer_current->ref)) {
1030 output_buffer = output_buffer_current;
1031 uint8_t *p = ((uint8_t*)output_buffer_current->payload - RIST_MAX_PAYLOAD_OFFSET);
1032 free(p);
1033 } else {
1034 free_data_block(&output_buffer_current);
1035 output_buffer = calloc(1, sizeof(*output_buffer));
1036 }
1037 }
1038 else
1039 output_buffer = calloc(1, sizeof(struct rist_data_block));
1040 if (!output_buffer) {
1041 rist_log_priv2(get_cctx(b->peer)->logging_settings, RIST_LOG_ERROR, "Error (re)allocating rist_data_block.");
1042 return NULL;
1043 }
1044 if (!output_buffer->ref) {
1045 output_buffer->ref = rist_ref_create(output_buffer);
1046 if (!output_buffer->ref) {
1047 rist_log_priv2(get_cctx(b->peer)->logging_settings, RIST_LOG_ERROR, "Error allocating rist_ref.");
1048 free(output_buffer);
1049 return NULL;
1050 }
1051 }
1052 output_buffer->peer = b->peer;
1053 output_buffer->flow_id = flow_id;
1054 output_buffer->payload = payload;
1055 output_buffer->payload_len = b->size;
1056 output_buffer->virt_src_port = b->src_port;
1057 output_buffer->virt_dst_port = b->dst_port;
1058 output_buffer->ts_ntp = b->source_time;
1059 output_buffer->seq = b->seq;
1060 output_buffer->flags = flags;
1061 return output_buffer;
1062 }
1063
1064 static void receiver_output(struct rist_receiver *ctx, struct rist_flow *f)
1065 {
1066
1067 uint64_t recovery_buffer_ticks = f->recovery_buffer_ticks;
1068 uint64_t now;
1069 if (RIST_LIKELY(!f->rtc_timing_mode))
1070 now = timestampNTP_u64();
1071 else
1072 now = timestampNTP_RTC_u64();
1073 size_t output_idx = atomic_load_explicit(&f->receiver_queue_output_idx, memory_order_acquire);
1074 while (atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire) > 0 && atomic_load_explicit(&f->shutdown, memory_order_acquire) == 0) {
1075 // Find the first non-null packet in the queuecounter loop
1076 struct rist_buffer *b = f->receiver_queue[output_idx];
1077 size_t holes = 0;
1078 if (!b) {
1079 //rist_log_priv(&ctx->common, RIST_LOG_ERROR, "\tLooking for first non-null packet (%zu)\n", f->receiver_queue_size);
1080 size_t counter = 0;
1081 counter = output_idx;
1082 while (!b) {
1083 counter = (counter + 1)& (f->receiver_queue_max -1);
1084 holes++;
1085 b = f->receiver_queue[counter];
1086 if (counter == output_idx) {
1087 // This should never happen, if this fires queue size is out of sync with reality.
1088 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Did not find any data after a full counter loop (%zu)\n", atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire));
1089 // if the entire buffer is empty, something is very wrong, reset the queue ...
1090 f->receiver_queue_has_items = false;
1091 atomic_store_explicit(&f->receiver_queue_size, 0, memory_order_release);
1092 // exit the function and wait 5ms (max jitter time)
1093 return;
1094 }
1095 }
1096 if (b) {
1097 uint64_t delay1 = (now - b->time);
1098 if (RIST_UNLIKELY(delay1 > (2LLU * recovery_buffer_ticks))) {
1099 // According to the real time clock, it is too late, continue.
1100 } else if (b->target_output_time > now) {
1101 // The block we found is not ready for output, so we wait.
1102 break;
1103 }
1104 }
1105 size_t max_holes = f->short_seq ? (UINT16_SIZE / 2) : (f->receiver_queue_max / 2);
1106 if (holes <= max_holes) {
1107 pthread_mutex_lock(&ctx->common.stats_lock);
1108 f->stats_instant.lost += holes;
1109 pthread_mutex_unlock(&ctx->common.stats_lock);
1110 }
1111 output_idx = counter;
1112 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1113 "Empty buffer element, flushing %"PRIu32" hole(s), now at index %zu, size is %zu\n",
1114 holes, counter, atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire));
1115 }
1116 if (b) {
1117 bool merged = false;
1118 if (b->type == RIST_PAYLOAD_TYPE_DATA_RAW) {
1119
1120 now = timestampNTP_u64();
1121 uint64_t delay_rtc = (now - b->time);
1122 if (RIST_UNLIKELY(delay_rtc > (1.1 * recovery_buffer_ticks) )) {
1123 // Double check the age of the packet within our receiver queue
1124 // Safety net for discontinuities in source timestamp, clock drift or improperly scaled timestamp
1125 uint64_t delay = now > b->packet_time ? (now - b->packet_time) : 0;
1126 bool drop = false;
1127 //This should be impossible as we should catch it with the normal case
1128 if (RIST_UNLIKELY(delay_rtc > (2ULL * recovery_buffer_ticks))) {
1129 f->too_late_ctr++;
1130 drop = true;
1131 if (f->too_late_ctr > 100) {
1132 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Too many old packets, resetting buffer\n");
1133 f->receiver_queue_has_items = false;
1134 return;
1135 }
1136 goto next;
1137 }
1138 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1139 "Packet %"PRIu32" (%zu bytes) is too old %"PRIu64"/%"PRIu64" ms, deadline = %"PRIu64", offset = %"PRId64" ms, %s data\n",
1140 b->seq, b->size,
1141 delay_rtc / RIST_CLOCK, delay / RIST_CLOCK,
1142 recovery_buffer_ticks / RIST_CLOCK, f->time_offset / RIST_CLOCK,
1143 drop? "dropping" : "releasing");
1144
1145 }
1146 else if (b->target_output_time > now && (!f->currently_scaling_buffer || (f->currently_scaling_buffer && (b->packet_time + f->recovery_buffer_ticks) > now))) {
1147 // This is how we keep the buffer at the correct level
1148 //rist_log_priv(&ctx->common, RIST_LOG_WARN, "age is %"PRIu64"/%"PRIu64" < %"PRIu64", size %zu\n",
1149 // delay_rtc / RIST_CLOCK , delay / RIST_CLOCK, recovery_buffer_ticks / RIST_CLOCK, f->receiver_queue_size);
1150 break;
1151 }
1152 if (holes > 0)
1153 {
1154 rist_log_priv(&ctx->common, RIST_LOG_DEBUG, "Did not find any data after %zu holes (%zu bytes in queue)\n",
1155 holes, atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire));
1156 }
1157 f->too_late_ctr = 0;
1158 // Check sequence number and report lost packet
1159 uint32_t next_seq = f->last_seq_output + 1;
1160 f->last_output_time = now;
1161 if (f->short_seq)
1162 next_seq = (uint16_t)next_seq;
1163 if (b->seq != next_seq && !holes) {
1164 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1165 "Discontinuity, expected %" PRIu32 " got %" PRIu32 "\n",
1166 f->last_seq_output + 1, b->seq);
1167 pthread_mutex_lock(&ctx->common.stats_lock);
1168 f->stats_instant.lost++;
1169 pthread_mutex_unlock(&ctx->common.stats_lock);
1170 holes = 1;
1171 }
1172 if (b->type == RIST_PAYLOAD_TYPE_DATA_RAW) {
1173 uint32_t flags = 0;
1174 if (holes)
1175 flags = RIST_DATA_FLAGS_DISCONTINUITY;
1176 if (f->flag_flow_buffer_start) {
1177 f->flag_flow_buffer_start = false;
1178 flags |= RIST_DATA_FLAGS_FLOW_BUFFER_START;
1179 }
1180
1181 bool merge_active = (ctx->merge_mode == LIBRIST_MERGE_MODE_PAIRS) ||
1182 (ctx->merge_mode == LIBRIST_MERGE_MODE_AUTO &&
1183 f->merge_auto_enabled);
1184
1185 struct rist_data_block *block = NULL;
1186
1187 if (merge_active && (b->seq & 1) == 0) {
1188 size_t partner_idx = (output_idx + 1) & (f->receiver_queue_max - 1);
1189 struct rist_buffer *b2 = f->receiver_queue[partner_idx];
1190 if (b2 && b2->type == RIST_PAYLOAD_TYPE_DATA_RAW &&
1191 b2->seq == rist_seq_next(b->seq, f->short_seq) &&
1192 b2->source_time == b->source_time) {
1193 size_t combined_len = b->size + b2->size;
1194 uint8_t *combined = malloc(RIST_MAX_PAYLOAD_OFFSET + combined_len);
1195 if (combined) {
1196 memcpy(combined + RIST_MAX_PAYLOAD_OFFSET,
1197 (uint8_t *)b->data + RIST_MAX_PAYLOAD_OFFSET, b->size);
1198 memcpy(combined + RIST_MAX_PAYLOAD_OFFSET + b->size,
1199 (uint8_t *)b2->data + RIST_MAX_PAYLOAD_OFFSET, b2->size);
1200 block = calloc(1, sizeof(*block));
1201 if (block) {
1202 block->ref = rist_ref_create(block);
1203 block->peer = b->peer;
1204 block->flow_id = f->flow_id;
1205 block->payload = combined + RIST_MAX_PAYLOAD_OFFSET;
1206 block->payload_len = combined_len;
1207 block->virt_src_port = b->src_port;
1208 block->virt_dst_port = b->dst_port;
1209 block->ts_ntp = b->source_time;
1210 block->seq = b->seq / 2;
1211 block->flags = flags;
1212 merged = true;
1213 ctx->stats_pairs_merged++;
1214 } else {
1215 free(combined);
1216 }
1217 }
1218 if (merged) {
1219 b->data = NULL;
1220 f->last_seq_output = b2->seq;
1221 atomic_fetch_sub_explicit(&f->receiver_queue_size, b2->size, memory_order_relaxed);
1222 f->receiver_queue[partner_idx] = NULL;
1223 free_rist_buffer(&ctx->common, b2);
1224 }
1225 } else {
1226 ctx->stats_orphan_first_delivered++;
1227 }
1228 } else if (merge_active && (b->seq & 1) == 1) {
1229 ctx->stats_orphan_last_delivered++;
1230 }
1231
1232 if (!merged) {
1233 uint8_t *payload = b->data;
1234 block = new_data_block(
1235 NULL, b,
1236 &payload[RIST_MAX_PAYLOAD_OFFSET], f->flow_id, flags);
1237 b->data = NULL;
1238 }
1239 if (ctx->receiver_data_fd >= 0 && block) {
1240 int written;
1241 if (ctx->receiver_data_fd_flags & RIST_DATA_FD_FLAG_TUN)
1242 written = rist_tun_write(ctx->receiver_data_fd, block->payload, block->payload_len);
1243 else
1244 written = (int)write(ctx->receiver_data_fd, block->payload, block->payload_len);
1245 if (written > 0) {
1246 atomic_fetch_add_explicit(&ctx->data_fd_rx_packets, 1, memory_order_relaxed);
1247 atomic_fetch_add_explicit(&ctx->data_fd_rx_bytes, (uint_fast64_t)written, memory_order_relaxed);
1248 }
1249 rist_receiver_data_block_free2(&block);
1250 } else if (ctx->receiver_data_callback && block) {
1251 rist_ref_inc(block->ref);
1252 // send to callback synchronously
1253 ctx->receiver_data_callback(ctx->receiver_data_callback_argument,
1254 block);
1255 }
1256
1257 size_t dataout_fifo_write_index = atomic_load_explicit(&f->dataout_fifo_queue_write_index, memory_order_relaxed);
1258 size_t dataout_fifo_read_index = atomic_load_explicit(&f->dataout_fifo_queue_read_index, memory_order_acquire);
1259 uint32_t fifo_count = (dataout_fifo_write_index - dataout_fifo_read_index)&(ctx->fifo_queue_size -1);
1260 if (fifo_count +1 == ctx->fifo_queue_size || !ctx->fifo_queue_size) {
1261 if (!ctx->receiver_data_callback && ctx->receiver_data_fd < 0)
1262 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Rist data out fifo queue overflow\n");
1263 rist_receiver_data_block_free2(&block);
1264 atomic_store_explicit(&f->fifo_overflow, true, memory_order_release);
1265 } else {
1266 if (RIST_UNLIKELY(atomic_load_explicit(&f->fifo_overflow, memory_order_relaxed) == true)) {
1267 atomic_store_explicit(&f->fifo_overflow, false, memory_order_release);
1268 }
1269 f->dataout_fifo_queue[dataout_fifo_write_index] = block;
1270 atomic_store_explicit(&f->dataout_fifo_queue_write_index, (dataout_fifo_write_index + 1)& (ctx->fifo_queue_size-1), memory_order_relaxed);
1271 // Wake up the fifo read thread (poll)
1272 if (ctx->receiver_data_ready_notify_fd) {
1273 // send a data ready signal by writing a single byte of value 0
1274 char empty = '\0';
1275 if(write(ctx->receiver_data_ready_notify_fd, &empty, 1) == -1)
1276 {
1277 // We ignore the error condition as missing data is not harmful here
1278 // It is only a signaling mechanism
1279 }
1280 }
1281 }
1282 pthread_mutex_lock(&ctx->common.stats_lock);
1283 if (f->stats_instant.buffer_duration_count < 2048)
1284 {
1285 f->stats_instant.buffer_duration[f->stats_instant.buffer_duration_count] = (uint32_t)(delay_rtc / RIST_CLOCK);
1286 f->stats_instant.buffer_duration_count++;
1287 }
1288 pthread_mutex_unlock(&ctx->common.stats_lock);
1289 if (pthread_cond_signal(&(ctx->condition)))
1290 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Call to pthread_cond_signal failed.\n");
1291 }
1292 // Track this one only for data
1293 f->last_seq_output_source_time = b->source_time;
1294 }
1295 //else
1296 // fprintf(stderr, "rtcp skip at %"PRIu32", just removing it from queue\n", b->seq);
1297
1298 next:
1299 if (!merged)
1300 f->last_seq_output = b->seq;
1301 atomic_fetch_sub_explicit(&f->receiver_queue_size, b->size, memory_order_relaxed);
1302 f->receiver_queue[output_idx] = NULL;
1303 free_rist_buffer(&ctx->common, b);
1304 output_idx = (output_idx + 1)& (f->receiver_queue_max -1);
1305 if (merged) {
1306 /* partner already freed and NULLed above; skip its slot */
1307 output_idx = (output_idx + 1) & (f->receiver_queue_max - 1);
1308 }
1309 atomic_store_explicit(&f->receiver_queue_output_idx, output_idx, memory_order_release);
1310 if (atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire) == 0) {
1311 if (f->last_output_time == 0)
1312 f->last_output_time = now;
1313 uint64_t delta = now - f->last_output_time;
1314 rist_log_priv(&ctx->common, RIST_LOG_DEBUG, "Buffer is empty, it has been for %"PRIu64" < %"PRIu64" (ms)!\n",
1315 delta / RIST_CLOCK, recovery_buffer_ticks / RIST_CLOCK);
1316 // if the entire buffer is empty, something is very wrong, reset the queue ...
1317 if (delta > recovery_buffer_ticks)
1318 {
1319 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "stream is dead (%"PRIu64" ms), re-initializing flow\n",
1320 delta/ RIST_CLOCK);
1321 f->receiver_queue_has_items = false;
1322 }
1323 // exit the function and wait 5ms (max jitter time)
1324 return;
1325 }
1326 f->last_output_time = now;
1327 }
1328 }
1329
1330 }
1331
1332 static void send_nack_group(struct rist_receiver *ctx, struct rist_flow *f)
1333 {
1334 // Now actually send all the nack IP packets for this flow (the above routing will process/group them)
1335 if (f->nacks.counter == 0)
1336 return;
1337 /* Lock order: peerlist_lock outside, f->mutex inside. */
1338 pthread_mutex_lock(&ctx->common.peerlist_lock);
1339 pthread_mutex_lock(&f->mutex);
1340 struct rist_peer *peer = NULL;
1341 uint64_t best_rtt = UINT64_MAX;
1342 uint32_t best_priority = 0;
1343 if (f->peer_lst_len == 0 || f->peer_lst == NULL)
1344 goto out;
1345 /* Route NACKs to the eligible peer with the highest recovery_priority,
1346 * tie-broken by lowest RTT. With the default priority of 0 on every
1347 * peer this reduces to the historical lowest-RTT selection. */
1348 for (size_t i = 0; i < f->peer_lst_len; i++)
1349 {
1350 struct rist_peer *check = f->peer_lst[i];
1351 if (!check->is_rtcp || check->dead)
1352 continue;
1353 uint32_t priority = check->config.recovery_priority;
1354 if (rist_nack_peer_preferred(priority, check->last_rtt,
1355 best_priority, best_rtt))
1356 {
1357 peer = check;
1358 best_priority = priority;
1359 best_rtt = check->last_rtt;
1360 }
1361 }
1362 if (peer != NULL)
1363 rist_receiver_send_nacks(peer,f->nacks.array, f->nacks.counter);
1364 else
1365 {
1366 for (size_t i = 0; i < f->peer_lst_len; i++)
1367 {
1368 struct rist_peer *check = f->peer_lst[i];
1369 uint64_t dead_since = 0;
1370 if (check->is_rtcp && check->dead_since > dead_since)
1371 {
1372 peer = check;
1373 }
1374 if (peer != NULL)
1375 rist_receiver_send_nacks(peer,f->nacks.array, f->nacks.counter);
1376 }
1377 }
1378 f->nacks.counter = 0;
1379 out:
1380 pthread_mutex_unlock(&f->mutex);
1381 pthread_mutex_unlock(&ctx->common.peerlist_lock);
1382 }
1383
1384 void receiver_nack_output(struct rist_receiver *ctx, struct rist_flow *f)
1385 {
1386
1387 if (!f->authenticated) {
1388 return;
1389 }
1390
1391 const size_t maxcounter = RIST_MAX_NACKS;
1392
1393 /* Now loop through missing queue and process items */
1394 struct rist_missing_buffer *mb = f->missing;
1395 struct rist_missing_buffer **prev = &f->missing;
1396 struct rist_missing_buffer *previous = NULL;
1397 int empty = 0;
1398 while (mb) {
1399 int remove_from_queue_reason = 0;
1400 struct rist_peer *peer = mb->peer;
1401 ssize_t idx = mb->seq& (f->receiver_queue_max -1);
1402 if (peer->config.recovery_mode == RIST_RECOVERY_MODE_DISABLED) {
1403 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1404 "Nack processing is disabled for this peer, removing seq %"PRIu32" from queue ...\n",
1405 mb->seq);
1406 remove_from_queue_reason = 10;
1407 f->stats_instant.missing--;
1408 goto nack_loop_continue;
1409 } else if (f->receiver_queue[idx]) {
1410 if (f->receiver_queue[idx]->seq == mb->seq) {
1411 pthread_mutex_lock(&ctx->common.stats_lock);
1412 // We filled in the hole already ... packet has been recovered
1413 remove_from_queue_reason = 3;
1414 if (mb->nack_count > 0)
1415 f->stats_instant.recovered++;
1416 switch(mb->nack_count) {
1417 case 0:
1418 break;
1419 case 1:
1420 f->stats_instant.recovered_0nack++;
1421 break;
1422 case 2:
1423 f->stats_instant.recovered_1nack++;
1424 break;
1425 case 3:
1426 f->stats_instant.recovered_2nack++;
1427 break;
1428 case 4:
1429 f->stats_instant.recovered_3nack++;
1430 break;
1431 default:
1432 f->stats_instant.recovered_morenack++;
1433 break;
1434 }
1435 f->stats_instant.recovered_sum += mb->nack_count;
1436 pthread_mutex_unlock(&ctx->common.stats_lock);
1437 }
1438 else {
1439 // Message with wrong seq!!!
1440 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1441 "Retry queue has the wrong seq %"PRIu32" != %"PRIu32", removing ...\n",
1442 f->receiver_queue[idx]->seq, mb->seq);
1443 remove_from_queue_reason = 4;
1444 pthread_mutex_lock(&ctx->common.stats_lock);
1445 f->stats_instant.missing--;
1446 pthread_mutex_unlock(&ctx->common.stats_lock);
1447 goto nack_loop_continue;
1448 }
1449 } else if (peer->buffer_bloat_active) {
1450 if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_AGGRESSIVE) {
1451 if (empty == 0) {
1452 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1453 "Retry queue is too large, %d, collapsed link (%u), flushing all nacks ...\n", f->missing_counter,
1454 f->stats_total.recovered_average/8);
1455 }
1456 remove_from_queue_reason = 5;
1457 empty = 1;
1458 } else if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_NORMAL) {
1459 if (mb->nack_count > 4) {
1460 if (empty == 0) {
1461 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1462 "Retry queue is too large, %d, collapsed link (%u), flushing old nacks (%u > %u) ...\n",
1463 f->missing_counter, f->stats_total.recovered_average/8, mb->nack_count, 4);
1464 }
1465 remove_from_queue_reason = 6;
1466 empty = 1;
1467 }
1468 }
1469 } else {
1470 // Packet is still missing, re-stamp the expiration time so we can re-add to queue
1471 // We reject the next retry for a number of reasons checked inside the function,
1472 // in which case the nack will never be resent and we signal a queue removal
1473 if (f->nacks.counter == (maxcounter - 1)) {
1474 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1475 "nack max counter per packet (%d) exceeded. Skipping the rest\n",
1476 maxcounter);
1477 send_nack_group(ctx, f);
1478 }
1479 else if (f->nacks.counter >= maxcounter) {
1480 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1481 "nack max counter per packet (%zu) exceeded. Something is very wrong and"
1482 " there is a strong chance memory is corrupt because we wrote past the end"
1483 "of the nacks.array max size!!!\n", f->nacks.counter );
1484 f->nacks.counter = 0;
1485 //TODO: maybe assert is more appropriate here?
1486 }
1487 remove_from_queue_reason = rist_process_nack(f, mb);
1488 }
1489 nack_loop_continue:
1490 if (remove_from_queue_reason != 0) {
1491 if (ctx->common.debug)
1492 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1493 "Removing seq %" PRIu32 " from missing, queue size is %d, retry #%u, age %"PRIu64"ms, reason %d\n",
1494 mb->seq, f->missing_counter, mb->nack_count, (timestampNTP_u64() - mb->insertion_time) / RIST_CLOCK, remove_from_queue_reason);
1495 struct rist_missing_buffer *next = mb->next;
1496 if (!next)
1497 f->missing_tail = previous;
1498 *prev = next;
1499 f->missing_counter--;
1500 free(mb);
1501 mb = next;
1502 } else {
1503 /* Move it to the end of the queue */
1504 // TODO: I think this is wrong and we loose nacks when we get here
1505 previous = mb;
1506 prev = &mb->next;
1507 mb = mb->next;
1508 }
1509 }
1510
1511 // Empty all peer nack queues, i.e. send them
1512 send_nack_group(ctx, f);
1513
1514 }
1515
1516 static int rist_set_manual_sockdata(struct rist_peer *peer, const struct rist_peer_config *config)
1517 {
1518 peer->address_family = (uint16_t)config->address_family;//TODO: should it not just be a uint16_t then?
1519 peer->listening = !config->initiate_conn;
1520 const char *hostname = config->address;
1521 int ret;
1522 if ((!hostname || !*hostname) && peer->listening) {
1523 if (peer->address_family == AF_INET) {
1524 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "No hostname specified: listening to 0.0.0.0\n");
1525 peer->address_len = sizeof(struct sockaddr_in);
1526 ((struct sockaddr_in *)&peer->u.address)->sin_family = AF_INET;
1527 ((struct sockaddr_in *)&peer->u.address)->sin_addr.s_addr = INADDR_ANY;
1528 } else {
1529 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "No hostname specified: listening to [::0]\n");
1530 peer->address_len = sizeof(struct sockaddr_in6);
1531 ((struct sockaddr_in6 *)&peer->u.address)->sin6_family = AF_INET6;
1532 ((struct sockaddr_in6 *)&peer->u.address)->sin6_addr = in6addr_any;
1533 }
1534 } else {
1535 ret = udpsocket_resolve_host(hostname, config->physical_port, &peer->u.address);
1536 if (ret != 0) {
1537 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Error trying to resolve hostname %s\n", hostname);
1538 goto err;
1539 }
1540 peer->address_family = ((struct sockaddr_in *)&peer->u.address)->sin_family;
1541 if (peer->address_family == AF_INET)
1542 peer->address_len = sizeof(struct sockaddr_in);
1543 else
1544 peer->address_len = sizeof(struct sockaddr_in6);
1545 }
1546 if (peer->listening)
1547 peer->local_port = config->physical_port;
1548 else
1549 peer->remote_port = config->physical_port;
1550
1551 return 0;
1552
1553 err:
1554 peer->address_family = AF_LOCAL;
1555 peer->address_len = 0;
1556 return -1;
1557 }
1558
1559
1560
1561 struct rist_peer *_librist_peer_create_common(struct rist_common_ctx *cctx, struct rist_receiver *rctx, struct rist_sender *sctx, const struct rist_peer_config *config)
1562 {
1563 int key_size = config->key_size;
1564 if (strlen(config->secret) && !key_size) {
1565 rist_log_priv(cctx, RIST_LOG_NOTICE, "PSK Set but key size not explicitly configured, defaulting to AES256");
1566 key_size = 256;
1567 }
1568 if (key_size) {
1569 if (key_size != 128 && key_size != 192 && key_size != 256) {
1570 rist_log_priv(cctx, RIST_LOG_ERROR, "Invalid encryption key length: %d\n", key_size);
1571 return NULL;
1572 }
1573 if (!strlen(config->secret)) {
1574
1575 rist_log_priv(cctx, RIST_LOG_ERROR, "Invalid secret passphrase\n");
1576 return NULL;
1577 }
1578 rist_log_priv(cctx, RIST_LOG_INFO, "Using %d bits secret key\n", key_size);
1579 }
1580 else {
1581 rist_log_priv(cctx, RIST_LOG_INFO, "Encryption is disabled for this peer\n");
1582 }
1583
1584 /* Initialize peer */
1585 struct rist_peer *p = peer_initialize(config->address, sctx, rctx);
1586 if (!p) {
1587 return NULL;
1588 }
1589
1590 strncpy(&p->miface[0], config->miface, RIST_MAX_STRING_SHORT);
1591 p->miface[RIST_MAX_STRING_SHORT - 1] = '\0';
1592 strncpy(&p->cname[0], config->cname, RIST_MAX_STRING_SHORT);
1593 p->cname[RIST_MAX_STRING_SHORT - 1] = '\0';
1594 if (config->address_family && rist_set_manual_sockdata(p, config)) {
1595 free(p);
1596 return NULL;
1597 }
1598
1599 _librist_crypto_psk_rist_key_init(&p->key_tx, key_size, config->key_rotation, config->secret, false);
1600 _librist_crypto_psk_rist_key_init(&p->key_tx_odd, key_size, config->key_rotation, config->secret, true);
1601 _librist_crypto_psk_rist_key_clone(&p->key_tx, &p->key_rx);
1602 _librist_crypto_psk_rist_key_clone(&p->key_tx_odd, &p->key_rx_odd);
1603
1604 if (config->keepalive_interval > 0) {
1605 p->rtcp_keepalive_interval = config->keepalive_interval * RIST_CLOCK;
1606 }
1607
1608 if (config->session_timeout > 0) {
1609 if (config->session_timeout < 250) {
1610 rist_log_priv(cctx, RIST_LOG_WARN, "The configured (%d ms) peer session timeout is too small, using %d ms instead\n",
1611 config->session_timeout, 250);
1612 p->session_timeout = 250 * RIST_CLOCK;
1613 }
1614 else
1615 p->session_timeout = config->session_timeout * RIST_CLOCK;
1616 }
1617 else {
1618 p->session_timeout = 250 * RIST_CLOCK;
1619 }
1620
1621 if (cctx->profile > RIST_PROFILE_SIMPLE) {
1622 if (_librist_network_get_macaddr(p->mac_addr) < 0)
1623 rist_log_priv(cctx, RIST_LOG_WARN, "Couldn't get a mac address for peer, keepalive will not contain a mac address\n");
1624 }
1625 /* Initialize socket */
1626 rist_create_socket(p);
1627 if (p->sd < 0) {
1628 rist_log_priv(cctx, RIST_LOG_ERROR, "Could not create socket\n");
1629 free(p);
1630 return NULL;
1631 }
1632 store_peer_settings(config, p);
1633 return p;
1634 }
1635
1636 struct rist_peer *rist_receiver_peer_insert_local(struct rist_receiver *ctx,
1637 const struct rist_peer_config *config)
1638 {
1639 struct rist_peer *p = _librist_peer_create_common(&ctx->common, ctx, NULL, config);
1640 if (!p)
1641 return NULL;
1642 if (config->virt_dst_port != 0) {
1643 p->remote_port = config->virt_dst_port + 1;
1644 }
1645
1646 p->adv_peer_id = ++ctx->common.peer_counter;
1647 return p;
1648 }
1649
1650 /* PEERS are created at startup. The default state is RIST_PEER_STATE_IDLE
1651 * This function will initiate the connection to the peer if a peer address is available.
1652 * If no address is configured for the endpoint, the peer is put in wait mode.
1653 */
1654 void rist_fsm_init_comm(struct rist_peer *peer)
1655 {
1656
1657 peer->authenticated = false;
1658
1659 if (!peer->receiver_mode) {
1660 if (peer->listening) {
1661 /* sender mode listening/waiting for receiver */
1662 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1663 "Initialized Sender Peer, listening mode ...\n");
1664 } else {
1665 /* sender mode connecting to receiver */
1666 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1667 "Initialized Sender Peer, connecting to receiver ...\n");
1668 }
1669 } else {
1670 if (peer->listening) {
1671 /* receiver mode listening/waiting for sender */
1672 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1673 "Initialized Receiver Peer, listening mode ...\n");
1674 } else {
1675 /* receiver mode connecting to sender */
1676 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1677 "Initialized Receiver Peer, connecting to sender ...\n");
1678 }
1679 }
1680 peer->authenticated = false;
1681 rist_print_inet_info("Active ", peer);
1682
1683 /* Start the timer that reads data from this peer */
1684 if (!peer->event_recv) {
1685 struct evsocket_ctx *evctx = get_cctx(peer)->evctx;
1686 peer->event_recv = evsocket_addevent(evctx, peer->sd, EVSOCKET_EV_READ,
1687 rist_peer_recv_wrap, rist_peer_sockerr, peer);
1688 }
1689
1690 /* Enable RTCP timer and jump start it */
1691 if (!peer->listening && peer->is_rtcp) {
1692 if (!peer->send_keepalive) {
1693 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Enabling keepalive for peer %"PRIu32"\n", peer->adv_peer_id);
1694 peer->send_keepalive = true;
1695 }
1696 if (get_cctx(peer)->profile > RIST_PROFILE_SIMPLE && !peer->eap_ctx) {
1697 //Try version 2 first
1698 _librist_proto_gre_send_keepalive(peer, 2);
1699 _librist_proto_gre_send_keepalive(peer, 2);
1700 _librist_proto_gre_send_keepalive(peer, 2);
1701 _librist_proto_gre_send_keepalive(peer, 1);
1702 _librist_proto_gre_send_keepalive(peer, 1);
1703 _librist_proto_gre_send_keepalive(peer, 1);
1704 if (peer->sender_ctx != NULL) {
1705 _librist_proto_gre_send_buffer_negotiation(peer, peer->sender_ctx->sender_recover_min_time, 0);
1706 _librist_proto_gre_send_buffer_negotiation(peer, peer->sender_ctx->sender_recover_min_time, 0);
1707 _librist_proto_gre_send_buffer_negotiation(peer, peer->sender_ctx->sender_recover_min_time, 0);
1708 }
1709 }
1710 /* call it the first time manually to speed up the handshake */
1711 rist_peer_rtcp(NULL, peer);
1712 /* send 3 echo requests to jumpstart accurate RTT calculation */
1713 rist_request_echo(peer);
1714 rist_request_echo(peer);
1715 rist_request_echo(peer);
1716 }
1717 }
1718
1719 void rist_peer_authenticate(struct rist_peer *peer)
1720 {
1721 peer->authenticated = true;
1722 if (peer->peer_data)
1723 peer->peer_data->authenticated = true;
1724
1725 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1726 "Successfully Authenticated peer %"PRIu32"\n", peer->adv_peer_id);
1727 }
1728
1729 void rist_calculate_bitrate(size_t len, struct rist_bandwidth_estimation *bw)
1730 {
1731 struct timeval tv;
1732 gettimeofday(&tv, NULL);
1733 uint64_t now = (uint64_t)tv.tv_sec * 1000000;
1734 now += tv.tv_usec;
1735 uint64_t time = now - bw->last_bitrate_calctime;
1736 uint64_t time_fast = now - bw->last_bitrate_calctime_fast;
1737
1738 if (!bw->last_bitrate_calctime) {
1739 bw->last_bitrate_calctime = now;
1740 bw->last_bitrate_calctime_fast = now;
1741 bw->eight_times_bitrate = 0;
1742 bw->eight_times_bitrate_fast = 0;
1743 bw->bytes = 0;
1744 bw->bytes_fast = 0;
1745 bw->bitrate = 0;
1746 bw->bitrate_fast = 0;
1747 return;
1748 }
1749
1750 if (time_fast < 100000 /* 100 ms */) {
1751 bw->bytes_fast += len;
1752 }
1753 else {
1754 bw->bytes_fast += len;
1755 bw->bitrate_fast = (size_t)((8 * bw->bytes_fast * 1000000) / time_fast);
1756 bw->eight_times_bitrate_fast += bw->bitrate_fast - bw->eight_times_bitrate_fast / 8;
1757 bw->last_bitrate_calctime_fast = now;
1758 bw->bytes_fast = 0;
1759 }
1760
1761 if (time < 1000000 /* 1 second */) {
1762 bw->bytes += len;
1763 return;
1764 }
1765 else {
1766 bw->bytes += len;
1767 bw->bitrate = (size_t)((8 * bw->bytes * 1000000) / time);
1768 bw->eight_times_bitrate += bw->bitrate - bw->eight_times_bitrate / 8;
1769 bw->last_bitrate_calctime = now;
1770 bw->bytes = 0;
1771 }
1772 }
1773
1774 /* Recompute bw->bitrate using zero new bytes so the value decays to
1775 * zero when the stats tick fires but no packets have arrived on this
1776 * counter since the last tick. Mirrors what rist_calculate_bitrate(0,
1777 * ...) does for peer-side counters, deliberately skipping the per-flow
1778 * inter-packet-spacing bookkeeping that lives in
1779 * rist_calculate_flow_bitrate(). */
1780 void rist_refresh_flow_bitrate(struct rist_bandwidth_estimation *bw)
1781 {
1782 if (!bw->last_bitrate_calctime)
1783 return;
1784
1785 struct timeval tv;
1786 gettimeofday(&tv, NULL);
1787 uint64_t now = (uint64_t)tv.tv_sec * 1000000;
1788 now += tv.tv_usec;
1789
1790 uint64_t time_fast = now - bw->last_bitrate_calctime_fast;
1791 if (time_fast >= 100000 /* 100 ms */) {
1792 bw->bitrate_fast = (size_t)((8 * bw->bytes_fast * 1000000) / time_fast);
1793 bw->eight_times_bitrate_fast += bw->bitrate_fast - bw->eight_times_bitrate_fast / 8;
1794 bw->last_bitrate_calctime_fast = now;
1795 bw->bytes_fast = 0;
1796 }
1797
1798 uint64_t time = now - bw->last_bitrate_calctime;
1799 if (time >= 1000000 /* 1 second */) {
1800 bw->bitrate = (size_t)((8 * bw->bytes * 1000000) / time);
1801 bw->eight_times_bitrate += bw->bitrate - bw->eight_times_bitrate / 8;
1802 bw->last_bitrate_calctime = now;
1803 bw->bytes = 0;
1804 }
1805 }
1806
1807 static void rist_calculate_flow_bitrate(struct rist_flow *flow, size_t len, struct rist_bandwidth_estimation *bw)
1808 {
1809 struct timeval tv;
1810 gettimeofday(&tv, NULL);
1811 uint64_t now = (uint64_t)tv.tv_sec * 1000000;
1812 now += tv.tv_usec;
1813 uint64_t time = now - bw->last_bitrate_calctime;
1814 uint64_t time_fast = now - bw->last_bitrate_calctime_fast;
1815
1816 if (!bw->last_bitrate_calctime) {
1817 bw->last_bitrate_calctime = now;
1818 bw->eight_times_bitrate = 0;
1819 bw->bitrate = 0;
1820 bw->bytes = 0;
1821 bw->eight_times_bitrate_fast = 0;
1822 bw->bitrate_fast = 0;
1823 bw->bytes_fast = 0;
1824 return;
1825 }
1826
1827 if (flow->last_ipstats_time == 0ULL) {
1828 // Initial values
1829 flow->stats_instant.cur_ips = 0ULL;
1830 flow->stats_instant.min_ips = 0xFFFFFFFFFFFFFFFFULL;
1831 flow->stats_instant.max_ips = 0ULL;
1832 flow->stats_instant.avg_count = 0UL;
1833 } else {
1834 flow->stats_instant.cur_ips = now - flow->last_ipstats_time;
1835 /* Set new min */
1836 if (flow->stats_instant.cur_ips < flow->stats_instant.min_ips)
1837 flow->stats_instant.min_ips = flow->stats_instant.cur_ips;
1838 /* Set new max */
1839 if (flow->stats_instant.cur_ips > flow->stats_instant.max_ips)
1840 flow->stats_instant.max_ips = flow->stats_instant.cur_ips;
1841
1842 /* Avg calculation */
1843 flow->stats_instant.total_ips += flow->stats_instant.cur_ips;
1844 flow->stats_instant.avg_count++;
1845 }
1846 flow->last_ipstats_time = now;
1847
1848
1849 if (time_fast < 100000 /* 100 ms */) {
1850 bw->bytes_fast += len;
1851 }
1852 else {
1853 bw->bitrate_fast = (size_t)((8 * bw->bytes_fast * 1000000) / time_fast);
1854 bw->eight_times_bitrate_fast += bw->bitrate_fast - bw->eight_times_bitrate_fast / 8;
1855 bw->last_bitrate_calctime_fast = now;
1856 bw->bytes_fast = 0;
1857 }
1858
1859 if (time < 1000000 /* 1 second */) {
1860 bw->bytes += len;
1861 return;
1862 }
1863 else {
1864 bw->bitrate = (size_t)((8 * bw->bytes * 1000000) / time);
1865 bw->eight_times_bitrate += bw->bitrate - bw->eight_times_bitrate / 8;
1866 bw->last_bitrate_calctime = now;
1867 bw->bytes = 0;
1868 }
1869 }
1870
1871 static void rist_sender_recv_nack(struct rist_peer *peer,
1872 uint32_t flow_id, uint16_t src_port, uint16_t dst_port, const uint8_t *payload,
1873 size_t payload_len, uint32_t nack_seq_msb)
1874 {
1875 RIST_MARK_UNUSED(flow_id);
1876 RIST_MARK_UNUSED(src_port);
1877 RIST_MARK_UNUSED(dst_port);
1878
1879 assert(payload_len >= sizeof(struct rist_rtcp_hdr));
1880
1881 if (peer->receiver_mode) {
1882 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
1883 "Received nack packet on receiver, ignoring ...\n");
1884 return;
1885 } else if (!peer->authenticated) {
1886 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
1887 "Received nack packet but handshake is still pending, ignoring ...\n");
1888 return;
1889 }
1890 assert(peer->sender_ctx != NULL);
1891
1892 struct rist_rtcp_hdr *rtcp = (struct rist_rtcp_hdr *) payload;
1893 uint32_t i,j;
1894
1895 if ((rtcp->flags & 0xc0) != 0x80) {
1896 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Malformed nack packet flags=%d.\n", rtcp->flags);
1897 return;
1898 }
1899
1900 if (rtcp->ptype == PTYPE_NACK_CUSTOM) {
1901 if (payload_len < sizeof(struct rist_rtcp_nack_range))
1902 return;
1903 struct rist_rtcp_nack_range *rtcp_nack = (struct rist_rtcp_nack_range *) payload;
1904 if (memcmp(rtcp_nack->name, "RIST", 4) != 0) {
1905 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Non-Rist nack packet (%.4s).\n", rtcp_nack->name);
1906 return; /* Ignore app-type not RIST */
1907 }
1908 uint16_t raw_len = ntohs(rtcp->len);
1909 if (raw_len < 2)
1910 return;
1911 uint16_t nrecords = raw_len - 2;
1912 size_t needed = sizeof(struct rist_rtcp_nack_range) + (size_t)nrecords * sizeof(struct rist_rtp_nack_record);
1913 if (needed > payload_len)
1914 return;
1915 //rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Nack (RbRR), %d record(s)\n", nrecords);
1916 for (i = 0; i < nrecords; i++) {
1917 uint16_t missing;
1918 uint16_t additional;
1919 struct rist_rtp_nack_record *nr = (struct rist_rtp_nack_record *)(payload + sizeof(struct rist_rtcp_nack_range) + i * sizeof(struct rist_rtp_nack_record));
1920 missing = ntohs(nr->start);
1921 additional = ntohs(nr->extra);
1922 rist_retry_enqueue(peer->sender_ctx, nack_seq_msb + (uint32_t)missing, peer);
1923 //rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Record %"PRIu32": base packet: %"PRIu32" range len: %d\n", i, nack_seq_msb + missing, additional);
1924 for (j = 0; j < additional; j++) {
1925 rist_retry_enqueue(peer->sender_ctx, nack_seq_msb + (uint32_t)missing + j + 1, peer);
1926 }
1927 }
1928 } else if (rtcp->ptype == PTYPE_NACK_BITMASK) {
1929 struct rist_rtcp_nack_bitmask *rtcp_nack = (struct rist_rtcp_nack_bitmask *) payload;
1930 (void)rtcp_nack;
1931 uint16_t raw_len = ntohs(rtcp->len);
1932 if (raw_len < 2)
1933 return;
1934 uint16_t nrecords = raw_len - 2;
1935 size_t needed = sizeof(struct rist_rtcp_nack_bitmask) + (size_t)nrecords * sizeof(struct rist_rtp_nack_record);
1936 if (needed > payload_len)
1937 return;
1938 //rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Nack (BbRR), %d record(s)\n", nrecords);
1939 for (i = 0; i < nrecords; i++) {
1940 uint16_t missing;
1941 uint16_t bitmask;
1942 struct rist_rtp_nack_record *nr = (struct rist_rtp_nack_record *)(payload + sizeof(struct rist_rtcp_nack_bitmask) + i * sizeof(struct rist_rtp_nack_record));
1943 missing = ntohs(nr->start);
1944 bitmask = ntohs(nr->extra);
1945 rist_retry_enqueue(peer->sender_ctx, nack_seq_msb + (uint32_t)missing, peer);
1946 //rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Record %"PRIu32": base packet: %"PRIu32" bitmask: %04x\n", i, nack_seq_msb + missing, bitmask);
1947 for (j = 0; j < 16; j++) {
1948 if ((bitmask & (1 << j)) == (1 << j))
1949 rist_retry_enqueue(peer->sender_ctx, nack_seq_msb + missing + j + 1, peer);
1950 }
1951 }
1952 } else {
1953 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Unsupported Type %d\n", rtcp->ptype);
1954 }
1955
1956 }
1957
1958 static bool address_compare(struct sockaddr* addr1, struct sockaddr* addr2) {
1959 if (addr1->sa_family != addr2->sa_family)
1960 return false;
1961 if (addr1->sa_family == AF_INET) {
1962 struct sockaddr_in *sa, *sb;
1963 sa = (struct sockaddr_in *)addr1;
1964 sb = (struct sockaddr_in *)addr2;
1965 return !(sa->sin_addr.s_addr - sb->sin_addr.s_addr);
1966 } else if (addr1->sa_family == AF_INET6) {
1967 struct sockaddr_in6 *sa, *sb;
1968 sa = (struct sockaddr_in6 *)addr1;
1969 sb = (struct sockaddr_in6 *)addr2;
1970 return !(memcmp(&sa->sin6_addr, &sb->sin6_addr, sizeof(sa->sin6_addr)));
1971 }
1972 return false;
1973 }
1974
1975 static bool rist_receiver_data_authenticate(struct rist_peer *peer,uint64_t packet_recv_time, uint32_t flow_id)
1976 {
1977 struct rist_receiver *ctx = peer->receiver_ctx;
1978
1979 if (ctx->common.profile == RIST_PROFILE_SIMPLE && !peer->authenticated)
1980 {
1981 //assert(0);
1982 if (peer->parent->peer_rtcp && peer->parent->peer_rtcp->authenticated) {
1983 peer->flow = peer->parent->peer_rtcp->flow;
1984 /* find correct rtcp */
1985 peer->peer_rtcp = NULL;
1986 struct rist_peer *tmp = peer->parent->peer_rtcp->child;
1987 uint16_t rtcp_port = peer->local_port+1;
1988 while (tmp) {
1989 if (tmp->is_rtcp) {
1990 if (tmp->local_port == rtcp_port && peer->adv_flow_id == tmp->adv_flow_id && address_compare(&peer->u.address, &tmp->u.address)) {
1991 if (tmp->dead)
1992 {
1993 tmp = tmp->sibling_next;
1994 continue;
1995 }
1996 peer->peer_rtcp = tmp;
1997 tmp->peer_data = peer;
1998 break;
1999 }
2000 }
2001 tmp = tmp->sibling_next;
2002 }
2003 if (!peer->peer_rtcp) {
2004 tmp = peer->parent->peer_rtcp->child;
2005 while (tmp) {
2006 if (tmp->is_rtcp) {
2007 if (tmp->local_port == rtcp_port && address_compare(&peer->u.address, &tmp->u.address)) {
2008 if (tmp->dead)
2009 {
2010 tmp = tmp->sibling_next;
2011 continue;
2012 }
2013 peer->peer_rtcp = tmp;
2014 tmp->peer_data = peer;
2015 break;
2016 }
2017 }
2018 tmp = tmp->sibling_next;
2019 }
2020 }
2021 peer->adv_flow_id = flow_id; // store the original ssrc here
2022 rist_peer_authenticate(peer);
2023 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2024 "Authenticated RTP peer %d and ssrc %"PRIu32" for connection with flowid %"PRIu32"\n",
2025 peer->adv_peer_id, peer->adv_flow_id, peer->flow->flow_id);
2026 } else {
2027 if (packet_recv_time > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
2028 rist_log_priv(&ctx->common, RIST_LOG_WARN,
2029 "Received data packet (%"PRIu32") but handshake is still pending (waiting for an RTCP packet with SDES on it), ignoring ...\n",
2030 flow_id);
2031 peer->log_repeat_timer = packet_recv_time;
2032 }
2033 return false;
2034 }
2035 }
2036 else if (ctx->common.profile > RIST_PROFILE_SIMPLE) {
2037 if (!peer->authenticated) {
2038 // rist_peer_authenticate is done during rtcp authentication (same peer)
2039 rist_log_priv(&ctx->common, RIST_LOG_WARN,
2040 "Received data packet (%"PRIu32") but handshake is still pending (waiting for an RTCP packet with SDES on it), ignoring ...\n",
2041 flow_id);
2042 return false;
2043 } else if (!peer->peer_rtcp) {
2044 peer->peer_rtcp = peer;
2045 peer->adv_flow_id = flow_id; // store the original ssrc here
2046 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2047 "Authenticated RTP peer %d and ssrc %"PRIu32" for connection with flowid %"PRIu32"\n",
2048 peer->adv_peer_id, peer->adv_flow_id, peer->peer_rtcp->adv_flow_id);
2049 }
2050 }
2051
2052 if (!peer->flow) {
2053 rist_log_priv(&ctx->common, RIST_LOG_WARN,
2054 "Received data packet but this peer (%d) is not associated with a flow, ignoring ...\n",
2055 peer->adv_peer_id);
2056 return false;
2057 } else if (!peer->flow->authenticated) {
2058 rist_log_priv(&ctx->common, RIST_LOG_WARN,
2059 "Flow %"PRIu32" has not yet been authenticated by an RTCP peer, %"PRIu32"!\n", flow_id);
2060 return false;
2061 }
2062 if (peer->parent && ctx->common.profile == RIST_PROFILE_SIMPLE)
2063 peer->parent->authenticated = true;
2064 return true;
2065 }
2066
2067 static bool rist_receiver_rtcp_authenticate(struct rist_peer *peer, uint32_t seq,
2068 uint32_t flow_id)
2069 {
2070 RIST_MARK_UNUSED(seq);
2071 assert(peer->receiver_ctx != NULL);
2072 struct rist_receiver *ctx = peer->receiver_ctx;
2073
2074 if (!strlen(peer->receiver_name)) {
2075 snprintf(peer->receiver_name, 128, "empty-sdes-name peer id#%i", peer->adv_peer_id);
2076 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Peer has empty cname in SDES packet, generating default name");
2077 }
2078
2079 // Check to see if this peer's flowid changed
2080 // (sender was restarted and we are in callback mode or sender happened to reuse the same port)
2081 if (peer->flow && (flow_id != peer->flow->flow_id)) {
2082 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Updating peer's flowid %"PRIu32"->%"PRIu32" (%zu)\n", peer->flow->flow_id, flow_id, peer->flow->peer_lst_len);
2083 if (peer->flow->peer_lst_len > 1) {
2084 remove_peer_from_flow(peer);
2085 }
2086 else {
2087 // Delete the flow and all of its resources
2088 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2089 "Old flow (%"PRIu32") has no peers left, deleting ...\n", peer->flow->flow_id);
2090 rist_delete_flow(ctx, peer->flow);
2091 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2092 "Old flow deletion complete\n");
2093 }
2094 // Reset the peer parameters
2095 peer->authenticated = false;
2096 peer->flow = NULL;
2097 }
2098
2099 if (!peer->authenticated) {
2100
2101 // the peer could already be part of a flow and it came back after timing out
2102 if (!peer->flow) {
2103 if (rist_receiver_associate_flow(peer, flow_id) != 1) {
2104 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Could not create/associate peer to flow.\n");
2105 return false;
2106 }
2107 if (ctx->common.profile == RIST_PROFILE_SIMPLE && peer->parent->peer_data->authenticated)
2108 {
2109 /* find correct data */
2110 struct rist_peer *tmp = peer->parent->peer_data->child;
2111 peer->is_data = false;
2112 peer->peer_data = NULL;
2113 peer->is_rtcp = true;
2114 uint16_t data_port = peer->local_port -1;
2115 while (tmp) {
2116 if (tmp->is_data) {
2117 if (tmp->local_port == data_port && peer->adv_flow_id == tmp->adv_flow_id && address_compare(&peer->u.address, &tmp->u.address)) {
2118 if (tmp->dead)
2119 {
2120 tmp = tmp->sibling_next;
2121 continue;
2122 }
2123 peer->peer_data = tmp;
2124 tmp->peer_rtcp = peer;
2125 break;
2126 }
2127 }
2128 tmp = tmp->sibling_next;
2129 }
2130 if (!peer->peer_data) {
2131 tmp = peer->parent->peer_data->child;
2132 while (tmp) {
2133 if (tmp->is_data) {
2134 if (tmp->local_port == data_port && address_compare(&peer->u.address, &tmp->u.address)) {
2135 if (tmp->dead)
2136 {
2137 tmp = tmp->sibling_next;
2138 continue;
2139 }
2140 peer->peer_data = tmp;
2141 tmp->peer_rtcp = peer;
2142 break;
2143 }
2144 }
2145 tmp = tmp->sibling_next;
2146 }
2147 }
2148 //randomly associate with first data peer without rtcp peer (ignores IP matching requirement)
2149 if (!peer->peer_data) {
2150 tmp = peer->parent->peer_data->child;
2151 while (tmp) {
2152 if (tmp->is_data) {
2153 if (tmp->local_port == data_port && tmp->peer_rtcp == NULL) {
2154 peer->peer_data = tmp;
2155 tmp->peer_rtcp = peer;
2156 break;
2157 }
2158 }
2159 tmp = tmp->sibling_next;
2160 }
2161 }
2162 peer->authenticated = true;
2163 return true;
2164 }
2165 }
2166
2167 if (peer->flow) {
2168 // We do multiple ifs to make these checks stateless
2169 pthread_mutex_lock(&peer->flow->mutex);
2170 if (!peer->flow->receiver_thread_running) {
2171 // Make sure this data out thread is created only once per flow
2172 if (rist_thread_create(&ctx->common, &peer->flow->receiver_thread, NULL, receiver_pthread_dataout, (void *)peer->flow) != 0) {
2173 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
2174 "Could not created receiver data output thread.\n");
2175 return false;
2176 }
2177 peer->flow->receiver_thread_running = true;
2178 }
2179 pthread_mutex_unlock(&peer->flow->mutex);
2180 rist_peer_authenticate(peer);
2181 peer->flow->authenticated = true;
2182 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2183 "Authenticated RTCP peer %d and flow %"PRIu32" for connection with cname: %s\n",
2184 peer->adv_peer_id, peer->adv_flow_id, peer->receiver_name);
2185 if (ctx->common.profile == RIST_PROFILE_SIMPLE)
2186 {
2187 peer->parent->authenticated = true;
2188 if (peer->parent->flow == NULL) {
2189 peer->parent->flow = peer->flow;
2190 peer->parent->flow->authenticated = true;
2191 }
2192 }
2193 }
2194 }
2195
2196 // The flow is added after we completed authentication
2197 if (peer->flow) {
2198 return true;
2199 } else {
2200 return false;
2201 }
2202 }
2203
2204 static void rist_receiver_recv_data(struct rist_peer *peer, uint32_t seq, uint32_t flow_id,
2205 uint64_t source_time, uint64_t packet_recv_time, struct rist_buffer *payload, uint8_t retry, uint8_t payload_type, size_t ingest_size, size_t ts_null_bytes, bool pkt_short_seq)
2206 {
2207 assert(peer->receiver_ctx != NULL);
2208 struct rist_receiver *ctx = peer->receiver_ctx;
2209
2210 if (!rist_receiver_data_authenticate(peer, packet_recv_time, flow_id)) {
2211 // Error logging happens inside the function
2212 return;
2213 }
2214
2215 /* Advanced contexts default to 32-bit framing but interoperate with a
2216 * Main-framed (16-bit) source: track the actual wire framing of the data
2217 * so the seq/wrap math matches. Simple/Main are always 16-bit.
2218 *
2219 * TR-06-3 Section 9 lets a flow switch framing mid-stream (Main->Advanced
2220 * upgrade once the peer advertises I=1, or a legacy Main-only source that
2221 * never upgrades). The two framings carry different seq widths AND
2222 * timestamp encodings, so mixing them in one flow corrupts the timing
2223 * baseline. Treat a framing change like a flow-id change: drop the old
2224 * baseline so the next enqueue re-derives time_offset and the seq->idx
2225 * mapping from the new framing instead of blending the two. */
2226 if (ctx->common.profile >= RIST_PROFILE_ADVANCED && peer->flow &&
2227 peer->flow->short_seq != pkt_short_seq) {
2228 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2229 "Flow %u wire framing changed to %s sequence numbers, "
2230 "resetting flow timing baseline\n",
2231 peer->flow->flow_id, pkt_short_seq ? "16-bit" : "32-bit");
2232 peer->flow->short_seq = pkt_short_seq;
2233 peer->flow->receiver_queue_has_items = false;
2234 }
2235
2236 //rist_log_priv(&ctx->common, RIST_LOG_ERROR,
2237 // "rist_recv_data, seq %"PRIu32", retry=%d\n", seq, retry);
2238
2239 // Just some debug output
2240 // if ((seq - peer->flow->last_seq_output) != 1)
2241 // rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Received seq %"PRIu32" and last %"PRIu32"\n\n\n", seq, peer->flow->last_seq_output);
2242
2243 /**************** WIP *****************/
2244 /* * * * * * * * * * * * * * * * * * * */
2245 /** Heuristics for receiver * * * * * */
2246 /* * * * * * * * * * * * * * * * * * * */
2247 /**************** WIP *****************/
2248 peer->stats_receiver_instant.received++;
2249 peer->stats_receiver_instant.received_bytes += (uint64_t)ingest_size;
2250
2251 uint64_t rtt;
2252 rtt = peer->eight_times_rtt / 8;
2253 if (rtt < peer->config.recovery_rtt_min) {
2254 rtt = peer->config.recovery_rtt_min;
2255 }
2256 else if (rtt > peer->config.recovery_rtt_max) {
2257 rtt = peer->config.recovery_rtt_max;
2258 }
2259 // Optimal dynamic time for first retry (reorder buffer) is rtt/2
2260 rtt = rtt / 2;
2261 if (rtt < peer->config.recovery_reorder_buffer)
2262 {
2263 rtt = peer->config.recovery_reorder_buffer;
2264 }
2265
2266 if (peer->peer_rtcp != NULL &&
2267 peer->peer_ssrc != peer->peer_rtcp->peer_ssrc &&
2268 peer->flow->flow_id_actual != flow_id)
2269 {
2270 rist_log_priv(&ctx->common, RIST_LOG_NOTICE,
2271 "Detected flow id change, old flow id: %u new id: %u, "
2272 "resetting state\n",
2273 peer->flow->flow_id_actual, flow_id);
2274 peer->flow->receiver_queue_has_items = false;
2275 peer->flow->flow_id_actual = flow_id;
2276 }
2277
2278 // Wake up output thread when data comes in
2279 if (pthread_cond_signal(&(peer->flow->condition)))
2280 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Call to pthread_cond_signal failed.\n");
2281 if (!receiver_enqueue(peer, source_time, packet_recv_time, payload->data, payload->size, seq, rtt, retry, payload->src_port, payload->dst_port, payload_type)) {
2282 pthread_mutex_lock(&ctx->common.stats_lock);
2283 // bitrate only if not a dupe or other failures
2284 if (retry)
2285 rist_calculate_flow_bitrate(peer->flow, ingest_size, &peer->flow->bw_retries);
2286 else
2287 rist_calculate_flow_bitrate(peer->flow, ingest_size, &peer->flow->bw);
2288 rist_calculate_flow_bitrate(peer->flow, ts_null_bytes, &peer->flow->bw_tsnull);
2289 pthread_mutex_unlock(&ctx->common.stats_lock);
2290 }
2291 else
2292 {
2293 pthread_mutex_lock(&ctx->common.stats_lock);
2294 if (retry)
2295 rist_calculate_flow_bitrate(peer->flow, ingest_size, &peer->flow->bw_retries);
2296 else
2297 rist_calculate_flow_bitrate(peer->flow, ingest_size, &peer->flow->bw_rejected);
2298 pthread_mutex_unlock(&ctx->common.stats_lock);
2299 }
2300 }
2301
2302 static void rist_recv_oob_data(struct rist_peer *peer, struct rist_buffer *payload)
2303 {
2304 // TODO: if the calling app locks the thread for long, the protocol management thread will suffer
2305 // either use a new thread with a fifo or write warning on documentation
2306 struct rist_common_ctx *ctx = get_cctx(peer);
2307 if (ctx->oob_data_enabled && ctx->oob_data_callback)
2308 {
2309 struct rist_oob_block oob_block;
2310 if (ctx->oob_current_peer == NULL || ctx->oob_current_peer->dead)
2311 ctx->oob_current_peer = peer;
2312 oob_block.peer = peer;
2313 oob_block.payload = payload->data;
2314 oob_block.payload_len = payload->size;
2315 ctx->oob_data_callback(ctx->oob_data_callback_argument, &oob_block);
2316 }
2317 }
2318
2319 static void rist_rtcp_handle_echo_request(struct rist_peer *peer, struct rist_rtcp_echoext *echoreq) {
2320 if (RIST_UNLIKELY(!peer->echo_enabled))
2321 peer->echo_enabled = true;
2322 uint64_t echo_request_time = ((uint64_t)be32toh(echoreq->ntp_msw) << 32) | be32toh(echoreq->ntp_lsw);
2323 uint32_t ssrc = be32toh(echoreq->ssrc);
2324 rist_respond_echoreq(peer, echo_request_time, ssrc);
2325 }
2326
2327 static void rist_rtcp_handle_echo_response(struct rist_peer *peer, struct rist_rtcp_echoext *echoreq) {
2328 peer->echo_enabled = true;
2329 if (be32toh(echoreq->ssrc) != peer->peer_ssrc)
2330 return;
2331 uint64_t request_time = ((uint64_t)be32toh(echoreq->ntp_msw) << 32) | be32toh(echoreq->ntp_lsw);
2332 uint64_t rtt = calculate_rtt_delay(request_time, timestampNTP_u64(), be32toh(echoreq->delay));
2333 peer->last_rtt = rtt;
2334 peer->eight_times_rtt -= peer->eight_times_rtt / 8;
2335 peer->eight_times_rtt += peer->last_rtt;
2336 if (peer->peer_data && peer->peer_data != peer)
2337 {
2338 peer->peer_data->last_rtt = peer->last_rtt;
2339 peer->peer_data->eight_times_rtt = peer->eight_times_rtt;
2340 }
2341 }
2342
2343 static void rist_handle_sr_pkt(struct rist_peer *peer, struct rist_rtcp_sr_pkt *sr) {
2344 uint64_t ntp_time = ((uint64_t)be32toh(sr->ntp_msw) << 32) | be32toh(sr->ntp_lsw);
2345 peer->last_sender_report_time = ntp_time;
2346 peer->last_sender_report_ts = timestampNTP_u64();
2347 if (peer->config.timing_mode == RIST_TIMING_MODE_RTC)
2348 {
2349 if (peer->flow && peer->flow->time_offset == 0)
2350 {
2351 uint64_t packet_timestamp = convertRTPtoNTP(RTP_PTYPE_MPEGTS, 0, be32toh(sr->rtp_ts));
2352 peer->flow->time_offset = ntp_time - packet_timestamp;
2353 }
2354 }
2355 }
2356
2357 static void rist_handle_rr_pkt(struct rist_peer *peer, struct rist_rtcp_rr_pkt *rr) {
2358 if (peer->echo_enabled)
2359 return;
2360 uint64_t lsr_tmp = (peer->last_sender_report_time >> 16) & 0xFFFFFFFF;
2361 uint64_t lsr_ntp = be32toh(rr->lsr);
2362 uint64_t rtt;
2363 if (!peer->last_sender_report_ts)
2364 return;
2365 uint64_t dlsr = (uint64_t)be32toh(rr->dlsr) << 16;
2366 if (lsr_ntp == lsr_tmp) {
2367 uint64_t now = timestampNTP_u64();
2368 // guard the unsigned subtraction; dlsr comes from the wire
2369 if (peer->last_sender_report_ts + dlsr > now)
2370 return;
2371 rtt = now - peer->last_sender_report_ts - dlsr;
2372
2373 } else {
2374 if (!lsr_ntp)//this can happen on the first time
2375 return;
2376 //Slightly less accurate, needed when RTT is bigger than our RTCP interval.
2377 // lsr in SR is populated from RTC, so be sure to use that when comparing.
2378 uint64_t now_rtc = timestampNTP_RTC_u64();
2379 lsr_ntp = (lsr_ntp << 16) & 0x0000FFFFFFFF0000;
2380 lsr_ntp |= (now_rtc & 0xFFFF000000000000);
2381 if (lsr_ntp > now_rtc || lsr_ntp + dlsr > now_rtc)
2382 return;
2383 rtt = now_rtc - lsr_ntp - dlsr;
2384 }
2385 peer->last_rtt = rtt;
2386 peer->eight_times_rtt -= peer->eight_times_rtt / 8;
2387 peer->eight_times_rtt += peer->last_rtt;
2388 if (peer->peer_data && peer->peer_data != peer)
2389 {
2390 peer->peer_data->last_rtt = peer->last_rtt;
2391 peer->peer_data->eight_times_rtt = peer->eight_times_rtt;
2392 }
2393 }
2394
2395 static void rist_handle_xr_pkt(struct rist_peer *peer, uint8_t xr_pkt[], size_t pkt_len)
2396 {
2397 size_t offset = 0;
2398 if (pkt_len < sizeof(struct rist_rtcp_hdr))
2399 return;
2400 struct rist_rtcp_hdr *hdr = (struct rist_rtcp_hdr *)&xr_pkt[offset];
2401 // clamp the declared len to what we actually received
2402 size_t payload_len = ((size_t)be16toh(hdr->len) + 1) * 4;
2403 if (payload_len > pkt_len)
2404 payload_len = pkt_len;
2405 if (payload_len < sizeof(struct rist_rtcp_hdr))
2406 return;
2407 size_t bytes_remaining = payload_len - sizeof(struct rist_rtcp_hdr);
2408 offset += sizeof(struct rist_rtcp_hdr);
2409 while (bytes_remaining >= sizeof(struct rist_rtcp_xr_block_hdr))
2410 {
2411 struct rist_rtcp_xr_block_hdr *block = (struct rist_rtcp_xr_block_hdr *)&xr_pkt[offset];
2412 uint8_t block_type = block->type;
2413 size_t block_length = ((size_t)be16toh(block->length) + 1) * 4;
2414 if (block_length < sizeof(struct rist_rtcp_xr_block_hdr) ||
2415 block_length > bytes_remaining)
2416 return;
2417 if (block_type == 5)
2418 {
2419 if (block_length < sizeof(struct rist_rtcp_xr_dlrr))
2420 return;
2421 struct rist_rtcp_xr_dlrr *dlrr = (struct rist_rtcp_xr_dlrr *)&xr_pkt[offset];
2422 uint32_t ssrc = be32toh(dlrr->ssrc);
2423 if (ssrc != peer->peer_ssrc)
2424 return;
2425 uint64_t lrr_tmp = (peer->last_sender_report_ts >> 16) & 0xFFFFFFFF;
2426 uint64_t lrr = be32toh(dlrr->lrr);
2427 uint64_t delay = (uint64_t)be32toh(dlrr->delay) << 16;
2428 uint64_t rtt;
2429 if (lrr == lrr_tmp)
2430 {
2431 uint64_t now = timestampNTP_u64();
2432 // guard the unsigned subtraction; delay comes from the wire
2433 if (peer->last_sender_report_ts + delay > now)
2434 return;
2435 rtt = now - peer->last_sender_report_ts - delay;
2436 } else {
2437 //Slightly less accurate, needed when RTT is bigger than our RTCP interval.
2438 uint64_t now = timestampNTP_u64();
2439 lrr = (lrr << 16) & 0x0000FFFFFFFF0000;
2440 lrr |= (now & 0xFFFF000000000000);
2441 if (lrr > now || lrr + delay > now)
2442 return;
2443 rtt = now - lrr - delay;
2444 }
2445 peer->last_rtt = rtt;
2446 peer->eight_times_rtt -= peer->eight_times_rtt /8;
2447 peer->eight_times_rtt += peer->last_rtt;
2448 if (peer->peer_data && peer->peer_data != peer)
2449 {
2450 peer->peer_data->last_rtt = peer->last_rtt;
2451 peer->peer_data->eight_times_rtt = peer->eight_times_rtt;
2452 }
2453 }
2454 offset += block_length;
2455 bytes_remaining -= block_length;
2456 }
2457 }
2458
2459 static char *get_ip_str(struct sockaddr *sa, char *s, size_t maxlen)
2460 {
2461 switch(sa->sa_family) {
2462 case AF_INET:
2463 inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
2464 s, (socklen_t)maxlen);
2465 break;
2466
2467 case AF_INET6:
2468 inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
2469 s, (socklen_t)maxlen);
2470 break;
2471
2472 default:
2473 strncpy(s, "Unknown AF", maxlen);
2474 return NULL;
2475 }
2476 return s;
2477 }
2478
2479 static bool try_listener_reassociate_by_cname(struct rist_peer *new_peer, uint64_t now);
2480 static bool try_caller_socket_rebind(struct rist_peer *peer, uint64_t now);
2481
2482 static void rist_recv_rtcp(struct rist_peer *peer, uint32_t seq,
2483 uint32_t flow_id, struct rist_buffer *payload)
2484 {
2485 uint8_t *pkt;
2486 uint8_t ptype;
2487 uint16_t processed_bytes = 0;
2488 uint16_t records;
2489 uint8_t subtype;
2490 peer->stats_receiver_instant.received_rtcp++;
2491 struct rist_common_ctx *ctx = get_cctx(peer);
2492
2493 while (processed_bytes < payload->size) {
2494 pkt = (uint8_t*)payload->data + processed_bytes;
2495 struct rist_rtcp_hdr *rtcp = (struct rist_rtcp_hdr *)pkt;
2496 /* safety checks */
2497 size_t bytes_left = payload->size - processed_bytes;
2498
2499 if ( bytes_left < 4 )
2500 {
2501 /* we must have at least 4 bytes */
2502 rist_log_priv(ctx, RIST_LOG_ERROR, "Rist rtcp packet must have at least 4 bytes, we have %zu\n",
2503 bytes_left);
2504 return;
2505 }
2506
2507 ptype = rtcp->ptype;
2508 subtype = rtcp->flags & 0x1f;
2509 records = be16toh(rtcp->len);
2510 // in size_t so 4*(1+0xFFFF) cannot wrap to 0 and spin the loop
2511 size_t bytes = (size_t)4 * ((size_t)1 + records);
2512 if (bytes < 4 || bytes > bytes_left)
2513 {
2514 /* check for a sane number of bytes */
2515 rist_log_priv(ctx, RIST_LOG_ERROR, "Malformed feedback packet, expecting %zu bytes in the" \
2516 " packet, got a buffer of %zu bytes. ptype = %d\n", bytes,
2517 bytes_left, ptype);
2518 return;
2519 }
2520
2521 switch(ptype) {
2522 case PTYPE_NACK_CUSTOM:
2523 if (subtype == ECHO_RESPONSE) {
2524 if (bytes < sizeof(struct rist_rtcp_echoext))
2525 break;
2526 struct rist_rtcp_echoext *echoresponse = (struct rist_rtcp_echoext *) pkt;
2527 rist_rtcp_handle_echo_response(peer, echoresponse);
2528 break;
2529 }
2530 else if (subtype == ECHO_REQUEST) {
2531 if (bytes < sizeof(struct rist_rtcp_echoext))
2532 break;
2533 struct rist_rtcp_echoext *echorequest = (struct rist_rtcp_echoext *)pkt;
2534 rist_rtcp_handle_echo_request(peer, echorequest);
2535 break;
2536 }
2537 else if (subtype == NACK_FMT_RANGE) {
2538 //Fallthrough
2539 RIST_FALLTHROUGH;
2540 }
2541 else {
2542 rist_log_priv(ctx, RIST_LOG_DEBUG, "Unsupported rtcp custom subtype %d, ignoring ...\n", subtype);
2543 break;
2544 }
2545 case PTYPE_NACK_BITMASK:
2546 //Also FMT Range
2547 rist_sender_recv_nack(peer, flow_id, payload->src_port, payload->dst_port, pkt, bytes_left, 0);
2548 break;
2549 case PTYPE_RR:
2550 if (ntohs(rtcp->len) == 7) {
2551 struct rist_rtcp_rr_pkt *rr = (struct rist_rtcp_rr_pkt *)pkt;
2552 rist_handle_rr_pkt(peer, rr);
2553 }
2554 break;
2555
2556 case PTYPE_SDES:
2557 {
2558 peer->stats_sender_instant.received++;
2559 if (bytes_left < RTCP_SDES_SIZE)
2560 {
2561 rist_log_priv(ctx, RIST_LOG_ERROR, "Malformed SDES packet, %zu bytes < SDES header size\n",
2562 bytes_left);
2563 return;
2564 }
2565 uint8_t name_length = pkt[9];
2566 // must fit the remaining packet AND receiver_name (incl NUL)
2567 if ((size_t)name_length + RTCP_SDES_SIZE > bytes_left ||
2568 name_length >= sizeof(peer->receiver_name))
2569 {
2570 rist_log_priv(ctx, RIST_LOG_ERROR, "Malformed SDES packet, cname len %u out of bounds (left %zu, max %zu)\n",
2571 name_length, bytes_left, sizeof(peer->receiver_name) - 1);
2572 return;
2573 }
2574 if (memcmp(pkt + RTCP_SDES_SIZE, peer->receiver_name, name_length) != 0)
2575 {
2576 memcpy(peer->receiver_name, pkt + RTCP_SDES_SIZE, name_length);
2577 peer->receiver_name[name_length] = '\0';
2578 rist_log_priv(ctx, RIST_LOG_INFO, "Peer %"PRIu32" receiver name is now: %s\n",
2579 peer->adv_peer_id, peer->receiver_name);
2580 }
2581 bool peer_authenticated = peer->authenticated;
2582 int connection_message = 0;
2583 if (peer->receiver_mode) {
2584 rist_receiver_rtcp_authenticate(peer, seq, flow_id);
2585 connection_message = RIST_CLIENT_CONNECTED;
2586 } else if (peer->sender_ctx && peer->listening) {
2587 // TODO: create rist_sender_recv_rtcp
2588 if (!peer->authenticated) {
2589 rist_peer_authenticate(peer);
2590 }
2591 connection_message = RIST_CLIENT_CONNECTED;
2592 }
2593 else {
2594 connection_message = RIST_CONNECTION_ESTABLISHED;
2595 /* Re-associate by cname before announcing a
2596 * brand-new caller. On success this kills the
2597 * new peer and returns, dropping any RTCP records
2598 * that followed the SDES in the same compound
2599 * packet. */
2600 if (!peer->send_first_connection_event &&
2601 try_listener_reassociate_by_cname(peer, timestampNTP_u64()))
2602 return;
2603 }
2604 if (peer->timed_out || !peer->send_first_connection_event || (!peer_authenticated && peer->authenticated)) {
2605 if (!peer->send_first_connection_event)
2606 rist_log_priv(ctx, RIST_LOG_INFO, "Peer %"PRIu32" receiver with name %s reconnected\n",
2607 peer->adv_peer_id, peer->receiver_name);
2608 peer->timed_out = 0;
2609 peer->send_first_connection_event = true;
2610 if (ctx->connection_status_callback)
2611 ctx->connection_status_callback(ctx->connection_status_callback_argument, peer, connection_message);
2612 }
2613 break;
2614 }
2615 case PTYPE_SR:;
2616 if (bytes < sizeof(struct rist_rtcp_sr_pkt))
2617 break;
2618 struct rist_rtcp_sr_pkt *sr = (struct rist_rtcp_sr_pkt *)pkt;
2619 rist_handle_sr_pkt(peer, sr);
2620 break;
2621 case PTYPE_XR:
2622 rist_handle_xr_pkt(peer, pkt, bytes);
2623 break;
2624 default:
2625 rist_log_priv(ctx, RIST_LOG_DEBUG, "Unrecognized RTCP packet with PTYPE=%02x!!\n", ptype);
2626 }
2627 processed_bytes += (uint16_t)bytes;
2628 }
2629
2630 }
2631
2632 void rist_peer_rtcp(struct evsocket_ctx *evctx, void *arg)
2633 {
2634 RIST_MARK_UNUSED(evctx);
2635 struct rist_peer *peer = (struct rist_peer *)arg;
2636 //struct rist_common_ctx *ctx = get_cctx(peer);
2637
2638 if (!peer || atomic_load_explicit(&peer->shutdown, memory_order_acquire) || !peer->is_rtcp) {
2639 return;
2640 }
2641
2642 if (peer->dead && peer->parent != NULL)
2643 return;//Don't send to peers that connect to us and have dropped silent
2644
2645 if (peer->receiver_mode) {
2646 rist_receiver_periodic_rtcp(peer);
2647 } else {
2648 rist_sender_periodic_rtcp(peer);
2649 }
2650 }
2651
2652 static void rist_peer_sockerr(struct evsocket_ctx *evctx, int fd, short revents, void *arg)
2653 {
2654 RIST_MARK_UNUSED(evctx);
2655 RIST_MARK_UNUSED(fd);
2656 RIST_MARK_UNUSED(revents);
2657 struct rist_peer *peer = (struct rist_peer *) arg;
2658 #ifdef _WIN32
2659 /* WSAECONNRESET indications are disabled at socket creation time via
2660 * WSAIoctl(SIO_UDP_CONNRESET, FALSE) - see udpsocket_open(). The earlier
2661 * recvfrom(drain[1], ...) drain has been removed because it could
2662 * cannibalise (or truncate via WSAEMSGSIZE) a real datagram queued
2663 * ahead of - or instead of - the synthetic error indication, leading
2664 * to malformed EAPOL packets and other downstream failures. */
2665 int wsa_err = WSAGetLastError();
2666 if (wsa_err == WSAECONNRESET)
2667 return;
2668 #endif
2669 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "\tSocket error!\n");
2670
2671 //rist_peer_remove(get_cctx(peer), peer, NULL);
2672 }
2673
2674 void sender_peer_append(struct rist_sender *ctx, struct rist_peer *peer)
2675 {
2676 /* Add a reference to ctx->peer_lst */
2677 ctx->peer_lst = realloc(ctx->peer_lst, (ctx->peer_lst_len + 1) * sizeof(*ctx->peer_lst));
2678 ctx->peer_lst[ctx->peer_lst_len] = peer;
2679 ctx->peer_lst_len++;
2680 }
2681
2682 static void peer_copy_settings(struct rist_peer *peer_src, struct rist_peer *peer)
2683 {
2684 _librist_crypto_psk_rist_key_clone(&peer_src->key_rx, &peer->key_rx);
2685 _librist_crypto_psk_rist_key_clone(&peer_src->key_rx_odd, &peer->key_rx_odd);
2686 _librist_crypto_psk_rist_key_clone(&peer_src->key_tx, &peer->key_tx);
2687 _librist_crypto_psk_rist_key_clone(&peer_src->key_tx, &peer->key_tx_odd);
2688 peer->key_tx_odd_active = peer_src->key_tx_odd_active;
2689 strncpy(&peer->cname[0], &peer_src->cname[0], RIST_MAX_STRING_SHORT);
2690 peer->cname[RIST_MAX_STRING_SHORT - 1] = '\0';
2691 strncpy(&peer->miface[0], &peer_src->miface[0], RIST_MAX_STRING_SHORT);
2692 peer->miface[RIST_MAX_STRING_SHORT - 1] = '\0';
2693 peer->config.weight = peer_src->config.weight;
2694 peer->config.recovery_priority = peer_src->config.recovery_priority;
2695 peer->config.virt_dst_port = peer_src->config.virt_dst_port;
2696 peer->config.recovery_mode = peer_src->config.recovery_mode;
2697 peer->config.recovery_maxbitrate = peer_src->config.recovery_maxbitrate;
2698 peer->config.recovery_maxbitrate_return = peer_src->config.recovery_maxbitrate_return;
2699 peer->config.recovery_length_min = peer_src->config.recovery_length_min;
2700 peer->config.recovery_length_max = peer_src->config.recovery_length_max;
2701 peer->config.recovery_reorder_buffer = peer_src->config.recovery_reorder_buffer;
2702 peer->config.recovery_rtt_min = peer_src->config.recovery_rtt_min;
2703 peer->config.recovery_rtt_max = peer_src->config.recovery_rtt_max;
2704 peer->config.congestion_control_mode = peer_src->config.congestion_control_mode;
2705 peer->config.min_retries = peer_src->config.min_retries;
2706 peer->config.max_retries = peer_src->config.max_retries;
2707 peer->config.timing_mode = peer_src->config.timing_mode;
2708 peer->config.reflector = peer_src->config.reflector;
2709 peer->config.multicast_ttl = peer_src->config.multicast_ttl;
2710 strncpy(peer->config.multicast_source, peer_src->config.multicast_source, RIST_MAX_STRING_LONG - 1);
2711 peer->config.multicast_source[RIST_MAX_STRING_LONG - 1] = '\0';
2712 peer->config.local_port = peer_src->config.local_port;
2713 peer->rtcp_keepalive_interval = peer_src->rtcp_keepalive_interval;
2714 peer->peer_ssrc = peer_src->peer_ssrc;
2715 peer->session_timeout = peer_src->session_timeout;
2716 peer->rist_gre_version = RIST_GRE_VERSION_MIN;
2717 memcpy(peer->mac_addr, peer_src->mac_addr, sizeof(peer->mac_addr));
2718 init_peer_settings(peer);
2719 }
2720
2721 static void kill_peer(struct rist_peer *peer)
2722 {
2723 bool current_state = peer->dead;
2724 peer->dead = true;
2725 if (peer->peer_data && (current_state != peer->peer_data->dead && peer->peer_data->parent))
2726 --peer->peer_data->parent->child_alive_count;
2727 peer->dead_since = timestampNTP_u64();
2728 }
2729
2730 /* Listener-side cname re-association for a NAT source-port rebind.
2731 * SRP only: the cname is not a per-peer secret, so an authenticated
2732 * per-peer session is required before migrating an identity to a new
2733 * source tuple. Returns true after killing new_peer. */
2734 static bool try_listener_reassociate_by_cname(struct rist_peer *new_peer, uint64_t now)
2735 {
2736 struct rist_peer *parent = new_peer->parent;
2737 if (!parent || !parent->listening || !new_peer->sender_ctx ||
2738 new_peer->receiver_mode || new_peer->receiver_name[0] == '\0')
2739 return false;
2740
2741 if (!new_peer->eap_ctx || !eap_is_authenticated(new_peer->eap_ctx))
2742 return false;
2743
2744 uint64_t ka = new_peer->rtcp_keepalive_interval
2745 ? new_peer->rtcp_keepalive_interval
2746 : (uint64_t)RIST_PING_INTERVAL * RIST_CLOCK;
2747 uint64_t silent_threshold = 2 * ka;
2748
2749 struct rist_peer *candidate = NULL;
2750 int alive_duplicates = 0;
2751 struct rist_peer *sib = parent->child;
2752 while (sib) {
2753 if (sib != new_peer &&
2754 sib->is_rtcp == new_peer->is_rtcp &&
2755 sib->is_data == new_peer->is_data &&
2756 sib->adv_flow_id == new_peer->adv_flow_id &&
2757 sib->receiver_name[0] != '\0' &&
2758 strncmp(sib->receiver_name, new_peer->receiver_name,
2759 RIST_MAX_HOSTNAME) == 0) {
2760 bool silent = sib->last_pkt_received > 0 &&
2761 now > sib->last_pkt_received &&
2762 (now - sib->last_pkt_received) > silent_threshold;
2763 if (sib->dead || silent) {
2764 if (candidate == NULL)
2765 candidate = sib;
2766 } else {
2767 alive_duplicates++;
2768 }
2769 }
2770 sib = sib->sibling_next;
2771 }
2772
2773 if (!candidate || alive_duplicates > 0)
2774 return false;
2775
2776 memcpy(&candidate->u.address, &new_peer->u.address, new_peer->address_len);
2777 candidate->address_len = new_peer->address_len;
2778 candidate->address_family = new_peer->address_family;
2779 candidate->remote_port = new_peer->remote_port;
2780 candidate->dead = 0;
2781 candidate->timed_out = 0;
2782 candidate->last_pkt_received = now;
2783 rist_log_priv(get_cctx(new_peer), RIST_LOG_INFO,
2784 "cname \"%s\" matched existing peer %"PRIu32
2785 "; migrated source tuple from new peer %"PRIu32
2786 " and retired it (NAT-rebind recovery, SRP).\n",
2787 new_peer->receiver_name, candidate->adv_peer_id,
2788 new_peer->adv_peer_id);
2789
2790 #if HAVE_SRP_SUPPORT
2791 /* Kick a fresh EAPOL START so re-auth fires now, not up to
2792 * EAP_REAUTH_PERIOD later. */
2793 if (candidate->eap_ctx)
2794 _librist_proto_eap_start(candidate->eap_ctx);
2795 #endif
2796
2797 kill_peer(new_peer);
2798 return true;
2799 }
2800
2801 /* Receiver-caller socket rebind on a NAT source-port rebind / sender
2802 * silence. Plaintext and shared-PSK callers; SRP callers recover via
2803 * the listener-side reassociation path. Linear backoff capped at
2804 * REBIND_BACKOFF_CAP. */
2805 #define REBIND_BACKOFF_CAP 10
2806 static bool try_caller_socket_rebind(struct rist_peer *peer, uint64_t now)
2807 {
2808 struct rist_common_ctx *cctx = get_cctx(peer);
2809 if (!peer || peer->parent || peer->listening ||
2810 !peer->receiver_mode || peer->multicast_sender ||
2811 peer->multicast_receiver)
2812 return false;
2813 if (cctx->profile <= RIST_PROFILE_SIMPLE)
2814 return false;
2815 if (peer->config.local_port != 0)
2816 return false;
2817 /* SRP recovers via the listener-side reassociation path. */
2818 if (peer->eap_ctx != NULL)
2819 return false;
2820
2821 /* Require silence beyond max(session_timeout, 4*keepalive) so a
2822 * misconfigured short session_timeout against a slower keepalive
2823 * cadence does not trigger a flap loop on legitimate streams. */
2824 uint64_t ka = peer->rtcp_keepalive_interval
2825 ? peer->rtcp_keepalive_interval
2826 : (uint64_t)RIST_PING_INTERVAL * RIST_CLOCK;
2827 uint64_t min_silence = peer->session_timeout > 4 * ka
2828 ? peer->session_timeout : 4 * ka;
2829 if (peer->last_pkt_received == 0 ||
2830 now <= peer->last_pkt_received ||
2831 (now - peer->last_pkt_received) <= min_silence)
2832 return false;
2833
2834 uint32_t backoff_mult = peer->rebind_attempts > REBIND_BACKOFF_CAP
2835 ? REBIND_BACKOFF_CAP : peer->rebind_attempts;
2836 uint64_t min_gap = (uint64_t)backoff_mult * peer->session_timeout;
2837 if (peer->last_rebind_time != 0 && now > peer->last_rebind_time &&
2838 (now - peer->last_rebind_time) < min_gap)
2839 return false;
2840
2841 struct evsocket_ctx *evctx = cctx->evctx;
2842 int old_sd = peer->sd;
2843 uint16_t old_local_port = peer->local_port;
2844
2845 if (peer->event_recv) {
2846 evsocket_delevent(evctx, peer->event_recv);
2847 peer->event_recv = NULL;
2848 }
2849 if (old_sd >= 0) {
2850 udpsocket_close(old_sd);
2851 peer->sd = -1;
2852 }
2853
2854 rist_create_socket(peer);
2855 if (peer->sd < 0) {
2856 rist_log_priv(cctx, RIST_LOG_ERROR,
2857 "Caller socket rebind failed for peer %"PRIu32
2858 " (errno=%d), falling through to kill_peer.\n",
2859 peer->adv_peer_id, errno);
2860 return false;
2861 }
2862
2863 peer->event_recv = evsocket_addevent(evctx, peer->sd, EVSOCKET_EV_READ,
2864 rist_peer_recv_wrap,
2865 rist_peer_sockerr, peer);
2866
2867 /* Force a fresh handshake on the new tuple. */
2868 peer->authenticated = false;
2869 peer->dead = 0;
2870 peer->timed_out = 0;
2871 peer->last_pkt_received = now;
2872 peer->next_periodic_rtcp = now;
2873 peer->next_keepalive_packet = now;
2874 peer->send_keepalive = true;
2875 peer->send_first_connection_event = false;
2876
2877 peer->rebind_attempts++;
2878 peer->last_rebind_time = now;
2879
2880 rist_log_priv(cctx, RIST_LOG_WARN,
2881 "Receiver peer %"PRIu32" silent past session_timeout "
2882 "(attempt %"PRIu32"); rebound caller socket %d->%d "
2883 "(local_port %u->%u) for NAT/dynamic-IP recovery.\n",
2884 peer->adv_peer_id, peer->rebind_attempts, old_sd, peer->sd,
2885 (unsigned)old_local_port, (unsigned)peer->local_port);
2886
2887 return true;
2888 }
2889
2890 static void rist_peer_recv_wrap(struct evsocket_ctx *evctx, int fd, short revents, void *arg) {
2891 bool again = true;
2892 while (true) {
2893 rist_peer_recv(evctx, fd, revents, arg, &again);
2894 if (!again)
2895 return;
2896 }
2897 }
2898
2899 static void rist_new_connection(struct rist_peer *peer, struct rist_peer *p, uint32_t flow_id) {
2900 const char *peer_type = "?";
2901 const char *id_name = "?";
2902 if (peer->is_rtcp) {
2903 peer_type = "RTCP";
2904 id_name = "flow_id";
2905 } else if (peer->is_data) {
2906 peer_type = "RTP";
2907 id_name = "ssrc";
2908 }
2909 if (peer->receiver_mode) {
2910 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "New %s peer connecting, %s %"PRIu32", peer_id %"PRIu32", ports %u <- %u\n",
2911 peer_type, id_name, flow_id, p->adv_peer_id, p->local_port, p->remote_port);
2912 p->adv_flow_id = flow_id;
2913 }
2914 else {
2915 if (flow_id) {
2916 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "New reverse %s peer connecting with old flow_id %"PRIu32", peer_id %"PRIu32", ports %u <- %u\n",
2917 peer_type, flow_id, p->adv_peer_id, p->local_port, p->remote_port);
2918 } else {
2919 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "New reverse %s peer connecting, peer_id %"PRIu32", ports %u <- %u\n",
2920 peer_type, p->adv_peer_id, p->local_port, p->remote_port);
2921 }
2922 p->peer_ssrc = p->adv_flow_id = p->sender_ctx->adv_flow_id;
2923 }
2924 }
2925
2926 static void rist_peer_recv(struct evsocket_ctx *evctx, int fd, short revents, void *arg, bool *again)
2927 {
2928 RIST_MARK_UNUSED(evctx);
2929 RIST_MARK_UNUSED(revents);
2930 RIST_MARK_UNUSED(fd);
2931
2932 struct rist_peer *peer = (struct rist_peer *) arg;
2933 if (atomic_load_explicit(&peer->shutdown, memory_order_acquire)) {
2934 return;
2935 }
2936 uint64_t now = timestampNTP_u64();
2937 struct rist_common_ctx *cctx = get_cctx(peer);
2938
2939 socklen_t addrlen = peer->address_len;
2940 size_t recv_bufsize = 0;
2941 uint16_t family = peer->address_family;
2942 struct sockaddr_storage ss = {0};
2943 struct sockaddr *addr = (struct sockaddr *)&ss;
2944 struct rist_peer *p = NULL;
2945 uint8_t *recv_buf = cctx->buf.recv;
2946 uint8_t *recv_buf_npd = cctx->buf.recv_npd;
2947 uint16_t port = 0;
2948
2949 ssize_t ret = rist_transport_recvfrom(peer, recv_buf, RIST_MAX_PACKET_SIZE, MSG_DONTWAIT, addr, &addrlen);
2950 if (ss.ss_family == AF_INET)
2951 port = htons(((struct sockaddr_in *)addr)->sin_port);
2952 else
2953 port = htons(((struct sockaddr_in6 *)addr)->sin6_port);
2954
2955 #ifndef _WIN32
2956 if (ret <= 0) {
2957 *again = false;
2958 int errorcode = errno;
2959 /* Custom transports compiled in a different TU may have EAGAIN
2960 * resolve to a different numeric value than this TU; match both
2961 * canonical values defensively. */
2962 if (errno == EAGAIN || errno == EWOULDBLOCK ||
2963 (ret == -1 && (errorcode == 11 || errorcode == 35)))
2964 return;
2965 #else
2966 if (ret == SOCKET_ERROR) {
2967 *again = false;
2968 int errorcode = WSAGetLastError();
2969 if (errorcode == WSAEWOULDBLOCK)
2970 return;
2971 #endif
2972 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Receive failed: errno=%d, ret=%d, socket=%d\n", errorcode, recv_bufsize, fd);
2973 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "%s\n", strerror(errorcode));
2974 return;
2975 }
2976
2977 recv_bufsize = ret;
2978
2979 /* Transparent one-to-many reflector: forward raw packets between
2980 * publisher and subscriber children before any decryption or
2981 * protocol processing. Only active when ?reflector=1 is set. */
2982 if (peer->config.reflector && peer->listening && !peer->multicast_receiver) {
2983 struct rist_peer *p_sender = _librist_peer_match_peer_addr(peer, family, addr);
2984 if (p_sender && p_sender->parent == peer) {
2985 struct rist_peer *child = peer->child;
2986 while (child) {
2987 if (child != p_sender) {
2988 if (p_sender->is_reflector_publisher) {
2989 /* Forward publisher's packet (RTP/RTCP) to subscriber children */
2990 if (!child->is_reflector_publisher) {
2991 sendto(peer->sd, (const char *)recv_buf, recv_bufsize, 0, &child->u.address, child->address_len);
2992 }
2993 } else {
2994 /* Forward subscriber's packet (NACK/RTCP) to publisher children */
2995 if (child->is_reflector_publisher) {
2996 sendto(peer->sd, (const char *)recv_buf, recv_bufsize, 0, &child->u.address, child->address_len);
2997 }
2998 }
2999 }
3000 child = child->sibling_next;
3001 }
3002 }
3003 }
3004
3005 struct rist_key *k = &peer->key_rx;
3006 uint32_t seq = 0;
3007 uint32_t time_extension = 0;
3008 uint8_t retry = 0;
3009 size_t payload_offset = 0;
3010 struct rist_buffer payload = { .data = NULL, .size = 0, .type = 0, .src_port = 0, .dst_port = 0 };
3011 uint32_t flow_id = 0;
3012 uint16_t gre_proto = 0;
3013 uint8_t rist_gre_version = RIST_GRE_VERSION_MIN;
3014 if (cctx->profile > RIST_PROFILE_SIMPLE)
3015 {
3016 /* Section 9 (TR-06-3): Auto-detect GRE vs RTP framing.
3017 * First byte bits [7:6]:
3018 * 0b0x = GRE (bit 7 = 0 → Main/Advanced GRE tunnel)
3019 * 0b10 = RTP V=2 → Advanced Profile if PT=127 */
3020 if (cctx->profile == RIST_PROFILE_ADVANCED &&
3021 recv_bufsize >= RIST_ADV_HEADER_MIN &&
3022 (recv_buf[0] & 0xC0) == 0x80) {
3023 /* Looks like RTP V=2. Check PT field for Advanced Profile. */
3024 uint8_t pt = recv_buf[1] & 0x7F;
3025 if (pt == RIST_ADV_PT || pt >= 96) {
3026 struct rist_adv_parsed adv_parsed;
3027 if (rist_adv_parse(recv_buf, recv_bufsize, &adv_parsed) == 0) {
3028 p = _librist_peer_match_peer_addr(peer, family, addr);
3029 if (!p) {
3030 if (peer->listening || peer->multicast_sender) {
3031 p = peer_initialize(NULL, peer->sender_ctx, peer->receiver_ctx);
3032 p->handled_first = false;
3033 p->adv_peer_id = ++cctx->peer_counter;
3034 p->parent = peer;
3035 peer_copy_settings(peer, p);
3036 if (peer->receiver_ctx) {
3037 p->remote_port = port;
3038 p->local_port = peer->local_port;
3039 } else {
3040 p->remote_port = peer->remote_port;
3041 p->local_port = peer->local_port;
3042 }
3043 p->address_family = family;
3044 p->address_len = addrlen;
3045 p->listening = 0;
3046 p->is_rtcp = peer->is_rtcp;
3047 p->is_data = peer->is_data;
3048 p->peer_data = p;
3049 p->is_advanced = true;
3050 memcpy(&p->u.address, addr, addrlen);
3051 p->sd = peer->sd;
3052 p->authenticated = false;
3053 p->event_recv = peer->event_recv;
3054 p->send_keepalive = true;
3055 if (cctx->auth.conn_cb) {
3056 char incoming_ip_str[INET6_ADDRSTRLEN];
3057 char *ip_str = get_ip_str(&p->u.address, incoming_ip_str, INET6_ADDRSTRLEN);
3058 char parent_ip_str[INET6_ADDRSTRLEN];
3059 char *parent_str = get_ip_str(&p->parent->u.address, parent_ip_str, INET6_ADDRSTRLEN);
3060 if (!parent_str) parent_str = "";
3061 uint16_t parent_port = 0;
3062 if (p->parent->u.storage.ss_family == AF_INET)
3063 parent_port = htons(p->parent->u.inaddr.sin_port);
3064 else
3065 parent_port = htons(p->parent->u.inaddr6.sin6_port);
3066 if (ip_str && cctx->auth.conn_cb(cctx->auth.arg, ip_str, port, parent_str, parent_port, p)) {
3067 free(p);
3068 return;
3069 }
3070 }
3071 peer_append(p);
3072 #if HAVE_SRP_SUPPORT
3073 eap_clone_ctx(peer->eap_ctx, p);
3074 {
3075 char ip_buf[INET6_ADDRSTRLEN];
3076 char *ip = get_ip_str(&p->u.address, ip_buf, INET6_ADDRSTRLEN);
3077 if (ip)
3078 eap_set_ip_string(p->eap_ctx, ip_buf);
3079 }
3080 #endif
3081 } else {
3082 return;
3083 }
3084 }
3085 p->is_advanced = true;
3086 p->last_pkt_received = now;
3087
3088 /* Dispatch by encapsulation type */
3089 if (adv_parsed.enc_type == RIST_ADV_TYPE_CONTROL) {
3090 rist_calculate_bitrate(recv_bufsize, &p->bw);
3091 rist_adv_recv_control(p, adv_parsed.payload,
3092 adv_parsed.payload_len);
3093 return;
3094 }
3095
3096 uint32_t adv_flow_id = adv_parsed.ssrc & ~(uint32_t)1;
3097 retry = adv_parsed.retransmit ? 1 : 0;
3098
3099 if (adv_parsed.enc_type == RIST_ADV_TYPE_DIRECT) {
3100 /* PSK decryption for Advanced Profile */
3101 uint8_t adv_dec_buf[RIST_MAX_PACKET_SIZE];
3102 const uint8_t *adv_data = adv_parsed.payload;
3103 size_t adv_data_len = adv_parsed.payload_len;
3104
3105 if (adv_parsed.psk_mode == RIST_ADV_PSK_AES_CTR) {
3106 if (!p->key_rx.key_size) {
3107 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3108 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3109 "Advanced Profile: encrypted data but no PSK configured\n");
3110 peer->log_repeat_timer = now;
3111 }
3112 return;
3113 }
3114 if (!adv_parsed.psk_nonce || !adv_parsed.psk_iv) {
3115 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3116 "Advanced Profile: PSK AES-CTR missing nonce/IV\n");
3117 return;
3118 }
3119 bool odd_nonce_adv = CHECK_BIT(adv_parsed.psk_nonce[0], 7);
3120 struct rist_key *ak = &p->key_rx;
3121 if (odd_nonce_adv)
3122 ak = &p->key_rx_odd;
3123 pthread_mutex_lock(&p->peer_lock);
3124 uint32_t seq_nbe;
3125 memcpy(&seq_nbe, adv_parsed.psk_iv, sizeof(seq_nbe));
3126 _librist_crypto_psk_decrypt(ak,
3127 (uint8_t *)adv_parsed.psk_nonce, seq_nbe, 1,
3128 adv_parsed.payload, adv_dec_buf, adv_data_len);
3129 pthread_mutex_unlock(&p->peer_lock);
3130 if (ak->bad_decryption)
3131 return;
3132 adv_data = adv_dec_buf;
3133 } else if (adv_parsed.psk_mode != RIST_ADV_PSK_NONE) {
3134 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3135 rist_log_priv(get_cctx(peer), RIST_LOG_WARN,
3136 "Advanced Profile: unsupported PSK mode %u\n",
3137 adv_parsed.psk_mode);
3138 peer->log_repeat_timer = now;
3139 }
3140 return;
3141 } else if (p->key_rx.key_size) {
3142 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3143 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3144 "Advanced Profile: expect encrypted data but received clear\n");
3145 peer->log_repeat_timer = now;
3146 }
3147 return;
3148 }
3149
3150 uint8_t adv_lz4_buf[RIST_MAX_PACKET_SIZE];
3151 if (adv_parsed.lpc_mode == RIST_ADV_LPC_LZ4 && adv_data_len > 0) {
3152 int dlen = LZ4_decompress_safe(
3153 (const char *)adv_data, (char *)adv_lz4_buf,
3154 (int)adv_data_len, RIST_MAX_PACKET_SIZE);
3155 if (dlen <= 0) {
3156 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3157 "Advanced Profile: LZ4 decompress failed\n");
3158 return;
3159 }
3160 adv_data = adv_lz4_buf;
3161 adv_data_len = (size_t)dlen;
3162 } else if (adv_parsed.lpc_mode != RIST_ADV_LPC_NONE) {
3163 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3164 rist_log_priv(get_cctx(peer), RIST_LOG_WARN,
3165 "Advanced Profile: unsupported LPC mode %u\n",
3166 adv_parsed.lpc_mode);
3167 peer->log_repeat_timer = now;
3168 }
3169 return;
3170 }
3171
3172 uint64_t adv_source_time = now;
3173
3174 if (peer->receiver_ctx) {
3175 rist_calculate_bitrate(recv_bufsize, &p->bw);
3176 uint16_t adv_src_port = (uint16_t)(32768 + p->adv_peer_id);
3177 uint16_t adv_dst_port = p->config.virt_dst_port;
3178 if (adv_parsed.has_flow_id && adv_parsed.flow_id) {
3179 adv_dst_port = rist_adv_flow_outer(adv_parsed.flow_id);
3180 adv_src_port = rist_adv_flow_inner(adv_parsed.flow_id);
3181 }
3182 struct rist_buffer adv_payload = {
3183 .data = (void *)adv_data,
3184 .size = adv_data_len,
3185 .type = RIST_PAYLOAD_TYPE_DATA_RAW,
3186 .src_port = adv_src_port,
3187 .dst_port = adv_dst_port,
3188 };
3189 /* Pass the delivered payload size (adv_data_len), not
3190 * the full datagram, so received_bytes and bitrate
3191 * match the Main path's payload-only accounting.
3192 * ts_null_bytes is 0: the Advanced receive path does
3193 * no ts-null reinsertion. */
3194 rist_receiver_recv_data(p, adv_parsed.seq, adv_flow_id,
3195 adv_source_time, now, &adv_payload, retry,
3196 RIST_PAYLOAD_TYPE_DATA_RAW, adv_data_len, 0, false);
3197 }
3198 return;
3199 }
3200
3201 if (adv_parsed.enc_type == RIST_ADV_TYPE_GRE_MAIN) {
3202 /* Type 8: Strip Advanced Profile header, process inner GRE.
3203 * The payload is a Main Profile GRE packet — feed it back
3204 * through the existing GRE receive path by updating the
3205 * buffer pointer and falling through. */
3206 recv_buf = (uint8_t *)adv_parsed.payload;
3207 recv_bufsize = adv_parsed.payload_len;
3208 /* Fall through to GRE processing below */
3209 } else {
3210 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
3211 "Advanced Profile: unsupported encapsulation type %u\n",
3212 adv_parsed.enc_type);
3213 return;
3214 }
3215 }
3216 }
3217 }
3218
3219 struct rist_gre_hdr *gre = NULL;
3220 // Make sure we have enough bytes
3221 if (recv_bufsize < (int)sizeof(*gre)) {
3222 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small: %d bytes, ignoring ...\n", recv_bufsize);
3223 return;
3224 }
3225
3226 gre = (void *) recv_buf;
3227 payload_offset += sizeof(*gre);
3228 gre_proto = be16toh(gre->prot_type);
3229 if (CHECK_BIT(gre->flags1, 6) != 0 || (gre->flags2 & 0x7) != 0) {
3230 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3231 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3232 "Non conformant main profile packet received\n");
3233 peer->log_repeat_timer = now;
3234 }
3235 return;
3236 }
3237 uint8_t has_checksum = CHECK_BIT(gre->flags1, 7);
3238 uint8_t has_key = CHECK_BIT(gre->flags1, 5);
3239 uint8_t has_seq = CHECK_BIT(gre->flags1, 4);
3240 rist_gre_version = (gre->flags2 >> 3) & 0x7;
3241
3242 if (recv_bufsize < (sizeof(*gre) + has_checksum*4 + has_key *4 + has_seq *4)) {
3243 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small: %d bytes, ignoring ...\n", recv_bufsize);
3244 return;
3245 }
3246
3247 if (has_checksum) {
3248 payload_offset += 4;
3249 }
3250
3251 size_t nonce_offset = 0;
3252 bool odd_nonce = false;
3253 if (has_key) {
3254 nonce_offset = payload_offset;
3255 odd_nonce = CHECK_BIT(recv_buf[nonce_offset], 7);
3256 payload_offset += 4;
3257 }
3258
3259 if (has_seq) {
3260 seq = recv_buf[payload_offset] << 24 | recv_buf[payload_offset+ 1] << 16 | recv_buf[payload_offset+ 2] << 8 | recv_buf[payload_offset+ 3];
3261 payload_offset += 4;
3262 }
3263
3264 p = _librist_peer_match_peer_addr(peer, family, addr);
3265
3266 if (has_seq && has_key && gre_proto != RIST_GRE_PROTOCOL_TYPE_EAPOL) {
3267 // Key bit is set, that means the other side want to send
3268 // encrypted data.
3269 //
3270 // make sure we have a key before attempting to decrypt
3271 if (!k->key_size) {
3272 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3273 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Receiving encrypted data, but configured without keysize!\n");
3274 peer->log_repeat_timer = now;
3275 }
3276 return;
3277 }
3278
3279
3280
3281 if (!p)
3282 p = peer;
3283 #if ALLOW_INSECURE_IV_FALLBACK == 1
3284 if (rist_gre_version < 1)
3285 p->rist_gre_version = rist_gre_version;
3286 #endif
3287 pthread_mutex_lock(&p->peer_lock);
3288 k = &p->key_rx;
3289 if (odd_nonce)
3290 k = &p->key_rx_odd;
3291 p->key_rx_odd_active = odd_nonce;
3292 //Read H bit and set keysize accordingly
3293 if (p->rist_gre_version)
3294 {
3295 int bits = (CHECK_BIT(gre->flags2, 6))? 256 : 128;
3296 k->key_size = bits;
3297 }
3298 _librist_crypto_psk_decrypt(k, &recv_buf[nonce_offset], htobe32(seq), rist_gre_version,&recv_buf[payload_offset], &recv_buf[payload_offset], (recv_bufsize - payload_offset));
3299 pthread_mutex_unlock(&p->peer_lock);
3300
3301 if (p == peer)
3302 p = NULL;
3303
3304 if (k->bad_decryption)
3305 return;
3306 } else if (k->key_size && gre_proto != RIST_GRE_PROTOCOL_TYPE_EAPOL && (!has_seq || !has_key)) {
3307 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3308 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3309 "We expect encrypted data and the peer sent clear communication, ignoring ...\n");
3310 peer->log_repeat_timer = now;
3311 }
3312 return;
3313 }
3314
3315 if (gre_proto == RIST_GRE_PROTOCOL_TYPE_FULL)
3316 {
3317 payload.type = RIST_PAYLOAD_TYPE_DATA_OOB;
3318 goto protocol_bypass;
3319 }
3320 if (gre_proto == RIST_GRE_PROTOCOL_TYPE_EAPOL)
3321 {
3322 payload.type = RIST_PAYLOAD_TYPE_EAPOL;
3323 goto protocol_bypass;
3324 }
3325
3326 if (gre_proto == RIST_GRE_PROTOCOL_TYPE_VSF) {
3327 if (recv_bufsize < payload_offset + 4) {
3328 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small: %d bytes, ignoring ...\n", recv_bufsize);
3329 return;
3330 }
3331
3332 uint16_t vsf_proto = 0;
3333 uint16_t vsf_subtype = 0;
3334 vsf_proto = recv_buf[payload_offset] << 8 | recv_buf[payload_offset +1];
3335 vsf_subtype = recv_buf[payload_offset + 2] << 8 | recv_buf[payload_offset +3];
3336
3337 payload_offset += 4;
3338
3339 if (vsf_proto != 0) {//0 = RIST, rest: reserved
3340 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Receiving unknown VSF Proto\n");
3341 return;
3342 }
3343
3344 if (vsf_subtype == 0) {
3345 gre_proto = RIST_GRE_PROTOCOL_TYPE_REDUCED;
3346 } else if (vsf_subtype >= 0x8000){//Control messages
3347 if (vsf_subtype == 0x8000) {
3348 gre_proto = RIST_GRE_PROTOCOL_TYPE_KEEPALIVE;
3349 } else if (vsf_subtype == 0x8001) {
3350 /* Flow Attribute (Main Profile VSF extension) — not parsed here */
3351 return;
3352 } else if (vsf_subtype == RIST_VSF_PROTOCOL_SUBTYPE_BUFFER_NEGOTIATION) {
3353 gre_proto = RIST_VSF_PROTOCOL_SUBTYPE_BUFFER_NEGOTIATION;
3354 } else {
3355 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Receiving unknown RIST control packet\n");
3356 return;
3357 }
3358 } else {
3359 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Receiving unknown RIST packet\n");
3360 return;
3361 }
3362 }
3363
3364 if (gre_proto != RIST_GRE_PROTOCOL_TYPE_REDUCED)
3365 goto protocol_bypass;
3366
3367 if (recv_bufsize < payload_offset + 4) {
3368 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small: %d bytes, ignoring ...\n", recv_bufsize);
3369 return;
3370 }
3371
3372 /* Map the first subheader and rtp payload area to our structure */
3373 payload.src_port = recv_buf[payload_offset] << 8 | recv_buf[payload_offset +1];
3374 payload.dst_port = recv_buf[payload_offset +2] << 8 | recv_buf[payload_offset +3];
3375 payload_offset += 4;
3376 }
3377
3378 protocol_bypass:
3379 if (!p)
3380 p = _librist_peer_match_peer_addr(peer, family, addr);
3381
3382 /* The RTP header only exists on the data path (Simple profile or
3383 * Main-profile REDUCED); leave the pointer NULL elsewhere so a
3384 * stray deref shows up at compile/run time instead of silently
3385 * reading past recv_bufsize on a short FULL/EAPOL/KEEPALIVE
3386 * datagram. */
3387 struct rist_rtp_hdr *rtp = NULL;
3388 if (cctx->profile == RIST_PROFILE_SIMPLE || gre_proto == RIST_GRE_PROTOCOL_TYPE_REDUCED) {
3389 if (recv_bufsize < payload_offset + sizeof(struct rist_rtp_hdr))
3390 {
3391 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small for RTP header: %zu bytes, ignoring ...\n", recv_bufsize);
3392 return;
3393 }
3394 rtp = (struct rist_rtp_hdr *)&recv_buf[payload_offset];
3395 /* Double check for a valid rtp header */
3396 if ((rtp->flags & 0xc0) != 0x80)
3397 {
3398 if (!p)
3399 p = peer;
3400 if (now > (p->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3401 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Malformed packet, rtp flag value is %02x instead of 0x80.\n",
3402 rtp->flags);
3403 p->log_repeat_timer = now;
3404 }
3405
3406 if (k && k->key_size > 0) {
3407 if (k->bad_count++ > 5) {
3408 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Disabling packet processing till new NONCE\n");
3409 k->bad_decryption = true;
3410 }
3411 }
3412 return;
3413 }
3414 }
3415
3416
3417 if (!p && (peer->listening || peer->multicast_sender) && (gre_proto == RIST_GRE_PROTOCOL_TYPE_REDUCED || gre_proto == RIST_GRE_PROTOCOL_TYPE_KEEPALIVE || gre_proto == RIST_GRE_PROTOCOL_TYPE_FULL || cctx->profile == RIST_PROFILE_SIMPLE)) {
3418 /* No match, new peer creation when on listening mode */
3419 p = peer_initialize(NULL, peer->sender_ctx, peer->receiver_ctx);
3420 p->handled_first = false;
3421 p->adv_peer_id = ++cctx->peer_counter;
3422 // Copy settings and init/update global variables that depend on settings
3423 p->parent = peer;
3424 peer_copy_settings(peer, p);
3425 if (cctx->profile == RIST_PROFILE_SIMPLE) {
3426 if (peer->address_family == AF_INET) {
3427 p->remote_port = htons( ((struct sockaddr_in *)addr)->sin_port);
3428 } else {
3429 p->remote_port = htons( ((struct sockaddr_in6 *)addr)->sin6_port);
3430 }
3431 p->local_port = peer->local_port;
3432 }
3433 else if (peer->receiver_ctx){
3434 // TODO: what happens if the first packet is a keepalive?? are we caching the wrong port?
3435 p->remote_port = payload.src_port;
3436 p->local_port = payload.dst_port;
3437 } else {
3438 p->remote_port = peer->remote_port;
3439 p->local_port = peer->local_port;
3440 }
3441
3442 // TODO: what if sender mode and flow_id != 0 and p->adv_flow_id != flow_id
3443 p->address_family = family;
3444 p->address_len = addrlen;
3445 p->listening = 0;
3446 p->is_rtcp = peer->is_rtcp;
3447 p->is_data = peer->is_data;
3448 p->peer_data = p;
3449 if (peer->multicast_sender)
3450 p->peer_data = peer->peer_data;
3451 memcpy(&p->u.address, addr, addrlen);
3452 p->sd = peer->sd;
3453 p->authenticated = false;
3454 // Copy the event handler reference to prevent the creation of a new one (they are per socket)
3455 p->event_recv = peer->event_recv;
3456 char incoming_ip_string_buffer[INET6_ADDRSTRLEN];
3457 char *incoming_ip_string = get_ip_str(&p->u.address, &incoming_ip_string_buffer[0], INET6_ADDRSTRLEN);
3458 #if HAVE_SRP_SUPPORT
3459 eap_clone_ctx(peer->eap_ctx, p);
3460 eap_set_ip_string(p->eap_ctx, incoming_ip_string_buffer);
3461 if (p->multicast_receiver && p->eap_ctx) {
3462 _librist_proto_eap_start(p->eap_ctx);
3463 }
3464 #endif
3465 // Optional validation of connecting sender
3466 if (cctx->auth.conn_cb) {
3467
3468 char parent_ip_string_buffer[INET6_ADDRSTRLEN];
3469 char *parent_ip_string = get_ip_str(&p->parent->u.address, &parent_ip_string_buffer[0], INET6_ADDRSTRLEN);
3470 if (!parent_ip_string){
3471 parent_ip_string = "";
3472 }
3473
3474 uint16_t parent_port = 0;
3475 if (p->parent->u.storage.ss_family == AF_INET)
3476 parent_port = htons(p->parent->u.inaddr.sin_port);
3477 else
3478 parent_port = htons(p->parent->u.inaddr6.sin6_port);
3479
3480 // Real source port vs virtual source port
3481 if (cctx->profile == RIST_PROFILE_SIMPLE)
3482 port = p->remote_port;
3483 if (incoming_ip_string) {
3484 if (cctx->auth.conn_cb(cctx->auth.arg,incoming_ip_string,port,parent_ip_string, parent_port, p)) {
3485 free(p->eap_ctx);
3486 free(p);
3487 return;
3488 }
3489 }
3490 }
3491
3492 if (peer->receiver_mode)
3493 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Enabling keepalive for peer %d\n", p->adv_peer_id);
3494 else {
3495 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Enabling reverse keepalive for peer %d\n", p->adv_peer_id);
3496 if (p->is_rtcp)
3497 sender_peer_append(peer->sender_ctx, p);
3498 }
3499 p->send_keepalive = true;
3500 p->rist_gre_version = rist_gre_version;
3501 if (cctx->profile > RIST_PROFILE_SIMPLE
3502 #if HAVE_SRP_SUPPORT
3503 && ((p->eap_ctx && eap_is_authenticated(p->eap_ctx)) || !p->eap_ctx)
3504 #endif
3505 ) {
3506 //Answer their keep alive with one from us
3507 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3508 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3509 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3510 if (p->rist_gre_version >= 2) {
3511 uint16_t sender_max_buffer = 0;
3512 if (p->sender_ctx != NULL) {
3513 sender_max_buffer = p->sender_ctx->sender_recover_min_time;
3514 } else if (peer->config.reflector && peer->listening && !peer->multicast_receiver) {
3515 struct rist_peer *child = peer->child;
3516 while (child) {
3517 if (child->is_reflector_publisher && child->sender_max_buffer_ticks > 0) {
3518 sender_max_buffer = (uint16_t)(child->sender_max_buffer_ticks / RIST_CLOCK);
3519 break;
3520 }
3521 child = child->sibling_next;
3522 }
3523 }
3524 if (sender_max_buffer > 0) {
3525 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3526 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3527 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3528 }
3529 }
3530 }
3531 peer_append(p);
3532 }
3533 if (!p)
3534 return;
3535
3536 //Only allow upgrade of gre version
3537 if (p->rist_gre_version < rist_gre_version
3538 #if HAVE_SRP_SUPPORT
3539 && ((p->eap_ctx && eap_is_authenticated(p->eap_ctx)) || !p->eap_ctx)
3540 #endif
3541 ) {
3542 //Our GRE version got upgraded, try kickstarting buffer negotiation
3543 if (p->rist_gre_version == RIST_GRE_VERSION_MIN) {
3544 uint16_t sender_max_buffer = 0;
3545 if (p->sender_ctx != NULL) {
3546 sender_max_buffer = p->sender_ctx->sender_recover_min_time;
3547 } else if (peer->config.reflector && peer->listening && !peer->multicast_receiver) {
3548 struct rist_peer *child = peer->child;
3549 while (child) {
3550 if (child->is_reflector_publisher && child->sender_max_buffer_ticks > 0) {
3551 sender_max_buffer = (uint16_t)(child->sender_max_buffer_ticks / RIST_CLOCK);
3552 break;
3553 }
3554 child = child->sibling_next;
3555 }
3556 }
3557 if (sender_max_buffer > 0) {
3558 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3559 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3560 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3561 }
3562 }
3563 p->rist_gre_version = rist_gre_version;
3564 }
3565
3566 if (gre_proto == RIST_GRE_PROTOCOL_TYPE_KEEPALIVE) {
3567 struct rist_keepalive_info info;
3568 if (_librist_proto_gre_parse_keepalive(&recv_buf[payload_offset], recv_bufsize - payload_offset, &info) != 0) {
3569 p->last_pkt_received = now;
3570 return;
3571 }
3572 if (memcmp(&info.ka, &p->data, sizeof(peer->data)) != 0) {
3573 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
3574 "New keepalive received. MAC: %x:%x:%x:%x:%x:%x"
3575 " X: %d R: %d B: %d A: %d P: %d E: %d L: %d: N: %d"
3576 " D: %d T: %d V: %d: J: %d F: %d\n",
3577 info.mac[0], info.mac[1], info.mac[2],
3578 info.mac[3], info.mac[4], info.mac[5],
3579 info.x, info.r, info.b, info.a,
3580 info.p, info.e, info.l, info.e,
3581 info.n, info.d, info.t, info.v,
3582 info.j, info.f);
3583 if (info.json_len) {
3584 /* %.*s precision must be int. Truncate the log line if some
3585 * weird future caller hands us a giant blob. */
3586 int json_log_len = info.json_len > (size_t)INT_MAX ? INT_MAX : (int)info.json_len;
3587 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Keepalive JSON:\n%.*s\n", json_log_len, info.json);
3588 }
3589 //TODO: add callback?
3590 /* TR-06-3 Section 9: detect Advanced Profile support via I bit */
3591 if (info.adv_i && !p->remote_supports_advanced) {
3592 p->remote_supports_advanced = true;
3593 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
3594 "Peer %u advertises Advanced Profile capability (I=1)\n",
3595 p->adv_peer_id);
3596 }
3597 memcpy(&p->data, &info.ka, sizeof(peer->data));
3598 }
3599 if (p->receiver_ctx &&
3600 p->receiver_ctx->merge_mode == LIBRIST_MERGE_MODE_AUTO) {
3601 struct rist_flow *fl = cctx->FLOWS;
3602 while (fl) {
3603 if (fl->merge_auto_enabled != (bool)info.l) {
3604 fl->merge_auto_enabled = (bool)info.l;
3605 rist_log_priv(cctx, RIST_LOG_INFO,
3606 "merge=auto: peer %s pair-split; "
3607 "merge %s for flow %u\n",
3608 info.l ? "advertises" : "stopped advertising",
3609 info.l ? "enabled" : "disabled",
3610 fl->flow_id);
3611 }
3612 fl = fl->next;
3613 }
3614 }
3615 p->last_pkt_received = now;
3616 return;
3617 }
3618
3619 if (gre_proto == RIST_VSF_PROTOCOL_SUBTYPE_BUFFER_NEGOTIATION) {
3620 uint16_t sender_max_buffer;
3621 uint16_t client_current_buffer;
3622 if (_librist_proto_gre_parse_buffer_negotiation(p, &recv_buf[payload_offset], recv_bufsize - payload_offset, &sender_max_buffer, &client_current_buffer) != 0)
3623 return;
3624
3625 p->is_reflector_publisher = sender_max_buffer != 0;
3626
3627 if (p->receiver_ctx != NULL && sender_max_buffer != 0) {
3628 if (sender_max_buffer < p->config.recovery_length_min) {
3629 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Sender max buffer %u smaller than min buffer %u, disabling buffer negotiation!\n", sender_max_buffer, p->config.recovery_length_min);
3630 p->sender_max_buffer_ticks = 0;
3631 } else {
3632 p->sender_max_buffer_ticks = sender_max_buffer * RIST_CLOCK;
3633 if (peer->config.reflector && peer->listening && !peer->multicast_receiver) {
3634 struct rist_peer *child = peer->child;
3635 while (child) {
3636 if (child != p && !child->is_reflector_publisher && child->rist_gre_version >= 2) {
3637 _librist_proto_gre_send_buffer_negotiation(child, sender_max_buffer, 0);
3638 }
3639 child = child->sibling_next;
3640 }
3641 }
3642 }
3643 }
3644 return;
3645 }
3646
3647 uint32_t rtp_time = 0;
3648 uint64_t source_time = 0;
3649 uint8_t payload_type = 0;
3650 int ts_null_bytes = 0;
3651
3652 if (cctx->profile == RIST_PROFILE_SIMPLE || gre_proto == RIST_GRE_PROTOCOL_TYPE_REDUCED) {
3653 // This is for legacy compatibility (to be removed later)
3654 if (rtp->payload_type == PTYPE_XR_LEGACY)
3655 rtp->payload_type = PTYPE_XR;
3656 payload_type = rtp->payload_type;
3657 uint8_t payload_type_nomarker_bit = rtp->payload_type & 127;
3658 // Finish defining the payload (we assume reduced header)
3659 // The check is for 200-205 and 72-77 (payload type minus 128)
3660 if(payload_type_nomarker_bit < 72 || payload_type_nomarker_bit > 77) {
3661 // This will mis-clasify rtp packets with payload types 72-77 as rtcp. However,
3662 // this range is reserved for "RTCP conflict avoidance” on RFC4855. Furthermore,
3663 // we are already using 77 for PTYPE_XR
3664 // Remove the marker bit as it is not part of the payload type for non-rtcp data
3665 payload_type = payload_type_nomarker_bit;
3666 flow_id = be32toh(rtp->ssrc);
3667 // If this is a retry, extract the information and restore correct flow_id
3668 if (flow_id & 1UL)
3669 {
3670 flow_id ^= 1UL;
3671 retry = 1;
3672 }
3673 payload_offset += sizeof(*rtp);
3674 uint8_t *data_payload = &recv_buf[payload_offset];
3675 payload.size = recv_bufsize - (payload_offset);
3676 payload.data = (void *)data_payload;
3677
3678 if (CHECK_BIT(rtp->flags, 4)) {
3679 // X bit promises an extension header, the packet may not actually have it
3680 if (payload.size < sizeof(struct rist_rtp_hdr_ext)) {
3681 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3682 "Packet too small for RTP extension header: %zu bytes, ignoring ...\n",
3683 payload.size);
3684 return;
3685 }
3686 uint8_t *data_payload_out = &recv_buf_npd[0];
3687 //RTP extension header
3688 struct rist_rtp_hdr_ext * hdr_ext = (struct rist_rtp_hdr_ext *)(&recv_buf[payload_offset]);
3689 payload.size -= sizeof(*hdr_ext);
3690 data_payload += sizeof(*hdr_ext);
3691 payload.data = (void *)data_payload;
3692 if (memcmp(&hdr_ext->identifier, "RI", 2) == 0 && be16toh(hdr_ext->length) == 1)
3693 {
3694 // Null packet expansion (use a separate buffer and replace it when we had nulls)
3695 if (CHECK_BIT(hdr_ext->flags, 7)) {
3696 ts_null_bytes = expand_null_packets(data_payload, data_payload_out, &payload.size, hdr_ext->npd_bits);
3697 if (ts_null_bytes)
3698 payload.data = (void *)data_payload_out;
3699 }
3700 }
3701 }
3702 payload.type = RIST_PAYLOAD_TYPE_DATA_RAW;
3703 } else {
3704 // remap the rtp payload to the correct rtcp header
3705 struct rist_rtcp_hdr *rtcp = (struct rist_rtcp_hdr *)rtp;
3706 //payload_offset += sizeof(*rtcp);
3707 uint8_t *data_payload = &recv_buf[payload_offset];
3708 payload.size = recv_bufsize - (payload_offset);
3709 payload.data = (void *)data_payload;
3710 flow_id = be32toh(rtcp->ssrc);
3711 payload.type = RIST_PAYLOAD_TYPE_RTCP;
3712 }
3713 }
3714
3715 // We need this protocol bypass to manage keepalives of any kind,
3716 // they need to trigger peering at the bottom of this function
3717
3718 ;
3719 bool failed_eap = false;
3720 if (p->eap_authentication_state != 1 && p->dead) {
3721 uint64_t dead_time = (now - p->last_pkt_received);
3722 p->dead = false;
3723 //Only used on main profile
3724 if (p->parent)
3725 ++p->parent->child_alive_count;
3726 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
3727 "Peer %u was dead for %"PRIu64" ms and it is now alive again\n",
3728 p->adv_peer_id, dead_time / RIST_CLOCK);
3729 if (p->peer_data)
3730 p->peer_data->dead = 0;
3731 }
3732 p->last_pkt_received = now;
3733 if (ts_null_bytes)
3734 p->stats_receiver_instant.ts_null++;
3735 if (p->flow)
3736 p->flow->last_recv_ts = now;
3737 payload.peer = p;
3738 if (cctx->profile == RIST_PROFILE_SIMPLE)
3739 {
3740 payload.src_port = p->remote_port;
3741 payload.dst_port = p->local_port;
3742 }
3743 //rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Port is %d !!!!!\n", addr4.sin_port);
3744 #if HAVE_SRP_SUPPORT
3745 if (payload.type != RIST_PAYLOAD_TYPE_EAPOL && p->eap_ctx && !eap_is_authenticated(p->eap_ctx))
3746 {
3747 if (now > (p->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3748 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Waiting for EAP authentication to happen for peer connecting on port %u\n", ((struct sockaddr_in *)addr)->sin_port);
3749 p->log_repeat_timer = now;
3750 }
3751 // Do not process non EAP packets until the peer has been authenticated!
3752 return;
3753 }
3754 #endif
3755 //Cobalt's implementation has an identity crisis in it's response to our echo packets & set's the wrong SSRC (ours) on the RTP packet. Work around this flaw.
3756 if (peer && peer->receiver_ctx && flow_id == peer->peer_ssrc && peer->flow && peer->flow->flow_id && peer->flow->flow_id != flow_id)
3757 flow_id = peer->flow->flow_id;
3758
3759 switch(payload.type) {
3760 case RIST_PAYLOAD_TYPE_UNKNOWN:
3761 // Do nothing ...TODO: check for port changes?
3762 break;
3763 case RIST_PAYLOAD_TYPE_DATA_OOB:
3764 payload.size = recv_bufsize - payload_offset;
3765 payload.data = (void *)(recv_buf + payload_offset);
3766 rist_recv_oob_data(p, &payload);
3767 break;
3768 case RIST_PAYLOAD_TYPE_RTCP:
3769 if (p->is_rtcp && !p->handled_first) {
3770 rist_new_connection(peer, p, flow_id);
3771 if (!peer->receiver_mode) {
3772 // only profile > simple
3773 // authenticate sender now that we have an address
3774 rist_peer_authenticate(p);
3775 }
3776 p->handled_first = true;
3777 }
3778 RIST_FALLTHROUGH;
3779 case RIST_PAYLOAD_TYPE_RTCP_NACK:
3780 /* Need this for interop, we should move this to a per flow level eventually once we support multiple flows on a single peer*/
3781 if (RIST_UNLIKELY(p->receiver_ctx && p->local_port != payload.dst_port)) {
3782 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Updating peer virt dst port to match remote source port: %u\n", payload.src_port);
3783 p->local_port = payload.dst_port;
3784 p->remote_port = payload.src_port;
3785 }
3786 rist_recv_rtcp(p, seq, flow_id, &payload);
3787 break;
3788 case RIST_PAYLOAD_TYPE_DATA_RAW:
3789 if (p->is_data && !p->handled_first) {
3790 rist_new_connection(peer, p, flow_id);
3791 p->handled_first = true;
3792 }
3793 rtp_time = be32toh(rtp->ts);
3794 if (RIST_UNLIKELY(p->config.timing_mode == RIST_TIMING_MODE_ARRIVAL))
3795 source_time = timestampNTP_u64();
3796 else
3797 source_time = convertRTPtoNTP(payload_type, time_extension, rtp_time);
3798 seq = (uint32_t)be16toh(rtp->seq);
3799 if (RIST_UNLIKELY(!p->receiver_mode))
3800 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
3801 "Received data packet on sender, ignoring (%d bytes)...\n", payload.size);
3802 else {
3803 size_t received_bytes = recv_bufsize - payload_offset; //use the unexpanded size to show real BW
3804 rist_calculate_bitrate(received_bytes, &p->bw);
3805 rist_receiver_recv_data(p, seq, flow_id, source_time, now, &payload, retry, payload_type, received_bytes, ts_null_bytes, true);
3806 }
3807 break;
3808 case RIST_PAYLOAD_TYPE_EAPOL:
3809 #if HAVE_SRP_SUPPORT
3810 if (p->eap_ctx == NULL) {
3811 rist_log_priv(get_cctx(p), RIST_LOG_ERROR, "EAP authentication requested but credentials have not been configured!\n");
3812 }
3813 else {
3814 int eapret = 0;
3815 if ((eapret = eap_process_eapol(p->eap_ctx,
3816 (recv_buf + payload_offset),
3817 (recv_bufsize - payload_offset))) < 0) {
3818 rist_log_priv(get_cctx(p), RIST_LOG_ERROR, "Failed to process EAPOL pkt, return code: %i\n", eapret);
3819 /* eap_process_eapol returns a negative code; was being
3820 * compared against +255 and never matched, so failed_eap
3821 * was effectively dead. */
3822 if (eapret == EAP_AUTH_TERMINATED)
3823 failed_eap = true;
3824 }
3825 else if (p->eap_authentication_state != 2 && eap_is_authenticated(p->eap_ctx)) {
3826 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
3827 "Peer %d EAP Authentication succeeded\n", peer->adv_peer_id);
3828 p->eap_authentication_state = 2;
3829 //First authentication, so send keepalive
3830 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3831 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3832 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3833 if (p->rist_gre_version >= 2 && p->sender_ctx != NULL) {
3834 _librist_proto_gre_send_buffer_negotiation(p, peer->sender_ctx->sender_recover_min_time, 0);
3835 _librist_proto_gre_send_buffer_negotiation(p, peer->sender_ctx->sender_recover_min_time, 0);
3836 _librist_proto_gre_send_buffer_negotiation(p, peer->sender_ctx->sender_recover_min_time, 0);
3837 }
3838 }
3839 }
3840 #else
3841 if (peer->eap_ctx == NULL) {
3842 rist_log_priv(get_cctx(p), RIST_LOG_ERROR, "EAP authentication requested but EAP support not available!\n");
3843 failed_eap = true;
3844 }
3845 #endif
3846 if (failed_eap) {
3847 //A previously authenticated client fails authentication, and we're running multicast, so we need to rollover the passphrase
3848 #if HAVE_SRP_SUPPORT
3849 if (p->eap_authentication_state == 2 && p->parent && p->parent->multicast_sender) {
3850 char newpass[65];
3851 newpass[64] = '\0';
3852 if (_librist_crypto_random_get_string(newpass, sizeof(newpass)-1) == 0) {
3853 rist_peer_update_secret(p->parent, newpass);
3854 }
3855 }
3856 #endif
3857 p->eap_authentication_state = 1;
3858 kill_peer(p);
3859 }
3860 // Never create new peers using EAP packets (exit loop here)
3861 return;
3862 break;
3863 default:
3864 rist_recv_rtcp(p, seq, flow_id, &payload);
3865 break;
3866 }
3867 return;
3868 }
3869
3870 int rist_oob_enqueue(struct rist_common_ctx *ctx, struct rist_peer *peer, const void *buf, size_t len)
3871 {
3872 if (RIST_UNLIKELY(!ctx->oob_data_enabled)) {
3873 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3874 "Trying to send oob but oob was not enabled\n");
3875 return -1;
3876 }
3877 else if ((ctx->oob_queue_write_index + 1) == ctx->oob_queue_read_index)
3878 {
3879 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3880 "oob queue is full (%zu bytes), try again later\n", ctx->oob_queue_bytesize);
3881 return -1;
3882 }
3883
3884 /* insert into oob fifo queue */
3885 pthread_rwlock_wrlock(&ctx->oob_queue_lock);
3886 ctx->oob_queue[ctx->oob_queue_write_index] = rist_new_buffer(ctx, buf, len, RIST_PAYLOAD_TYPE_DATA_OOB, 0, 0, 0, 0);
3887 if (RIST_UNLIKELY(!ctx->oob_queue[ctx->oob_queue_write_index])) {
3888 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "\t Could not create oob packet buffer, OOM\n");
3889 pthread_rwlock_unlock(&ctx->oob_queue_lock);
3890 return -1;
3891 }
3892 ctx->oob_queue[ctx->oob_queue_write_index]->peer = peer;
3893 ctx->oob_queue_write_index = (ctx->oob_queue_write_index + 1);
3894 ctx->oob_queue_bytesize += len;
3895 pthread_rwlock_unlock(&ctx->oob_queue_lock);
3896
3897 return 0;
3898 }
3899
3900 static void rist_oob_dequeue(struct rist_common_ctx *ctx, int maxcount)
3901 {
3902 int counter = 0;
3903
3904 while (1) {
3905 // If we fall behind, only empty 100 every 5ms (master loop)
3906 if (counter++ > maxcount) {
3907 break;
3908 }
3909
3910 if (ctx->oob_queue_read_index == ctx->oob_queue_write_index) {
3911 //rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
3912 // "\tWe are all up to date, index is %u/%u and bytes = %zu\n",
3913 // ctx->oob_queue_read_index, ctx->oob_queue_write_index, ctx->oob_queue_bytesize);
3914 break;
3915 }
3916
3917 struct rist_buffer *oob_buffer = ctx->oob_queue[ctx->oob_queue_read_index];
3918 if (!oob_buffer->data) {
3919 rist_log_priv(ctx, RIST_LOG_ERROR, "Null oob buffer, skipping!!!\n");
3920 ctx->oob_queue_read_index++;
3921 continue;
3922 }
3923
3924 uint8_t *payload = oob_buffer->data;
3925 struct rist_peer *p = oob_buffer->peer;
3926 if (p->listening) {
3927 /* Listener peer: send OOB to all alive child peers.
3928 * Hold peerlist_lock while walking the child list to
3929 * prevent a concurrent peer add/remove from freeing a
3930 * sibling_next pointer underneath us. */
3931 pthread_mutex_lock(&ctx->peerlist_lock);
3932 struct rist_peer *child = p->child;
3933 bool sent = false;
3934 while (child) {
3935 if (!child->dead) {
3936 rist_send_common_rtcp(child, RIST_PAYLOAD_TYPE_DATA_OOB, &payload[RIST_MAX_PAYLOAD_OFFSET],
3937 oob_buffer->size, 0, 0, 0, 0, 0);
3938 sent = true;
3939 }
3940 child = child->sibling_next;
3941 }
3942 pthread_mutex_unlock(&ctx->peerlist_lock);
3943 if (!sent)
3944 rist_log_priv(ctx, RIST_LOG_WARN, "OOB: listener peer has no alive children, dropping\n");
3945 } else {
3946 rist_send_common_rtcp(p, RIST_PAYLOAD_TYPE_DATA_OOB, &payload[RIST_MAX_PAYLOAD_OFFSET],
3947 oob_buffer->size, 0, 0, 0, 0, 0);
3948 }
3949 ctx->oob_queue_bytesize -= oob_buffer->size;
3950 ctx->oob_queue_read_index++;
3951 }
3952
3953 return;
3954 }
3955
3956 static void sender_send_nacks(struct rist_sender *ctx)
3957 {
3958 // Send retries from the queue (if any)
3959 uint32_t counter = 1;
3960 int errors = 0;
3961 size_t total_bytes = 0;
3962
3963 if (ctx->max_nacksperloop == 0)
3964 return; // No peers yet
3965
3966 // Send nack retries. Stop when the retry queue is empty or when the data in the
3967 // send fifo queue grows to 10 packets (we do not want to harm real-time data)
3968 // We also stop on maxcounter (jitter control and max bandwidth protection)
3969 size_t queued_items = (atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire) - atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire)) &ctx->sender_queue_max;
3970 uint64_t start_time = timestampNTP_u64();
3971 while (queued_items < 10) {
3972 ssize_t ret = rist_retry_dequeue(ctx);
3973 if (ret == 0) {
3974 // ret == 0 is valid (nothing to send)
3975 break;
3976 } else if (ret < 0) {
3977 errors++;
3978 } else {
3979 total_bytes += ret;
3980 counter++;
3981 }
3982 if (counter > ctx->max_nacksperloop) {
3983 break;
3984 }
3985 if (((timestampNTP_u64() - start_time) / RIST_CLOCK) > 100)
3986 {
3987 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Nack processing loop took longer than 100ms. Something is wrong!\n");
3988 // TODO: clear out the nack queue here?
3989 break;
3990 }
3991 queued_items = (atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire) - atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire)) & ctx->sender_queue_max;
3992 }
3993 if (ctx->common.debug && 2 * (counter - 1) > ctx->max_nacksperloop)
3994 {
3995 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
3996 "Had to process multiple fifo nacks: c=%d, e=%d, b=%zu, s=%zu, m=%zu\n",
3997 counter - 1, errors, total_bytes, rist_get_sender_retry_queue_size(ctx),
3998 ctx->max_nacksperloop);
3999 }
4000
4001 }
4002
4003 static void sender_send_data(struct rist_sender *ctx, int maxcount)
4004 {
4005 int counter = 0;
4006
4007 while (1) {
4008 // If we fall behind, only empty 100 every 5ms (master loop)
4009 if (counter++ > maxcount) {
4010 break;
4011 }
4012
4013 size_t idx = ((size_t)atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire) + 1)& (ctx->sender_queue_max-1);
4014
4015 if (idx == (size_t)atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_relaxed)) {
4016 //rist_log_priv(&ctx->common, RIST_LOG_ERROR,
4017 // "\t[GOOD] We are all up to date, index is %d\n",
4018 // ctx->sender_queue_read_index);
4019 break;
4020 }
4021
4022 atomic_store_explicit(&ctx->sender_queue_read_index, idx, memory_order_release);
4023 if (RIST_UNLIKELY(ctx->sender_queue[idx] == NULL)) {
4024 ctx->sender_queue_size--;
4025 // This should never happen!
4026 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
4027 "FIFO data block was null (read/write) (%zu/%zu)\n",
4028 idx, atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_relaxed));
4029 continue;
4030 } else {
4031 struct rist_buffer *buffer = ctx->sender_queue[idx];
4032 // Send fifo data (handshake and data payloads)
4033 if (buffer->type == RIST_PAYLOAD_TYPE_RTCP) {
4034 // TODO can we ever have a null or dead buffer->peer?
4035 uint8_t *payload = buffer->data;
4036 rist_send_common_rtcp(buffer->peer, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, 0, ctx->sender_queue[idx]->ts_null_bytes);
4037 buffer->seq = ctx->common.seq;
4038 buffer->seq_rtp = ctx->common.seq_rtp;
4039 }
4040 else {
4041 rist_sender_send_data_balanced(ctx, buffer);
4042 if (ctx->common.profile == RIST_PROFILE_ADVANCED)
4043 ctx->seq_index[buffer->seq & (ctx->sender_queue_max - 1)] = (uint32_t)idx;
4044 else
4045 ctx->seq_index[buffer->seq_rtp] = (uint32_t)idx;
4046 }
4047 }
4048
4049 // Keep only sender_buffer_size items in buffer (this controls the size of the sender queue used on retries)
4050 int reduce = 0;
4051 do {
4052 size_t delete_idx = ((size_t)atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire) - ctx->sender_buffer_size) & (ctx->sender_queue_max - 1);
4053 ctx->sender_queue_delete_index = delete_idx;
4054 if (ctx->sender_queue[delete_idx] && ctx->sender_queue[delete_idx]->data) {
4055 /* perform the deletion based on the buffer size plus twice the configured/measured avg_rtt */
4056 uint64_t delay = (timestampNTP_u64() - ctx->sender_queue[delete_idx]->time) / RIST_CLOCK;
4057 ctx->sender_queue_timelength = delay;
4058 if (delay < ctx->sender_recover_min_time) {
4059 if (ctx->sender_buffer_size < ctx->sender_queue_max - 1)
4060 ctx->sender_buffer_size++;
4061 reduce = 0;
4062 break;
4063 }
4064 else if (reduce == 0 && delay > ctx->sender_recover_min_time * 1.1) {
4065 // Shrink the buffer size by one (packet is old enough)
4066 if (ctx->sender_buffer_size > 0) {
4067 reduce = 1;
4068 ctx->sender_buffer_size--;
4069 }
4070 }
4071 else {
4072 // We are not reducing the buffer size a second time
4073 reduce = 0;
4074 }
4075 ctx->sender_queue_bytesize -= ctx->sender_queue[delete_idx]->size;
4076 ctx->sender_queue_size--;
4077 free(ctx->sender_queue[delete_idx]->data);
4078 ctx->sender_queue[delete_idx]->data = NULL;
4079 }
4080 if (ctx->sender_queue[delete_idx]) {
4081 free(ctx->sender_queue[delete_idx]);
4082 ctx->sender_queue[delete_idx] = NULL;
4083 }
4084 } while (reduce && ctx->sender_queue_size > 0);
4085
4086 }
4087 }
4088
4089 static struct rist_peer *peer_initialize(const char *url, struct rist_sender *sender_ctx,
4090 struct rist_receiver *receiver_ctx)
4091 {
4092 struct rist_common_ctx *cctx;
4093 if (receiver_ctx)
4094 cctx = &receiver_ctx->common;
4095 else
4096 cctx = &sender_ctx->common;
4097
4098 struct rist_peer *p = calloc(1, sizeof(*p));
4099 if (!p) {
4100 rist_log_priv(cctx, RIST_LOG_ERROR, "\tNot enough memory creating peer!\n");
4101 return NULL;
4102 }
4103
4104 if (pthread_mutex_init(&p->peer_lock, NULL) != 0) {
4105 rist_log_priv(cctx, RIST_LOG_ERROR, "\tError initializing peer lock!\n");
4106 free(p);
4107 return NULL;
4108 }
4109
4110 if (url) {
4111 p->url = strdup(url);
4112 }
4113
4114 p->receiver_mode = (receiver_ctx != NULL);
4115 p->config.recovery_mode = RIST_RECOVERY_MODE_UNCONFIGURED;
4116 p->rtcp_keepalive_interval = RIST_PING_INTERVAL * RIST_CLOCK;
4117 p->sender_ctx = sender_ctx;
4118 p->receiver_ctx = receiver_ctx;
4119 p->birthtime_local = timestampNTP_u64();
4120 p->handled_first = true;
4121 p->sd = -1;
4122
4123 return p;
4124 }
4125
4126 static PTHREAD_START_FUNC(receiver_pthread_dataout, arg)
4127 {
4128 struct rist_flow *flow = (struct rist_flow *)arg;
4129 struct rist_receiver *receiver_ctx = (void *)flow->receiver_id;
4130
4131 #ifndef _WIN32
4132 int prio_max = sched_get_priority_max(SCHED_RR);
4133 struct sched_param param = { 0 };
4134 param.sched_priority = prio_max;
4135 if (pthread_setschedparam(pthread_self(), SCHED_RR, &param) != 0)
4136 rist_log_priv(&receiver_ctx->common, RIST_LOG_WARN, "Failed to set data output thread to RR scheduler with prio of %i\n", prio_max);
4137 #else
4138 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
4139 #endif
4140 // Default max jitter is 5ms
4141 int max_output_jitter_ms = flow->max_output_jitter / RIST_CLOCK;
4142 if (max_output_jitter_ms > 100)
4143 max_output_jitter_ms = 100;
4144
4145 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO, "Starting data output thread with %d ms max output jitter\n", max_output_jitter_ms);
4146
4147 pthread_mutex_lock(&(flow->mutex));
4148 uint64_t target_recovery_buffer_size = flow->recovery_buffer_ticks;
4149 pthread_mutex_unlock(&(flow->mutex));
4150
4151 uint64_t next_buffer_adjust_step = timestampNTP_u64() + ONE_SECOND;
4152 uint64_t buffer_adjust_step_time = 0;
4153 int64_t buffer_adjust_step_size = 0;
4154 int buffer_adjust_steps_left = 0;
4155
4156 while (true) {
4157 pthread_mutex_lock(&(flow->mutex));
4158 int ret = pthread_cond_timedwait_ms(&flow->condition, &flow->mutex, max_output_jitter_ms);
4159 if (ret && ret != ETIMEDOUT)
4160 rist_log_priv(&receiver_ctx->common, RIST_LOG_ERROR, "Error %d in receiver data out loop\n", ret);
4161 if (atomic_load_explicit(&flow->shutdown,memory_order_acquire) > 0)
4162 break;
4163 if (atomic_load_explicit(&flow->receiver_queue_size, memory_order_acquire) > 0) {
4164 receiver_output(receiver_ctx, flow);
4165 }
4166
4167 if (flow->flow_auto_buffer_scaling) {
4168 uint64_t now = timestampNTP_u64();
4169 if (target_recovery_buffer_size == flow->recovery_buffer_ticks) {
4170 if (now >= next_buffer_adjust_step) {
4171 if (flow->currently_scaling_buffer) {
4172 flow->currently_scaling_buffer = false;
4173 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO, "Done rescaling buffer\n");
4174 }
4175 next_buffer_adjust_step += ONE_SECOND;
4176 uint64_t tmp_target_buffer_size = 0;
4177 for (size_t i=0; i < flow->peer_lst_len; i++) {
4178 struct rist_peer *p = flow->peer_lst[i];
4179 if (p->recovery_buffer_ticks > tmp_target_buffer_size) {
4180 tmp_target_buffer_size = p->recovery_buffer_ticks;
4181 }
4182 }
4183
4184 uint64_t diff = target_recovery_buffer_size - tmp_target_buffer_size;
4185 if (tmp_target_buffer_size > target_recovery_buffer_size)
4186 diff = tmp_target_buffer_size - target_recovery_buffer_size;
4187
4188 if (diff > RIST_CLOCK * 15) {
4189 target_recovery_buffer_size = tmp_target_buffer_size;
4190 buffer_adjust_step_size = diff / 100;
4191 buffer_adjust_steps_left = 100;
4192 buffer_adjust_step_time = buffer_adjust_step_size * 8;//Magic factor of 8 to ensure our changes aren't too dramatic
4193 if (flow->recovery_buffer_ticks > target_recovery_buffer_size)
4194 buffer_adjust_step_size *= -1;
4195 next_buffer_adjust_step = now + buffer_adjust_step_time;
4196 if ((target_recovery_buffer_size *2ULL) > flow->session_timeout)
4197 flow->session_timeout = 2ULL * target_recovery_buffer_size;
4198 flow->currently_scaling_buffer = true;
4199 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO, "Adjusting flow buffer time to %"PRIu64"ms, flow timeout is %"PRIu64"ms\n", tmp_target_buffer_size/ RIST_CLOCK, flow->session_timeout/ RIST_CLOCK);
4200
4201 }
4202 }
4203 } else if (now >= next_buffer_adjust_step) {
4204 flow->recovery_buffer_ticks += buffer_adjust_step_size;
4205 buffer_adjust_steps_left--;
4206 next_buffer_adjust_step += buffer_adjust_step_time;
4207 if (buffer_adjust_steps_left == 0) {
4208 flow->recovery_buffer_ticks = target_recovery_buffer_size;
4209 uint64_t next_min = 2 * ONE_SECOND;
4210 if (flow->recovery_buffer_ticks *1.5 > next_min)
4211 next_min = flow->recovery_buffer_ticks *1.5;
4212 next_buffer_adjust_step = now + 2 *ONE_SECOND;// We don't want to adjust to often, so keep 2 seconds between adjustments
4213 }
4214 }
4215 }
4216
4217 pthread_mutex_unlock(&(flow->mutex));
4218 }
4219 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO, "Data output thread shutting down\n");
4220 atomic_store_explicit(&flow->shutdown, 2, memory_order_release);
4221 pthread_mutex_unlock(&flow->mutex);
4222 return 0;
4223 }
4224
4225 static void rist_peer_periodic(struct rist_peer *p, uint64_t now) {
4226 bool adv_negotiated = (get_cctx(p)->profile == RIST_PROFILE_ADVANCED &&
4227 p->is_advanced && p->remote_supports_advanced);
4228 if (p->send_keepalive) {
4229 if (now > p->next_periodic_rtcp) {
4230 p->next_periodic_rtcp = now + p->rtcp_keepalive_interval;
4231 if (p->remote_port != 0) {
4232 rist_peer_rtcp(NULL, p);
4233 if (adv_negotiated)
4234 rist_adv_send_rtt_echo_request(p);
4235 }
4236 }
4237 if (get_cctx(p)->profile >= RIST_PROFILE_MAIN && p->next_keepalive_packet <= now) {
4238 p->next_keepalive_packet = now + ONE_SECOND;
4239 if (adv_negotiated) {
4240 rist_adv_send_keepalive(p);
4241 if (p->sender_ctx && p->next_flow_attr <= now) {
4242 p->next_flow_attr = now + ONE_SECOND;
4243 rist_adv_send_flow_attr(p);
4244 }
4245 } else
4246 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
4247 #if HAVE_SRP_SUPPORT
4248 if (!p->child && !eap_is_authenticated(p->eap_ctx) && p->eap_authentication_state == 2 && p->parent && p->parent->multicast_sender) {
4249 p->eap_authentication_state = 1;
4250 char newpass[65];
4251 newpass[64] = '\0';
4252 if (_librist_crypto_random_get_string(newpass, sizeof(newpass)-1) == 0) {
4253 rist_peer_update_secret(p->parent, newpass);
4254 }
4255 }
4256 #endif
4257 }
4258 }
4259 #if HAVE_SRP_SUPPORT
4260 if ((!p->listening || p->parent) && !p->multicast_sender)
4261 eap_periodic(p->eap_ctx);
4262 #endif
4263 }
4264
4265 static void sender_peer_events(struct rist_sender *ctx, uint64_t now)
4266 {
4267 pthread_mutex_lock(&ctx->common.peerlist_lock);
4268 for (size_t j = 0; j < ctx->peer_lst_len; j++) {
4269 rist_peer_periodic(ctx->peer_lst[j], now);
4270 }
4271 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4272 }
4273
4274
4275 static void receiver_peer_events(struct rist_receiver *ctx, uint64_t now)
4276 {
4277 pthread_mutex_lock(&ctx->common.peerlist_lock);
4278
4279 for (struct rist_peer *p = ctx->common.PEERS; p != NULL; p = p->next) {
4280 rist_peer_periodic(p, now);
4281 }
4282 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4283 }
4284
4285 void rist_timeout_check(struct rist_common_ctx *cctx, uint64_t now)
4286 {
4287 struct rist_peer *peer = cctx->PEERS;
4288 while (peer)
4289 {
4290 struct rist_peer *next = peer->next;
4291 uint64_t last_rtcp_received = peer->last_pkt_received;
4292 if (cctx->profile == RIST_PROFILE_SIMPLE &&
4293 !peer->is_rtcp && peer->peer_rtcp != NULL &&
4294 peer->peer_rtcp->last_pkt_received > last_rtcp_received)
4295 last_rtcp_received = peer->peer_rtcp->last_pkt_received;
4296 if (!peer->dead && now > last_rtcp_received && last_rtcp_received > 0)
4297 {
4298 if ((now - last_rtcp_received) > peer->session_timeout)
4299 {
4300 rist_log_priv2(cctx->logging_settings, RIST_LOG_WARN, "Listening peer %u timed out after %"PRIu64" ms\n", peer->adv_peer_id,
4301 (now - last_rtcp_received)/ RIST_CLOCK);
4302 if (try_caller_socket_rebind(peer, now))
4303 {
4304 /* Rebind kept the peer alive with a fresh
4305 * socket; skip kill_peer. */
4306 peer = next;
4307 continue;
4308 }
4309 kill_peer(peer);
4310 }
4311 } else if (peer->dead && peer->parent)
4312 {
4313 if ( peer->dead_since < now && (now - peer->dead_since) > 5000 * RIST_CLOCK)
4314 {
4315 rist_log_priv2(cctx->logging_settings, RIST_LOG_INFO, "Removing timed-out peer %u\n", peer->adv_peer_id);
4316 rist_peer_remove(cctx, peer, NULL);
4317 }
4318 } else if (!peer->timed_out && peer->dead && peer->dead_since < now && (now - peer->dead_since) > 5000 * RIST_CLOCK) {
4319 peer->timed_out = 1;
4320 if (cctx->connection_status_callback && peer->send_first_connection_event)
4321 cctx->connection_status_callback( cctx->connection_status_callback_argument, peer, RIST_CONNECTION_TIMED_OUT);
4322 }
4323 peer = next;
4324 }
4325 }
4326
4327 PTHREAD_START_FUNC(sender_pthread_protocol, arg)
4328 {
4329 struct rist_sender *ctx = (struct rist_sender *) arg;
4330 // loop behavior parameters
4331 int max_dataperloop = 100;
4332 int max_oobperloop = 100;
4333
4334 int max_jitter_ms = ctx->common.rist_max_jitter / RIST_CLOCK;
4335 uint64_t rist_stats_interval = ctx->stats_report_time; // 1 second
4336
4337 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Starting master sender loop at %d ms max jitter\n",
4338 max_jitter_ms);
4339
4340 uint64_t now = timestampNTP_u64();
4341 ctx->stats_next_time = now;
4342 ctx->checks_next_time = now;
4343 uint64_t nacks_next_time = now;
4344 while(!atomic_load_explicit(&ctx->common.shutdown, memory_order_acquire)) {
4345 // Conditional 5ms sleep that is woken by data coming in
4346 pthread_mutex_lock(&(ctx->mutex));
4347 int ret = pthread_cond_timedwait_ms(&(ctx->condition), &(ctx->mutex), max_jitter_ms);
4348 if (RIST_UNLIKELY(!atomic_load_explicit(&ctx->common.startup_complete, memory_order_acquire))) {
4349 pthread_mutex_unlock(&(ctx->mutex));
4350 continue;
4351 }
4352 pthread_mutex_unlock(&(ctx->mutex));
4353 if (ret && ret != ETIMEDOUT)
4354 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Error %d in sender protocol loop, loop time was %d us\n", ret, (timestampNTP_u64() - now));
4355
4356 now = timestampNTP_u64();
4357
4358 /* marks peer as dead, run every second */
4359 if (now > ctx->checks_next_time)
4360 {
4361 ctx->checks_next_time += (uint64_t)1000 * (uint64_t)RIST_CLOCK;
4362 pthread_mutex_lock(&ctx->common.peerlist_lock);
4363 rist_timeout_check(&ctx->common, now);
4364 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4365 }
4366
4367 // stats timer
4368 if (now > ctx->stats_next_time) {
4369 ctx->stats_next_time += rist_stats_interval;
4370 rist_sender_flow_statistics(ctx);
4371 // TODO: remove dead peers after stale flow time (both sender list and peer chain)
4372 // sender_peer_delete(peer->sender_ctx, peer);
4373 }
4374
4375 // socket polls (returns as fast as possible and processes the next 100 socket events)
4376 pthread_mutex_lock(&ctx->common.peerlist_lock);
4377 evsocket_loop_single(ctx->common.evctx, 0, 100);
4378 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4379
4380 // keepalive timer
4381 sender_peer_events(ctx, now);
4382
4383
4384 // Send data and process nacks
4385 pthread_mutex_lock(&ctx->queue_lock);
4386 if (ctx->sender_queue_bytesize > 0) {
4387 pthread_mutex_lock(&ctx->common.peerlist_lock);
4388 sender_send_data(ctx, max_dataperloop);
4389 // Group nacks and send them all at rist_max_jitter intervals.
4390 // sender_send_nacks() dereferences retry->peer for every
4391 // entry in the retry queue; the peer list (and hence any
4392 // given peer) can be torn down from rist_peer_destroy()
4393 // concurrently, so we must hold peerlist_lock across the
4394 // whole dequeue loop to prevent a use-after-free.
4395 if (now > nacks_next_time) {
4396 sender_send_nacks(ctx);
4397 nacks_next_time += ctx->common.rist_max_jitter;
4398 }
4399 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4400 }
4401 pthread_mutex_unlock(&ctx->queue_lock);
4402 // Send oob data
4403 if (ctx->common.oob_queue_bytesize > 0)
4404 rist_oob_dequeue(&ctx->common, max_oobperloop);
4405
4406 }
4407
4408 #ifdef _WIN32
4409 WSACleanup();
4410 #endif
4411 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Exiting master sender loop\n");
4412 atomic_store_explicit(&ctx->common.shutdown, 2, memory_order_release);
4413
4414 return 0;
4415 }
4416
4417 /* Idempotent: re-init is fine if cctx->profile is upgraded to Advanced
4418 * after the original init_common_ctx ran (e.g. via ?profile= URL override
4419 * in rist_peer_create). Re-rolls SSRC base and clears the seq counters. */
4420 void init_advanced_state(struct rist_common_ctx *ctx)
4421 {
4422 /* Generate a random even SSRC base for the Protected flow.
4423 * The Unprotected flow uses ssrc_base | 1 (Section 5.2.1). */
4424 uint32_t rnd = 0;
4425 _librist_crypto_ramdom_get_bytes((uint8_t *)&rnd, sizeof(rnd));
4426 ctx->adv_ssrc_base = rnd & ~(uint32_t)1;
4427 ctx->adv_seq_protected = 0;
4428 ctx->adv_seq_unprotected = 0;
4429 }
4430
4431 int init_common_ctx(struct rist_common_ctx *ctx, enum rist_profile profile)
4432 {
4433 #ifdef _WIN32
4434 int ret;
4435 WSADATA wsaData;
4436 ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
4437 if (ret < 0) {
4438 rist_log_priv3(RIST_LOG_ERROR, "Failed to initialize WSA\n");
4439 return -1;
4440 }
4441 #endif
4442 ctx->evctx = evsocket_create();
4443 ctx->rist_max_jitter = RIST_MAX_JITTER * RIST_CLOCK;
4444 ctx->recovery_queue_max = RIST_SERVER_QUEUE_BUFFERS;
4445 if (profile > RIST_PROFILE_ADVANCED) {
4446 rist_log_priv3( RIST_LOG_ERROR, "Profile not supported (%d), using main profile instead\n", profile);
4447 profile = RIST_PROFILE_MAIN;
4448 }
4449 if (profile == RIST_PROFILE_SIMPLE)
4450 rist_log_priv3( RIST_LOG_INFO, "Starting in Simple Profile Mode\n");
4451 else if (profile == RIST_PROFILE_MAIN)
4452 rist_log_priv3( RIST_LOG_INFO, "Starting in Main Profile Mode\n");
4453 else if (profile == RIST_PROFILE_ADVANCED)
4454 rist_log_priv3( RIST_LOG_INFO, "Starting in Advanced Profile Mode\n");
4455
4456 ctx->profile = profile;
4457 atomic_store_explicit(&ctx->profile_locked, false, memory_order_release);
4458 ctx->stats_report_time = 0;
4459
4460 if (profile == RIST_PROFILE_ADVANCED)
4461 init_advanced_state(ctx);
4462
4463 if (pthread_mutex_init(&ctx->peerlist_lock, NULL) != 0) {
4464 rist_log_priv3( RIST_LOG_ERROR, "Failed to init ctx->peerlist_lock\n");
4465 return -1;
4466 }
4467 if (pthread_mutex_init(&ctx->rist_free_buffer_mutex, NULL) != 0) {
4468 rist_log_priv3( RIST_LOG_ERROR, "Failed to init ctx->rist_free_buffer_mutex\n");
4469 return -1;
4470 }
4471 if (pthread_mutex_init(&ctx->flows_lock, NULL) != 0) {
4472 rist_log_priv3( RIST_LOG_ERROR, "Failed to init ctx->flows_lock\n");
4473 return -1;
4474 }
4475 if (pthread_mutex_init(&ctx->stats_lock, NULL) != 0) {
4476 rist_log_priv3( RIST_LOG_ERROR, "Failed to init ctx->stats_lock\n");
4477 return -1;
4478 }
4479 return 0;
4480 }
4481
4482 static inline void peer_remove_child(struct rist_peer *peer) {
4483 assert(peer->parent);
4484 //head
4485 if (!peer->sibling_prev) {
4486 peer->parent->child = peer->sibling_next;
4487 //middle or tail
4488 } else {
4489 peer->sibling_prev->sibling_next = peer->sibling_next;
4490 }
4491 if (peer->sibling_next)
4492 peer->sibling_next->sibling_prev = peer->sibling_prev;
4493 return;
4494 }
4495
4496 static inline void peer_remove_linked_list(struct rist_peer *peer) {
4497 assert(peer);
4498 struct rist_common_ctx *ctx = get_cctx(peer);
4499 if (!peer->prev) {
4500 ctx->PEERS = peer->next;
4501 } else {
4502 peer->prev->next = peer->next;
4503 }
4504 if (peer->next)
4505 peer->next->prev = peer->prev;
4506 return;
4507 }
4508
4509
4510 void remove_peer_from_flow(struct rist_peer *peer)
4511 {
4512 struct rist_flow *f = peer->flow;
4513 if (f == NULL)
4514 return;
4515 pthread_mutex_lock(&f->mutex);
4516 bool found = false;
4517 for (size_t i = 0; i < f->peer_lst_len; i++)
4518 {
4519 if (f->peer_lst[i] == peer)
4520 {
4521 f->peer_lst[i] = f->peer_lst[(f->peer_lst_len -1)];
4522 found = true;
4523 break;
4524 }
4525 }
4526 if (found)
4527 {
4528 if (f->peer_lst_len > 1)
4529 {
4530 struct rist_peer **shrunk = realloc(f->peer_lst, sizeof(peer) * (f->peer_lst_len -1));
4531 /* Shrink realloc may fail; keep the oversized allocation. */
4532 if (shrunk)
4533 f->peer_lst = shrunk;
4534 f->peer_lst_len--;
4535 } else
4536 {
4537 free(f->peer_lst);
4538 f->peer_lst_len = 0;
4539 f->peer_lst = NULL;
4540 }
4541 }
4542 pthread_mutex_unlock(&f->mutex);
4543 }
4544
4545 int rist_peer_remove(struct rist_common_ctx *ctx, struct rist_peer *peer, struct rist_peer **next)
4546 {
4547 if (peer == NULL) {
4548 if (next)
4549 *next = NULL;
4550 return -1;
4551 }
4552 atomic_store_explicit(&peer->shutdown, true, memory_order_release);
4553 if (peer->send_first_connection_event && !peer->timed_out && ctx->connection_status_callback && (ctx->profile != RIST_PROFILE_SIMPLE || peer->is_rtcp))
4554 ctx->connection_status_callback(ctx->connection_status_callback_argument, peer, RIST_CONNECTION_TIMED_OUT);
4555 if (peer->child)
4556 {
4557 while (peer->child) {
4558 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] removing child peer %u from peer %u\n", peer->child->adv_peer_id, peer->adv_peer_id);
4559 rist_peer_remove(ctx, peer->child, NULL);
4560 }
4561 }
4562
4563 struct rist_peer *check = ctx->PEERS;
4564 while (check)
4565 {
4566 if (check->peer_data == peer)
4567 check->peer_data = NULL;
4568 if (check->peer_rtcp == peer)
4569 check->peer_rtcp = NULL;
4570 check = check->next;
4571 }
4572
4573 /* Defensive: scrub any references to this peer from the sender's
4574 * retry queue. The protocol thread now drains that queue under
4575 * peerlist_lock, so it will never see a dangling retry->peer from
4576 * here, but clearing the slot makes later triage easier and keeps
4577 * the invariant explicit. */
4578 if (peer->sender_ctx && peer->sender_ctx->sender_retry_queue) {
4579 struct rist_sender *sctx = peer->sender_ctx;
4580 for (size_t i = 0; i < sctx->sender_retry_queue_size; i++) {
4581 if (sctx->sender_retry_queue[i].peer == peer) {
4582 sctx->sender_retry_queue[i].peer = NULL;
4583 sctx->sender_retry_queue[i].active = false;
4584 }
4585 }
4586 }
4587 if (peer->parent) {
4588 peer_remove_child(peer);
4589 if (peer->parent->child == NULL) {
4590 peer->parent->authenticated = false;
4591 if (peer->sender_ctx)
4592 peer->sender_ctx->total_weight -= peer->parent->config.weight;
4593 }
4594 }
4595 peer_remove_linked_list(peer);
4596
4597 if (peer->parent && peer->flow && peer->flow->peer_lst_len > 0 && peer->flow->peer_lst != NULL) {
4598 remove_peer_from_flow(peer);
4599 }
4600
4601 if (peer->sender_ctx && peer->sender_ctx->peer_lst_len > 0) {
4602 bool found = false;
4603 for (size_t i = 0; i < peer->sender_ctx->peer_lst_len; i++) {
4604 if (peer->sender_ctx->peer_lst[i] == peer) {
4605 peer->sender_ctx->peer_lst[i] = peer->sender_ctx->peer_lst[(peer->sender_ctx->peer_lst_len -1)];
4606 found = true;
4607 break;
4608 }
4609 }
4610 if (found) {
4611 if (peer->sender_ctx->peer_lst_len > 1)
4612 {
4613 peer->sender_ctx->peer_lst = realloc(peer->sender_ctx->peer_lst, sizeof(peer) * (peer->sender_ctx->peer_lst_len -1));
4614 peer->sender_ctx->peer_lst_len--;
4615 } else
4616 {
4617 free(peer->sender_ctx->peer_lst);
4618 peer->sender_ctx->peer_lst_len = 0;
4619 peer->sender_ctx->peer_lst = NULL;
4620 }
4621 }
4622 }
4623
4624 if (peer->receiver_ctx != NULL && peer->flow != NULL) {
4625 pthread_mutex_lock(&peer->flow->mutex);
4626 bool found = false;
4627 for (size_t i=0; i < peer->flow->peer_lst_len; i++) {
4628 if (peer->flow->peer_lst[i] == peer) {
4629 peer->flow->peer_lst[i] = peer->flow->peer_lst[(peer->flow->peer_lst_len -1)];
4630 found = true;
4631 break;
4632 }
4633 }
4634
4635 if (found) {
4636 if (peer->flow->peer_lst_len > 1) {
4637 /* Shrink realloc may fail; keep the oversized allocation. */
4638 struct rist_peer **shrunk = realloc(peer->flow->peer_lst, sizeof(peer) * (peer->flow->peer_lst_len -1));
4639 if (shrunk)
4640 peer->flow->peer_lst = shrunk;
4641 peer->flow->peer_lst_len--;
4642 } else {
4643 free(peer->flow->peer_lst);
4644 peer->flow->peer_lst_len = 0;
4645 peer->flow->peer_lst = NULL;
4646 }
4647 }
4648 pthread_mutex_unlock(&peer->flow->mutex);
4649 }
4650
4651
4652 /* data receive event */
4653 if (!peer->parent && peer->event_recv)
4654 {
4655 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] Removing peer data received event\n");
4656 struct evsocket_ctx *evctx = ctx->evctx;
4657 evsocket_delevent(evctx, peer->event_recv);
4658 }
4659
4660 /* rtcp timer */
4661 if (peer->send_keepalive)
4662 {
4663 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] Removing peer handshake/ping timer\n");
4664 peer->send_keepalive = false;
4665 }
4666
4667
4668 if (!peer->parent && peer->sd > -1)
4669 {
4670 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] Closing peer socket on port %d\n", peer->local_port);
4671 udpsocket_close(peer->sd);
4672 peer->sd = -1;
4673 }
4674 _librist_crypto_psk_rist_key_destroy(&peer->key_rx);
4675 _librist_crypto_psk_rist_key_destroy(&peer->key_rx_odd);
4676 _librist_crypto_psk_rist_key_destroy(&peer->key_tx);
4677 _librist_crypto_psk_rist_key_destroy(&peer->key_tx_odd);
4678 #if HAVE_SRP_SUPPORT
4679 eap_delete_ctx(&peer->eap_ctx);
4680 #endif
4681 if (peer->url)
4682 free(peer->url);
4683
4684 if (peer->parent != NULL && ctx->auth.disconn_cb) {
4685 ctx->auth.disconn_cb(ctx->auth.arg, peer);
4686 }
4687 if (next != NULL)
4688 *next = peer->next;
4689 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] cleanup done for peer %u\n", peer->adv_peer_id);
4690
4691 if (ctx->oob_current_peer == peer) {
4692 ctx->oob_current_peer = NULL;
4693 }
4694
4695 free(peer);
4696 return 0;
4697 }
4698
4699 int rist_auth_handler(struct rist_common_ctx *ctx,
4700 int (*conn_cb)(void *arg, const char* connecting_ip, uint16_t connecting_port, const char* local_ip, uint16_t local_port, struct rist_peer *peer),
4701 int (*disconn_cb)(void *arg, struct rist_peer *peer),
4702 void *arg)
4703 {
4704 ctx->auth.conn_cb = conn_cb;
4705 ctx->auth.disconn_cb = disconn_cb;
4706 ctx->auth.arg = arg;
4707 return 0;
4708 }
4709
4710 static void store_peer_settings(const struct rist_peer_config *settings, struct rist_peer *peer)
4711 {
4712 uint32_t recovery_rtt_min;
4713 uint32_t min_retries;
4714 uint32_t max_retries;
4715
4716 // TODO: Consolidate the two settings objects into one
4717
4718 /* Set recovery options */
4719 peer->config.recovery_mode = settings->recovery_mode;
4720 peer->config.recovery_maxbitrate = settings->recovery_maxbitrate;
4721 peer->config.recovery_maxbitrate_return = settings->recovery_maxbitrate_return;
4722 peer->config.recovery_length_min = settings->recovery_length_min;
4723 peer->config.recovery_length_max = settings->recovery_length_max;
4724 peer->config.recovery_reorder_buffer = settings->recovery_reorder_buffer;
4725 /* Set buffer-bloating */
4726 if (settings->min_retries < 2 || settings->min_retries > 100) {
4727 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
4728 "The configured value for min_retries 2 <= %u <= 100 is invalid, using %u instead\n",
4729 settings->min_retries, 6);
4730 min_retries = 6;
4731 } else {
4732 min_retries = settings->min_retries;
4733 }
4734 if (settings->max_retries < 2 || settings->max_retries > 100) {
4735 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
4736 "The configured value for max_retries 2 <= %u <= 100 is invalid, using %u instead\n",
4737 settings->max_retries, 20);
4738 max_retries = 20;
4739 } else {
4740 max_retries = settings->max_retries;
4741 }
4742 if (settings->recovery_rtt_min < RIST_RTT_MIN) {
4743 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "rtt_min is too small (%u), using %dms instead\n",
4744 settings->recovery_rtt_min, RIST_RTT_MIN);
4745 recovery_rtt_min = RIST_RTT_MIN;
4746 } else {
4747 recovery_rtt_min = settings->recovery_rtt_min;
4748 }
4749 // Override rtt min if value is unreasonable
4750 uint32_t min_rtt = settings->recovery_length_min / max_retries;
4751 if (recovery_rtt_min < min_rtt) {
4752 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "rtt_min is too small (%u) for the buffer size, using %u/%u = %dms instead\n",
4753 recovery_rtt_min, settings->recovery_length_min, max_retries, min_rtt);
4754 recovery_rtt_min = min_rtt;
4755 }
4756 if (settings->recovery_rtt_max < recovery_rtt_min)
4757 {
4758 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "rtt_max is too small (%u), using %u instead\n",
4759 settings->recovery_rtt_max, recovery_rtt_min);
4760 peer->config.recovery_rtt_max = recovery_rtt_min * RIST_CLOCK;
4761 }
4762 else
4763 peer->config.recovery_rtt_max = settings->recovery_rtt_max * RIST_CLOCK;
4764 peer->config.recovery_rtt_min = recovery_rtt_min * RIST_CLOCK;
4765 peer->config.congestion_control_mode = settings->congestion_control_mode;
4766 peer->config.min_retries = min_retries;
4767 peer->config.max_retries = max_retries;
4768 peer->config.weight = settings->weight;
4769 peer->config.recovery_priority = settings->recovery_priority;
4770 peer->config.timing_mode = settings->timing_mode;
4771 peer->config.virt_dst_port = settings->virt_dst_port;
4772 if (settings->version >= 2)
4773 peer->config.reflector = settings->reflector;
4774 else
4775 peer->config.reflector = 0;
4776 if (settings->version >= 3)
4777 peer->config.srp_compat_legacy = settings->srp_compat_legacy; //read by rist_enable_eap_srp_2 after peer_create
4778 else
4779 peer->config.srp_compat_legacy = 0;
4780
4781 init_peer_settings(peer);
4782 }
4783
4784 struct rist_peer *rist_sender_peer_insert_local(struct rist_sender *ctx,
4785 const struct rist_peer_config *config, bool b_rtcp)
4786 {
4787 struct rist_peer *newpeer = _librist_peer_create_common(&ctx->common, NULL, ctx, config);
4788 if (!newpeer)
4789 return NULL;
4790 if (b_rtcp)
4791 {
4792 if (newpeer->u.address.sa_family == AF_INET) {
4793 struct sockaddr_in *addrv4 = (struct sockaddr_in *)&(newpeer->u);
4794 newpeer->remote_port = htons(addrv4->sin_port) + 1;
4795 addrv4->sin_port = be16toh(newpeer->remote_port);
4796 } else {
4797 struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *)&(newpeer->u);
4798 newpeer->remote_port = htons(addrv6->sin6_port) + 1;
4799 addrv6->sin6_port = be16toh(newpeer->remote_port);
4800 }
4801 }
4802 else
4803 {
4804 newpeer->local_port = 32768 + (ctx->common.peer_counter % 28232);
4805 // This overrides the physical port populate in rist_create_socket with the gre dst port
4806 if (ctx->common.profile != RIST_PROFILE_SIMPLE && config->virt_dst_port != 0)
4807 newpeer->remote_port = config->virt_dst_port + 1;
4808 }
4809
4810 newpeer->cooldown_time = 0;
4811 newpeer->is_rtcp = b_rtcp;
4812 newpeer->adv_peer_id = ++ctx->common.peer_counter;
4813 newpeer->peer_ssrc = newpeer->adv_flow_id = ctx->adv_flow_id;
4814
4815 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Advertising flow_id %" PRIu64 " and peer_id %u, %u/%u\n",
4816 newpeer->adv_flow_id, newpeer->adv_peer_id, newpeer->local_port, newpeer->remote_port);
4817
4818 return newpeer;
4819
4820 }
4821
4822
4823 void rist_empty_oob_queue(struct rist_common_ctx *ctx)
4824 {
4825 uint16_t index = 0;
4826 while (1) {
4827 if (index == ctx->oob_queue_write_index) {
4828 break;
4829 }
4830 struct rist_buffer *oob_buffer = ctx->oob_queue[index];
4831 if (oob_buffer->data) {
4832 free(oob_buffer->data);
4833 oob_buffer->data = NULL;
4834 }
4835 if (oob_buffer) {
4836 free(oob_buffer);
4837 oob_buffer = NULL;
4838 }
4839 index++;
4840 }
4841 ctx->oob_queue_bytesize = 0;
4842 }
4843
4844 void rist_receiver_destroy_local(struct rist_receiver *ctx)
4845 {
4846
4847 pthread_mutex_lock(&ctx->common.peerlist_lock);
4848
4849 // Destroy all flows
4850 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Starting Flows cleanup\n");
4851 struct rist_flow *f = ctx->common.FLOWS;
4852 while (f) {
4853 struct rist_flow *nextflow = f->next;
4854 rist_delete_flow(ctx, f);
4855 f = nextflow;
4856 }
4857 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Flows cleanup complete\n");
4858
4859 // Destroy all peers
4860 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Starting Peers cleanup\n");
4861 struct rist_peer *peer, *next;
4862 peer = ctx->common.PEERS;
4863 for (;;) {
4864 if (!peer)
4865 break;
4866 rist_peer_remove(&ctx->common, peer, &next);
4867 peer = next;
4868 }
4869 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Peers cleanup complete\n");
4870
4871 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4872
4873 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Freeing main data buffers\n");
4874 struct rist_buffer *b = ctx->common.rist_free_buffer;
4875 struct rist_buffer *next_buf;
4876 while (b) {
4877 next_buf = b->next_free;
4878 free_rist_buffer(&ctx->common, b);
4879 b = next_buf;
4880 }
4881 evsocket_destroy(ctx->common.evctx);
4882
4883 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Removing peerlist_lock\n");
4884 pthread_mutex_destroy(&ctx->common.peerlist_lock);
4885 if (ctx->common.oob_data_enabled) {
4886 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Freeing oob fifo queue\n");
4887 rist_empty_oob_queue(&ctx->common);
4888 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Removing oob_queue_lock\n");
4889 pthread_rwlock_destroy(&ctx->common.oob_queue_lock);
4890 }
4891
4892 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Removing data fifo signaling variables (condition and mutex)\n");
4893 pthread_cond_destroy(&ctx->condition);
4894 pthread_mutex_destroy(&ctx->mutex);
4895
4896 rist_logging_unset_global_if_matches(ctx->common.logging_settings);
4897
4898 free(ctx);
4899 ctx = NULL;
4900 }
4901
4902 void _librist_receiver_buffer_calc(struct rist_receiver *ctx) {
4903 pthread_mutex_lock(&ctx->common.peerlist_lock);
4904 struct rist_peer *p = ctx->common.PEERS;
4905 while (p != NULL) {
4906 if (p->config.recovery_length_max != p->config.recovery_length_min && !p->listening && p->sender_max_buffer_ticks > 0 && p->flow && p->rist_gre_version >= 2) {
4907 //Optimal default according to rist spec (multiplier configurable via API):
4908 int rtt_mult = ctx->common.recovery_rtt_multiplier > 0 ? ctx->common.recovery_rtt_multiplier : 7;
4909 uint64_t desired_buffer_level = (p->eight_times_rtt / 8) * rtt_mult + p->config.recovery_reorder_buffer;
4910
4911 bool has_high_loss = false;
4912 double modifier = 1.0;
4913
4914 //Modify our buffersize based on some magic numbers, these likely still need tuning
4915 pthread_mutex_lock(&p->flow->mutex);
4916 modifier += p->flow->stats_instant.lost * 0.05;//5% extra per packet lost
4917 if (p->flow->stats_instant.lost > 25)
4918 has_high_loss = true;
4919
4920 modifier += p->flow->stats_instant.recovered_morenack * 0.02;
4921 modifier += p->flow->stats_instant.recovered_3nack * 0.01;
4922 pthread_mutex_unlock(&p->flow->mutex);
4923
4924 desired_buffer_level *= modifier;
4925
4926 if (has_high_loss)
4927 desired_buffer_level = p->sender_max_buffer_ticks;
4928
4929
4930 if (desired_buffer_level < p->recovery_buffer_ticks && (p->recovery_buffer_ticks - desired_buffer_level) > 50 * RIST_CLOCK) {
4931 desired_buffer_level = p->recovery_buffer_ticks - 50 * RIST_CLOCK;
4932 }
4933
4934 uint64_t recovery_base_min = p->config.recovery_length_min * RIST_CLOCK;
4935 uint64_t recovery_base_max = p->config.recovery_length_max * RIST_CLOCK;
4936
4937 if (desired_buffer_level < recovery_base_min)
4938 desired_buffer_level = recovery_base_min;
4939 else if (desired_buffer_level > recovery_base_max)
4940 desired_buffer_level = recovery_base_max;
4941
4942 if (desired_buffer_level > p->sender_max_buffer_ticks)
4943 desired_buffer_level = p->sender_max_buffer_ticks;
4944
4945 if (p->recovery_buffer_ticks != desired_buffer_level)
4946 _librist_proto_gre_send_buffer_negotiation(p, 0, desired_buffer_level/ RIST_CLOCK);
4947
4948 p->recovery_buffer_ticks = desired_buffer_level;
4949 }
4950 p = p->next;
4951 }
4952 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4953 }
4954
4955 PTHREAD_START_FUNC(receiver_pthread_protocol, arg)
4956 {
4957 struct rist_receiver *ctx = (struct rist_receiver *) arg;
4958 uint64_t now = timestampNTP_u64();
4959 int max_oobperloop = 100;
4960 uint64_t no_flow_time_check = timestampNTP_u64();
4961
4962 uint64_t rist_nack_interval = (uint64_t)ctx->common.rist_max_jitter;
4963 int max_jitter_ms = ctx->common.rist_max_jitter / RIST_CLOCK;
4964 ctx->common.nacks_next_time = timestampNTP_u64();
4965 uint64_t checks_next_time = now;
4966 uint64_t buffer_check_next_time = now + ONE_SECOND;
4967 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Starting receiver protocol loop with %d ms timer\n", max_jitter_ms);
4968
4969 while (!atomic_load_explicit(&ctx->common.shutdown, memory_order_acquire)) {
4970 now = timestampNTP_u64();
4971 pthread_mutex_lock(&ctx->common.peerlist_lock);
4972 if (ctx->common.PEERS == NULL) {
4973 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4974 usleep(5000);
4975 continue;
4976 }
4977 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4978
4979 // Limit scope of `struct rist_flow *f` for clarity since it is used again later in this loop.
4980 {
4981 // stats and session timeout timer
4982 struct rist_flow *f = ctx->common.FLOWS;
4983 if (!f)
4984 {
4985 // no flow timeout callback
4986 if ((now - no_flow_time_check) > ONE_SECOND && ctx->receiver_session_timeout_callback) {
4987 no_flow_time_check = now;
4988 ctx->receiver_session_timeout_callback(ctx->receiver_session_timeout_callback_argument, 0);
4989 }
4990 }
4991 while (f) {
4992 no_flow_time_check = now;
4993 pthread_mutex_lock(&f->mutex);
4994 if (!f->receiver_queue_has_items) {
4995 pthread_mutex_unlock(&f->mutex);
4996 f = f->next;
4997 continue;
4998 }
4999 if (now > f->checks_next_time) {
5000 if (f->last_recv_ts == 0)
5001 f->last_recv_ts = now;
5002 uint64_t flow_age = (now - f->last_recv_ts);
5003 f->checks_next_time += f->recovery_buffer_ticks;
5004 if (flow_age > f->flow_timeout) {
5005 if (f->dead != 1) {
5006 f->dead = 1;
5007 rist_log_priv(&ctx->common, RIST_LOG_WARN,
5008 "Flow with id %"PRIu32" is dead, age is %"PRIu64"ms\n",
5009 f->flow_id, flow_age / RIST_CLOCK);
5010 }
5011 }
5012 else {
5013 if (f->dead != 0) {
5014 f->dead = 0;
5015 rist_log_priv(&ctx->common, RIST_LOG_INFO,
5016 "Flow with id %"PRIu32" was dead and is now alive again\n", f->flow_id);
5017 }
5018 }
5019 if (flow_age > f->session_timeout) {
5020 f->dead = 2;
5021 struct rist_flow *next = f->next;
5022 rist_receiver_flow_statistics(ctx, f);
5023 rist_log_priv(&ctx->common, RIST_LOG_INFO,
5024 "\t************** Session Timeout after %" PRIu64 "s of no data, deleting flow with id %"PRIu32" ***************\n",
5025 flow_age / RIST_CLOCK / 1000, f->flow_id);
5026 if (ctx->receiver_session_timeout_callback) {
5027 ctx->receiver_session_timeout_callback(ctx->receiver_session_timeout_callback_argument, f->flow_id);
5028 }
5029 pthread_mutex_unlock(&f->mutex);
5030 pthread_mutex_lock(&ctx->common.peerlist_lock);
5031 pthread_mutex_lock(&f->mutex);
5032 for (size_t i = 0; i < f->peer_lst_len; i++) {
5033 struct rist_peer *peer = f->peer_lst[i];
5034 peer->flow = NULL;
5035 }
5036 pthread_mutex_unlock(&f->mutex);
5037 rist_delete_flow(ctx, f);
5038 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5039 f = next;
5040 continue;
5041 }
5042 }
5043 if (now > f->stats_next_time) {
5044 f->stats_next_time += f->stats_report_time;
5045 rist_receiver_flow_statistics(ctx, f);
5046 }
5047 pthread_mutex_unlock(&f->mutex);
5048 f = f->next;
5049 }
5050 }
5051
5052 // TODO: rist_max_jitter should be proportional to the max bitrate according to the
5053 // following table
5054 //Mbps ms
5055 //125 8.00
5056 //250 4.00
5057 //520 1.92
5058 //1000 1.00
5059
5060 // socket polls (returns in max_jitter_ms max and processes the next 100 socket events)
5061 pthread_mutex_lock(&ctx->common.peerlist_lock);
5062 evsocket_loop_single(ctx->common.evctx, max_jitter_ms, 100);
5063 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5064 // keepalive timer
5065 receiver_peer_events(ctx, now);
5066
5067 // nacks timer
5068 if (now > ctx->common.nacks_next_time) {
5069 ctx->common.nacks_next_time += rist_nack_interval;
5070 // process nacks on every loop (5 ms interval max)
5071 struct rist_flow *f = ctx->common.FLOWS;
5072 while (f) {
5073 receiver_nack_output(ctx, f);
5074 f = f->next;
5075 }
5076 }
5077 /* marks peer as dead, run every second */
5078 if (now > checks_next_time)
5079 {
5080 checks_next_time += (uint64_t)50 * (uint64_t)RIST_CLOCK;
5081 pthread_mutex_lock(&ctx->common.peerlist_lock);
5082 rist_timeout_check(&ctx->common, now);
5083 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5084 }
5085 // Send oob data
5086 if (ctx->common.oob_queue_bytesize > 0)
5087 rist_oob_dequeue(&ctx->common, max_oobperloop);
5088
5089 if (now >= buffer_check_next_time) {
5090 _librist_receiver_buffer_calc(ctx);
5091 buffer_check_next_time += 2 * ONE_SECOND;
5092 }
5093
5094 }
5095 #ifdef _WIN32
5096 WSACleanup();
5097 #endif
5098 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Exiting master receiver loop\n");
5099 atomic_store_explicit(&ctx->common.shutdown, 2, memory_order_release);
5100
5101 return 0;
5102 }
5103
5104 void rist_sender_destroy_local(struct rist_sender *ctx)
5105 {
5106 rist_log_priv(&ctx->common, RIST_LOG_INFO,
5107 "Starting peers cleanup, count %d\n",
5108 (unsigned) ctx->peer_lst_len);
5109
5110 pthread_mutex_lock(&ctx->common.peerlist_lock); // Destroy all peers
5111 while (ctx->peer_lst_len > 0) {
5112 rist_peer_remove(&ctx->common, ctx->peer_lst[0], NULL);
5113 }
5114 struct rist_peer *peer, *next;
5115 peer = ctx->common.PEERS;
5116 for (;;) {
5117 if (!peer)
5118 break;
5119 rist_peer_remove(&ctx->common, peer, &next);
5120 peer = next;
5121 }
5122 evsocket_destroy(ctx->common.evctx);
5123
5124 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5125 pthread_mutex_destroy(&ctx->common.peerlist_lock);
5126 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Peers cleanup complete\n");
5127
5128 if (ctx->common.oob_data_enabled) {
5129 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Freeing oob fifo queue\n");
5130 rist_empty_oob_queue(&ctx->common);
5131 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Removing oob_queue_lock\n");
5132 pthread_rwlock_destroy(&ctx->common.oob_queue_lock);
5133 }
5134
5135 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Freeing up context memory allocations\n");
5136 free(ctx->sender_retry_queue);
5137 ctx->sender_retry_queue = NULL;
5138 struct rist_buffer *b = NULL;
5139 while(1) {
5140 b = ctx->sender_queue[ctx->sender_queue_delete_index];
5141 while (!b) {
5142 ctx->sender_queue_delete_index = (ctx->sender_queue_delete_index + 1)& (ctx->sender_queue_max -1);
5143 b = ctx->sender_queue[ctx->sender_queue_delete_index];
5144 if ((size_t)atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_relaxed) == ctx->sender_queue_delete_index)
5145 break;
5146 }
5147 if (b) {
5148 ctx->sender_queue_bytesize -= b->size;
5149 ctx->sender_queue_size--;
5150 free_rist_buffer(&ctx->common, b);
5151 ctx->sender_queue[ctx->sender_queue_delete_index] = NULL;
5152 }
5153 if ((size_t)atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire) == ctx->sender_queue_delete_index) {
5154 break;
5155 }
5156 ctx->sender_queue_delete_index = (ctx->sender_queue_delete_index + 1)& (ctx->sender_queue_max -1);
5157 }
5158
5159 rist_logging_unset_global_if_matches(ctx->common.logging_settings);
5160
5161 free(ctx->sender_queue);
5162 ctx->sender_queue = NULL;
5163 free(ctx->seq_index);
5164 ctx->seq_index = NULL;
5165 free(ctx);
5166 ctx = NULL;
5167 }