Debian Codegraph @

tools/ristsender.c

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