Debian Codegraph @

src/rist-common.c

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