Debian Codegraph @

tools/ristsender.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 © 2020 SipRadius LLC. All right reserved.
2 * Author: Sergio Ammirata, Ph.D. <[email protected]>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7 #include <librist/librist.h>
8 #include <librist/udpsocket.h>
9 #include <stdint.h>
10 #include "librist/version.h"
11 #include "config.h"
12 #if HAVE_SRP_SUPPORT
13 #include "librist/librist_srp.h"
14 #include "srp_shared.h"
15 #endif
16 #include "vcs_version.h"
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <sys/types.h>
22 #include "getopt-shim.h"
23 #include <stdbool.h>
24 #include <signal.h>
25 #include "common/attributes.h"
26 #include "risturlhelp.h"
27 #include "rist-private.h"
28 #include <stdatomic.h>
29 #include "oob_shared.h"
30 #include "prometheus-exporter.h"
31 #include "endian-shim.h"
32 #if defined(__unix) || defined(__APPLE__)
33 #include <sys/ioctl.h>
34 #endif
35 #include "yamlparse.h"
36 #include "string-shim.h"
37
38 #if defined(_WIN32) || defined(_WIN64)
39 #define MSG_DONTWAIT (0)
40 #endif
41
42 #define RIST_MARK_UNUSED(unused_param) ((void)(unused_param))
43
44 #define RISTSENDER_VERSION "30"
45
46 #define MAX_INPUT_COUNT 20
47 #define MAX_OUTPUT_COUNT 20
48
49 static int signalReceived = 0;
50 static int peer_connected_count = 0;
51 static bool blind_send = false;
52 static struct rist_logging_settings logging_settings = LOGGING_SETTINGS_INITIALIZER;
53 static struct rist_callback_object *g_callback_objects = NULL;
54 static int g_callback_object_count = 0;
55
56 uint64_t prometheus_id = 0;
57
58 struct rist_ctx_wrap {
59 struct rist_ctx *ctx;
60 uintptr_t id;
61 bool sender;
62 };
63
64 struct rist_callback_object {
65 int sd;
66 struct evsocket_ctx *evctx;
67 struct rist_ctx_wrap *receiver_ctx;
68 struct rist_ctx_wrap *sender_ctx;
69 struct rist_udp_config *udp_config;
70 uint8_t recv[RIST_MAX_PACKET_SIZE + 100];
71 bool mcast_deferred;
72 char mcast_host[256];
73 uint16_t mcast_port;
74 char mcast_miface[RIST_MAX_STRING_SHORT];
75 };
76
77 struct rist_callback_tun_object {
78 struct rist_ctx *sender_ctx;
79 int tun;
80 int tun_mode;
81 bool send_rist;
82 };
83
84 struct receive_thread_object {
85 int sd;
86 struct rist_ctx *ctx[MAX_OUTPUT_COUNT];
87 struct rist_udp_config *udp_config;
88 uint8_t recv[RIST_MAX_PACKET_SIZE];
89 };
90
91 struct rist_sender_args {
92 char* token;
93 int profile;
94 enum rist_log_level loglevel;
95 int encryption_type;
96 char* shared_secret;
97 int buffer_size;
98 int statsinterval;
99 uint16_t stream_id;
100 struct rist_callback_tun_object *callback_tun_object;
101 };
102
103 #if HAVE_PROMETHEUS_SUPPORT
104 struct rist_prometheus_stats *prom_stats_ctx;
105 bool prometheus_multipoint = false;
106 bool prometheus_nocreated = false;
107 bool prometheus_httpd = false;
108 bool enable_prometheus = false;
109 char *prometheus_tags = NULL;
110 uint16_t prometheus_port = 9100;
111 char *prometheus_ip = NULL;
112 char *prometheus_unix_sock = NULL;
113 #endif
114
115 static struct option long_options[] = {
116 { "inputurl", required_argument, NULL, 'i' },
117 { "outputurl", required_argument, NULL, 'o' },
118 { "buffer", required_argument, NULL, 'b' },
119 { "secret", required_argument, NULL, 's' },
120 { "encryption-type", required_argument, NULL, 'e' },
121 { "profile", required_argument, NULL, 'p' },
122 { "null-packet-deletion", no_argument, NULL, 'n' },
123 { "tun", required_argument, NULL, 't' },
124 { "tun-mode", required_argument, NULL, 'm' },
125 { "stats", required_argument, NULL, 'S' },
126 { "verbose-level", required_argument, NULL, 'v' },
127 { "remote-logging", required_argument, NULL, 'r' },
128 #if HAVE_SRP_SUPPORT
129 { "srpfile", required_argument, NULL, 'F' },
130 #endif
131 { "fast-start", required_argument, NULL, 'f' },
132 { "config", required_argument, NULL, 'c' },
133 { "blind-send", no_argument, NULL, 5 },
134 { "help", no_argument, NULL, 'h' },
135 { "help-url", no_argument, NULL, 'u' },
136 #if HAVE_PROMETHEUS_SUPPORT
137 { "enable-metrics", no_argument, NULL, 'M' },
138 { "metrics-tags", required_argument, NULL, 1 },
139 { "metrics-multipoint",no_argument, (int*)&prometheus_multipoint, true },
140 { "metrics-nocreated",no_argument, (int*)&prometheus_nocreated, true },
141 #if HAVE_LIBMICROHTTPD
142 { "metrics-http", no_argument, (int*)&prometheus_httpd, true },
143 { "metrics-port", required_argument, NULL, 2 },
144 { "metrics-ip", required_argument, NULL, 3 },
145 #endif //HAVE_LIBMICROHTTPD
146 #if HAVE_SOCK_UN_H
147 { "metrics-unix", required_argument, NULL, 4 },
148 #endif //HAVE_SOCK_UN_H
149 #endif //HAVE_PROMETHEUS_SUPPORT
150 { 0, 0, 0, 0 },
151 };
152
153 const char help_str[] = "Usage: %s [OPTIONS] \nWhere OPTIONS are:\n"
154 " -i | --inputurl udp://... or rtp://... * | Comma separated list of input udp or rtp URLs |\n"
155 " | Use tun://@ to read udp data from a tun device defined |\n"
156 " | using the -t option |\n"
157 " -o | --outputurl rist://... * | Comma separated list of output rist URLs |\n"
158 " -b | --buffer value | Default buffer size for packet retransmissions |\n"
159 " -s | --secret PWD | Default pre-shared encryption secret |\n"
160 " -e | --encryption-type TYPE | Default Encryption type (0, 128 = AES-128, 256 = AES-256)|\n"
161 " -p | --profile number | Rist profile (0 = simple, 1 = main, 2 = advanced) |\n"
162 " -n | --null-packet-deletion | Enable NPD, receiver needs to support this! |\n"
163 " -S | --statsinterval value (ms) | Interval at which stats get printed, 0 to disable |\n"
164 " -v | --verbose-level value | To disable logging: -1, log levels match syslog levels |\n"
165 " -r | --remote-logging IP:PORT | Send logs and stats to this IP:PORT using udp messages |\n"
166 #if HAVE_SRP_SUPPORT
167 " -F | --srpfile filepath | When in listening mode, use this file to hold the list |\n"
168 " | of usernames and passwords to validate against. Use the |\n"
169 " | ristsrppasswd tool to create the line entries. |\n"
170 #endif
171 " -t | --tun name | Create a tun device and use it for data communications |\n"
172 " -m | --tun-mode number | Data management on the tun interface: |\n"
173 " | 0 = all data is accepted into and out of oob channel |\n"
174 " | 1 = only non udp data is accepted (default) |\n"
175 " | 2 = no data goes into or out of oob channel |\n"
176 " -f | --fast-start value | Controls data output flow before handshake is completed |\n"
177 " -c | --config name.yaml | YAML config file |\n"
178 //" | -1 = hold data out and igmp source joins |\n"
179 " | 0 = hold data out |\n"
180 " | 1 = start to send data immediately |\n"
181 #if HAVE_PROMETHEUS_SUPPORT
182 " -M | --enable-metrics | Enable OpenMetrics/Prometheus compatible metrics |\n"
183 " | --metrics-tags | Additional tags to add to the metrics |\n"
184 " | --metrics-multipoint | Metrics return multiple timestamped data points |\n"
185 " | --metrics-nocreated | Metrics skip the created metric for Prometheus compat |\n"
186 #if HAVE_LIBMICROHTTPD
187 " | --metrics-http | Start HTTP Server to expose metrics on |\n"
188 " | defaults to http://0.0.0.0:9100/metrics |\n"
189 " | --metrics-port | Port for metrics HTTP server to listen on |\n"
190 " | --metrics-ip | IP for metrics HTTP server to listen on |\n"
191 #endif //HAVE_LIBMICROHTTPD
192 #if HAVE_SOCK_UN_H
193 " | --metrics-unix | Unix socket to expose metrics on |\n"
194 #endif //HAVE_SOCK_UN_H
195 #endif //HAVE_PROMETHEUS_SUPPORT
196 " | --blind-send | Stream regardless of peer state (fire-and-forget mode) |\n"
197 " -h | --help | Show this help |\n"
198 " -u | --help-url | Show all the possible url options |\n"
199 " * == mandatory value \n"
200 "Default values: %s \n"
201 " --profile 1 \\\n"
202 " --statsinterval 1000 \\\n"
203 " --verbose-level 6 \n";
204
205 static uint64_t risttools_convertRTPtoNTP(uint32_t i_rtp)
206 {
207 uint64_t i_ntp;
208 int32_t clock = 90000;
209 i_ntp = (uint64_t)i_rtp << 32;
210 i_ntp /= clock;
211 return i_ntp;
212 }
213
214 #if HAVE_SRP_SUPPORT
215 char *srpfile = NULL;
216 #endif
217
218 static void input_udp_recv(struct evsocket_ctx *evctx, int fd, short revents, void *arg)
219 {
220 struct rist_callback_object *callback_object = (void *) arg;
221 RIST_MARK_UNUSED(evctx);
222 RIST_MARK_UNUSED(revents);
223 RIST_MARK_UNUSED(fd);
224
225 ssize_t recv_bufsize = -1;
226 struct sockaddr_in addr4 = {0};
227 struct sockaddr_in6 addr6 = {0};
228 struct sockaddr *addr;
229 uint8_t *recv_buf = callback_object->recv;
230 struct ipheader ipv4hdr;
231 struct udpheader udphdr;
232 size_t ipheader_bytes = sizeof(ipv4hdr) + sizeof(udphdr);
233 socklen_t addrlen = 0;
234
235 uint16_t address_family = (uint16_t)callback_object->udp_config->address_family;
236 if (address_family == AF_INET6) {
237 addrlen = sizeof(struct sockaddr_in6);
238 recv_bufsize = udpsocket_recvfrom(callback_object->sd, recv_buf + ipheader_bytes, RIST_MAX_PACKET_SIZE, MSG_DONTWAIT, (struct sockaddr *) &addr6, &addrlen);
239 addr = (struct sockaddr *) &addr6;
240 } else {
241 addrlen = sizeof(struct sockaddr_in);
242 recv_bufsize = udpsocket_recvfrom(callback_object->sd, recv_buf + ipheader_bytes, RIST_MAX_PACKET_SIZE, MSG_DONTWAIT, (struct sockaddr *) &addr4, &addrlen);
243 addr = (struct sockaddr *) &addr4;
244 }
245
246 if (recv_bufsize > 0) {
247 ssize_t offset = 0;
248 struct rist_data_block data_block = { 0 };
249 // Delegate ts_ntp to the library by default.
250 // If we wanted to be more accurate, we could use the kernel nic capture timestamp (linux)
251 data_block.ts_ntp = 0;
252 data_block.flags = 0;
253 uint8_t *rtp_hdr = recv_buf + ipheader_bytes;
254 if (callback_object->udp_config->rtp_timestamp && recv_bufsize > 12)
255 {
256 uint32_t rtp_time = ((uint32_t)rtp_hdr[4] << 24) |
257 ((uint32_t)rtp_hdr[5] << 16) |
258 ((uint32_t)rtp_hdr[6] << 8) |
259 (uint32_t)rtp_hdr[7];
260 data_block.ts_ntp = risttools_convertRTPtoNTP(rtp_time);
261 }
262 if (callback_object->udp_config->rtp_sequence && recv_bufsize > 12)
263 {
264 data_block.seq = (uint64_t)(((uint16_t)rtp_hdr[2] << 8) | rtp_hdr[3]);
265 data_block.flags = RIST_DATA_FLAGS_USE_SEQ;
266 }
267 if (callback_object->udp_config->version == 1 && callback_object->udp_config->multiplex_mode == LIBRIST_MULTIPLEX_MODE_IPV4) {
268 data_block.virt_src_port = UINT16_MAX;
269 data_block.payload = recv_buf + offset;
270 data_block.payload_len = recv_bufsize - offset + ipheader_bytes;
271 populate_ipv4_rist_header(address_family, recv_buf, recv_bufsize, addr, addrlen);
272 }
273 else {
274 // rtp header will not be stripped out in IPV4 mux mode
275 if (callback_object->udp_config->rtp && recv_bufsize > 12)
276 offset = 12; // TODO: check for header extensions and remove them as well
277 if (callback_object->udp_config->version == 1 && callback_object->udp_config->multiplex_mode == LIBRIST_MULTIPLEX_MODE_VIRT_SOURCE_PORT) {
278 data_block.virt_src_port = callback_object->udp_config->stream_id;
279 }
280 data_block.payload = recv_buf + offset + ipheader_bytes;
281 data_block.payload_len = recv_bufsize - offset;
282 }
283 if (peer_connected_count || blind_send) {
284 if (rist_sender_data_write(callback_object->sender_ctx->ctx, &data_block) < 0)
285 rist_log(&logging_settings, RIST_LOG_ERROR, "Error writing data in input_udp_recv, socket=%d\n", callback_object->sd);
286 }
287 }
288 else
289 {
290 // EWOULDBLOCK = EAGAIN = 11 would be the most common recoverable error (if any)
291 if (errno != EWOULDBLOCK)
292 rist_log(&logging_settings, RIST_LOG_ERROR, "Input receive failed: errno=%d, ret=%d, socket=%d\n", errno, recv_bufsize, callback_object->sd);
293 }
294 }
295
296 static void input_udp_sockerr(struct evsocket_ctx *evctx, int fd, short revents, void *arg)
297 {
298 struct rist_callback_object *callback_object = (void *) arg;
299 RIST_MARK_UNUSED(evctx);
300 RIST_MARK_UNUSED(revents);
301 RIST_MARK_UNUSED(fd);
302 rist_log(&logging_settings, RIST_LOG_ERROR, "Socket error on sd=%d, stream-id=%d !\n", callback_object->sd, callback_object->udp_config->stream_id);
303 }
304
305 static void usage(char *cmd)
306 {
307 rist_log(&logging_settings, RIST_LOG_INFO, "%s\n%s version %s libRIST library: %s API version: %s\n", cmd, help_str, RISTSENDER_VERSION, librist_version(), librist_api_version());
308 exit(1);
309 }
310
311 static void connection_status_callback(void *arg, struct rist_peer *peer, enum rist_connection_status peer_connection_status)
312 {
313 (void)arg;
314 if (peer_connection_status == RIST_CONNECTION_ESTABLISHED || peer_connection_status == RIST_CLIENT_CONNECTED) {
315 peer_connected_count++;
316 for (int j = 0; j < g_callback_object_count; j++) {
317 if (g_callback_objects[j].mcast_deferred) {
318 struct sockaddr_in6 sa;
319 memset(&sa, 0, sizeof(sa));
320 if (udpsocket_resolve_host(g_callback_objects[j].mcast_host,
321 g_callback_objects[j].mcast_port, (struct sockaddr *)&sa) == 0) {
322 if (udpsocket_join_mcast_group(g_callback_objects[j].sd,
323 g_callback_objects[j].mcast_miface,
324 (struct sockaddr *)&sa, sa.sin6_family, NULL) == 0) {
325 rist_log(&logging_settings, RIST_LOG_INFO,
326 "Deferred multicast join for %s succeeded\n",
327 g_callback_objects[j].mcast_host);
328 } else {
329 rist_log(&logging_settings, RIST_LOG_ERROR,
330 "Deferred multicast join for %s failed\n",
331 g_callback_objects[j].mcast_host);
332 }
333 }
334 g_callback_objects[j].mcast_deferred = false;
335 }
336 }
337 } else {
338 peer_connected_count--;
339 }
340 rist_log(&logging_settings, RIST_LOG_INFO,"Connection Status changed for Peer %"PRIu64", new status is %d, peer connected count is %d\n",
341 peer, peer_connection_status, peer_connected_count);
342 }
343
344 static int cb_auth_connect(void *arg, const char* connecting_ip, uint16_t connecting_port, const char* local_ip, uint16_t local_port, struct rist_peer *peer)
345 {
346 struct rist_ctx_wrap *w = (struct rist_ctx_wrap *)arg;
347 #if HAVE_PROMETHEUS_SUPPORT
348 if (w->sender && prom_stats_ctx != NULL) {
349 uint32_t id = rist_peer_get_id(peer);
350 char url[256];
351 snprintf(url, sizeof(url), "%s:%u", connecting_ip, connecting_port);
352 char local_url[256];
353 snprintf(local_url, sizeof(local_url), "%s:%u", local_ip, local_port);
354 rist_prometheus_sender_add_peer(prom_stats_ctx, w->id, id, url, local_url, true);
355 }
356 #endif
357 struct rist_ctx *ctx = w->ctx;
358 uint16_t buffer[250];
359 char message[200];
360 int message_len = snprintf(message, 200, "auth,%s:%d,%s:%d", connecting_ip, connecting_port, local_ip, local_port);
361 // To be compliant with the spec, the message must have an ipv4 header
362 int ret = oob_build_api_payload(buffer, (char *)connecting_ip, (char *)local_ip, message, message_len);
363 rist_log(&logging_settings, RIST_LOG_INFO,"Peer has been peer_connected_count, sending oob/api message: %s\n", message);
364 struct rist_oob_block oob_block;
365 oob_block.peer = peer;
366 oob_block.payload = buffer;
367 oob_block.payload_len = ret;
368 rist_oob_write(ctx, &oob_block);
369 return 0;
370 }
371
372 static int cb_auth_disconnect(void *arg, struct rist_peer *peer)
373 {
374 struct rist_ctx *ctx = (struct rist_ctx *)arg;
375 (void)ctx;
376 (void)peer;
377 return 0;
378 }
379
380 static int rist_validate_tun_data(uint8_t *buffer, ssize_t buffer_len)
381 {
382 struct ipheader *ip = (struct ipheader *) buffer;
383 int protocol = 0;
384 ssize_t payload_len = 0;
385 // Double check the validity of the packet and get the protocol number
386 if (RIST_IPH_GET_VER(ip->iph_verlen) == 4) {
387 protocol = (int) ip->iph_protocol;
388 payload_len = (ssize_t)be16toh(ip->iph_len);
389 if (payload_len != buffer_len) {
390 rist_log(&logging_settings, RIST_LOG_INFO, "Malformed ipv4 packet %d != %d\n",
391 payload_len != buffer_len);
392 return -1;
393 }
394 }
395 else if (RIST_IPH_GET_VER(ip->iph_verlen) == 6) {
396 // TODO: how do I get the protocol?
397 // For now, send all IPv6 over OOB channel
398 }
399 else {
400 rist_log(&logging_settings, RIST_LOG_INFO, "Unknown ipv? payload %d\n",
401 RIST_IPH_GET_VER(ip->iph_verlen));
402 return -1;
403 }
404 return protocol;
405 }
406
407 static int cb_recv_oob(void *arg, const struct rist_oob_block *oob_block)
408 {
409 struct rist_callback_tun_object *callback_tun_object = (void *) arg;
410 int message_len = 0;
411 char *message = oob_process_api_message((int)oob_block->payload_len, (char *)oob_block->payload, &message_len);
412 if (message) {
413 rist_log(&logging_settings, RIST_LOG_INFO,"Out-of-band api data received: %.*s\n", message_len, message);
414 }
415 else if (callback_tun_object->tun)
416 {
417 // Process non-api based data
418 int protocol = rist_validate_tun_data((uint8_t *)oob_block->payload, oob_block->payload_len);
419 if (protocol >= 0)
420 {
421 if (callback_tun_object->tun_mode == 0 ||
422 (callback_tun_object->tun_mode == 1 && protocol != 17)) {
423 if (rist_tun_write(callback_tun_object->tun, oob_block->payload, oob_block->payload_len) < 0) {
424 rist_log(&logging_settings, RIST_LOG_ERROR, "Error %d writing %d bytes to output tun\n", errno, oob_block->payload_len);
425 }
426 }
427 }
428 }
429 return 0;
430 }
431
432 static int sender_stats_callback(void *arg, uint16_t version, char *stats_json, uint32_t json_size)
433 {
434 (void) arg;
435 (void) version;
436 rist_log(&logging_settings, RIST_LOG_INFO, "%s\n\n", stats_json, json_size);
437 #if HAVE_PROMETHEUS_SUPPORT
438 if (prom_stats_ctx != NULL)
439 rist_prometheus_parse_sender_stats(prom_stats_ctx, version, stats_json, json_size, (uintptr_t)arg);
440 #else
441 (void)arg;
442 #endif
443 return 0;
444 }
445
446 static void intHandler(int signal)
447 {
448 rist_log(&logging_settings, RIST_LOG_INFO, "Signal %d received\n", signal);
449 signalReceived = signal;
450 }
451
452 static struct rist_peer* setup_rist_peer(struct rist_ctx_wrap *w, struct rist_sender_args *setup)
453 {
454 struct rist_ctx *ctx = w->ctx;
455 if (rist_sender_stats_callback_set(ctx, setup->statsinterval, sender_stats_callback, (void*)w->id) == -1) {
456 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not enable stats callback\n");
457 return NULL;
458 }
459
460 if (rist_auth_handler_set(ctx, cb_auth_connect, cb_auth_disconnect, w) < 0) {
461 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not initialize rist auth handler\n");
462 return NULL;
463 }
464
465 if (rist_connection_status_callback_set(ctx, connection_status_callback, NULL) == -1) {
466 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not initialize rist connection status callback\n");
467 return NULL;
468 }
469
470 if (setup->profile != RIST_PROFILE_SIMPLE) {
471 if (rist_oob_callback_set(ctx, cb_recv_oob, setup->callback_tun_object) == -1) {
472 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not enable out-of-band data\n");
473 return NULL;
474 }
475 }
476
477 // Rely on the library to parse the url
478 struct rist_peer_config *peer_config_link = NULL;
479 if (rist_parse_address2(setup->token, (void *)&peer_config_link))
480 {
481 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse peer options for sender: %s\n", setup->token);
482 return NULL;
483 }
484
485 /* Process overrides */
486 struct rist_peer_config *overrides_peer_config = (void *)peer_config_link;
487 if (setup->shared_secret && peer_config_link->secret[0] == 0) {
488 strncpy(overrides_peer_config->secret, setup->shared_secret, RIST_MAX_STRING_SHORT -1);
489 if (setup->encryption_type)
490 overrides_peer_config->key_size = setup->encryption_type;
491 else if (!overrides_peer_config->key_size)
492 overrides_peer_config->key_size = 128;
493 }
494 if (setup->buffer_size) {
495 overrides_peer_config->recovery_length_min = setup->buffer_size;
496 overrides_peer_config->recovery_length_max = setup->buffer_size;
497 }
498 if (setup->stream_id) {
499 if (setup->stream_id % 2 != 0) {
500 rist_log(&logging_settings, RIST_LOG_ERROR, "Error parsing peer options for sender: %s, stream-id (%d) must be even!\n\n", setup->token, setup->stream_id);
501 return NULL;
502 }
503 else {
504 overrides_peer_config->virt_dst_port = setup->stream_id;
505 }
506 }
507
508 /* Print config */
509 rist_log(&logging_settings, RIST_LOG_INFO, "Link configured with maxrate=%d bufmin=%d bufmax=%d reorder=%d rttmin=%d rttmax=%d congestion_control=%d min_retries=%d max_retries=%d\n",
510 peer_config_link->recovery_maxbitrate, peer_config_link->recovery_length_min, peer_config_link->recovery_length_max,
511 peer_config_link->recovery_reorder_buffer, peer_config_link->recovery_rtt_min, peer_config_link->recovery_rtt_max,
512 peer_config_link->congestion_control_mode, peer_config_link->min_retries, peer_config_link->max_retries);
513
514 struct rist_peer *peer;
515 if (rist_peer_create(ctx, &peer, peer_config_link) == -1) {
516
517 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not add peer connector to %s\n", peer_config_link->address);
518 free((void *)peer_config_link);
519 return NULL;
520 }
521
522 #if HAVE_PROMETHEUS_SUPPORT
523 if (w->sender && prom_stats_ctx != NULL) {
524 char *p = strchr(overrides_peer_config->address, '@');
525 if (p == NULL) {
526 p = strstr(overrides_peer_config->address, "://");
527 if (p == NULL) {
528 p = overrides_peer_config->address;
529 } else {
530 p+= strlen("://");
531 }
532 uint32_t id = rist_peer_get_id(peer);
533 rist_prometheus_sender_add_peer(prom_stats_ctx, w->id, id, p, NULL, false);
534 }
535 }
536 #endif
537 #if HAVE_SRP_SUPPORT
538 int srp_error = 0;
539 if (setup->profile != RIST_PROFILE_SIMPLE) {
540 if (strlen(peer_config_link->srp_username) > 0 && strlen(peer_config_link->srp_password) > 0)
541 {
542 srp_error = rist_enable_eap_srp_2(peer, peer_config_link->srp_username, peer_config_link->srp_password, NULL, NULL);
543 if (srp_error)
544 rist_log(&logging_settings, RIST_LOG_WARN, "Error %d trying to enable SRP for peer\n", srp_error);
545 }
546 if (srpfile)
547 {
548 srp_error = rist_enable_eap_srp_2(peer, NULL, NULL, user_verifier_lookup, srpfile);
549 if (srp_error)
550 rist_log(&logging_settings, RIST_LOG_WARN, "Error %d trying to enable SRP global authenticator, file %s\n", srp_error, srpfile);
551 }
552 }
553 else
554 rist_log(&logging_settings, RIST_LOG_WARN, "SRP Authentication is not available for Rist Simple Profile\n");
555 #endif
556
557 rist_peer_config_free2(&peer_config_link);
558
559 return peer;
560 }
561
562 static void rist_process_tun_data(struct rist_callback_tun_object *callback_tun_object, uint8_t *buffer, ssize_t buffer_len)
563 {
564 int protocol = rist_validate_tun_data(buffer, buffer_len);
565 if (protocol >=0) {
566 // Send data through oob channel
567 if (callback_tun_object->tun_mode == 0 ||
568 (callback_tun_object->tun_mode == 1 && protocol != 17)) {
569 struct rist_oob_block oob_block = { 0 };
570 oob_block.peer = NULL;
571 oob_block.payload = &buffer[0];
572 oob_block.payload_len = buffer_len;
573 if (rist_oob_write(callback_tun_object->sender_ctx, &oob_block) < 0)
574 rist_log(&logging_settings, RIST_LOG_ERROR, "Error writing %d bytes to rist_oob_write\n", buffer_len);
575 }
576 // Send data through rist channel
577 if (callback_tun_object->send_rist == true &&
578 callback_tun_object->tun_mode != 0 && protocol == 17) {
579 struct rist_data_block data_block = { 0 };
580 // We use this source port to signal a non standard stream, i.e. tun mux
581 data_block.virt_src_port = 1;
582 // Delegate ts_ntp to the library by default.
583 // If we wanted to be more accurate, we could use the kernel nic capture timestamp (linux)
584 data_block.ts_ntp = 0;
585 data_block.flags = 0;
586 data_block.payload = &buffer[0];
587 data_block.payload_len = buffer_len;
588 if (rist_sender_data_write(callback_tun_object->sender_ctx, &data_block) < 0)
589 rist_log(&logging_settings, RIST_LOG_ERROR, "Error writing %d bytes to rist_sender_data_write\n", buffer_len);
590 }
591 }
592 }
593
594 static PTHREAD_START_FUNC(tun_loop, arg)
595 {
596 struct rist_callback_tun_object *callback_tun_object = (void *) arg;
597 while (!signalReceived) {
598 uint8_t buffer[RIST_MAX_PACKET_SIZE];
599 fd_set read_fds;
600 FD_ZERO(&read_fds);
601 FD_SET(callback_tun_object->tun, &read_fds);
602 // Set timeout to 100 ms
603 struct timeval timeout;
604 timeout.tv_sec = 0;
605 timeout.tv_usec = 100000;
606 // Wait for input to become ready or until the time out;
607 if (select(FD_SETSIZE, &read_fds, NULL, NULL, &timeout) == 1)
608 {
609 ssize_t r = rist_tun_read(callback_tun_object->tun, &buffer[0], RIST_MAX_PACKET_SIZE);
610 if (r > 0) {
611 rist_process_tun_data(callback_tun_object, &buffer[0], r);
612 }
613 else
614 break;
615 }
616 }
617 return 0;
618 }
619
620 static PTHREAD_START_FUNC(input_loop, arg)
621 {
622 struct rist_callback_object *callback_object = (void *) arg;
623 // This is my main loop (one thread per receiver)
624 while (!signalReceived) {
625 if (callback_object->receiver_ctx)
626 {
627 // RIST receiver
628 struct rist_data_block *b = NULL;
629 int queue_size = rist_receiver_data_read2(callback_object->receiver_ctx->ctx, &b, 5);
630 if (queue_size > 0) {
631 if (queue_size % 10 == 0 || queue_size > 50)
632 rist_log(&logging_settings, RIST_LOG_WARN, "Falling behind on rist_receiver_data_read: %d\n", queue_size);
633 if (b && b->payload) {
634 if (peer_connected_count) {
635 int w = rist_sender_data_write(callback_object->sender_ctx->ctx, b);
636 // TODO: report error?
637 (void) w;
638 }
639 rist_receiver_data_block_free2(&b);
640 }
641 }
642 }
643 else
644 {
645 // UDP receiver. Infinite wait, 100 socket events
646 evsocket_loop_single(callback_object->evctx, 5, 100);
647 }
648 }
649 return 0;
650 }
651
652 static struct rist_ctx_wrap *configure_rist_output_context(char* outputurl,
653 struct rist_sender_args *peer_args, const struct rist_udp_config *udp_config,
654 bool npd, enum rist_profile profile)
655 {
656 struct rist_ctx *sender_ctx;
657 // Setup the output rist objects (a brand new instance per receiver)
658 char *saveptroutput;
659 char *tmpoutputurl = malloc(strlen(outputurl) +1);
660 strcpy(tmpoutputurl, outputurl);
661 char *outputtoken = strtok_r(tmpoutputurl, ",", &saveptroutput);
662
663 // All output peers should be on the same context per receiver
664 if (rist_sender_create(&sender_ctx, peer_args->profile, 0, &logging_settings) != 0) {
665 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not create rist sender context\n");
666 goto fail;
667 }
668 struct rist_ctx_wrap *w = malloc(sizeof(*w));
669 w->ctx = sender_ctx;
670 w->id = prometheus_id++;
671 w->sender = true;
672 if (npd) {
673 if (profile == RIST_PROFILE_SIMPLE)
674 rist_log(&logging_settings, RIST_LOG_INFO, "NULL packet deletion enabled on SIMPLE profile. This is non-compliant but might work if receiver supports it (librist does)\n");
675 else
676 rist_log(&logging_settings, RIST_LOG_INFO, "NULL packet deletion enabled. Support for this feature is not guaranteed to be present on receivers. Please make sure the receiver supports it (librist does)\n");
677 if (rist_sender_npd_enable(sender_ctx) != 0) {
678 rist_log(&logging_settings, RIST_LOG_ERROR, "Failed to enable null packet deletion\n");
679 }
680 }
681 for (size_t j = 0; j < MAX_OUTPUT_COUNT; j++) {
682 peer_args->token = outputtoken;
683 peer_args->stream_id = udp_config->stream_id;
684 struct rist_peer *peer = setup_rist_peer(w, peer_args);
685 if (peer == NULL)
686 goto fail;
687 outputtoken = strtok_r(NULL, ",", &saveptroutput);
688 if (!outputtoken)
689 break;
690 }
691 free(tmpoutputurl);
692
693 return w;
694 fail:
695 return NULL;
696 }
697
698 int main(int argc, char *argv[])
699 {
700 int c;
701 int option_index;
702 struct rist_callback_object callback_object[MAX_INPUT_COUNT] = { {0} };
703 struct evsocket_event *event[MAX_INPUT_COUNT];
704 char *inputurl = NULL;
705 char *outputurl = NULL;
706 struct rist_callback_tun_object callback_tun_object = {0};
707 callback_tun_object.tun_mode = 1;
708 char *oobtun = NULL;
709 char *shared_secret = NULL;
710 int buffer_size = 0;
711 int encryption_type = 0;
712 int statsinterval = 1000;
713 enum rist_profile profile = RIST_DEFAULT_PROFILE;
714 enum rist_log_level loglevel = RIST_LOG_INFO;
715 bool npd = false;
716 int faststart = 0;
717 struct rist_sender_args peer_args;
718 char *remote_log_address = NULL;
719 bool thread_started[MAX_INPUT_COUNT +1] = {false};
720 pthread_t thread_main_loop[MAX_INPUT_COUNT+2] = { 0 };
721 rist_tools_config_object *yaml_config = NULL;
722 char *yamlfile = NULL;
723
724 for (size_t i = 0; i < MAX_INPUT_COUNT; i++)
725 event[i] = NULL;
726
727 #ifdef _WIN32
728 #define STDERR_FILENO 2
729 signal(SIGINT, intHandler);
730 signal(SIGTERM, intHandler);
731 signal(SIGABRT, intHandler);
732 #else
733 struct sigaction act = { {0} };
734 act.sa_handler = intHandler;
735 sigaction(SIGINT, &act, NULL);
736 #endif
737
738 // Default log settings
739 struct rist_logging_settings *log_ptr = &logging_settings;
740 if (rist_logging_set(&log_ptr, loglevel, NULL, NULL, NULL,
741 stderr) != 0) {
742 fprintf(stderr, "Failed to setup default logging!\n");
743 exit(1);
744 }
745
746 rist_log(&logging_settings, RIST_LOG_INFO, "Starting ristsender version: %s libRIST library: %s API version: %s\n", RISTSENDER_VERSION, librist_version(), librist_api_version());
747
748 while ((c = getopt_long(argc, argv, "r:i:o:b:s:e:t:m:p:S:F:f:c:v:hunM", long_options, &option_index)) != -1) {
749 switch (c) {
750 case 'i':
751 inputurl = strdup(optarg);
752 break;
753 case 'o':
754 outputurl = strdup(optarg);
755 break;
756 case 'b':
757 buffer_size = atoi(optarg);
758 break;
759 case 's':
760 shared_secret = strdup(optarg);
761 break;
762 case 'e':
763 encryption_type = atoi(optarg);
764 break;
765 case 't':
766 oobtun = strdup(optarg);
767 break;
768 case 'm':
769 callback_tun_object.tun_mode = atoi(optarg);
770 break;
771 case 'p':
772 profile = atoi(optarg);
773 break;
774 case 'S':
775 statsinterval = atoi(optarg);
776 break;
777 case 'v':
778 loglevel = atoi(optarg);
779 break;
780 case 'r':
781 remote_log_address = strdup(optarg);
782 break;
783 #if HAVE_SRP_SUPPORT
784 case 'F': {
785 FILE* f = fopen(optarg, "r");
786 if (!f) {
787 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not open srp file %s\n", optarg);
788 return 1;
789 }
790 srpfile = strdup(optarg);
791 }
792 break;
793 #endif
794 case 'u':
795 rist_log(&logging_settings, RIST_LOG_INFO, "%s", help_urlstr);
796 exit(1);
797 break;
798 case 'f':
799 faststart = atoi(optarg);
800 break;
801 case 'n':
802 npd = true;
803 break;
804 #if HAVE_PROMETHEUS_SUPPORT
805 case 'M':
806 enable_prometheus = true;
807 break;
808 case 0:
809 //long option, value get's set directly
810 break;
811 case 1:
812 //long option metric tags
813 prometheus_tags = strdup(optarg);
814 break;
815 case 2:
816 //prometheus port long opt
817 prometheus_httpd = true;
818 prometheus_port = atoi(optarg);
819 break;
820 case 3:
821 //prometheus IP long opt
822 prometheus_httpd = true;
823 prometheus_ip = strdup(optarg);
824 break;
825 case 4:
826 //prometheus unix socket long opt
827 enable_prometheus = true;
828 prometheus_unix_sock = strdup(optarg);
829 break;
830 #endif
831 case 'c':
832 yamlfile = strdup(optarg);
833 yaml_config = parse_yaml(yamlfile);
834 free(yamlfile);
835 if (!yaml_config){
836 fprintf(stderr,"Could not import yaml file %s\n",optarg);
837 cleanup_tools_config(yaml_config);
838 exit(1);
839 }
840 if (yaml_config->input_url)
841 inputurl = strdup(yaml_config->input_url);
842 if (yaml_config->output_url)
843 outputurl = strdup(yaml_config->output_url);
844 buffer_size = yaml_config->buffer;
845 if (yaml_config->secret)
846 shared_secret = strdup(yaml_config->secret);
847 encryption_type = yaml_config->encryption_type;
848 loglevel = yaml_config->verbose_level;
849 if (yaml_config->remote_log_address)
850 remote_log_address = strdup(yaml_config->remote_log_address);
851 faststart = yaml_config->fast_start;
852 npd = yaml_config->null_packet_deletion;
853 profile = yaml_config->profile;
854 statsinterval = yaml_config->stats_interval;
855 // hardcoded mode for now
856 // callback_tun_object.tun_mode = 1; (yaml_config->tun_mode)
857 if (yaml_config->tunnel_interface)
858 oobtun = strdup(yaml_config->tunnel_interface);
859 #if HAVE_SRP_SUPPORT
860 if (yaml_config->srp_file)
861 srpfile = strdup(yaml_config->srp_file);
862 #endif
863 #if HAVE_PROMETHEUS_SUPPORT
864 enable_prometheus = yaml_config->enable_metrics;
865 if (yaml_config->metrics_tags)
866 prometheus_tags = strdup(yaml_config->metrics_tags);
867 prometheus_multipoint = yaml_config->metrics_multipoint;
868 prometheus_nocreated = yaml_config->metrics_nocreated;
869 #if HAVE_LIBMICROHTTPD
870 prometheus_httpd = yaml_config->metrics_http;
871 prometheus_port = yaml_config->metrics_port;
872 if (yaml_config->metrics_ip)
873 prometheus_ip = strdup(yaml_config->metrics_ip);
874 #endif
875 #if HAVE_SOCK_UN_H
876 if (yaml_config->metrics_unix)
877 prometheus_unix_sock = strdup(yaml_config->metrics_unix);
878 #endif
879 #endif
880 cleanup_tools_config(yaml_config);
881 break;
882 case 5:
883 blind_send = true;
884 break;
885 case 'h':
886 /* Fall through */
887 default:
888 usage(argv[0]);
889 break;
890 }
891 }
892
893 if (inputurl == NULL || outputurl == NULL) {
894 usage(argv[0]);
895 }
896
897 if (argc < 2) {
898 usage(argv[0]);
899 }
900
901 if (faststart < 0 || faststart > 1) {
902 fprintf(stderr,"Invalid or not implemented fast-start mode %d\n", faststart);
903 exit(1);
904 }
905
906 if (profile == RIST_PROFILE_SIMPLE || faststart > 0)
907 peer_connected_count = 1;
908
909 // Update log settings with custom loglevel and remote address if necessary
910 if (rist_logging_set(&log_ptr, loglevel, NULL, NULL, remote_log_address, stderr) != 0) {
911 fprintf(stderr,"Failed to setup logging\n");
912 exit(1);
913 }
914
915 #if HAVE_PROMETHEUS_SUPPORT
916 if (enable_prometheus || prometheus_httpd) {
917 rist_log(log_ptr, RIST_LOG_INFO, "Enabling Metrics output\n");
918 struct prometheus_httpd_options httpd_opt;
919 httpd_opt.enabled = prometheus_httpd;
920 httpd_opt.port = prometheus_port;
921 httpd_opt.ip = prometheus_ip;
922 prom_stats_ctx = rist_setup_prometheus_stats(log_ptr, prometheus_tags,prometheus_multipoint, prometheus_nocreated, &httpd_opt, prometheus_unix_sock);
923 if (prom_stats_ctx == NULL) {
924 rist_log(log_ptr, RIST_LOG_ERROR, "Failed to setup Metrics output\n");
925 exit(1);
926 }
927 }
928 #endif
929 peer_args.loglevel = loglevel;
930 peer_args.profile = profile;
931 peer_args.encryption_type = encryption_type;
932 peer_args.shared_secret = shared_secret;
933 peer_args.buffer_size = buffer_size;
934 peer_args.statsinterval = statsinterval;
935
936 // Setup tun device
937 if (oobtun) {
938 char tun_ifname[64] = {0};
939 callback_tun_object.tun = rist_tun_open(oobtun, tun_ifname, sizeof(tun_ifname));
940 if (callback_tun_object.tun >= 0)
941 rist_tun_bring_up(tun_ifname);
942 else {
943 rist_log(&logging_settings, RIST_LOG_ERROR, "tun open error: %s\n", strerror(errno));
944 exit(1);
945 }
946 }
947
948 bool rist_listens = false;
949 if (strstr(outputurl, "://@") != NULL) {
950 rist_listens = true;
951 }
952
953 // Setup the input udp/rist objects: listen to the given address(es)
954 int32_t stream_id_check[MAX_INPUT_COUNT ];
955 for (size_t j = 0; j < MAX_INPUT_COUNT; j++)
956 stream_id_check[j] = -1;
957 struct evsocket_ctx *evctx = NULL;
958 bool atleast_one_socket_opened = false;
959 char *saveptrinput;
960 char *inputtoken = strtok_r(inputurl, ",", &saveptrinput);
961 struct rist_udp_config *udp_config = NULL;
962 for (size_t i = 0; i < MAX_INPUT_COUNT; i++) {
963 if (!inputtoken)
964 break;
965
966 // First parse extra url and parameters
967 if (rist_parse_udp_address2(inputtoken, &udp_config)) {
968 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse inputurl %s\n", inputtoken);
969 goto next;
970 }
971
972 // Check for duplicate stream-ids and reject the entire config if we have any dups
973 bool found_empty = false;
974 for (size_t j = 0; j < MAX_INPUT_COUNT; j++) {
975 if (stream_id_check[j] == -1 && !found_empty) {
976 stream_id_check[j] = (int32_t)udp_config->stream_id;
977 rist_log(&logging_settings, RIST_LOG_INFO, "Assigning stream-id %d to this input\n", udp_config->stream_id);
978 found_empty = true;
979 } else if ((uint16_t)stream_id_check[j] == udp_config->stream_id) {
980 rist_log(&logging_settings, RIST_LOG_ERROR, "Every input must have a unique stream-id (%d) when you multiplex\n", udp_config->stream_id);
981 goto shutdown;
982 }
983 }
984
985 peer_args.callback_tun_object = &callback_tun_object;
986
987 // Setup the output rist objects
988 if (rist_listens && i > 0) {
989 if (callback_object[0].udp_config->version == 1 && (callback_object[0].udp_config->multiplex_mode == LIBRIST_MULTIPLEX_MODE_VIRT_DESTINATION_PORT || udp_config->multiplex_mode == LIBRIST_MULTIPLEX_MODE_VIRT_DESTINATION_PORT)) {
990 rist_log(&logging_settings, RIST_LOG_ERROR, "Multiplexing is not allowed when any peer is in listening mode unless you enable non standard muxing on all inputs\n");
991 goto shutdown;
992 }
993 else {
994 // Single context for all inputs, we multiplex on the payload
995 callback_object[i].sender_ctx = callback_object[0].sender_ctx;
996 }
997 }
998 else
999 {
1000 // A brand new instance/context per receiver
1001 callback_object[i].sender_ctx = configure_rist_output_context(outputurl, &peer_args, udp_config, npd, profile);
1002 if (callback_object[i].sender_ctx == NULL)
1003 goto shutdown;
1004 }
1005 for (size_t j = 0; j < MAX_OUTPUT_COUNT; j++) {
1006 // Use the first context for OOB tun context
1007 if (!callback_tun_object.sender_ctx) {
1008 callback_tun_object.sender_ctx = callback_object[i].sender_ctx->ctx;
1009 }
1010 }
1011
1012 if (strcmp(udp_config->prefix, "rist") == 0) {
1013 // This is a rist input (new context for each listener)
1014 struct rist_ctx_wrap *w = calloc(1, sizeof(*w));
1015 w->id = prometheus_id++;
1016 callback_object[i].receiver_ctx = w;
1017 if (rist_receiver_create(&callback_object[i].receiver_ctx->ctx, peer_args.profile, &logging_settings) != 0) {
1018 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not create rist receiver context\n");
1019 goto next;
1020 }
1021 peer_args.token = inputtoken;
1022 struct rist_peer *peer = setup_rist_peer(callback_object[i].receiver_ctx, &peer_args);
1023 if (peer == NULL)
1024 atleast_one_socket_opened = true;
1025 rist_udp_config_free2(&udp_config);
1026 udp_config = NULL;
1027 }
1028 else if (strcmp(udp_config->prefix, "tun") == 0) {
1029 atleast_one_socket_opened = true;
1030 callback_tun_object.send_rist = true;
1031 }
1032 else {
1033 if(!evctx)
1034 evctx = evsocket_create();
1035 // This is a udp input, i.e. 127.0.0.1:5000
1036 char hostname[200] = {0};
1037 int inputlisten;
1038 uint16_t inputport;
1039 if (udpsocket_parse_url((void *)udp_config->address, hostname, 200, &inputport, &inputlisten) || !inputport || strlen(hostname) == 0) {
1040 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse input url %s\n", inputtoken);
1041 goto next;
1042 }
1043 rist_log(&logging_settings, RIST_LOG_INFO, "URL parsed successfully: Host %s, Port %d\n", (char *) hostname, inputport);
1044
1045 int is_mcast = 0;
1046 {
1047 struct sockaddr_in6 probe;
1048 memset(&probe, 0, sizeof(probe));
1049 if (udpsocket_resolve_host(hostname, inputport, (struct sockaddr *)&probe) == 0) {
1050 if (probe.sin6_family == AF_INET6)
1051 is_mcast = IN6_IS_ADDR_MULTICAST(&probe.sin6_addr);
1052 else
1053 is_mcast = IN_MULTICAST(ntohl(((struct sockaddr_in *)&probe)->sin_addr.s_addr));
1054 }
1055 }
1056
1057 if (is_mcast) {
1058 struct sockaddr_in6 mcast_sa;
1059 memset(&mcast_sa, 0, sizeof(mcast_sa));
1060 if (udpsocket_resolve_host(hostname, inputport, (struct sockaddr *)&mcast_sa) < 0) {
1061 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not resolve %s\n", hostname);
1062 goto next;
1063 }
1064 uint16_t af = mcast_sa.sin6_family;
1065 int sd = udpsocket_open(af);
1066 if (sd < 0) {
1067 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not open socket for %s\n", hostname);
1068 goto next;
1069 }
1070 int yes_val = 1;
1071 setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes_val, sizeof(yes_val));
1072 struct sockaddr_storage bind_addr;
1073 socklen_t bind_len;
1074 memset(&bind_addr, 0, sizeof(bind_addr));
1075 if (af == AF_INET6) {
1076 struct sockaddr_in6 *a6 = (struct sockaddr_in6 *)&bind_addr;
1077 a6->sin6_family = AF_INET6;
1078 a6->sin6_port = htons(inputport);
1079 a6->sin6_addr = in6addr_any;
1080 bind_len = sizeof(struct sockaddr_in6);
1081 } else {
1082 struct sockaddr_in *a4 = (struct sockaddr_in *)&bind_addr;
1083 a4->sin_family = AF_INET;
1084 a4->sin_port = htons(inputport);
1085 a4->sin_addr.s_addr = INADDR_ANY;
1086 bind_len = sizeof(struct sockaddr_in);
1087 }
1088 if (bind(sd, (struct sockaddr *)&bind_addr, bind_len) < 0) {
1089 #ifdef _WIN32
1090 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not bind to port %d: WSAGetLastError=%d\n", inputport, WSAGetLastError());
1091 #else
1092 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not bind to port %d: %s\n", inputport, strerror(errno));
1093 #endif
1094 udpsocket_close(sd);
1095 goto next;
1096 }
1097 callback_object[i].sd = sd;
1098 if (blind_send) {
1099 if (udpsocket_join_mcast_group(sd, udp_config->miface,
1100 (struct sockaddr *)&mcast_sa, af, NULL) != 0) {
1101 rist_log(&logging_settings, RIST_LOG_ERROR,
1102 "Could not join multicast group %s on %s\n",
1103 hostname, udp_config->miface[0] ? udp_config->miface : "default");
1104 udpsocket_close(sd);
1105 goto next;
1106 }
1107 rist_log(&logging_settings, RIST_LOG_INFO,
1108 "Multicast input %s:%d joined immediately (--blind-send)\n",
1109 hostname, inputport);
1110 } else {
1111 callback_object[i].mcast_deferred = true;
1112 snprintf(callback_object[i].mcast_host, sizeof(callback_object[i].mcast_host), "%s", hostname);
1113 callback_object[i].mcast_port = inputport;
1114 snprintf(callback_object[i].mcast_miface, sizeof(callback_object[i].mcast_miface), "%s", udp_config->miface);
1115 rist_log(&logging_settings, RIST_LOG_INFO,
1116 "Multicast input %s:%d bound, join deferred until peer handshake\n",
1117 hostname, inputport);
1118 }
1119 udpsocket_set_nonblocking(callback_object[i].sd);
1120 atleast_one_socket_opened = true;
1121 } else {
1122 callback_object[i].sd = udpsocket_open_bind(hostname, inputport, udp_config->miface);
1123 if (callback_object[i].sd < 0) {
1124 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not bind to: Host %s, Port %d, miface %s.\n",
1125 (char *) hostname, inputport, udp_config->miface);
1126 goto next;
1127 } else {
1128 udpsocket_set_nonblocking(callback_object[i].sd);
1129 rist_log(&logging_settings, RIST_LOG_INFO, "Input socket is open and bound %s:%d\n", (char *) hostname, inputport);
1130 atleast_one_socket_opened = true;
1131 }
1132 }
1133 callback_object[i].udp_config = udp_config;
1134 udp_config = NULL;
1135 callback_object[i].evctx = evctx;
1136 event[i] = evsocket_addevent(callback_object[i].evctx, callback_object[i].sd, EVSOCKET_EV_READ, input_udp_recv, input_udp_sockerr,
1137 (void *)&callback_object[i]);
1138 }
1139
1140 next:
1141 inputtoken = strtok_r(NULL, ",", &saveptrinput);
1142 }
1143
1144 if (!atleast_one_socket_opened && !callback_tun_object.tun) {
1145 goto shutdown;
1146 }
1147
1148 g_callback_objects = callback_object;
1149 g_callback_object_count = MAX_INPUT_COUNT;
1150
1151 if (evctx && pthread_create(&thread_main_loop[0], NULL, input_loop, (void *)callback_object) != 0)
1152 {
1153 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not start udp receiver thread\n");
1154 goto shutdown;
1155 }
1156 thread_started[0] = true;
1157
1158 for (size_t i = 0; i < MAX_INPUT_COUNT; i++) {
1159 if (((rist_listens && i == 0) || !rist_listens) &&
1160 callback_object[i].sender_ctx && rist_start(callback_object[i].sender_ctx->ctx) == -1) {
1161 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not start rist sender\n");
1162 goto shutdown;
1163 }
1164 if (callback_object[i].receiver_ctx && rist_start(callback_object[i].receiver_ctx->ctx) == -1) {
1165 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not start rist receiver\n");
1166 goto shutdown;
1167 }
1168 if (callback_object[i].receiver_ctx && pthread_create(&thread_main_loop[i+1], NULL, input_loop, (void *)&callback_object[i]) != 0)
1169 {
1170 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not start send rist receiver thread\n");
1171 goto shutdown;
1172 } else if (callback_object[i].receiver_ctx) {
1173 thread_started[i+1] = true;
1174 }
1175 }
1176
1177 if (callback_tun_object.tun && pthread_create(&thread_main_loop[MAX_INPUT_COUNT + 1], NULL, tun_loop, (void *)&callback_tun_object) != 0)
1178 {
1179 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not start tun read thread\n");
1180 goto shutdown;
1181 }
1182
1183 #ifdef _WIN32
1184 system("pause");
1185 #else
1186 pause();
1187 #endif
1188
1189 shutdown:
1190 if (udp_config) {
1191 rist_udp_config_free2(&udp_config);
1192 }
1193 for (size_t i = 0; i < MAX_INPUT_COUNT; i++) {
1194 // Remove socket events
1195 if (event[i])
1196 evsocket_delevent(callback_object[i].evctx, event[i]);
1197 // Free udp_config object
1198 if ((void *)callback_object[i].udp_config)
1199 rist_udp_config_free2(&callback_object[i].udp_config);
1200 // Cleanup rist listeners
1201 if (callback_object[i].receiver_ctx) {
1202 rist_destroy(callback_object[i].receiver_ctx->ctx);
1203 free(callback_object[i].receiver_ctx);
1204 }
1205 // Cleanup rist sender and their peers
1206 if (callback_object[i].sender_ctx) {
1207 rist_destroy(callback_object[i].sender_ctx->ctx);
1208 free(callback_object[i].sender_ctx);
1209 }
1210 }
1211
1212 for (size_t i = 0; i <= MAX_INPUT_COUNT; i++) {
1213 if (thread_started[i])
1214 pthread_join(thread_main_loop[i], NULL);
1215 }
1216
1217 rist_logging_unset_global();
1218 if (inputurl)
1219 free(inputurl);
1220 if (outputurl)
1221 free(outputurl);
1222 if (thread_main_loop[MAX_INPUT_COUNT+1])
1223 pthread_join(thread_main_loop[MAX_INPUT_COUNT+1], NULL);
1224 if (oobtun)
1225 free(oobtun);
1226 if (callback_tun_object.tun)
1227 close(callback_tun_object.tun);
1228 if (shared_secret)
1229 free(shared_secret);
1230
1231 #if HAVE_PROMETHEUS_SUPPORT
1232 rist_prometheus_stats_destroy(prom_stats_ctx);
1233 free(prometheus_ip);
1234 free(prometheus_tags);
1235 free(prometheus_unix_sock);
1236 #endif
1237 return 0;
1238 }