Debian Codegraph @

src/udp.c

raw symbols SCIP
1 /* librist. Copyright © 2019-2020 SipRadius LLC. All right reserved.
2 * Author: Daniele Lacamera <[email protected]>
3 * Author: Kuldeep Singh Dhaka <[email protected]>
4 * Author: Sergio Ammirata, Ph.D. <[email protected]>
5 *
6 * SPDX-License-Identifier: BSD-2-Clause
7 */
8
9 #include "logging.h"
10 #include "proto/gre.h"
11 #include "proto/protocol_gre.h"
12 #include "udp-private.h"
13 #include "rist-private.h"
14 #include "log-private.h"
15 #include "socket-shim.h"
16 #include "endian-shim.h"
17 #include "proto/rist_time.h"
18 #include "proto/protocol_rtp.h"
19 #if HAVE_SRP_SUPPORT
20 #include "proto/eap.h"
21 #endif
22 #include "crypto/psk.h"
23 #include "mpegts.h"
24 #include <lz4.h>
25 #include "transport-private.h"
26 #include <stdlib.h>
27 #include <stddef.h>
28 #include <errno.h>
29 #include <stdint.h>
30 #include <assert.h>
31 #include <fcntl.h>
32
33 /* EMSGSIZE-aware send-failure logger, rate-limited to one line per peer
34 * every 5 seconds to avoid drowning the log when the application is
35 * pushing a stream of oversized packets. The hint on the PMTU case is
36 * deliberately explicit and actionable: an operator who sees this once
37 * should be able to fix it by lowering the application packet size
38 * (e.g. risttunnel -m), without having to chase ICMP filtering. */
39 void _librist_log_send_error(struct rist_peer *p, int sock_errno,
40 size_t attempted, const char *origin)
41 {
42 struct rist_common_ctx *ctx = get_cctx(p);
43 uint64_t now = timestampNTP_u64();
44 bool is_pmtu;
45 #ifdef _WIN32
46 is_pmtu = (sock_errno == WSAEMSGSIZE);
47 #else
48 is_pmtu = (sock_errno == EMSGSIZE);
49 #endif
50 if (is_pmtu) {
51 const uint64_t five_seconds = (uint64_t)5 * 65536 * 1000;
52 if (p->last_pmtu_error_log != 0 &&
53 now - p->last_pmtu_error_log < five_seconds)
54 return;
55 p->last_pmtu_error_log = now;
56 rist_log_priv(ctx, RIST_LOG_ERROR,
57 "PMTU exceeded sending %zu-byte datagram via %s (errno=%d). The path "
58 "MTU to this peer is smaller than our RIST packet size and the "
59 "don't-fragment bit is set, so the kernel refused to fragment. "
60 "Lower the application packet size (e.g. risttunnel -m, or upstream "
61 "MPEG-TS UDP size) so that payload + ~40 bytes of headers fits in the "
62 "path MTU. Further PMTU errors on this peer will be silenced for 5s.\n",
63 attempted, origin, sock_errno);
64 } else {
65 rist_log_priv(ctx, RIST_LOG_ERROR,
66 "Send failed via %s: errno=%d, size=%zu, socket=%d\n",
67 origin, sock_errno, attempted, p->sd);
68 }
69 }
70
71 size_t rist_send_seq_rtcp(struct rist_peer *p, uint32_t seq_rtp, uint8_t payload_type, uint8_t *payload, size_t payload_len, uint64_t source_time, uint16_t src_port, uint16_t dst_port, bool retry, uint16_t ts_null_bytes)
72 {
73 struct rist_common_ctx *ctx = get_cctx(p);
74 uint8_t *data;
75 size_t len;
76 size_t hdr_len = 0;
77 ssize_t ret = 0;
78
79 uint8_t *_payload = NULL;
80 _payload = payload;
81
82 /* Advanced Profile (VSF TR-06-3): build RTP-based packet directly,
83 * bypassing GRE framing entirely. Control and OOB are handled
84 * separately through rist_adv_send_control().
85 *
86 * TR-06-3 Section 9 (interop): an Advanced device "shall start in Main
87 * Profile mode" and only switch to Advanced framing for a peer once that
88 * peer advertises Advanced capability (I=1 in its Main keep-alives, which
89 * sets remote_supports_advanced). Until then we emit Main-conformant
90 * media so a Main-only peer can decode it. */
91 if (ctx->profile == RIST_PROFILE_ADVANCED &&
92 p->remote_supports_advanced &&
93 payload_type != RIST_PAYLOAD_TYPE_DATA_OOB &&
94 payload_type != RIST_PAYLOAD_TYPE_RTCP &&
95 payload_type != RIST_PAYLOAD_TYPE_RTCP_NACK) {
96 uint8_t adv_buf[RIST_MAX_PACKET_SIZE + RIST_ADV_MAX_FIXED_HEADER];
97 struct rist_adv_params params;
98 memset(&params, 0, sizeof(params));
99
100 params.seq = seq_rtp;
101 params.timestamp = (uint32_t)((source_time * 1000000ULL) >> 16);
102 params.ssrc = rist_adv_ssrc_protected(ctx->adv_ssrc_base);
103 params.enc_type = RIST_ADV_TYPE_DIRECT;
104 params.psk_mode = RIST_ADV_PSK_NONE;
105 params.lpc_mode = RIST_ADV_LPC_NONE;
106 params.first_frag = true;
107 params.last_frag = true;
108 params.expedite = false;
109 params.retransmit = retry;
110
111 struct rist_adv_flow_id fid;
112 if (dst_port || src_port) {
113 fid.outer = htons(dst_port);
114 fid.inner_hi = (uint8_t)((src_port >> 4) & 0xFF);
115 fid.inner_lo_sub = (uint8_t)((src_port & 0x0F) << 4);
116 params.flow_id = &fid;
117 }
118
119 uint8_t *wire_payload = payload;
120 size_t wire_payload_len = payload_len;
121 uint8_t lz4_buf[RIST_MAX_PACKET_SIZE];
122 uint8_t enc_buf[RIST_MAX_PACKET_SIZE];
123 uint8_t psk_iv_bytes[RIST_ADV_PSK_IV_SIZE];
124
125 if (p->compression && payload_len > 0) {
126 int bound = LZ4_compressBound((int)payload_len);
127 if (bound > 0 && (size_t)bound <= sizeof(lz4_buf)) {
128 int clen = LZ4_compress_default((const char *)payload,
129 (char *)lz4_buf, (int)payload_len, (int)sizeof(lz4_buf));
130 if (clen > 0 && (size_t)clen < payload_len) {
131 wire_payload = lz4_buf;
132 wire_payload_len = (size_t)clen;
133 params.lpc_mode = RIST_ADV_LPC_LZ4;
134 }
135 }
136 }
137
138 if (p->key_tx.key_size > 0) {
139 uint32_t seq_nbe = htobe32(seq_rtp);
140 params.psk_mode = RIST_ADV_PSK_AES_CTR;
141 uint8_t old_nonce[4];
142 memcpy(old_nonce, p->key_tx.gre_nonce, 4);
143 _librist_crypto_psk_encrypt(&p->key_tx, seq_nbe, 1,
144 wire_payload, enc_buf, wire_payload_len);
145 if (p->key_tx.csprng_failed) {
146 rist_log_priv(ctx, RIST_LOG_ERROR,
147 "Advanced Profile: PSK encrypt failed (CSPRNG)\n");
148 return 0;
149 }
150 if (memcmp(old_nonce, p->key_tx.gre_nonce, 4) != 0)
151 rist_adv_send_psk_nonce(p, p->key_tx.gre_nonce,
152 (uint16_t)p->key_tx.key_size);
153 wire_payload = enc_buf;
154 params.psk_nonce = p->key_tx.gre_nonce;
155 memcpy(psk_iv_bytes, &seq_nbe, sizeof(seq_nbe));
156 params.psk_iv = psk_iv_bytes;
157 }
158
159 int total = rist_adv_build(adv_buf, &params, wire_payload, wire_payload_len);
160 if (total < 0) {
161 rist_log_priv(ctx, RIST_LOG_ERROR, "Advanced Profile: failed to build packet\n");
162 return 0;
163 }
164
165 if (RIST_UNLIKELY((p->sender_ctx && p->sender_ctx->simulate_loss) ||
166 (p->receiver_ctx && p->receiver_ctx->simulate_loss))) {
167 uint16_t loss_percentage = p->sender_ctx ?
168 p->sender_ctx->loss_percentage : p->receiver_ctx->loss_percentage;
169 uint16_t compare = rand() % 1001;
170 if (compare <= loss_percentage) {
171 ret = total;
172 goto adv_out;
173 }
174 }
175
176 int retries_count = 0;
177 int errorcode = 0;
178 do {
179 ret = rist_transport_sendto(p, adv_buf, (size_t)total, 0);
180 if (RIST_UNLIKELY(ret < 0)) {
181 errorcode = errno;
182 retries_count++;
183 } else {
184 errorcode = 0;
185 break;
186 }
187 } while (errorcode == EAGAIN && retries_count < RIST_MAX_SEND_RETRIES);
188
189 if (RIST_UNLIKELY(ret < 0))
190 _librist_log_send_error(p, errorcode, (size_t)total, "advanced-profile sendto");
191
192 adv_out:
193 if (ret > 0) {
194 p->stats_sender_instant.sent++;
195 p->stats_sender_instant.sent_bytes += (uint64_t)ret;
196 if (ts_null_bytes)
197 p->stats_sender_instant.ts_null++;
198 p->stats_receiver_instant.sent_rtcp++;
199 rist_calculate_bitrate((size_t)ret, &p->bw);
200 rist_calculate_bitrate(ts_null_bytes, &p->ts_nulls_bw);
201 }
202 return (size_t)ret;
203 }
204
205 // TODO: write directly on the payload to make it faster
206 uint8_t header_buf[RIST_MAX_HEADER_SIZE] = {0};
207 uint16_t proto_type;
208 if (RIST_UNLIKELY(payload_type == RIST_PAYLOAD_TYPE_DATA_OOB)) {
209 proto_type = RIST_GRE_PROTOCOL_TYPE_FULL;
210 } else {
211 proto_type = RIST_GRE_PROTOCOL_TYPE_REDUCED;
212 struct rist_protocol_hdr *hdr = (void *) (header_buf);
213 hdr->src_port = htobe16(src_port);
214 hdr->dst_port = htobe16(dst_port);
215 if (payload_type == RIST_PAYLOAD_TYPE_RTCP || payload_type == RIST_PAYLOAD_TYPE_RTCP_NACK)
216 {
217 hdr_len = RIST_GRE_PROTOCOL_REDUCED_SIZE;
218 }
219 else
220 {
221 hdr_len = sizeof(*hdr);
222 // RTP header for data packets
223 hdr->rtp.flags = RTP_MPEGTS_FLAGS;
224 if (payload_type == RIST_PAYLOAD_TYPE_DATA_RAW_RTP_EXT)
225 SET_BIT(hdr->rtp.flags, 4);
226 hdr->rtp.ssrc = htobe32(p->adv_flow_id);
227 hdr->rtp.seq = htobe16(seq_rtp);
228 if (retry)
229 {
230 // This is a retransmission
231 //rist_log_priv(&ctx->common, RIST_LOG_ERROR, "\tResending: %"PRIu32"/%"PRIu16"/%"PRIu32"\n", seq, seq_rtp, ctx->seq);
232 /* Mark SSRC for retransmission (change the last bit of the ssrc to 1) */
233 //hdr->rtp.ssrc |= (1 << 31);
234 hdr->rtp.ssrc = htobe32(p->adv_flow_id | 0x01);
235 }
236 hdr->rtp.payload_type = RTP_PTYPE_MPEGTS;
237 hdr->rtp.ts = htobe32(timestampRTP_u32(0, source_time));
238 }
239 // copy the rtp header data (needed for encryption)
240 memcpy(_payload - hdr_len, hdr, hdr_len);
241 }
242
243 if (RIST_UNLIKELY(payload_type == RIST_PAYLOAD_TYPE_DATA_OOB)) {
244 /* OOB uses GRE FULL protocol with no reduced/RTP header prepended,
245 so send the raw payload without the reduced-header offset */
246 len = payload_len;
247 data = _payload;
248 } else {
249 len = hdr_len + payload_len - RIST_GRE_PROTOCOL_REDUCED_SIZE;
250 data = _payload - hdr_len + RIST_GRE_PROTOCOL_REDUCED_SIZE;
251 }
252
253
254 // TODO: compare p->sender_ctx->sender_queue_read_index and p->sender_ctx->sender_queue_write_index
255 // and warn when the difference is a multiple of 10 (slow CPU or overtaxed algorithm)
256 // The difference should always stay very low < 10
257
258 if (RIST_UNLIKELY((p->sender_ctx && p->sender_ctx->simulate_loss) || (p->receiver_ctx && p->receiver_ctx->simulate_loss))) {
259 uint16_t loss_percentage = p->sender_ctx? p->sender_ctx->loss_percentage : p->receiver_ctx->loss_percentage;
260 /* very crude calculation to see if we "randomly" drop packets, good enough for testing */
261 uint16_t compare = rand() % 1001;
262 if (compare <= loss_percentage) {
263 ret = len;
264 goto out;
265 }
266 }
267
268 int retries = 0;
269 int errorcode = 0;
270 if (ctx->profile == RIST_PROFILE_SIMPLE) {
271 // retry when kernel buffer is full instead of dropping packet (EAGAIN)
272 do {
273 ret = rist_transport_sendto(p, data, len, 0);
274 if (RIST_UNLIKELY(ret < 0))
275 {
276 errorcode = errno;
277 retries++;
278 }
279 else {
280 errorcode = 0;
281 break;
282 }
283 } while (errorcode == EAGAIN && retries < RIST_MAX_SEND_RETRIES);
284 if (RIST_UNLIKELY(retries > (RIST_MAX_SEND_RETRIES / 5)))
285 rist_log_priv(ctx, RIST_LOG_WARN, "UDP Pacing Send Succeded after retries=%d, ret=%d, socket=%d\n", retries, ret, p->sd);
286 if (RIST_UNLIKELY(ret < 0))
287 _librist_log_send_error(p, errorcode, len, "simple-profile sendto");
288 }
289 else
290 ret = _librist_proto_gre_send_data(p, payload_type, proto_type, data, len, src_port, dst_port, p->rist_gre_version);
291
292 out:
293 if (RIST_UNLIKELY(ret <= 0 && ctx->profile == RIST_PROFILE_SIMPLE && errorcode == 0)) {
294 /* Generic safety net for ret == 0 or ret < 0 without errorcode
295 * captured (out-of-band failure paths). PMTU-aware send errors
296 * have already been logged above. */
297 rist_log_priv(ctx, RIST_LOG_ERROR, "\tSend failed: errno=%d, ret=%d, socket=%d\n", errno, ret, p->sd);
298 } else if (ret > 0) {
299 p->stats_sender_instant.sent++;
300 p->stats_sender_instant.sent_bytes += (uint64_t)ret;
301 if (ts_null_bytes)
302 p->stats_sender_instant.ts_null++;
303 p->stats_receiver_instant.sent_rtcp++;
304 }
305
306 return ret;
307 }
308
309 /* This function is used by receiver for all and by sender only for rist-data and oob-data */
310 int rist_send_common_rtcp(struct rist_peer *p, uint8_t payload_type, uint8_t *payload, size_t payload_len, uint64_t source_time, uint16_t src_port, uint16_t dst_port, uint32_t seq_rtp, uint16_t ts_null_bytes)
311 {
312 // This can only and will most likely be zero for data packets. RTCP should always have a value.
313 assert(payload_type != RIST_PAYLOAD_TYPE_DATA_RAW && payload_type != RIST_PAYLOAD_TYPE_DATA_RAW_RTP_EXT && payload_type != RIST_PAYLOAD_TYPE_DATA_OOB ? dst_port != 0 : 1);
314 if (dst_port == 0)
315 dst_port = p->config.virt_dst_port;
316 if (src_port == 0)
317 src_port = 32768 + p->adv_peer_id;
318
319 struct rist_common_ctx *cctx = get_cctx(p);
320 if (p->sd < 0 || !p->address_len) {
321 rist_log_priv(cctx, RIST_LOG_ERROR, "rist_send_common_rtcp failed\n");
322 return -1;
323 }
324
325 if (payload_type == RIST_PAYLOAD_TYPE_DATA_RAW || payload_type == RIST_PAYLOAD_TYPE_DATA_OOB)
326 {
327 if (cctx->oob_current_peer == NULL || cctx->oob_current_peer->dead)
328 cctx->oob_current_peer = p;
329 }
330
331 if (RIST_UNLIKELY(p->config.timing_mode == RIST_TIMING_MODE_ARRIVAL) && !p->receiver_mode)
332 source_time = timestampNTP_u64();
333
334 size_t ret = rist_send_seq_rtcp(p, seq_rtp, payload_type, payload, payload_len, source_time, src_port, dst_port, false, ts_null_bytes);
335
336 if ((!p->compression && ret < payload_len) || ret == (size_t)-1)
337 {
338 if (p->address_family == AF_INET6) {
339 // TODO: print IP and port (and error number?)
340 rist_log_priv(cctx, RIST_LOG_ERROR,
341 "\tError on transmission sendto for seq #%"PRIu32"\n", seq_rtp);
342 } else {
343 struct sockaddr_in *sin4 = (struct sockaddr_in *)&p->u.address;
344 unsigned char *ip = (unsigned char *)&sin4->sin_addr.s_addr;
345 rist_log_priv(cctx, RIST_LOG_ERROR,
346 "\tError on transmission sendto, ret=%d to %d.%d.%d.%d:%d/%d, seq #%"PRIu32", %d bytes\n",
347 ret, ip[0], ip[1], ip[2], ip[3], htons(sin4->sin_port),
348 p->local_port, seq_rtp, payload_len);
349 }
350 }
351 else
352 {
353 // update bandwidth value
354 rist_calculate_bitrate(ret, &p->bw);
355 rist_calculate_bitrate(ts_null_bytes, &p->ts_nulls_bw);
356 }
357
358 // TODO:
359 // This should return something meaningful, however ret is always >= 0 by virtue of being unsigned.
360 /*if (ret >= 0)
361 * return 0;
362 * else
363 * return -1;
364 */
365 return 0;
366 }
367
368 int rist_set_url(struct rist_peer *peer)
369 {
370 char host[512];
371 uint16_t port;
372 int local;
373 if (!peer->url) {
374 if (peer->local_port > 0) {
375 /* Put sender in IPv4 learning mode */
376 peer->address_family = AF_INET;
377 peer->address_len = sizeof(struct sockaddr_in);
378 memset(&peer->u.address, 0, sizeof(struct sockaddr_in));
379 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
380 "Sender: in learning mode\n");
381 }
382 return 1;
383 }
384 if (udpsocket_parse_url(peer->url, host, 512, &port, &local) != 0) {
385 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "%s / %s\n", strerror(errno), peer->url);
386 return -1;
387 } else {
388 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "URL parsed successfully: Host %s, Port %hu\n",
389 (char *) host, port);
390 }
391 if (udpsocket_resolve_host(host, port, &peer->u.address) < 0) {
392 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Host %s cannot be resolved\n",
393 (char *) host);
394 return -1;
395 }
396 if (peer->u.inaddr6.sin6_family == AF_INET6) {
397 peer->address_family = AF_INET6;
398 peer->address_len = sizeof(struct sockaddr_in6);
399 } else {
400 peer->address_family = AF_INET;
401 peer->address_len = sizeof(struct sockaddr_in);
402 }
403 if (local) {
404 peer->listening = 1;
405 peer->local_port = port;
406 } else {
407 peer->listening = 0;
408 peer->remote_port = port;
409 }
410 if (peer->address_family == AF_INET) {
411 peer->u.inaddr.sin_port = htons(port);
412 } else {
413 peer->u.inaddr6.sin6_port = htons(port);
414 }
415 return 0;
416 }
417
418 void rist_populate_cname(struct rist_peer *peer)
419 {
420 int fd = peer->sd;
421 char *identifier = peer->cname;
422 struct rist_common_ctx *ctx = get_cctx(peer);
423 if (strlen((char *)ctx->cname) != 0)
424 {
425 ctx->cname[RIST_MAX_HOSTNAME-1] = 0;
426 strncpy(identifier, (char * )ctx->cname, RIST_MAX_HOSTNAME);
427 return;
428 }
429 /* Set the CNAME Identifier as host@ip:port and fallback to hostname if needed */
430 char hostname[RIST_MAX_HOSTNAME];
431 struct sockaddr_storage peer_sockaddr;
432 peer_sockaddr.ss_family = AF_UNSPEC;
433 int name_length = 0;
434 socklen_t peer_socklen = sizeof(peer_sockaddr);
435 int ret_hostname = gethostname(hostname, RIST_MAX_HOSTNAME);
436 if (ret_hostname == -1) {
437 snprintf(hostname, RIST_MAX_HOSTNAME, "UnknownHost");
438 }
439
440 int ret_sockname = getsockname(fd, (struct sockaddr *)&peer_sockaddr, &peer_socklen);
441 if (ret_sockname == 0)
442 {
443 struct sockaddr *xsa = (struct sockaddr *)&peer_sockaddr;
444 // TODO: why is this returning non-sense?
445 if (xsa->sa_family == AF_INET) {
446 char addr[INET_ADDRSTRLEN] = {'\0'};
447 struct sockaddr_in *xin = (struct sockaddr_in*)&peer_sockaddr;
448 inet_ntop(AF_INET, &xin->sin_addr, addr, INET_ADDRSTRLEN);
449 if (strcmp(addr, "0.0.0.0") != 0) {
450 name_length = snprintf(identifier, RIST_MAX_HOSTNAME, "%s@%s:%u", hostname,
451 addr, ntohs(xin->sin_port));
452 if (name_length >= RIST_MAX_HOSTNAME)
453 identifier[RIST_MAX_HOSTNAME-1] = 0;
454 }
455 }/* else if (xsa->sa_family == AF_INET6) {
456 struct sockaddr_in6 *xin6 = (void*)peer;
457 char str[INET6_ADDRSTRLEN];
458 inet_ntop(xin6->sin6_family, &xin6->sin6_addr, str, sizeof(struct in6_addr));
459 name_length = snprintf(identifier, RIST_MAX_HOSTNAME, "%s@%s:%u", hostname,
460 str, ntohs(xin6->sin6_port));
461 if (name_length >= RIST_MAX_HOSTNAME)
462 identifier[RIST_MAX_HOSTNAME-1] = 0;
463 }*/
464 }
465
466 if (name_length == 0)
467 {
468 name_length = snprintf(identifier, RIST_MAX_HOSTNAME, "%s", hostname);
469 if (name_length >= RIST_MAX_HOSTNAME)
470 identifier[RIST_MAX_HOSTNAME-1] = 0;
471 }
472 }
473
474 void rist_create_socket(struct rist_peer *peer)
475 {
476 if(!peer->address_family && rist_set_url(peer)) {
477 return;
478 }
479
480 if (peer->listening) {
481 const char* host;
482 uint16_t port;
483
484 char buffer[256];
485 if (peer->u.address.sa_family == AF_INET) {
486 struct sockaddr_in *addrv4 = (struct sockaddr_in *)&(peer->u);
487 host = inet_ntop(AF_INET, &(addrv4->sin_addr), buffer, sizeof(buffer));
488 port = htons(addrv4->sin_port);
489 } else {
490 struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *)&(peer->u);
491 host = inet_ntop(AF_INET6, &(addrv6->sin6_addr), buffer, sizeof(buffer));
492 port = htons(addrv6->sin6_port);
493 }
494 if (!host) {
495 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "failed to convert address to string (errno=%d)", errno);
496 return;
497 }
498
499 if (peer->u.address.sa_family == AF_INET)
500 {
501 struct sockaddr_in *addrv4 = (struct sockaddr_in *)&(peer->u);
502 peer->multicast_receiver = IN_MULTICAST(ntohl(addrv4->sin_addr.s_addr));
503 }
504 else
505 {
506 struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *)&(peer->u);
507 peer->multicast_receiver = IN6_IS_ADDR_MULTICAST(&addrv6->sin6_addr);
508 }
509
510 peer->sd = udpsocket_open_bind_mcast(host, port, peer->miface,
511 peer->config.multicast_ttl, peer->config.multicast_source);
512 if (peer->sd >= 0) {
513 if (port == 0)
514 {
515 // Populate peer->local_port with ephemeral port assigned
516 struct sockaddr_storage local_addr;
517 socklen_t n = sizeof( struct sockaddr_storage );
518 if( getsockname( peer->sd, (struct sockaddr *) &local_addr, &n ) != 0)
519 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Could not find assigned port (socket# %d)\n", peer->sd);
520 else
521 {
522 if (local_addr.ss_family == AF_INET) {
523 struct sockaddr_in *a = (struct sockaddr_in *)&local_addr;
524 port = a->sin_port;
525 } else {
526 /* ipv6 */
527 struct sockaddr_in6 *a = (struct sockaddr_in6 *)&local_addr;
528 port = a->sin6_port;
529 }
530 peer->local_port = port;
531 }
532 }
533 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Starting in URL listening mode (socket# %d)\n", peer->sd);
534 } else {
535 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Could not start in URL listening mode. %s\n", strerror(errno));
536 }
537
538 // Set non-blocking only for receive sockets
539 udpsocket_set_nonblocking(peer->sd);
540 }
541 else {
542 if (peer->u.address.sa_family == AF_INET)
543 {
544 struct sockaddr_in *addrv4 = (struct sockaddr_in *)&(peer->u);
545 peer->multicast_sender = IN_MULTICAST(ntohl(addrv4->sin_addr.s_addr));
546 }
547 else
548 {
549 struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *)&(peer->u);
550 peer->multicast_sender = IN6_IS_ADDR_MULTICAST(&addrv6->sin6_addr);
551 }
552 if (peer->multicast_sender) {
553 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Peer configured for multicast\n");
554 }
555 // We use sendto ... so, no need to connect directly here
556 peer->sd = udpsocket_open(peer->address_family);
557 if (peer->sd >= 0)
558 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Starting in URL connect mode (%d)\n", peer->sd);
559 else {
560 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Could not start in URL connect mode. %s\n", strerror(errno));
561 }
562 if (peer->miface[0] != '\0') {
563 struct sockaddr_storage ss = {0};
564 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Binding socket to %s\n", peer->miface);
565 if (inet_pton(AF_INET, peer->miface, &((struct sockaddr_in *)&ss)->sin_addr) != 0) {
566 ((struct sockaddr_in *)&ss)->sin_family = AF_INET;
567 ((struct sockaddr_in *)&ss)->sin_port = htons(peer->config.local_port);
568 if (bind(peer->sd, (struct sockaddr*)&ss, sizeof(struct sockaddr_in)) != 0) {
569 #ifdef _WIN32
570 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s:%u: WSAGetLastError=%d\n", peer->miface, peer->config.local_port, WSAGetLastError());
571 #else
572 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s:%u: %s\n", peer->miface, peer->config.local_port, strerror(errno));
573 #endif
574 }
575 }
576 else if (inet_pton(AF_INET6, peer->miface, &((struct sockaddr_in6 *)&ss)->sin6_addr) != 0) {
577 ((struct sockaddr_in6 *)&ss)->sin6_family = AF_INET6;
578 ((struct sockaddr_in6 *)&ss)->sin6_port = htons(peer->config.local_port);
579 if (bind(peer->sd, (struct sockaddr*)&ss, sizeof(struct sockaddr_in6)) != 0) {
580 #ifdef _WIN32
581 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s:%u: WSAGetLastError=%d\n", peer->miface, peer->config.local_port, WSAGetLastError());
582 #else
583 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s:%u: %s\n", peer->miface, peer->config.local_port, strerror(errno));
584 #endif
585 }
586 }
587 #ifdef __linux__
588 else {
589 struct ifreq ifr = {0};
590 memcpy(ifr.ifr_name, peer->miface, IF_NAMESIZE);
591 if (setsockopt(peer->sd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) != 0) {
592 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s: %s\n", peer->miface, strerror(errno));
593 }
594 }
595 #elif defined(__APPLE__)
596 else {
597 int idx = if_nametoindex(peer->miface);
598 if (idx == 0) {
599 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't get device %s index: %s\n", peer->miface, strerror(errno));
600 } else {
601 int proto = peer->u.address.sa_family == AF_INET? IPPROTO_IP : IPPROTO_IPV6;
602 int bound = peer->u.address.sa_family == AF_INET? IP_BOUND_IF : IPV6_BOUND_IF;
603 if (setsockopt(peer->sd, proto, bound, &idx, sizeof(idx)) != 0) {
604 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s: %s\n", peer->miface, strerror(errno));
605 }
606 }
607 }
608 #else
609 else {
610 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "No method available to bind to %s please supply an IP to bind to\n", peer->miface);
611 }
612 #endif
613 } else if (peer->config.local_port > 0) {
614 struct sockaddr_storage ss = {0};
615 if (peer->address_family == AF_INET6) {
616 ((struct sockaddr_in6 *)&ss)->sin6_family = AF_INET6;
617 ((struct sockaddr_in6 *)&ss)->sin6_port = htons(peer->config.local_port);
618 ((struct sockaddr_in6 *)&ss)->sin6_addr = in6addr_any;
619 } else {
620 ((struct sockaddr_in *)&ss)->sin_family = AF_INET;
621 ((struct sockaddr_in *)&ss)->sin_port = htons(peer->config.local_port);
622 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = INADDR_ANY;
623 }
624 socklen_t ss_len = peer->address_family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
625 if (bind(peer->sd, (struct sockaddr *)&ss, ss_len) != 0) {
626 #ifdef _WIN32
627 rist_log_priv(get_cctx(peer), RIST_LOG_WARN, "Couldn't bind to local port %u: WSAGetLastError=%d\n", peer->config.local_port, WSAGetLastError());
628 #else
629 rist_log_priv(get_cctx(peer), RIST_LOG_WARN, "Couldn't bind to local port %u: %s\n", peer->config.local_port, strerror(errno));
630 #endif
631 } else {
632 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Bound caller socket to local port %u\n", peer->config.local_port);
633 }
634 }
635 if (peer->multicast_sender && peer->config.multicast_ttl > 0)
636 udpsocket_set_mcast_ttl(peer->sd, peer->address_family, peer->config.multicast_ttl);
637 udpsocket_set_dontfragment(peer->sd, peer->address_family);
638 if (peer->config.local_port > 0)
639 peer->local_port = peer->config.local_port;
640 else
641 peer->local_port = 32768 + (get_cctx(peer)->peer_counter % 28232);
642 #ifdef _WIN32
643 udpsocket_set_nonblocking(peer->sd);
644 #endif
645 }
646
647 // Increase default OS udp receive buffer size
648 if (udpsocket_set_optimal_buffer_size(peer->sd)) {
649 rist_log_priv(get_cctx(peer), RIST_LOG_WARN, "Unable to set the socket receive buffer size to %d Bytes. %s\n",
650 UDPSOCKET_SOCK_BUFSIZE, strerror(errno));
651 } else {
652 uint32_t current_recvbuf = udpsocket_get_buffer_size(peer->sd);
653 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Configured the starting socket receive buffer size to %d Bytes.\n",
654 current_recvbuf);
655 }
656 // Increase default OS udp send buffer size
657 if (udpsocket_set_optimal_buffer_send_size(peer->sd)) {
658 rist_log_priv(get_cctx(peer), RIST_LOG_WARN, "Unable to set the socket send buffer size to %d Bytes. %s\n",
659 UDPSOCKET_SOCK_BUFSIZE, strerror(errno));
660 } else {
661 uint32_t current_sendbuf = udpsocket_get_buffer_send_size(peer->sd);
662 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Configured the starting socket send buffer size to %d Bytes.\n",
663 current_sendbuf);
664 }
665
666 if (peer->cname[0] == 0)
667 rist_populate_cname(peer);
668 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Peer cname is %s\n", peer->cname);
669 #ifndef _WIN32
670 if (fcntl(peer->sd, F_SETFD, FD_CLOEXEC) == -1) {
671 udpsocket_close(peer->sd);
672 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Could not set close-on-exec\n");
673 peer->sd = -1;
674 }
675 #endif
676 }
677
678 int rist_receiver_periodic_rtcp(struct rist_peer *peer) {
679 uint8_t payload_type = RIST_PAYLOAD_TYPE_RTCP;
680 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
681
682 int payload_len = 0;
683 rist_rtcp_write_rr(rtcp_buf, &payload_len, peer);
684 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
685 if (peer->echo_enabled == false)
686 rist_rtcp_write_xr_echoreq(rtcp_buf, &payload_len, peer);
687 rist_rtcp_write_echoreq(rtcp_buf, &payload_len, peer->peer_ssrc);
688 return rist_send_common_rtcp(peer, payload_type, &rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
689 }
690
691 static int rist_receiver_send_nacks_advanced(struct rist_peer *peer, uint32_t seq_array[], size_t array_len)
692 {
693 struct rist_common_ctx *ctx = get_cctx(peer);
694 uint32_t media_ssrc = rist_adv_ssrc_protected(ctx->adv_ssrc_base);
695
696 if (peer->receiver_ctx->nack_type == RIST_NACK_BITMASK) {
697 uint32_t pss = seq_array[0];
698 uint32_t blp = 0;
699 for (size_t i = 1; i < array_len; i++) {
700 uint32_t offset = seq_array[i] - pss;
701 if (offset >= 1 && offset <= 32) {
702 blp |= (1u << (offset - 1));
703 } else {
704 rist_adv_send_nack_bitmask(peer, media_ssrc, pss, blp);
705 pss = seq_array[i];
706 blp = 0;
707 }
708 }
709 rist_adv_send_nack_bitmask(peer, media_ssrc, pss, blp);
710 } else {
711 uint32_t pss = seq_array[0];
712 uint32_t nalp = 0;
713 for (size_t i = 1; i < array_len; i++) {
714 if (seq_array[i] == pss + nalp + 1) {
715 nalp++;
716 } else {
717 rist_adv_send_nack_range(peer, media_ssrc, pss, nalp);
718 pss = seq_array[i];
719 nalp = 0;
720 }
721 }
722 rist_adv_send_nack_range(peer, media_ssrc, pss, nalp);
723 }
724 return 0;
725 }
726
727 int rist_receiver_send_nacks(struct rist_peer *peer, uint32_t seq_array[], size_t array_len)
728 {
729 if (get_cctx(peer)->debug && array_len > 0)
730 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Sending %zu nacks starting with %"PRIu32"\n",
731 array_len, seq_array[0]);
732
733 if (get_cctx(peer)->profile == RIST_PROFILE_ADVANCED &&
734 peer->is_advanced && peer->remote_supports_advanced &&
735 array_len > 0) {
736 return rist_receiver_send_nacks_advanced(peer, seq_array, array_len);
737 }
738
739 uint8_t payload_type = RIST_PAYLOAD_TYPE_RTCP;
740 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
741
742 int payload_len = 0;
743 rist_rtcp_write_empty_rr(rtcp_buf, &payload_len, peer->adv_flow_id);
744 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
745 if (RIST_LIKELY(array_len > 0)) {
746 struct rist_rtp_nack_record *rec;
747 uint32_t fci_count = 1;
748
749 if (peer->receiver_ctx->nack_type == RIST_NACK_BITMASK)
750 {
751 struct rist_rtcp_nack_bitmask *rtcp = (struct rist_rtcp_nack_bitmask *)(rtcp_buf + RIST_MAX_PAYLOAD_OFFSET + payload_len);
752 rtcp->flags = RTCP_NACK_BITMASK_FLAGS;
753 rtcp->ptype = PTYPE_NACK_BITMASK;
754 rtcp->ssrc_source = 0; // TODO
755 rtcp->ssrc = htobe32(peer->adv_flow_id);
756 rec = (struct rist_rtp_nack_record *)(rtcp_buf + RIST_MAX_PAYLOAD_OFFSET + payload_len + RTCP_FB_HEADER_SIZE);
757 uint32_t last_seq, tmp_seq;
758 tmp_seq = last_seq = seq_array[0];
759 uint32_t boundary = tmp_seq +16;
760 rec->start = htons((uint16_t)tmp_seq);
761 uint16_t extra = 0;
762 for (size_t i = 1; i < array_len; i++)
763 {
764 tmp_seq = seq_array[i];
765 if (last_seq < tmp_seq && tmp_seq <= boundary) {
766 uint32_t bitnum = tmp_seq - last_seq;
767 SET_BIT(extra, (bitnum -1));
768 } else {
769 rec->extra = htons(extra);
770 rec++;
771 fci_count++;
772 extra = 0;
773 rec->start = htons((uint16_t)tmp_seq);
774 last_seq = tmp_seq;
775 boundary = tmp_seq + 16;
776 }
777 }
778 rec->extra = htons(extra);
779 rtcp->len = htons((uint16_t)(2 + fci_count));
780 }
781 else // PTYPE_NACK_CUSTOM
782 {
783 struct rist_rtcp_nack_range *rtcp = (struct rist_rtcp_nack_range *)(rtcp_buf + RIST_MAX_PAYLOAD_OFFSET + payload_len);
784 rtcp->flags = RTCP_NACK_RANGE_FLAGS;
785 rtcp->ptype = PTYPE_NACK_CUSTOM;
786 rtcp->ssrc_source = htobe32(peer->adv_flow_id);
787 memcpy(rtcp->name, "RIST", 4);
788 rec = (struct rist_rtp_nack_record *)(rtcp_buf + RIST_MAX_PAYLOAD_OFFSET + payload_len + RTCP_FB_HEADER_SIZE);
789 uint16_t tmp_seq = (uint16_t)seq_array[0];
790 uint16_t last_seq = tmp_seq;
791 rec->start = htons(tmp_seq);
792 uint16_t extra = 0;
793 for (size_t i = 1; i < array_len; i++)
794 {
795 tmp_seq = (uint16_t)seq_array[i];
796 if (RIST_UNLIKELY(extra == UINT16_MAX)) {
797 rec->extra = htons(extra);
798 rec++;
799 fci_count++;
800 rec->start = htons(tmp_seq);
801 extra = 0;
802 } else if (tmp_seq == last_seq +1) {
803 extra++;
804 } else {
805 rec->extra = htons(extra);
806 rec++;
807 fci_count++;
808 rec->start = htons(tmp_seq);
809 extra = 0;
810 }
811 last_seq = tmp_seq;
812 }
813 rec->extra = htons(extra);
814 rtcp->len = htons((uint16_t)(2 + fci_count));
815 }
816 int nack_bufsize = RTCP_FB_HEADER_SIZE + RTCP_FB_FCI_GENERIC_NACK_SIZE * fci_count;
817 payload_len += nack_bufsize;
818 payload_type = RIST_PAYLOAD_TYPE_RTCP_NACK;
819 }
820
821 // We use direct send from receiver to sender (no fifo to keep track of seq/idx)
822 return rist_send_common_rtcp(peer, payload_type, &rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
823 }
824
825 static void rist_sender_send_rtcp(uint8_t *rtcp_buf, int payload_len, struct rist_peer *peer) {
826 rist_send_common_rtcp(peer, RIST_PAYLOAD_TYPE_RTCP, rtcp_buf, payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
827 }
828
829 void rist_sender_periodic_rtcp(struct rist_peer *peer) {
830 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
831 int payload_len = 0;
832
833 rist_rtcp_write_sr(rtcp_buf, &payload_len, peer);
834 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
835 if (peer->echo_enabled)
836 rist_rtcp_write_echoreq(rtcp_buf, &payload_len, peer->peer_ssrc);
837 // Push it to the FIFO buffer to be sent ASAP (even in the simple profile case)
838 rist_sender_send_rtcp(&rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, peer);
839 return;
840 }
841
842 int rist_respond_echoreq(struct rist_peer *peer, const uint64_t echo_request_time, uint32_t ssrc) {
843 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
844 int payload_len = 0;
845 rist_rtcp_write_empty_rr(rtcp_buf, &payload_len, peer->adv_flow_id);
846 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
847 rist_rtcp_write_echoresp(rtcp_buf, &payload_len, echo_request_time, ssrc);
848 if (peer->receiver_mode) {
849 uint8_t payload_type = RIST_PAYLOAD_TYPE_RTCP;
850 return rist_send_common_rtcp(peer, payload_type, &rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
851 } else {
852 /* I do this to not break advanced mode, however echo responses should really NOT be resend when lost ymmv */
853 rist_sender_send_rtcp(&rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, peer);
854 return 0;
855 }
856 }
857
858 int rist_request_echo(struct rist_peer *peer) {
859 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
860 int payload_len = 0;
861 rist_rtcp_write_empty_rr(rtcp_buf, &payload_len, peer->adv_flow_id);
862 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
863 rist_rtcp_write_echoreq(rtcp_buf, &payload_len, peer->peer_ssrc);
864 if (peer->receiver_mode)
865 {
866 uint8_t payload_type = RIST_PAYLOAD_TYPE_RTCP;
867 return rist_send_common_rtcp(peer, payload_type, &rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
868 }
869 else
870 {
871 rist_sender_send_rtcp(&rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, peer);
872 return 0;
873 }
874 }
875
876 int rist_sender_enqueue(struct rist_sender *ctx, const void *data, size_t len, uint64_t datagram_time, uint16_t src_port, uint16_t dst_port, uint32_t seq_rtp)
877 {
878 uint8_t payload_type = RIST_PAYLOAD_TYPE_DATA_RAW;
879 const void * payload = data;
880 if (ctx->common.PEERS == NULL) {
881 // Do not cache data if the lib user has not added peers
882 return -1;
883 }
884
885 /* insert into sender fifo queue */
886
887 pthread_mutex_lock(&ctx->queue_lock);
888 size_t sender_write_index = atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire);
889 if (RIST_UNLIKELY(ctx->sender_queue_size >= ctx->sender_queue_max - 1)) {
890 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "\nSender queue is full (size=%zu max=%zu), dropping packet, decrease bitrate, buffer time length or increase packet size\n",
891 ctx->sender_queue_size,
892 ctx->sender_queue_max);
893 // Another solution is to increase the size of RIST_SERVER_QUEUE_BUFFERS at compile time
894 pthread_mutex_unlock(&ctx->queue_lock);
895 return -2;
896 }
897
898 ctx->last_datagram_time = datagram_time;
899 /* Worst-case write into payload_out is (count - 1) * 204 = 6 * 204 = 1224
900 * bytes (if exactly one of the seven 204-byte packets is suppressed),
901 * sitting after the 8-byte rist_rtp_hdr_ext at offset 0. The previous
902 * sizing of 6 * 204 + 4 was 4 bytes short and let suppress_null_packets
903 * smash four bytes of stack past tmp_buf. */
904 uint8_t tmp_buf[7 * 204 + sizeof(struct rist_rtp_hdr_ext)];
905 int ts_null_bytes = 0;
906 if (ctx->null_packet_suppression && len <= 7 * 204)
907 {
908
909 struct rist_rtp_hdr_ext *hdr_ext = (struct rist_rtp_hdr_ext *)&tmp_buf;
910 memset(tmp_buf, 0, sizeof(*hdr_ext));//hdr_ext
911 ts_null_bytes = suppress_null_packets(data, &tmp_buf[sizeof(*hdr_ext)], &len, hdr_ext);
912 if (ts_null_bytes > 0)
913 {
914 memcpy(&hdr_ext->identifier, "RI", 2);
915 hdr_ext->length = htobe16(1);
916 len += sizeof(*hdr_ext);
917 payload = tmp_buf;
918 payload_type = RIST_PAYLOAD_TYPE_DATA_RAW_RTP_EXT;
919 }
920 }
921
922 ctx->sender_queue[sender_write_index] = rist_new_buffer(&ctx->common, payload, len, payload_type, 0, datagram_time, src_port, dst_port);
923 if (RIST_UNLIKELY(!ctx->sender_queue[sender_write_index])) {
924 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "\t Could not create packet buffer inside sender buffer, OOM\n");
925 pthread_mutex_unlock(&ctx->queue_lock);
926 return -3;
927 }
928 ctx->sender_queue[sender_write_index]->seq_rtp = (uint16_t)seq_rtp;
929 ctx->sender_queue[sender_write_index]->ts_null_bytes = (uint16_t)ts_null_bytes;
930 ctx->sender_queue_bytesize += len;
931 ctx->sender_queue_size++;
932 atomic_store_explicit(&ctx->sender_queue_write_index, (sender_write_index + 1) & (ctx->sender_queue_max - 1), memory_order_release);
933 pthread_mutex_unlock(&ctx->queue_lock);
934
935 return 0;
936 }
937
938 void rist_sender_send_data_balanced(struct rist_sender *ctx, struct rist_buffer *buffer)
939 {
940 struct rist_peer *peer;
941 struct rist_peer *selected_peer_by_weight = NULL;
942 uint32_t max_remainder = 0;
943 int peercnt;
944 bool looped = false;
945
946 //We can do it safely here, since this function is only to be called once per packet
947 buffer->seq = ctx->common.seq++;
948 uint32_t wire_seq = (ctx->common.profile == RIST_PROFILE_ADVANCED) ? buffer->seq : (uint32_t)buffer->seq_rtp;
949 uint64_t now = timestampNTP_u64();
950
951 peer_select:
952
953 peercnt = 0;
954 for (peer = ctx->common.PEERS; peer; peer = peer->next) {
955
956 if (!peer->is_data || peer->parent)
957 continue;
958 #if HAVE_SRP_SUPPORT
959 if (!peer->listening && !peer->multicast_sender && !eap_is_authenticated(peer->eap_ctx))
960 continue;
961 #endif
962 /* A peer is "hard dead" only after the recovery buffer grace period expires.
963 * This prevents single-path streams from being interrupted by temporary
964 * ECHO/RTCP response delays while still eventually stopping if the peer
965 * is truly gone. */
966 bool hard_dead = peer->dead && (peer->dead_since + peer->recovery_buffer_ticks) < now;
967 if ((!peer->listening && !peer->authenticated) || hard_dead
968 || (peer->listening && !peer->child_alive_count)) {
969 ctx->weight_counter -= peer->config.weight;
970 if (ctx->weight_counter <= 0) {
971 ctx->weight_counter = ctx->total_weight;
972 }
973 peer->w_count = peer->config.weight;
974 continue;
975 }
976 peercnt++;
977
978 /*************************************/
979 /* * * * * * * * * * * * * * * * * * */
980 /** Heuristics for sender goes here **/
981 /* * * * * * * * * * * * * * * * * * */
982 /*************************************/
983
984 if (peer->config.weight == RIST_PEER_WEIGHT_DUPLICATE && !looped) {
985 if (peer->listening) {
986 struct rist_peer *child = peer->child;
987 while (child) {
988 #if HAVE_SRP_SUPPORT
989 if (!eap_is_authenticated(child->eap_ctx))
990 {
991 //do nothing
992 } else
993 #endif
994 if (child->authenticated && child->is_data && (!child->dead || (child->dead && (child->dead_since + peer->recovery_buffer_ticks) < now))) {
995 uint8_t *payload = buffer->data;
996 rist_send_common_rtcp(child, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
997 }
998 child = child->sibling_next;
999 }
1000 } else if (!peer->dead || (peer->dead && (peer->dead_since + peer->recovery_buffer_ticks) < now)) {
1001 uint8_t *payload = buffer->data;
1002 rist_send_common_rtcp(peer, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1003 }
1004 } else {
1005 /* Election of next peer */
1006 // printf("peer election: considering %p, count=%d (wc: %d)\n",
1007 // peer, peer->w_count, ctx->weight_counter);
1008 if (peer->w_count > max_remainder) {
1009 max_remainder = peer->w_count;
1010 selected_peer_by_weight = peer;
1011 }
1012 }
1013 }
1014 looped = true;
1015 if (selected_peer_by_weight) {
1016 peer = selected_peer_by_weight;
1017 if (peer->listening) {
1018 struct rist_peer *child = peer->child;
1019 while (child) {
1020 #if HAVE_SRP_SUPPORT
1021 if (!eap_is_authenticated(child->eap_ctx))
1022 {
1023 //do nothing
1024 } else
1025 #endif
1026 if (child->authenticated && child->is_data && (!child->dead || (child->dead && (child->dead_since + peer->recovery_buffer_ticks) < now))) {
1027 uint8_t *payload = buffer->data;
1028 rist_send_common_rtcp(child, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1029 }
1030 child = child->sibling_next;
1031 }
1032 } else if (!peer->dead || (peer->dead && (peer->dead_since + peer->recovery_buffer_ticks) < now)) {
1033 uint8_t *payload = buffer->data;
1034 rist_send_common_rtcp(peer, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1035 }
1036 ctx->weight_counter--;
1037 peer->w_count--;
1038 }
1039
1040 if (ctx->total_weight > 0 && (ctx->weight_counter == 0 || !selected_peer_by_weight)) {
1041 peer = ctx->common.PEERS;
1042 ctx->weight_counter = ctx->total_weight;
1043 for (; peer; peer = peer->next) {
1044 peer->w_count = peer->config.weight;
1045 }
1046 if (!looped && !selected_peer_by_weight && peercnt > 0)
1047 goto peer_select;
1048 }
1049 }
1050
1051 static size_t rist_sender_index_get(struct rist_sender *ctx, uint32_t seq)
1052 {
1053 if (ctx->common.profile == RIST_PROFILE_ADVANCED)
1054 return ctx->seq_index[seq & (ctx->sender_queue_max - 1)];
1055 return ctx->seq_index[(uint16_t)seq];
1056 }
1057
1058 size_t rist_get_sender_retry_queue_size(struct rist_sender *ctx)
1059 {
1060 size_t retry_queue_size = (ctx->sender_retry_queue_write_index - ctx->sender_retry_queue_read_index)
1061 & (ctx->sender_retry_queue_size - 1);
1062 return retry_queue_size;
1063 }
1064
1065 /* This function must return, 0 when there is nothing to send, < 0 on error and > 0 for bytes sent */
1066 ssize_t rist_retry_dequeue(struct rist_sender *ctx)
1067 {
1068 size_t sender_retry_queue_read_index = (ctx->sender_retry_queue_read_index + 1)& (ctx->sender_retry_queue_size -1);
1069
1070 if (sender_retry_queue_read_index == ctx->sender_retry_queue_write_index) {
1071 return 0;
1072 }
1073
1074 ctx->sender_retry_queue_read_index = sender_retry_queue_read_index;
1075 struct rist_retry *retry = &ctx->sender_retry_queue[ctx->sender_retry_queue_read_index];
1076
1077 /* The peer this retry belongs to may have been destroyed while this
1078 * entry was sitting in the queue. rist_peer_remove() scrubs the slot
1079 * to NULL under peerlist_lock, and we are called with peerlist_lock
1080 * held, so seeing NULL here simply means the retry is stale; drop
1081 * it and let the caller move on to the next entry (returning 0 would
1082 * abort sender_send_nacks() and starve legitimate retries queued
1083 * behind this one). */
1084 if (RIST_UNLIKELY(!retry->peer)) {
1085 retry->active = false;
1086 return -1;
1087 }
1088
1089 // If they request a non-sense seq number, we will catch it when we check the seq number against
1090 // the one on that buffer position and it does not match
1091
1092 size_t idx = rist_sender_index_get(ctx, retry->seq);
1093 if (RIST_UNLIKELY(ctx->sender_queue[idx] == NULL)) {
1094 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1095 " Couldn't find block %" PRIu32 " (i=%zu/r=%zu/w=%zu/d=%zu/rs=%zu), consider increasing the buffer size\n",
1096 retry->seq, idx, atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire), atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire), ctx->sender_queue_delete_index,
1097 rist_get_sender_retry_queue_size(ctx));
1098 retry->peer->stats_sender_instant.retrans_skip++;
1099 return -1;
1100 } else if (RIST_UNLIKELY(
1101 ctx->common.profile == RIST_PROFILE_ADVANCED
1102 ? (retry->seq != ctx->sender_queue[idx]->seq)
1103 : ((uint16_t)retry->seq != ctx->sender_queue[idx]->seq_rtp))) {
1104 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1105 " Couldn't find block %" PRIu32 " (i=%zu/r=%zu/w=%zu/d=%zu/rs=%zu), found an old one instead %" PRIu32 " (%" PRIu64 "), bitrate is too high\n",
1106 retry->seq, idx, atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire), atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire), ctx->sender_queue_delete_index,
1107 rist_get_sender_retry_queue_size(ctx), ctx->sender_queue[idx]->seq, ctx->sender_queue_max);
1108 retry->peer->stats_sender_instant.retrans_skip++;
1109 return -1;
1110 }
1111 /* we're consuming the retry for an existing buffer, set it to false to allow new retries to come in */
1112 ctx->sender_queue[idx]->retry_queued = false;
1113 retry->active = false;
1114
1115 // TODO: re-enable rist_send_data_allowed (cooldown feature)
1116
1117 struct rist_bandwidth_estimation *retry_bw = &retry->peer->retry_bw;
1118 struct rist_bandwidth_estimation *cli_bw = &retry->peer->bw;
1119 if (retry->peer->peer_data)
1120 {
1121 retry_bw = &retry->peer->peer_data->retry_bw;
1122 }
1123 // update bandwidth values
1124 rist_calculate_bitrate(0, cli_bw);
1125 rist_calculate_bitrate(0, retry_bw);
1126
1127 // Make sure we do not flood the network with retries
1128 size_t current_bitrate = 0;
1129 size_t data_bitrate = 0;
1130 size_t retry_bitrate = 0;
1131 if (retry->peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_AGGRESSIVE) {
1132 data_bitrate = cli_bw->eight_times_bitrate_fast / 8;
1133 retry_bitrate = retry_bw->eight_times_bitrate_fast / 8;
1134 } else if (retry->peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_NORMAL) {
1135 data_bitrate = cli_bw->eight_times_bitrate / 8;
1136 retry_bitrate = retry_bw->eight_times_bitrate_fast / 8;
1137 } else {
1138 data_bitrate = cli_bw->eight_times_bitrate / 8;
1139 retry_bitrate = retry_bw->eight_times_bitrate / 8;
1140 }
1141 current_bitrate = data_bitrate + retry_bitrate;
1142 size_t max_bitrate = retry->peer->config.recovery_maxbitrate * 1000;
1143 if (current_bitrate > max_bitrate) {
1144 rist_log_priv(&ctx->common, RIST_LOG_DEBUG, "Max bandwidth exceeded: (%zu + %zu) > %zu, not resending packet %"PRIu64".\n",
1145 data_bitrate, retry_bitrate, max_bitrate, idx);
1146 retry->peer->stats_sender_instant.bandwidth_skip++;
1147 return -2;
1148 }
1149
1150 // Check buffer element age
1151 uint64_t now = timestampNTP_u64();
1152 /* queue_time holds the original insertion time for this seq */
1153 uint64_t data_age = (now - ctx->sender_queue[idx]->time) / RIST_CLOCK;
1154 uint64_t retry_age = (now - retry->insert_time) / RIST_CLOCK;
1155 if (RIST_UNLIKELY(retry_age > retry->peer->config.recovery_length_max)) {
1156 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1157 "Retry-request of element %" PRIu32 " (idx %zu) that was sent %" PRIu64
1158 "ms ago has been in the queue too long to matter: %"PRIu64"ms > %ums\n",
1159 retry->seq, idx, data_age, retry_age, retry->peer->config.recovery_length_max);
1160 retry->peer->stats_sender_instant.retrans_skip++;
1161 return -1;
1162 }
1163
1164 struct rist_buffer *buffer = ctx->sender_queue[idx];
1165 if (ctx->common.debug)
1166 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1167 "Resending %"PRIu32"/%"PRIu32"/%"PRIu16" (idx %zu) after %" PRIu64
1168 "ms of first transmission and %"PRIu64"ms in queue, bitrate is %zu + %zu, %zu\n",
1169 retry->seq, buffer->seq, buffer->seq_rtp, idx, data_age, retry_age, data_bitrate,
1170 retry_bitrate, current_bitrate);
1171
1172 uint8_t *payload = buffer->data;
1173
1174 size_t ret = 0;
1175 if (buffer->transmit_count >= retry->peer->config.max_retries) {
1176 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Datagram %"PRIu32
1177 " is missing, but nack count is too large (%u), age is %"PRIu64"ms, retry #%lu\n",
1178 retry->seq, buffer->transmit_count, data_age, buffer->transmit_count);
1179 retry->peer->stats_sender_instant.retrans_skip++;
1180 return -1;
1181 }
1182
1183 uint16_t src_port = buffer->src_port;
1184 if (src_port == 0)
1185 src_port = 32768 + retry->peer->peer_data->adv_peer_id;
1186 uint32_t retry_wire_seq = (ctx->common.profile == RIST_PROFILE_ADVANCED) ? buffer->seq : (uint32_t)buffer->seq_rtp;
1187 ret = rist_send_seq_rtcp(retry->peer->peer_data, retry_wire_seq, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, src_port, (retry->peer->peer_data->config.virt_dst_port & ~1UL), true, ctx->sender_queue[idx]->ts_null_bytes);
1188 // update bandwidth value
1189 rist_calculate_bitrate(ret, retry_bw);
1190
1191 if ((ret == (size_t)-1) || (!retry->peer->peer_data->compression && ret < buffer->size)) {
1192 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1193 "Resending of packet failed %zu != %zu for seq %"PRIu32"\n", ret, buffer->size, retry->seq);
1194 retry->peer->stats_sender_instant.retrans_skip++;
1195 return -1;
1196 }
1197
1198 buffer->transmit_count++;
1199 if (retry->peer->peer_data) {
1200 retry->peer->peer_data->stats_sender_instant.retrans++;
1201 retry->peer->peer_data->stats_sender_instant.retransmitted_bytes += (uint64_t)ret;
1202 } else {
1203 retry->peer->stats_sender_instant.retrans++;
1204 retry->peer->stats_sender_instant.retransmitted_bytes += (uint64_t)ret;
1205 }
1206 return ret;
1207 }
1208
1209 void rist_retry_enqueue(struct rist_sender *ctx, uint32_t seq, struct rist_peer *peer)
1210 {
1211 uint64_t now = timestampNTP_u64();
1212 size_t idx = rist_sender_index_get(ctx, seq);
1213 struct rist_buffer *buffer = ctx->sender_queue[idx];
1214 struct rist_retry *retry;
1215
1216 // Even though all the checks are on the dequeue function, we leave one here
1217 // to prevent the flooding of our fifo .. It is based on the date of the
1218 // last queued item with the same seq for this peer.
1219 // The policy of whether to allow or not allow duplicate inactive seq entries in the retry queue
1220 // is dependent on the bloat_mode.
1221 // No duplicate unhandled (i.e.: still queued) retries are accepted.
1222 // bloat_mode disabled mode = unlimited duplicates
1223 // bloat_mode normal mode = we enforce rtt spacing and allow duplicates
1224 // bloat_mode aggressive mode = we enforce 2*rtt spacing and allow duplicates
1225 // This is a safety check to protect against buggy or non compliant receivers that request the
1226 // same seq number without waiting one RTT.
1227
1228 if (peer->config.recovery_mode == RIST_RECOVERY_MODE_DISABLED) {
1229 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1230 "Nack request for seq %"PRIu32" but nack processing is disabled for this peer\n", seq);
1231 peer->stats_sender_instant.retrans_skip++;
1232 return;
1233 }
1234 else if (!buffer) {
1235 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1236 "Nack request for seq %"PRIu32" but we do not have it in the buffer (%zu ms)\n", seq,
1237 ctx->sender_recover_min_time);
1238 peer->stats_sender_instant.retrans_skip++;
1239 return;
1240 } else {
1241 uint64_t age_ticks = (now - buffer->time);
1242 if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_OFF) {
1243 // All duplicates allowed, just report it
1244 if (ctx->common.debug)
1245 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1246 "Nack request for seq %" PRIu32 " with age %" PRIu64 "ms and rtt_min %" PRIu64 " for peer #%d\n",
1247 seq, age_ticks / RIST_CLOCK, peer->config.recovery_rtt_min / RIST_CLOCK, peer->adv_peer_id);
1248 } else if (ctx->peer_lst_len == 1) {
1249 /* there is a retry outstanding for this buffer, no need to add another */
1250 if (buffer->retry_queued)
1251 return;
1252 // Only one peer (faster algorithm with no lookups)
1253 if (buffer->last_retry_request != 0)
1254 {
1255 // This is a safety check to protect against buggy or non compliant receivers that request the
1256 // same seq number without waiting one RTT.
1257 uint64_t delta = (now - buffer->last_retry_request);
1258 if (ctx->common.debug)
1259 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1260 "Nack request for seq %" PRIu32 " with delta %" PRIu64 "ms, age %" PRIu64 "ms and rtt_min %" PRIu64 "\n",
1261 seq, delta /RIST_CLOCK, age_ticks / RIST_CLOCK, peer->config.recovery_rtt_min / RIST_CLOCK);
1262 uint64_t rtt = peer->last_rtt;
1263 if (peer->config.recovery_rtt_min > rtt)
1264 rtt = peer->config.recovery_rtt_min;
1265 if (peer->config.recovery_rtt_max < rtt)
1266 rtt = peer->config.recovery_rtt_max;
1267 if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_AGGRESSIVE) {
1268 // Aggressive congestion control only allows every two RTTs
1269 rtt = rtt * 2;
1270 }
1271 if (delta < rtt)
1272 {
1273 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1274 "Nack request for seq %" PRIu32 ", age %"PRIu64"ms, is already queued (too soon to add another one), skipped, %" PRIu64 " < %" PRIu64 " ms\n",
1275 seq, age_ticks / RIST_CLOCK, delta / RIST_CLOCK, rtt);
1276 peer->stats_sender_instant.bloat_skip++;
1277 return;
1278 }
1279 buffer->retry_queued = true;
1280 }
1281 else
1282 {
1283 if (ctx->common.debug)
1284 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1285 "First nack request for seq %"PRIu32", age %"PRIu64"ms\n", seq, age_ticks / RIST_CLOCK);
1286 }
1287 } else {
1288 // Multiple peers, we need to search for other retries in the queue for comparison
1289 uint64_t delta = 0;
1290 //We work backwards from the write index till we either find a retry with same peer & seq
1291 //or it's too old to matter,looking up to 8 RTT's ago (4 in normal mode, 8 in aggressive)
1292 size_t index = (ctx->sender_retry_queue_write_index -1) & (ctx->sender_retry_queue_size -1);
1293 uint64_t rtt = peer->last_rtt;
1294 if (peer->config.recovery_length_min > rtt)
1295 rtt = peer->config.recovery_length_min;
1296 // Aggressive congestion control only allows every two RTTs
1297 if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_AGGRESSIVE)
1298 rtt *= 2;
1299 struct rist_retry *lookup = NULL;
1300 uint64_t search_period = rtt * 4;
1301 while (index != ctx->sender_retry_queue_write_index) {
1302 lookup = &ctx->sender_retry_queue[index];
1303 if (lookup->seq == seq && lookup->peer == peer)
1304 break;
1305 if (lookup->insert_time < (now - search_period))
1306 break;
1307 index = (index -1 ) & (ctx->sender_retry_queue_size -1);
1308 }
1309 retry = &ctx->sender_retry_queue[index];
1310 if (retry->seq == seq && retry->peer == peer) {
1311 delta = (now - retry->insert_time);
1312 /* this retry hasn't been handled yet, it makes no sense to insert a duplicate */
1313 if (retry->active)
1314 return;
1315 if (delta < rtt)
1316 {
1317 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1318 "Nack request for seq %" PRIu32 " with delta %" PRIu64 "ms (age %"PRIu64"ms) is already queued (too soon to add another one), skipped, peer #%d '%s'\n",
1319 seq, delta / RIST_CLOCK, age_ticks / RIST_CLOCK, peer->adv_peer_id, peer->receiver_name);
1320 peer->stats_sender_instant.bloat_skip++;
1321 return;
1322 }
1323 }
1324 if (ctx->common.debug) {
1325 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1326 "Nack request for seq %" PRIu32 " with delta %" PRIu64 "ms (age %"PRIu64"ms) and rtt_min %" PRIu64 " for peer #%"PRIu32" '%s'\n",
1327 seq, delta / RIST_CLOCK, age_ticks / RIST_CLOCK, peer->config.recovery_rtt_min / RIST_CLOCK, peer->adv_peer_id, peer->receiver_name);
1328 }
1329 }
1330 }
1331 // Now insert into the missing queue
1332 buffer->last_retry_request = now;
1333 retry = &ctx->sender_retry_queue[ctx->sender_retry_queue_write_index];
1334 retry->seq = seq;
1335 retry->peer = peer;
1336 retry->insert_time = now;
1337 retry->active = true;
1338 if (++ctx->sender_retry_queue_write_index >= ctx->sender_retry_queue_size) {
1339 ctx->sender_retry_queue_write_index = 0;
1340 }
1341 }
1342
1343 void rist_print_inet_info(char *prefix, struct rist_peer *peer)
1344 {
1345 char ipstr[INET6_ADDRSTRLEN];
1346 uint32_t port;
1347 // deal with both IPv4 and IPv6:
1348 struct sockaddr_in6 *s = (struct sockaddr_in6 *) &peer->u.address;
1349 inet_ntop(peer->address_family, &s->sin6_addr, ipstr, sizeof ipstr);
1350 if (peer->address_family == AF_INET6) {
1351 port = ntohs(s->sin6_port);
1352 } else {
1353 struct sockaddr_in *addr = (void *) &peer->u.address;
1354 port = ntohs(addr->sin_port);
1355 }
1356
1357 struct rist_common_ctx *ctx = get_cctx(peer);
1358 if (ctx->profile == RIST_PROFILE_SIMPLE)
1359 {
1360 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1361 "%sPeer Information, IP:Port => %s:%u (%d), id: %"PRIu32", simple profile\n",
1362 prefix, ipstr, port, peer->listening, peer->adv_peer_id);
1363 }
1364 else
1365 {
1366 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1367 "%sPeer Information, IP:Port => %s:%u (%d), id: %"PRIu32", ports: %u->%u\n",
1368 prefix, ipstr, port, peer->listening, peer->adv_peer_id,
1369 peer->local_port, peer->remote_port);
1370 }
1371
1372 }
1373