Debian Codegraph @

tools/ristreceiver.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 "headers.h"
11 #include "librist/version.h"
12 #include "config.h"
13 #if HAVE_SRP_SUPPORT
14 #include "librist/librist_srp.h"
15 #include "srp_shared.h"
16 #endif
17 #include "vcs_version.h"
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <sys/types.h>
23 #include "getopt-shim.h"
24 #include "pthread-shim.h"
25 #include <stdbool.h>
26 #include <signal.h>
27 #include "risturlhelp.h"
28 #define __STDC_FORMAT_MACROS
29 #include <inttypes.h>
30 #include "oob_shared.h"
31 #include "prometheus-exporter.h"
32 #include "rist-private.h"
33 #include "endian-shim.h"
34 #ifndef _WIN32
35 #include <sys/ioctl.h>
36 #endif
37 #include "yamlparse.h"
38 #include "string-shim.h"
39
40 #define RISTRECEIVER_VERSION "30"
41
42 #define MAX_INPUT_COUNT 20
43 #define MAX_OUTPUT_COUNT 20
44 #define ReadEnd 0
45 #define WriteEnd 1
46 #define DATA_READ_MODE_CALLBACK 0
47 #define DATA_READ_MODE_POLL 1
48 #define DATA_READ_MODE_API 2
49
50 pthread_mutex_t signal_lock;
51 static int signalReceived = 0;
52 static struct rist_logging_settings logging_settings = LOGGING_SETTINGS_INITIALIZER;
53 enum rist_profile profile = RIST_DEFAULT_PROFILE;
54 static int peer_connected_count = 0;
55 static int noflow_counter = 0;
56
57 #if HAVE_PROMETHEUS_SUPPORT
58 struct rist_prometheus_stats *prom_stats_ctx;
59 int prometheus_multipoint = 0;
60 int prometheus_nocreated = 0;
61 int prometheus_httpd = 0;
62 bool enable_prometheus = false;
63 char *prometheus_tags = NULL;
64 uint16_t prometheus_port = 9100;
65 char *prometheus_ip = NULL;
66 char *prometheus_unix_sock = NULL;
67 #endif
68
69 static struct option long_options[] = {
70 { "inputurl", required_argument, NULL, 'i' },
71 { "outputurl", required_argument, NULL, 'o' },
72 { "buffer", required_argument, NULL, 'b' },
73 { "secret", required_argument, NULL, 's' },
74 { "encryption-type", required_argument, NULL, 'e' },
75 { "profile", required_argument, NULL, 'p' },
76 { "tun", required_argument, NULL, 't' },
77 { "tun-mode", required_argument, NULL, 'm' },
78 { "stats", required_argument, NULL, 'S' },
79 { "verbose-level", required_argument, NULL, 'v' },
80 { "remote-logging", required_argument, NULL, 'r' },
81 #if HAVE_SRP_SUPPORT
82 { "srpfile", required_argument, NULL, 'F' },
83 #endif
84 { "config", required_argument, NULL, 'c' },
85 { "session-timeout-exit", no_argument, NULL, 'x' },
86 { "cbr-output", required_argument, NULL, 5 },
87 { "help", no_argument, NULL, 'h' },
88 { "help-url", no_argument, NULL, 'u' },
89 #if HAVE_PROMETHEUS_SUPPORT
90 { "enable-metrics", no_argument, NULL, 'M' },
91 { "metrics-tags", required_argument, NULL, 1 },
92 { "metrics-multipoint",no_argument, &prometheus_multipoint, 1 },
93 { "metrics-nocreated",no_argument, &prometheus_nocreated, 1 },
94 #if HAVE_LIBMICROHTTPD
95 { "metrics-http", no_argument, &prometheus_httpd, 1 },
96 { "metrics-port", required_argument, NULL, 2 },
97 { "metrics-ip", required_argument, NULL, 3 },
98 #endif //HAVE_LIBMICROHTTPD
99 #if HAVE_SOCK_UN_H
100 { "metrics-unix", required_argument, NULL, 4 },
101 #endif //HAVE_SOCK_UN_H
102 #endif //HAVE_PROMETHEUS_SUPPORT
103 { 0, 0, 0, 0 },
104 };
105
106 const char help_str[] = "Usage: %s [OPTIONS] \nWhere OPTIONS are:\n"
107 " -i | --inputurl rist://... * | Comma separated list of input rist URLs |\n"
108 " -o | --outputurl udp://... or rtp://... * | Comma separated list of output udp or rtp URLs |\n"
109 " | --cbr-output 0|1 | Space the output at the stream rate (CBR consumers) |\n"
110 " | Use tun://@ to write udp data to a tun device defined |\n"
111 " | using the -t option |\n"
112 " -b | --buffer value | Default buffer size for packet retransmissions |\n"
113 " -s | --secret PWD | Default pre-shared encryption secret |\n"
114 " -e | --encryption-type TYPE | Default Encryption type (0, 128 = AES-128, 256 = AES-256)|\n"
115 " -p | --profile number | Rist profile (0 = simple, 1 = main, 2 = advanced) |\n"
116 " -S | --statsinterval value (ms) | Interval at which stats get printed, 0 to disable |\n"
117 " -c | --config name.yaml | YAML config file |\n"
118 " -v | --verbose-level value | To disable logging: -1, log levels match syslog levels |\n"
119 " -r | --remote-logging IP:PORT | Send logs and stats to this IP:PORT using udp messages |\n"
120 #if HAVE_SRP_SUPPORT
121 " -F | --srpfile filepath | When in listening mode, use this file to hold the list |\n"
122 " | of usernames and passwords to validate against. Use the |\n"
123 " | ristsrppasswd tool to create the line entries. |\n"
124 #endif
125 " -t | --tun name | Create a tun device and use it for data communications |\n"
126 " -m | --tun-mode number | Data management on the tun interface: |\n"
127 " | 0 = all tun data is accepted into or out of oob channel |\n"
128 " | 1 = only non udp data is accepted (default) |\n"
129 " | 2 = no data goes into or out of oob channel |\n"
130 #if HAVE_PROMETHEUS_SUPPORT
131 " -M | --enable-metrics | Enable OpenMetrics/Prometheus compatible metrics |\n"
132 " | --metrics-tags | Additional tags to add to the metrics |\n"
133 " | --metrics-multipoint | Metrics return multiple timestamped data points |\n"
134 " | --metrics-nocreated | Metrics skip the created metric for Prometheus compat |\n"
135 #if HAVE_LIBMICROHTTPD
136 " | --metrics-http | Start HTTP Server to expose metrics on |\n"
137 " | defaults to http://0.0.0.0:9100/metrics |\n"
138 " | --metrics-port | Port for metrics HTTP server to listen on |\n"
139 " | --metrics-ip | IP for metrics HTTP server to listen on |\n"
140 #endif //HAVE_LIBMICROHTTPD
141 #if HAVE_SOCK_UN_H
142 " | --metrics-unix | Unix socket to expose metrics on |\n"
143 #endif //HAVE_SOCK_UN_H
144 #endif //HAVE_PROMETHEUS_SUPPORT
145 " -f | --noflow-timeout-exit value (ms) | Exit on no flow after Timeout |\n"
146 " -h | --help | Show this help |\n"
147 " -u | --help-url | Show all the possible url options |\n"
148 " * == mandatory value \n"
149 "Default values: %s \n"
150 " --profile 1 \\\n"
151 " --statsinterval 1000 \\\n"
152 " --verbose-level 6 \n";
153
154 static void usage(char *cmd)
155 {
156 rist_log(&logging_settings, RIST_LOG_INFO, "%s\n%s version %s libRIST library: %s API version: %s\n", cmd, help_str, RISTRECEIVER_VERSION, librist_version(), librist_api_version());
157 exit(1);
158 }
159
160 struct rist_callback_object {
161 int mpeg[MAX_OUTPUT_COUNT];
162 struct rist_udp_config *udp_config[MAX_OUTPUT_COUNT];
163 uint16_t i_seqnum[MAX_OUTPUT_COUNT];
164 struct rist_ctx *receiver_ctx;
165 int tun;
166 int tun_mode;
167 int noflow_timeout_exit;
168 };
169
170 static inline void risttools_rtp_set_hdr(uint8_t *p_rtp, uint8_t i_type, uint16_t i_seqnum, uint32_t i_timestamp, uint32_t i_ssrc)
171 {
172 p_rtp[0] = 0x80;
173 p_rtp[1] = i_type & 0x7f;
174 p_rtp[2] = i_seqnum >> 8;
175 p_rtp[3] = i_seqnum & 0xff;
176 p_rtp[4] = (i_timestamp >> 24) & 0xff;
177 p_rtp[5] = (i_timestamp >> 16) & 0xff;
178 p_rtp[6] = (i_timestamp >> 8) & 0xff;
179 p_rtp[7] = i_timestamp & 0xff;
180 p_rtp[8] = (i_ssrc >> 24) & 0xff;
181 p_rtp[9] = (i_ssrc >> 16) & 0xff;
182 p_rtp[10] = (i_ssrc >> 8) & 0xff;
183 p_rtp[11] = i_ssrc & 0xff;
184 }
185
186 static uint32_t risttools_convertNTPtoRTP(uint64_t i_ntp)
187 {
188 i_ntp *= 90000;
189 i_ntp = i_ntp >> 32;
190 return (uint32_t)i_ntp;
191 }
192
193 static void connection_status_callback(void *arg, struct rist_peer *peer, enum rist_connection_status peer_connection_status)
194 {
195 (void)arg;
196 if (peer_connection_status == RIST_CONNECTION_ESTABLISHED || peer_connection_status == RIST_CLIENT_CONNECTED) {
197 peer_connected_count++;
198 }
199 else {
200 peer_connected_count--;
201 }
202 rist_log(&logging_settings, RIST_LOG_INFO,"Connection Status changed for Peer %"PRIu64", new status is %d, peer connected count is %d\n",
203 peer, peer_connection_status, peer_connected_count);
204 }
205
206 static int cb_recv(void *arg, struct rist_data_block *b)
207 {
208 struct rist_callback_object *callback_object = (void *) arg;
209 int found = 0;
210 int i = 0;
211 for (i = 0; i < MAX_OUTPUT_COUNT; i++) {
212 if (!callback_object->udp_config[i])
213 continue;
214 struct rist_udp_config *udp_config = callback_object->udp_config[i];
215 bool found_it = false;
216 int mux_mode = 0;
217 if (udp_config->version >= 1)
218 mux_mode = udp_config->multiplex_mode;
219 // The stream-id on the udp url gets translated into the virtual destination port of the GRE tunnel
220 // and we match on that. The other two muxing modes are not spec compliant and are only
221 // guaranteed to work from librist to librist
222 if (profile == RIST_PROFILE_SIMPLE || udp_config->stream_id == 0 ||
223 (mux_mode == LIBRIST_MULTIPLEX_MODE_VIRT_DESTINATION_PORT && udp_config->stream_id == b->virt_dst_port) ||
224 (mux_mode == LIBRIST_MULTIPLEX_MODE_VIRT_SOURCE_PORT && udp_config->stream_id == b->virt_src_port) ||
225 (mux_mode == LIBRIST_MULTIPLEX_MODE_IPV4))
226 {
227 // Normal manual match
228 found_it = true;
229 }
230 else if (mux_mode == LIBRIST_MULTIPLEX_MODE_AUTO)
231 {
232 // Auto-detect (librist to librist)
233 if (b->virt_src_port == UINT16_MAX) {
234 mux_mode = LIBRIST_MULTIPLEX_MODE_IPV4;
235 found_it = true;
236 }
237 if (b->virt_src_port < 32768 && udp_config->stream_id == b->virt_src_port) {
238 mux_mode = LIBRIST_MULTIPLEX_MODE_VIRT_SOURCE_PORT;
239 found_it = true;
240 }
241 else if (b->virt_src_port >= 32768 && udp_config->stream_id == b->virt_dst_port) {
242 mux_mode = LIBRIST_MULTIPLEX_MODE_VIRT_DESTINATION_PORT;
243 found_it = true;
244 }
245 }
246
247 if (found_it) {
248 if (callback_object->mpeg[i] > 0) {
249 uint8_t *payload = NULL;
250 size_t payload_len = 0;
251 if (udp_config->rtp) {
252 payload = malloc(12 + b->payload_len);
253 payload_len = 12 + b->payload_len;
254 // Transfer payload
255 memcpy(payload + 12, b->payload, b->payload_len);
256 // Set RTP header (mpegts)
257 uint16_t i_seqnum = udp_config->rtp_sequence ? (uint16_t)b->seq : callback_object->i_seqnum[i]++;
258 uint32_t i_timestamp = risttools_convertNTPtoRTP(b->ts_ntp);
259 uint8_t ptype = 0x21;
260 if (udp_config->rtp_ptype != 0)
261 ptype = udp_config->rtp_ptype;
262 risttools_rtp_set_hdr(payload, ptype, i_seqnum, i_timestamp, b->flow_id);
263 }
264 else if (mux_mode == LIBRIST_MULTIPLEX_MODE_IPV4) {
265 // TODO: filtering based on ip header?
266 // with an input string for destination ip and port
267 // for now, forward it all
268 // use output_udp_config->mux_filter
269 size_t ipheader_bytes = sizeof(struct ipheader) + sizeof(struct udpheader);
270 if (b->payload_len < ipheader_bytes) {
271 rist_log(&logging_settings, RIST_LOG_ERROR,
272 "Short ipv4-mux payload (%zu < %zu), dropping\n",
273 b->payload_len, ipheader_bytes);
274 continue;
275 }
276 payload = (uint8_t *)b->payload;
277 payload += ipheader_bytes;
278 payload_len = b->payload_len - ipheader_bytes;
279 }
280 else {
281 payload = (uint8_t *)b->payload;
282 payload_len = b->payload_len;
283 }
284 int ret = udpsocket_send(callback_object->mpeg[i], payload, payload_len);
285 if (udp_config->rtp)
286 free(payload);
287 if (ret <= 0 && errno != ECONNREFUSED)
288 rist_log(&logging_settings, RIST_LOG_ERROR, "Error %d sending udp packet to socket %d\n", errno, callback_object->mpeg[i]);
289 found = 1;
290 }
291 }
292 }
293
294 if (b->virt_src_port == 1 && found == 0)
295 {
296 // This is a tun mux
297 if (callback_object->tun) {
298 if (rist_tun_write(callback_object->tun, b->payload, b->payload_len) < 0) {
299 rist_log(&logging_settings, RIST_LOG_ERROR, "Error %d writing %d rist bytes to output tun\n", errno, b->payload_len);
300 }
301 }
302 rist_receiver_data_block_free2(&b);
303 return 0;
304 }
305
306 if (found == 0)
307 {
308 rist_log(&logging_settings, RIST_LOG_ERROR, "Destination port mismatch, no output found for %d\n", b->virt_dst_port);
309 rist_receiver_data_block_free2(&b);
310 return -1;
311 }
312 rist_receiver_data_block_free2(&b);
313 return 0;
314 }
315
316 static void intHandler(int signal) {
317 pthread_mutex_lock(&signal_lock);
318 signalReceived = signal;
319 pthread_mutex_unlock(&signal_lock);
320 }
321
322 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)
323 {
324 struct rist_callback_object *callback_object = (void *) arg;
325 uint16_t buffer[250];
326 char message[200];
327 int message_len = snprintf(message, 200, "auth,%s:%d,%s:%d", connecting_ip, connecting_port, local_ip, local_port);
328 // To be compliant with the spec, the message must have an ipv4 header
329 int ret = oob_build_api_payload(buffer, (char *)connecting_ip, (char *)local_ip, message, message_len);
330 rist_log(&logging_settings, RIST_LOG_INFO,"Peer has been authenticated, sending oob/api message: %s\n", message);
331 struct rist_oob_block oob_block;
332 oob_block.peer = peer;
333 oob_block.payload = buffer;
334 oob_block.payload_len = ret;
335 rist_oob_write(callback_object->receiver_ctx, &oob_block);
336 return 0;
337 }
338
339 static int cb_auth_disconnect(void *arg, struct rist_peer *peer)
340 {
341 (void)peer;
342 struct rist_callback_object *callback_object = (void *) arg;
343 (void)callback_object;
344 return 0;
345 }
346
347 static int rist_validate_tun_data(uint8_t *buffer, ssize_t buffer_len)
348 {
349 struct ipheader *ip = (struct ipheader *) buffer;
350 int protocol = 0;
351 ssize_t payload_len = 0;
352 // Double check the validity of the packet and get the protocol number
353 if (RIST_IPH_GET_VER(ip->iph_verlen) == 4) {
354 protocol = (int) ip->iph_protocol;
355 payload_len = (ssize_t)be16toh(ip->iph_len);
356 if (payload_len != buffer_len) {
357 rist_log(&logging_settings, RIST_LOG_INFO, "Malformed ipv4 packet %zd != %zd\n",
358 payload_len, buffer_len);
359 return -1;
360 }
361 }
362 else if (RIST_IPH_GET_VER(ip->iph_verlen) == 6) {
363 // TODO: how do I get the protocol?
364 // For now, send all IPv6 over OOB channel
365 }
366 else {
367 rist_log(&logging_settings, RIST_LOG_INFO, "Unknown ipv? payload %d\n",
368 RIST_IPH_GET_VER(ip->iph_verlen));
369 return -1;
370 }
371 return protocol;
372 }
373
374 static int cb_recv_oob(void *arg, const struct rist_oob_block *oob_block)
375 {
376 struct rist_callback_object *callback_object = (void *) arg;
377 int message_len = 0;
378 char *message = oob_process_api_message((int)oob_block->payload_len, (char *)oob_block->payload, &message_len);
379 if (message) {
380 rist_log(&logging_settings, RIST_LOG_INFO,"Out-of-band api data received: %.*s\n", message_len, message);
381 }
382 else if (callback_object->tun)
383 {
384 // Process non-api based data
385 int protocol = rist_validate_tun_data((uint8_t *)oob_block->payload, oob_block->payload_len);
386 if (protocol >= 0)
387 {
388 if (callback_object->tun_mode == 0 ||
389 (callback_object->tun_mode == 1 && protocol != 17)) {
390 if (rist_tun_write(callback_object->tun, oob_block->payload, oob_block->payload_len) < 0) {
391 rist_log(&logging_settings, RIST_LOG_ERROR, "Error %d writing %d bytes to output tun\n", errno, oob_block->payload_len);
392 }
393 }
394 }
395 }
396 return 0;
397 }
398
399 struct ristreceiver_flow_cumulative_stats {
400 uint32_t flow_id;
401 uint64_t received;
402 uint64_t recovered;
403 uint64_t lost;
404 struct ristreceiver_flow_cumulative_stats *next;
405 };
406
407 struct ristreceiver_flow_cumulative_stats *stats_list;
408
409 static int session_timeout_callback(void *arg, uint32_t flow_id) {
410 struct rist_callback_object *callback_object = (void *) arg;
411 if (flow_id == 0 && callback_object->noflow_timeout_exit > 0)
412 {
413 // It is triggered once per second when there is no flow (startup for example)
414 noflow_counter++;
415 rist_log(&logging_settings, RIST_LOG_INFO, "No flow detected for %d ms, deadline is %d ms\n", noflow_counter * 1000, callback_object->noflow_timeout_exit);
416 if (1000*noflow_counter >= callback_object->noflow_timeout_exit)
417 {
418 rist_log(&logging_settings, RIST_LOG_INFO, "Timeout limit reached, exiting\n", noflow_counter);
419 exit(1);
420 }
421 }
422 return 0;
423 }
424
425 static int cb_stats(void *arg, const struct rist_stats *stats_container) {
426 rist_log(&logging_settings, RIST_LOG_INFO, "%s\n", stats_container->stats_json);
427 if (stats_container->stats_type == RIST_STATS_RECEIVER_FLOW)
428 {
429 struct ristreceiver_flow_cumulative_stats *stats = stats_list;
430 struct ristreceiver_flow_cumulative_stats **prev = &stats_list;
431 while (stats && stats->flow_id != stats_container->stats.receiver_flow.flow_id)
432 {
433 prev = &stats->next;
434 stats = stats->next;
435 }
436 if (!stats) {
437 stats = calloc(1, sizeof(*stats));
438 stats->flow_id = stats_container->stats.receiver_flow.flow_id;
439 *prev = stats;
440 }
441 stats->received += stats_container->stats.receiver_flow.received;
442 stats->lost += stats_container->stats.receiver_flow.lost;
443 stats->recovered += stats_container->stats.receiver_flow.recovered;
444 //Bit ugly, but linking in cJSON seems a bit excessive for this 4 variable JSON string
445 rist_log(&logging_settings, RIST_LOG_INFO,
446 "{\"flow_cumulative_stats\":{\"flow_id\":%"PRIu32",\"received\":%"PRIu64",\"recovered\":%"PRIu64",\"lost\":%"PRIu64"}}\n",
447 stats->flow_id, stats->received, stats->recovered, stats->lost);
448 #if HAVE_PROMETHEUS_SUPPORT
449 if (prom_stats_ctx != NULL)
450 rist_prometheus_parse_stats(prom_stats_ctx, stats_container, (uintptr_t)arg);
451 #else
452 (void)arg;
453 #endif
454 }
455 rist_stats_free(stats_container);
456 return 0;
457 }
458
459 static void rist_process_tun_data(struct rist_callback_object *callback_object, uint8_t *buffer, ssize_t buffer_len)
460 {
461 int protocol = rist_validate_tun_data(buffer, buffer_len);
462 if (protocol >=0) {
463 // Send data through oob channel
464 if (callback_object->tun_mode == 0 ||
465 (callback_object->tun_mode == 1 && protocol != 17)) {
466 struct rist_oob_block oob_block = { 0 };
467 oob_block.peer = NULL;
468 oob_block.payload = &buffer[0];
469 oob_block.payload_len = buffer_len;
470 if (rist_oob_write(callback_object->receiver_ctx, &oob_block) < 0)
471 rist_log(&logging_settings, RIST_LOG_INFO, "Error writing %d bytes to rist_oob_write\n", buffer_len);
472 }
473 }
474 }
475
476 static PTHREAD_START_FUNC(tun_loop, arg)
477 {
478 struct rist_callback_object *callback_object = (void *) arg;
479 while (!signalReceived) {
480 uint8_t buffer[RIST_MAX_PACKET_SIZE];
481 fd_set read_fds;
482 FD_ZERO(&read_fds);
483 FD_SET(callback_object->tun, &read_fds);
484 // Set timeout to 100 ms
485 struct timeval timeout;
486 timeout.tv_sec = 0;
487 timeout.tv_usec = 100000;
488 // Wait for input to become ready or until the time out;
489 if (select(FD_SETSIZE, &read_fds, NULL, NULL, &timeout) == 1)
490 {
491 ssize_t r = rist_tun_read(callback_object->tun, &buffer[0], RIST_MAX_PACKET_SIZE);
492 if (r > 0) {
493 rist_process_tun_data(callback_object, &buffer[0], r);
494 }
495 else
496 break;
497 }
498 }
499 return 0;
500 }
501
502 int main(int argc, char *argv[])
503 {
504 int option_index;
505 int c;
506 int data_read_mode = DATA_READ_MODE_CALLBACK;
507 const struct rist_peer_config *peer_input_config[MAX_INPUT_COUNT];
508 char *inputurl = NULL;
509 char *outputurl = NULL;
510 int cbr_output_cli = -1; /* -1 = not asked for; URLs may still ask */
511 char *oobtun = NULL;
512 char *shared_secret = NULL;
513 int buffer = 0;
514 int encryption_type = 0;
515 struct rist_callback_object callback_object = { 0 };
516 enum rist_log_level loglevel = RIST_LOG_INFO;
517 int statsinterval = 1000;
518 char *remote_log_address = NULL;
519 if (pthread_mutex_init(&signal_lock, NULL) != 0)
520 {
521 fprintf(stderr, "Could not initialize signal lock\n");
522 exit(1);
523 }
524 #ifndef _WIN32
525 /* Receiver pipe handle */
526 int receiver_pipe[2];
527 #endif
528 rist_tools_config_object *yaml_config = NULL;
529 char *yamlfile = NULL;
530
531 #if HAVE_SRP_SUPPORT
532 char *srpfile = NULL;
533 #endif
534
535 for (size_t i = 0; i < MAX_OUTPUT_COUNT; i++)
536 {
537 callback_object.mpeg[i] = 0;
538 callback_object.udp_config[i] = NULL;
539 }
540 #ifdef _WIN32
541 #define STDERR_FILENO 2
542 signal(SIGINT, intHandler);
543 signal(SIGTERM, intHandler);
544 signal(SIGABRT, intHandler);
545 #else
546 struct sigaction act = { {0} };
547 act.sa_handler = intHandler;
548 sigaction(SIGINT, &act, NULL);
549 #endif
550 // Default log settings
551 struct rist_logging_settings *log_ptr = &logging_settings;
552 if (rist_logging_set(&log_ptr, loglevel, NULL, NULL, NULL,
553 stderr) != 0) {
554 fprintf(stderr, "Failed to setup default logging!\n");
555 exit(1);
556 }
557
558 rist_log(&logging_settings, RIST_LOG_INFO, "Starting ristreceiver version: %s libRIST library: %s API version: %s\n", RISTRECEIVER_VERSION, librist_version(), librist_api_version());
559
560 while ((c = getopt_long(argc, argv, "r:i:o:b:s:e:t:m:p:S:v:F:c:h:x:uM", long_options, &option_index)) != -1) {
561 switch (c) {
562 case 'i':
563 inputurl = strdup(optarg);
564 break;
565 case 'o':
566 outputurl = strdup(optarg);
567 break;
568 case 'b':
569 buffer = atoi(optarg);
570 break;
571 case 's':
572 shared_secret = strdup(optarg);
573 break;
574 case 'e':
575 encryption_type = atoi(optarg);
576 break;
577 case 't':
578 oobtun = strdup(optarg);
579 break;
580 case 'm':
581 callback_object.tun_mode = atoi(optarg);
582 break;
583 case 'p':
584 profile = atoi(optarg);
585 break;
586 case 'S':
587 statsinterval = atoi(optarg);
588 break;
589 case 'v':
590 loglevel = atoi(optarg);
591 break;
592 case 'r':
593 remote_log_address = strdup(optarg);
594 break;
595 #if HAVE_SRP_SUPPORT
596 case 'F': {
597 FILE* f = fopen(optarg, "r");
598 if (!f) {
599 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not open srp file %s\n", optarg);
600 return 1;
601 }
602 srpfile = strdup(optarg);
603 }
604 break;
605 #endif
606 case 'u':
607 rist_log(&logging_settings, RIST_LOG_INFO, "%s", help_urlstr);
608 exit(1);
609 break;
610 #if HAVE_PROMETHEUS_SUPPORT
611 case 'M':
612 enable_prometheus = true;
613 break;
614 case 0:
615 //long option, value get's set directly
616 break;
617 case 1:
618 //long option metric tags
619 prometheus_tags = strdup(optarg);
620 break;
621 case 2:
622 //prometheus port long opt
623 prometheus_httpd = true;
624 prometheus_port = atoi(optarg);
625 break;
626 case 3:
627 //prometheus IP long opt
628 prometheus_httpd = true;
629 prometheus_ip = strdup(optarg);
630 break;
631 case 5:
632 if (strcmp(optarg, "0") && strcmp(optarg, "1")) {
633 rist_log(&logging_settings, RIST_LOG_ERROR,
634 "Invalid --cbr-output '%s' (expected 0 or 1)\n", optarg);
635 exit(1);
636 }
637 cbr_output_cli = atoi(optarg);
638 break;
639 case 4:
640 //prometheus unix socket long opt
641 enable_prometheus = true;
642 prometheus_unix_sock = strdup(optarg);
643 break;
644 #endif
645 case 'c':
646 yamlfile = strdup(optarg);
647 yaml_config = parse_yaml(yamlfile);
648 free(yamlfile);
649 if (!yaml_config){
650 fprintf(stderr,"Could not import yaml file %s\n",optarg);
651 cleanup_tools_config(yaml_config);
652 exit(1);
653 }
654 if (yaml_config->input_url)
655 inputurl = strdup(yaml_config->input_url);
656 if (yaml_config->output_url)
657 outputurl = strdup(yaml_config->output_url);
658 buffer = yaml_config->buffer;
659 if (yaml_config->secret)
660 shared_secret = strdup(yaml_config->secret);
661 encryption_type = yaml_config->encryption_type;
662 loglevel = yaml_config->verbose_level;
663 if (yaml_config->remote_log_address)
664 remote_log_address = strdup(yaml_config->remote_log_address);
665 profile = yaml_config->profile;
666 statsinterval = yaml_config->stats_interval;
667 // hardcoded mode for now
668 // callback_tun_object.tun_mode = 1; (yaml_config->tun_mode)
669 if (yaml_config->tunnel_interface)
670 oobtun = strdup(yaml_config->tunnel_interface);
671 #if HAVE_SRP_SUPPORT
672 if (yaml_config->srp_file)
673 srpfile = strdup(yaml_config->srp_file);
674 #endif
675 #if HAVE_PROMETHEUS_SUPPORT
676 enable_prometheus = yaml_config->enable_metrics;
677 if (yaml_config->metrics_tags)
678 prometheus_tags = strdup(yaml_config->metrics_tags);
679 prometheus_multipoint = yaml_config->metrics_multipoint;
680 prometheus_nocreated = yaml_config->metrics_nocreated;
681 #if HAVE_LIBMICROHTTPD
682 prometheus_httpd = yaml_config->metrics_http;
683 prometheus_port = yaml_config->metrics_port;
684 if (yaml_config->metrics_ip)
685 prometheus_ip = strdup(yaml_config->metrics_ip);
686 #endif
687 #if HAVE_SOCK_UN_H
688 if (yaml_config->metrics_unix)
689 prometheus_unix_sock = strdup(yaml_config->metrics_unix);
690 #endif
691 #endif
692 cleanup_tools_config(yaml_config);
693 break;
694 case 'x':
695 callback_object.noflow_timeout_exit = atoi(optarg);
696 break;
697 case 'h':
698 /* Fall through */
699 default:
700 usage(argv[0]);
701 break;
702 }
703 }
704
705 if (inputurl == NULL || outputurl == NULL) {
706 usage(argv[0]);
707 }
708
709 if (argc < 2) {
710 usage(argv[0]);
711 }
712
713 // Update log settings with custom loglevel and remote address if necessary
714 if (rist_logging_set(&log_ptr, loglevel, NULL, NULL, remote_log_address, stderr) != 0) {
715 fprintf(stderr,"Failed to setup logging!\n");
716 exit(1);
717 }
718
719 #if HAVE_PROMETHEUS_SUPPORT
720 if (enable_prometheus || prometheus_httpd) {
721 rist_log(log_ptr, RIST_LOG_INFO, "Enabling Metrics output\n");
722 struct prometheus_httpd_options httpd_opt;
723 httpd_opt.enabled = prometheus_httpd;
724 httpd_opt.port = prometheus_port;
725 httpd_opt.ip = prometheus_ip;
726 prom_stats_ctx = rist_setup_prometheus_stats(log_ptr, prometheus_tags,prometheus_multipoint, prometheus_nocreated, &httpd_opt, prometheus_unix_sock);
727 if (prom_stats_ctx == NULL) {
728 rist_log(log_ptr, RIST_LOG_ERROR, "Failed to setup Metrics output\n");
729 exit(1);
730 }
731 }
732 #endif
733 /* rist side */
734
735 struct rist_ctx *ctx;
736 if (rist_receiver_create(&ctx, profile, &logging_settings) != 0) {
737 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not create rist receiver context\n");
738 exit(1);
739 }
740
741 callback_object.receiver_ctx = ctx;
742
743 if (rist_auth_handler_set(ctx, cb_auth_connect, cb_auth_disconnect, (void *)&callback_object) != 0) {
744
745 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not init rist auth handler\n");
746 exit(1);
747 }
748
749 if (rist_connection_status_callback_set(ctx, connection_status_callback, NULL) == -1) {
750 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not initialize rist connection status callback\n");
751 exit(1);
752 }
753
754 if (profile != RIST_PROFILE_SIMPLE) {
755 if (rist_oob_callback_set(ctx, cb_recv_oob, (void *)&callback_object) == -1) {
756 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not add enable out-of-band data\n");
757 exit(1);
758 }
759 }
760
761 if (rist_stats_callback_set(ctx, statsinterval, cb_stats, (void*)0) == -1) {
762 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not enable stats callback\n");
763 exit(1);
764 }
765
766 double api_version = strtod(librist_api_version(), NULL);
767 if (api_version > 4.5)
768 {
769 if (rist_receiver_session_timeout_callback_set(ctx, session_timeout_callback, (void *)&callback_object) == -1) {
770 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not enable session timeout callback\n");
771 exit(1);
772 }
773 }
774
775 // Setup tun device
776 if (oobtun) {
777 char tun_ifname[64] = {0};
778 callback_object.tun = rist_tun_open(oobtun, tun_ifname, sizeof(tun_ifname));
779 if (callback_object.tun >= 0)
780 rist_tun_bring_up(tun_ifname);
781 if (callback_object.tun < 0) {
782 rist_log(&logging_settings, RIST_LOG_ERROR, "tun open error: %s\n", strerror(errno));
783 exit(1);
784 }
785 }
786
787 char *saveptr1;
788 char *inputtoken = strtok_r(inputurl, ",", &saveptr1);
789 for (size_t i = 0; i < MAX_INPUT_COUNT; i++) {
790 if (!inputtoken)
791 break;
792
793 // Rely on the library to parse the url
794 struct rist_peer_config *peer_config = NULL;
795 if (rist_parse_address2(inputtoken, &peer_config))
796 {
797 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse peer options for receiver #%d\n", (int)(i + 1));
798 exit(1);
799 }
800
801 /* Process overrides */
802 struct rist_peer_config *overrides_peer_config = peer_config;
803 if (shared_secret && peer_config->secret[0] == 0) {
804 strncpy(overrides_peer_config->secret, shared_secret, RIST_MAX_STRING_SHORT -1);
805 if (encryption_type)
806 overrides_peer_config->key_size = encryption_type;
807 else if (!overrides_peer_config->key_size)
808 overrides_peer_config->key_size = 128;
809 }
810 if (buffer) {
811 overrides_peer_config->recovery_length_min = buffer;
812 overrides_peer_config->recovery_length_max = buffer;
813 }
814
815 /* Print config */
816 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",
817 peer_config->recovery_maxbitrate, peer_config->recovery_length_min, peer_config->recovery_length_max,
818 peer_config->recovery_reorder_buffer, peer_config->recovery_rtt_min,peer_config->recovery_rtt_max,
819 peer_config->congestion_control_mode, peer_config->min_retries, peer_config->max_retries);
820
821 peer_input_config[i] = peer_config;
822
823 struct rist_peer *peer;
824 if (rist_peer_create(ctx, &peer, peer_input_config[i]) == -1) {
825 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not add peer connector to receiver #%i\n", (int)(i + 1));
826 exit(1);
827 }
828 #if HAVE_SRP_SUPPORT
829 int srp_error = 0;
830 if (profile != RIST_PROFILE_SIMPLE) {
831 if (strlen(peer_config->srp_username) > 0 && strlen(peer_config->srp_password) > 0)
832 {
833 srp_error = rist_enable_eap_srp_2(peer, peer_config->srp_username, peer_config->srp_password, NULL, NULL);
834 if (srp_error)
835 rist_log(&logging_settings, RIST_LOG_WARN, "Error %d trying to enable SRP for peer\n", srp_error);
836 }
837 if (srpfile)
838 {
839 srp_error = rist_enable_eap_srp_2(peer, NULL, NULL, user_verifier_lookup, srpfile);
840 if (srp_error)
841 rist_log(&logging_settings, RIST_LOG_WARN, "Error %d trying to enable SRP global authenticator, file %s\n", srp_error, srpfile);
842 }
843 }
844 else
845 rist_log(&logging_settings, RIST_LOG_WARN, "SRP Authentication is not available for Rist Simple Profile\n");
846 #endif
847
848 rist_peer_config_free2(&peer_config);
849 inputtoken = strtok_r(NULL, ",", &saveptr1);
850 }
851
852 /* Mpeg side */
853 bool atleast_one_socket_opened = false;
854 char *saveptr2;
855 char *outputtoken = strtok_r(outputurl, ",", &saveptr2);
856 for (size_t i = 0; i < MAX_OUTPUT_COUNT; i++) {
857
858 if (!outputtoken)
859 break;
860
861 // First parse extra parameters (?miface=lo&stream-id=1971) and separate the address
862 // We are using the rist_parse_address function to create a config object that does not really
863 // belong to the udp output. We do this only to avoid writing another parser for the two url
864 // parameters available to the udp input/output url
865 struct rist_udp_config *udp_config = NULL;
866 if (rist_parse_udp_address2(outputtoken, &udp_config)) {
867 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse outputurl %s\n", outputtoken);
868 goto next;
869 }
870
871 if (strcmp(udp_config->prefix, "tun") == 0) {
872 if (!callback_object.tun) {
873 rist_log(&logging_settings, RIST_LOG_ERROR, "Detected 'tun://' usage in output url but '--tun' argument was not given\n");
874 exit(1);
875 }
876 atleast_one_socket_opened = true;
877 goto next;
878 }
879
880 // Now parse the address 127.0.0.1:5000
881 char hostname[200] = {0};
882 int outputlisten;
883 uint16_t outputport = 0;
884 if (udpsocket_parse_url((void *)udp_config->address, hostname, 200, &outputport, &outputlisten) || !outputport || strlen(hostname) == 0) {
885 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not parse output url %s\n", outputtoken);
886 goto next;
887 }
888 rist_log(&logging_settings, RIST_LOG_INFO, "URL parsed successfully: Host %s, Port %d\n", (char *) hostname, outputport);
889
890 // Open the output socket
891 callback_object.mpeg[i] = udpsocket_open_connect(hostname, outputport, udp_config->miface);
892 if (callback_object.mpeg[i] < 0) {
893 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not connect to: Host %s, Port %d\n", (char *) hostname, outputport);
894 goto next;
895 } else {
896 rist_log(&logging_settings, RIST_LOG_INFO, "Output socket is open and bound %s:%d\n", (char *) hostname, outputport);
897 atleast_one_socket_opened = true;
898 }
899 callback_object.udp_config[i] = udp_config;
900
901 next:
902 outputtoken = strtok_r(NULL, ",", &saveptr2);
903 }
904
905 /* Output pacing, from the command line and from any output URL asking for
906 * it. Both go through the same setter, so a disagreement between them is
907 * refused there rather than resolved differently here. */
908 if (cbr_output_cli >= 0 && rist_receiver_set_cbr_output(ctx, cbr_output_cli != 0) != 0)
909 exit(1);
910 for (size_t i = 0; i < MAX_OUTPUT_COUNT; i++) {
911 struct rist_udp_config *uc = callback_object.udp_config[i];
912 if (!uc || uc->version < 2 || !uc->cbr_output_set)
913 continue;
914 if (rist_receiver_set_cbr_output(ctx, uc->cbr_output != 0) != 0)
915 exit(1);
916 }
917
918 if (!atleast_one_socket_opened) {
919 exit(1);
920 }
921
922 pthread_t thread_tun_loop = { 0 };
923 if (callback_object.tun && pthread_create(&thread_tun_loop, NULL, tun_loop, (void *)&callback_object) != 0)
924 {
925 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not start tun read thread\n");
926 exit(1);
927 }
928
929 if (data_read_mode == DATA_READ_MODE_CALLBACK) {
930 if (rist_receiver_data_callback_set2(ctx, cb_recv, &callback_object))
931 {
932 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not set data_callback pointer\n");
933 exit(1);
934 }
935 }
936 #ifndef _WIN32
937 else if (data_read_mode == DATA_READ_MODE_POLL) {
938 if (pipe(receiver_pipe))
939 {
940 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not create pipe for file descriptor channel\n");
941 exit(1);
942 }
943 if (fcntl(receiver_pipe[WriteEnd], F_SETFL, O_NONBLOCK) < 0)
944 {
945 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not set pipe to non blocking mode\n");
946 exit(1);
947 }
948 if (fcntl(receiver_pipe[ReadEnd], F_SETFL, O_NONBLOCK) < 0)
949 {
950 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not set pipe to non blocking mode\n");
951 exit(1);
952 }
953 if (rist_receiver_data_notify_fd_set(ctx, receiver_pipe[WriteEnd]))
954 {
955 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not set file descriptor channel\n");
956 exit(1);
957 }
958 }
959 #endif
960
961 if (rist_start(ctx)) {
962 rist_log(&logging_settings, RIST_LOG_ERROR, "Could not start rist receiver\n");
963 exit(1);
964 }
965 /* Start the rist protocol thread */
966 if (data_read_mode == DATA_READ_MODE_CALLBACK) {
967 #ifdef _WIN32
968 system("pause");
969 #else
970 pause();
971 #endif
972 }
973 else if (data_read_mode == DATA_READ_MODE_API) {
974 #ifndef _WIN32
975 int prio_max = sched_get_priority_max(SCHED_RR);
976 struct sched_param param = { 0 };
977 param.sched_priority = prio_max;
978 if (pthread_setschedparam(pthread_self(), SCHED_RR, &param) != 0)
979 rist_log(&logging_settings, RIST_LOG_WARN, "Failed to set data output thread to RR scheduler with prio of %i\n", prio_max);
980 #else
981 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
982 #endif
983 // Master loop
984 while (true)
985 {
986 struct rist_data_block *b = NULL;
987 int queue_size = rist_receiver_data_read2(ctx, &b, 5);
988 if (queue_size > 0) {
989 if (queue_size % 10 == 0 || queue_size > 50) {
990 // We need a better way to report on this
991 uint32_t flow_id = b ? b->flow_id : 0;
992 rist_log(&logging_settings, RIST_LOG_WARN, "Falling behind on rist_receiver_data_read: count %d, flow id %u\n", queue_size, flow_id);
993 }
994 if (b && b->payload) cb_recv(&callback_object, b);
995 }
996 pthread_mutex_lock(&signal_lock);
997 if (signalReceived)
998 {
999 rist_log(&logging_settings, RIST_LOG_INFO, "Signal %d received\n", signal);
1000 break;
1001 }
1002 pthread_mutex_unlock(&signal_lock);
1003 }
1004 }
1005 #ifndef _WIN32
1006 else if (data_read_mode == DATA_READ_MODE_POLL) {
1007 char pipebuffer[256];
1008 fd_set readfds;
1009 struct timeval timeout;
1010 timeout.tv_sec = 0;
1011 timeout.tv_usec = 5000;
1012 while (true) {
1013 FD_ZERO(&readfds);
1014 FD_SET(receiver_pipe[ReadEnd], &readfds);
1015 int ret = select(FD_SETSIZE, &readfds, NULL, NULL, &timeout);
1016 if (ret == -1 && errno != EINTR) {
1017 fprintf(stderr, "Pipe read error %d, exiting\n", errno);
1018 break;
1019 }
1020 else if (ret == 0) {
1021 // Normal timeout (loop and wait)
1022 continue;
1023 }
1024 /* Consume bytes from pipe (irrelevant data) */
1025 for (;;) {
1026 if (read(receiver_pipe[ReadEnd], &pipebuffer, sizeof(pipebuffer)) <= 0) {
1027 if (errno != EAGAIN)
1028 fprintf(stderr, "Error reading data from pipe: %d\n", errno);
1029 break;
1030 }
1031 }
1032 /* Consume data from library */
1033 struct rist_data_block *b = NULL;
1034 int queue_size = 0;
1035 for (;;) {
1036 queue_size = rist_receiver_data_read2(ctx, &b, 0);
1037 if (queue_size > 0) {
1038 if (queue_size % 10 == 0 || queue_size > 50) {
1039 // We need a better way to report on this
1040 uint32_t flow_id = b ? b->flow_id : 0;
1041 rist_log(&logging_settings, RIST_LOG_WARN, "Falling behind on rist_receiver_data_read: count %d, flow id %u\n", queue_size, flow_id);
1042 }
1043 if (b && b->payload) cb_recv(&callback_object, b);
1044 }
1045 else
1046 break;
1047 }
1048 pthread_mutex_lock(&signal_lock);
1049 if (signalReceived)
1050 {
1051 rist_log(&logging_settings, RIST_LOG_INFO, "Signal %d received\n", signal);
1052 break;
1053 }
1054 pthread_mutex_unlock(&signal_lock);
1055 }
1056 }
1057 #endif
1058 rist_destroy(ctx);
1059
1060 for (size_t i = 0; i < MAX_OUTPUT_COUNT; i++) {
1061 // Free udp_config object
1062 if ((void *)callback_object.udp_config[i])
1063 rist_udp_config_free2(&callback_object.udp_config[i]);
1064 }
1065
1066 rist_logging_unset_global();
1067 if (inputurl)
1068 free(inputurl);
1069 if (outputurl)
1070 free(outputurl);
1071 if (thread_tun_loop)
1072 pthread_join(thread_tun_loop, NULL);
1073 if (oobtun)
1074 free(oobtun);
1075 if (callback_object.tun)
1076 close(callback_object.tun);
1077 if (shared_secret)
1078 free(shared_secret);
1079
1080 struct ristreceiver_flow_cumulative_stats *stats, *next;
1081 stats = stats_list;
1082 while (stats)
1083 {
1084 next = stats->next;
1085 free(stats);
1086 stats = next;
1087 }
1088 #if HAVE_PROMETHEUS_SUPPORT
1089 rist_prometheus_stats_destroy(prom_stats_ctx);
1090 free(prometheus_ip);
1091 free(prometheus_tags);
1092 free(prometheus_unix_sock);
1093 #endif
1094 return 0;
1095 }