Debian Codegraph @

tools/udp2udp.c

raw symbols SCIP
1 /* librist. Copyright © 2024 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 #include "vcs_version.h"
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <sys/types.h>
18 #include "getopt-shim.h"
19 #include <stdbool.h>
20 #include <signal.h>
21 #include "common/attributes.h"
22 #include "risturlhelp.h"
23 #include "rist-private.h"
24 #include <stdatomic.h>
25 #include "oob_shared.h"
26 #include "prometheus-exporter.h"
27 #include "yamlparse.h"
28
29 #if defined(_WIN32) || defined(_WIN64)
30 #define strtok_r strtok_s
31 #define MSG_DONTWAIT (0)
32 #endif
33
34 #define RIST_MARK_UNUSED(unused_param) ((void)(unused_param))
35
36 #define UDP2UDP_VERSION "1"
37
38 #define MAX_OUTPUT_COUNT 20
39
40 static int signalReceived = 0;
41 static struct rist_logging_settings logging_settings = LOGGING_SETTINGS_INITIALIZER;
42
43 uint64_t prometheus_id = 0;
44
45 struct rist_callback_object {
46 int sd;
47 struct evsocket_ctx *evctx;
48 struct rist_udp_config *udp_config;
49 uint8_t recv[RIST_MAX_PACKET_SIZE + 100];
50 int out_sd[MAX_OUTPUT_COUNT];
51 struct rist_udp_config *output_udp_config[MAX_OUTPUT_COUNT];
52 };
53
54 #if HAVE_PROMETHEUS_SUPPORT
55 struct rist_prometheus_stats *prom_stats_ctx;
56 bool prometheus_multipoint = false;
57 bool prometheus_nocreated = false;
58 bool prometheus_httpd = false;
59 bool enable_prometheus = false;
60 char *prometheus_tags = NULL;
61 uint16_t prometheus_port = 9100;
62 char *prometheus_ip = NULL;
63 char *prometheus_unix_sock = NULL;
64 #endif
65
66 static struct option long_options[] = {
67 { "inputurl", required_argument, NULL, 'i' },
68 { "outputurl", required_argument, NULL, 'o' },
69 { "verbose-level", required_argument, NULL, 'v' },
70 { "remote-logging", required_argument, NULL, 'r' },
71 { "config", required_argument, NULL, 'c' },
72 { "help", no_argument, NULL, 'h' },
73 { "help-url", no_argument, NULL, 'u' },
74 #if HAVE_PROMETHEUS_SUPPORT
75 { "enable-metrics", no_argument, NULL, 'M' },
76 { "metrics-tags", required_argument, NULL, 1 },
77 { "metrics-multipoint",no_argument, (int*)&prometheus_multipoint, true },
78 { "metrics-nocreated",no_argument, (int*)&prometheus_nocreated, true },
79 #if HAVE_LIBMICROHTTPD
80 { "metrics-http", no_argument, (int*)&prometheus_httpd, true },
81 { "metrics-port", required_argument, NULL, 2 },
82 { "metrics-ip", required_argument, NULL, 3 },
83 #endif //HAVE_LIBMICROHTTPD
84 #if HAVE_SOCK_UN_H
85 { "metrics-unix", required_argument, NULL, 4 },
86 #endif //HAVE_SOCK_UN_H
87 #endif //HAVE_PROMETHEUS_SUPPORT
88 { 0, 0, 0, 0 },
89 };
90
91 const char help_str[] = "Usage: %s [OPTIONS] \nWhere OPTIONS are:\n"
92 " -i | --inputurl udp://... * | Input udp URL |\n"
93 " -o | --outputurl udp://... * | Comma separated list of output udp URLs |\n"
94 " -v | --verbose-level value | To disable logging: -1, log levels match syslog levels |\n"
95 " -r | --remote-logging IP:PORT | Send logs and stats to this IP:PORT using udp messages |\n"
96 " -c | --config name.yaml | YAML config file |\n"
97 #if HAVE_PROMETHEUS_SUPPORT
98 " -M | --enable-metrics | Enable OpenMetrics/Prometheus compatible metrics |\n"
99 " | --metrics-tags | Additional tags to add to the metrics |\n"
100 " | --metrics-multipoint | Metrics return multiple timestamped data points |\n"
101 " | --metrics-nocreated | Metrics skip the created metric for Prometheus compat |\n"
102 #if HAVE_LIBMICROHTTPD
103 " | --metrics-http | Start HTTP Server to expose metrics on |\n"
104 " | defaults to http://0.0.0.0:9100/metrics |\n"
105 " | --metrics-port | Port for metrics HTTP server to listen on |\n"
106 " | --metrics-ip | IP for metrics HTTP server to listen on |\n"
107 #endif //HAVE_LIBMICROHTTPD
108 #if HAVE_SOCK_UN_H
109 " | --metrics-unix | Unix socket to expose metrics on |\n"
110 #endif //HAVE_SOCK_UN_H
111 #endif //HAVE_PROMETHEUS_SUPPORT
112 " -h | --help | Show this help |\n"
113 " -u | --help-url | Show all the possible url options |\n"
114 " * == mandatory value \n"
115 "Default values: %s \n"
116 " --verbose-level 6 \n";
117
118 static void input_udp_recv(struct evsocket_ctx *evctx, int fd, short revents, void *arg)
119 {
120 struct rist_callback_object *callback_object = (void *) arg;
121 RIST_MARK_UNUSED(evctx);
122 RIST_MARK_UNUSED(revents);
123 RIST_MARK_UNUSED(fd);
124
125 ssize_t recv_bufsize = -1;
126 struct sockaddr_in addr4 = {0};
127 struct sockaddr_in6 addr6 = {0};
128 struct sockaddr *addr;
129 uint8_t *recv_buf = callback_object->recv;
130 socklen_t addrlen = 0;
131 RIST_MARK_UNUSED(addr);
132
133 uint16_t address_family = (uint16_t)callback_object->udp_config->address_family;
134 if (address_family == AF_INET6) {
135 addrlen = sizeof(struct sockaddr_in6);
136 recv_bufsize = udpsocket_recvfrom(callback_object->sd, recv_buf, RIST_MAX_PACKET_SIZE, MSG_DONTWAIT, (struct sockaddr *) &addr6, &addrlen);
137 addr = (struct sockaddr *) &addr6;
138 } else {
139 addrlen = sizeof(struct sockaddr_in);
140 recv_bufsize = udpsocket_recvfrom(callback_object->sd, recv_buf, RIST_MAX_PACKET_SIZE, MSG_DONTWAIT, (struct sockaddr *) &addr4, &addrlen);
141 addr = (struct sockaddr *) &addr4;
142 }
143
144 if (recv_bufsize > 0) {
145 int i = 0;
146 for (i = 0; i < MAX_OUTPUT_COUNT; i++) {
147 if (!callback_object->output_udp_config[i])
148 continue;
149 struct rist_udp_config *udp_config = callback_object->output_udp_config[i];
150 RIST_MARK_UNUSED(udp_config);
151 if (callback_object->out_sd[i] > 0) {
152 int ret = udpsocket_send_nonblocking(callback_object->out_sd[i], recv_buf, recv_bufsize);
153 if (ret <= 0 && errno != ECONNREFUSED)
154 rist_log(&logging_settings, RIST_LOG_ERROR, "Error %d sending udp packet to socket %d\n", errno, callback_object->out_sd[i]);
155 }
156 }
157 }
158 }
159
160 static void input_udp_sockerr(struct evsocket_ctx *evctx, int fd, short revents, void *arg)
161 {
162 struct rist_callback_object *callback_object = (void *) arg;
163 RIST_MARK_UNUSED(evctx);
164 RIST_MARK_UNUSED(revents);
165 RIST_MARK_UNUSED(fd);
166 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);
167 }
168
169 static void usage(char *cmd)
170 {
171 rist_log(&logging_settings, RIST_LOG_INFO, "%s\n%s version %s libRIST library: %s API version: %s\n", cmd, help_str, UDP2UDP_VERSION, librist_version(), librist_api_version());
172 exit(1);
173 }
174
175 static void intHandler(int signal)
176 {
177 rist_log(&logging_settings, RIST_LOG_INFO, "Signal %d received\n", signal);
178 signalReceived = signal;
179 }
180
181 static PTHREAD_START_FUNC(input_loop, arg)
182 {
183 struct rist_callback_object *callback_object = (void *) arg;
184 // This is my main loop
185 while (!signalReceived) {
186 // UDP receiver. Infinite wait, 100 socket events
187 evsocket_loop_single(callback_object->evctx, 5, 100);
188 }
189 return 0;
190 }
191
192 int main(int argc, char *argv[])
193 {
194 int c;
195 int option_index;
196 struct rist_callback_object callback_object = { 0 };
197 struct evsocket_event *event;
198 char *inputurl = NULL;
199 char *outputurl = NULL;
200 enum rist_log_level loglevel = RIST_LOG_INFO;
201 char *remote_log_address = NULL;
202 bool thread_started = {false};
203 pthread_t thread_main_loop = { 0 };
204 rist_tools_config_object *yaml_config = NULL;
205 char *yamlfile = NULL;
206 unsigned i = 0;
207
208 event = NULL;
209
210 #ifdef _WIN32
211 #define STDERR_FILENO 2
212 signal(SIGINT, intHandler);
213 signal(SIGTERM, intHandler);
214 signal(SIGABRT, intHandler);
215 #else
216 struct sigaction act = { {0} };
217 act.sa_handler = intHandler;
218 sigaction(SIGINT, &act, NULL);
219 #endif
220
221 // Default log settings
222 struct rist_logging_settings *log_ptr = &logging_settings;
223 if (rist_logging_set(&log_ptr, loglevel, NULL, NULL, NULL,
224 stderr) != 0) {
225 fprintf(stderr, "Failed to setup default logging!\n");
226 exit(1);
227 }
228
229 rist_log(&logging_settings, RIST_LOG_INFO, "Starting udp2udp version: %s libRIST library: %s API version: %s\n", UDP2UDP_VERSION, librist_version(), librist_api_version());
230
231 while ((c = getopt_long(argc, argv, "r:i:o:c:v:hunM", long_options, &option_index)) != -1) {
232 switch (c) {
233 case 'i':
234 inputurl = strdup(optarg);
235 break;
236 case 'o':
237 outputurl = strdup(optarg);
238 break;
239 case 'v':
240 loglevel = atoi(optarg);
241 break;
242 case 'r':
243 remote_log_address = strdup(optarg);
244 break;
245 case 'u':
246 rist_log(&logging_settings, RIST_LOG_INFO, "%s", help_urlstr);
247 exit(1);
248 break;
249 #if HAVE_PROMETHEUS_SUPPORT
250 case 'M':
251 enable_prometheus = true;
252 break;
253 case 0:
254 //long option, value get's set directly
255 break;
256 case 1:
257 //long option metric tags
258 prometheus_tags = strdup(optarg);
259 break;
260 case 2:
261 //prometheus port long opt
262 prometheus_httpd = true;
263 prometheus_port = atoi(optarg);
264 break;
265 case 3:
266 //prometheus IP long opt
267 prometheus_httpd = true;
268 prometheus_ip = strdup(optarg);
269 break;
270 case 4:
271 //prometheus unix socket long opt
272 enable_prometheus = true;
273 prometheus_unix_sock = strdup(optarg);
274 break;
275 #endif
276 case 'c':
277 yamlfile = strdup(optarg);
278 yaml_config = parse_yaml(yamlfile);
279 free(yamlfile);
280 if (!yaml_config){
281 fprintf(stderr,"Could not import yaml file %s\n",optarg);
282 cleanup_tools_config(yaml_config);
283 exit(1);
284 }
285 if (yaml_config->input_url)
286 inputurl = strdup(yaml_config->input_url);
287 if (yaml_config->output_url)
288 outputurl = strdup(yaml_config->output_url);
289 loglevel = yaml_config->verbose_level;
290 if (yaml_config->remote_log_address)
291 remote_log_address = strdup(yaml_config->remote_log_address);
292 #if HAVE_PROMETHEUS_SUPPORT
293 enable_prometheus = yaml_config->enable_metrics;
294 if (yaml_config->metrics_tags)
295 prometheus_tags = strdup(yaml_config->metrics_tags);
296 prometheus_multipoint = yaml_config->metrics_multipoint;
297 prometheus_nocreated = yaml_config->metrics_nocreated;
298 #if HAVE_LIBMICROHTTPD
299 prometheus_httpd = yaml_config->metrics_http;
300 prometheus_port = yaml_config->metrics_port;
301 if (yaml_config->metrics_ip)
302 prometheus_ip = strdup(yaml_config->metrics_ip);
303 #endif
304 #if HAVE_SOCK_UN_H
305 if (yaml_config->metrics_unix)
306 prometheus_unix_sock = strdup(yaml_config->metrics_unix);
307 #endif
308 #endif
309 cleanup_tools_config(yaml_config);
310 break;
311 case 'h':
312 /* Fall through */
313 default:
314 usage(argv[0]);
315 break;
316 }
317 }
318
319 if (inputurl == NULL || outputurl == NULL) {
320 usage(argv[0]);
321 }
322
323 if (argc < 2) {
324 usage(argv[0]);
325 }
326
327 // Update log settings with custom loglevel and remote address if necessary
328 if (rist_logging_set(&log_ptr, loglevel, NULL, NULL, remote_log_address, stderr) != 0) {
329 fprintf(stderr,"Failed to setup logging\n");
330 exit(1);
331 }
332
333 #if HAVE_PROMETHEUS_SUPPORT
334 if (enable_prometheus || prometheus_httpd) {
335 rist_log(log_ptr, RIST_LOG_INFO, "Enabling Metrics output\n");
336 struct prometheus_httpd_options httpd_opt;
337 httpd_opt.enabled = prometheus_httpd;
338 httpd_opt.port = prometheus_port;
339 httpd_opt.ip = prometheus_ip;
340 prom_stats_ctx = rist_setup_prometheus_stats(log_ptr, prometheus_tags,prometheus_multipoint, prometheus_nocreated, &httpd_opt, prometheus_unix_sock);
341 if (prom_stats_ctx == NULL) {
342 rist_log(log_ptr, RIST_LOG_ERROR, "Failed to setup Metrics output\n");
343 exit(1);
344 }
345 /* udp2udp is a plain UDP relay; it doesn't run any RIST
346 * sender or receiver and therefore never feeds the Prometheus
347 * exporter. Make that clear so users don't expect rist_*
348 * series to show up at the scrape endpoint. */
349 rist_log(log_ptr, RIST_LOG_WARN,
350 "udp2udp does not produce RIST traffic, so no rist_* metrics will be exported. "
351 "Use ristsender/ristreceiver for end-to-end RIST stats.\n");
352 }
353 #endif
354
355 for (i = 0; i < MAX_OUTPUT_COUNT; i++)
356 {
357 callback_object.out_sd[i] = 0;
358 callback_object.output_udp_config[i] = NULL;
359 }
360
361 struct evsocket_ctx *evctx = NULL;
362 bool atleast_one_socket_opened = false;
363 struct rist_udp_config *udp_config = NULL;
364
365 // Setup udp input
366 if(!evctx)
367 evctx = evsocket_create();
368 char hostname[200] = {0};
369 int inputlisten;
370 uint16_t inputport;
371 // First parse extra parameters (?miface=lo) and separate the address
372 // We are using the rist_parse_address function to create a config object that does not really
373 // belong to the udp output. We do this only to avoid writing another parser for the two url
374 // parameters available to the udp input/output url
375 if (rist_parse_udp_address2(inputurl, &udp_config)) {
376 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse inputurl %s\n", inputurl);
377 goto next;
378 }
379 // Now parse host and port
380 if (udpsocket_parse_url((void *)udp_config->address, hostname, 200, &inputport, &inputlisten) || !inputport || strlen(hostname) == 0) {
381 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse input url %s\n", inputurl);
382 goto next;
383 }
384 rist_log(&logging_settings, RIST_LOG_INFO, "URL parsed successfully: Host %s, Port %d\n", (char *) hostname, inputport);
385 // Open and/or bind ip and port
386 callback_object.sd = udpsocket_open_bind(hostname, inputport, udp_config->miface);
387 if (callback_object.sd < 0) {
388 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not bind to: Host %s, Port %d, miface %s.\n",
389 (char *) hostname, inputport, udp_config->miface);
390 goto next;
391 } else {
392 udpsocket_set_nonblocking(callback_object.sd);
393 rist_log(&logging_settings, RIST_LOG_INFO, "Input socket is open and bound %s:%d\n", (char *) hostname, inputport);
394 atleast_one_socket_opened = true;
395 }
396 // Increase default OS udp receive buffer size
397 if (udpsocket_set_optimal_buffer_size(callback_object.sd)) {
398 rist_log(&logging_settings, RIST_LOG_WARN, "Unable to set the socket receive buffer size to %d Bytes. %s\n",
399 UDPSOCKET_SOCK_BUFSIZE, strerror(errno));
400 } else {
401 uint32_t current_recvbuf = udpsocket_get_buffer_size(callback_object.sd);
402 rist_log(&logging_settings, RIST_LOG_INFO, "Configured the starting socket receive buffer size to %d Bytes.\n",
403 current_recvbuf);
404 }
405 callback_object.udp_config = udp_config;
406 udp_config = NULL;
407 callback_object.evctx = evctx;
408 event = evsocket_addevent(callback_object.evctx, callback_object.sd, EVSOCKET_EV_READ, input_udp_recv, input_udp_sockerr,
409 (void *)&callback_object);
410
411 if (!atleast_one_socket_opened)
412 {
413 rist_log(&logging_settings, RIST_LOG_INFO, "Input socket could not be oppened\n");
414 goto shutdown;
415 }
416
417 /* Setup udp output */
418 atleast_one_socket_opened = false;
419 char *saveptr2;
420 char *outputtoken = strtok_r(outputurl, ",", &saveptr2);
421 for (i = 0; i < MAX_OUTPUT_COUNT; i++) {
422
423 if (!outputtoken)
424 break;
425 // First parse extra parameters
426 struct rist_udp_config *output_udp_config = NULL;
427 if (rist_parse_udp_address2(outputtoken, &output_udp_config)) {
428 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse outputurl %s\n", outputtoken);
429 goto next;
430 }
431 // Now parse the host and port
432 memset(&hostname, 0, sizeof(hostname));
433
434 int outputlisten;
435 uint16_t outputport;
436 if (udpsocket_parse_url((void *)output_udp_config->address, hostname, 200, &outputport, &outputlisten) || !outputport || strlen(hostname) == 0) {
437 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse output url %s\n", outputtoken);
438 goto next;
439 }
440 rist_log(&logging_settings, RIST_LOG_INFO, "URL parsed successfully: Host %s, Port %d\n", (char *) hostname, outputport);
441
442 // Open the output socket
443 callback_object.out_sd[i] = udpsocket_open_connect(hostname, outputport, output_udp_config->miface);
444 if (callback_object.out_sd[i] < 0) {
445 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not connect to: Host %s, Port %d\n", (char *) hostname, outputport);
446 goto next;
447 } else {
448 rist_log(&logging_settings, RIST_LOG_INFO, "Output socket is open and bound %s:%d\n", (char *) hostname, outputport);
449 atleast_one_socket_opened = true;
450 }
451 // Increase default OS udp send buffer size
452 if (udpsocket_set_optimal_buffer_send_size(callback_object.out_sd[i])) {
453 rist_log(&logging_settings, RIST_LOG_WARN, "Unable to set the socket send buffer size to %d Bytes. %s\n",
454 UDPSOCKET_SOCK_BUFSIZE, strerror(errno));
455 } else {
456 uint32_t current_sendbuf = udpsocket_get_buffer_send_size(callback_object.out_sd[i]);
457 rist_log(&logging_settings, RIST_LOG_INFO, "Configured the starting socket send buffer size to %d Bytes.\n",
458 current_sendbuf);
459 }
460 callback_object.output_udp_config[i] = output_udp_config;
461
462 next:
463 outputtoken = strtok_r(NULL, ",", &saveptr2);
464 }
465
466 if (!atleast_one_socket_opened) {
467 rist_log(&logging_settings, RIST_LOG_INFO, "Output sockets could not be oppened\n");
468 goto shutdown;
469 }
470
471 // Now start main listener thread
472 if (evctx && pthread_create(&thread_main_loop, NULL, input_loop, (void *)&callback_object) != 0)
473 {
474 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not start udp receiver thread\n");
475 goto shutdown;
476 }
477 thread_started = true;
478
479 #ifdef _WIN32
480 system("pause");
481 #else
482 pause();
483 #endif
484
485 shutdown:
486 // Cleanup for input
487 if (udp_config) {
488 rist_udp_config_free2(&udp_config);
489 }
490 // Remove input socket event
491 if (event)
492 evsocket_delevent(callback_object.evctx, event);
493 // Free udp_config object
494 if ((void *)callback_object.udp_config)
495 rist_udp_config_free2(&callback_object.udp_config);
496
497 // Cleanup for output
498 for (i = 0; i < MAX_OUTPUT_COUNT; i++) {
499 // Free output_udp_config object
500 if ((void *)callback_object.output_udp_config[i])
501 rist_udp_config_free2(&callback_object.output_udp_config[i]);
502 }
503
504 // Wait for main input thread
505 if (thread_started)
506 pthread_join(thread_main_loop, NULL);
507
508 rist_logging_unset_global();
509 if (inputurl)
510 free(inputurl);
511 if (outputurl)
512 free(outputurl);
513
514 #if HAVE_PROMETHEUS_SUPPORT
515 rist_prometheus_stats_destroy(prom_stats_ctx);
516 free(prometheus_ip);
517 free(prometheus_tags);
518 free(prometheus_unix_sock);
519 #endif
520 return 0;
521 }