1 /*
2 * Copyright (c) 2004-2006 Maxim Sobolev <sobomax@FreeBSD.org>
3 * Copyright (c) 2006-2007 Sippy Software, Inc., http://www.sippysoft.com
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 *
27 */
28
29 #ifdef LINUX_XXX
30 /* Apparently needed for drand48(3) */
31 #define _SVID_SOURCE 1
32 /* Needed for the asprintf(3) */
33 #define _GNU_SOURCE 1
34 #endif
35
36 #include <sys/types.h>
37 #include <sys/resource.h>
38 #include <sys/socket.h>
39 #include <sys/stat.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <getopt.h>
43 #include <grp.h>
44 #include <math.h>
45 #include <pthread.h>
46 #include <pwd.h>
47 #include <stdio.h>
48 #include <stdint.h>
49 #include <stdlib.h>
50 #include <signal.h>
51 #include <string.h>
52 #include <unistd.h>
53
54 #include "config_pp.h"
55
56 #if !defined(NO_ERR_H)
57 #include <err.h>
58 #include "rtpp_util.h"
59 #else
60 #include "rtpp_util.h"
61 #endif
62
63 #ifdef HAVE_SYSTEMD_DAEMON
64 #include <systemd/sd-daemon.h>
65 #endif
66
67 #include "rtpp_types.h"
68 #include "rtpp_refcnt.h"
69 #include "rtpp_log.h"
70 #include "rtpp_log_obj.h"
71 #include "rtpp_cfg_stable.h"
72 #include "rtpp_defines.h"
73 #include "rtpp_controlfd.h"
74 #include "rtpp_genuid_singlet.h"
75 #include "rtpp_hash_table.h"
76 #include "rtpp_command.h"
77 #include "rtpp_command_async.h"
78 #include "rtpp_port_table.h"
79 #include "rtpp_proc_async.h"
80 #include "rtpp_bindaddrs.h"
81 #include "rtpp_network.h"
82 #include "rtpp_notify.h"
83 #include "rtpp_math.h"
84 #include "rtpp_mallocs.h"
85 #if ENABLE_MODULE_IF
86 #include "rtpp_module_if.h"
87 #endif
88 #include "rtpp_stats.h"
89 #include "rtpp_sessinfo.h"
90 #include "rtpp_list.h"
91 #include "rtpp_time.h"
92 #include "rtpp_timed.h"
93 #include "rtpp_tnotify_set.h"
94 #include "rtpp_weakref.h"
95 #include "rtpp_debug.h"
96 #ifdef RTPP_CHECK_LEAKS
97 #include "rtpp_memdeb_internal.h"
98 #endif
99 #if RTPP_DEBUG_catchtrace
100 #include "rtpp_stacktrace.h"
101 #endif
102
103 #ifndef RTPP_DEBUG
104 # define RTPP_DEBUG 0
105 #else
106 # define RTPP_DEBUG 1
107 #endif
108
109 static void usage(void);
110
111 #ifdef RTPP_CHECK_LEAKS
112 RTPP_MEMDEB_STATIC(rtpproxy);
113 #endif
114
115 static void
usage(void)116 usage(void)
117 {
118
119 fprintf(stderr, "usage:\trtpproxy [-2fvFiPaRbD] [-l addr1[/addr2]] "
120 "[-6 addr1[/addr2]] [-s path]\n\t [-t tos] [-r rdir [-S sdir]] [-T ttl] "
121 "[-L nfiles] [-m port_min]\n\t [-M port_max] [-u uname[:gname]] [-w sock_mode] "
122 "[-n timeout_socket]\n\t [-d log_level[:log_facility]] [-p pid_file]\n"
123 "\t [-c fifo|rr] [-A addr1[/addr2] [-N random/sched_offset] [-W setup_ttl]\n"
124 "\trtpproxy -V\n");
125 exit(1);
126 }
127
128 static struct cfg *_sig_cf;
129
130 static void rtpp_exit(int) __attribute__ ((noreturn));
131
132 static void
rtpp_exit(int memdeb)133 rtpp_exit(int memdeb)
134 {
135 int ecode;
136
137 ecode = 0;
138 #ifdef RTPP_CHECK_LEAKS
139 if (memdeb) {
140 ecode = rtpp_memdeb_dumpstats(_rtpproxy_memdeb, 0) == 0 ? 0 : 1;
141 }
142 #ifdef RTPP_MEMDEB_STDOUT
143 fclose(stdout);
144 #endif
145 #endif
146 exit(ecode);
147 }
148
149 static void
fatsignal(int sig)150 fatsignal(int sig)
151 {
152
153 RTPP_LOG(_sig_cf->stable->glog, RTPP_LOG_INFO, "got signal %d", sig);
154 if (_sig_cf->stable->fastshutdown == 0) {
155 _sig_cf->stable->fastshutdown = 1;
156 return;
157 }
158 /*
159 * Got second signal while already in the fastshutdown mode, something
160 * probably jammed, do quick exit right from sighandler.
161 */
162 rtpp_exit(1);
163 }
164
165 static void
sighup(int sig)166 sighup(int sig)
167 {
168
169 if (_sig_cf->stable->slowshutdown == 0) {
170 RTPP_LOG(_sig_cf->stable->glog, RTPP_LOG_INFO,
171 "got SIGHUP, initiating deorbiting-burn sequence");
172 }
173 _sig_cf->stable->slowshutdown = 1;
174 }
175
176 static void
ehandler(void)177 ehandler(void)
178 {
179
180 #ifdef MP_MPATROL_H
181 __mp_leaktable(0, MP_LT_UNFREED, 0);
182 #endif
183
184 #if RTPP_DEBUG_catchtrace
185 rtpp_stacktrace_print("Exiting from: ehandler()");
186 #endif
187 rtpp_controlfd_cleanup(_sig_cf);
188 unlink(_sig_cf->stable->pid_file);
189 RTPP_LOG(_sig_cf->stable->glog, RTPP_LOG_INFO, "rtpproxy ended");
190 CALL_SMETHOD(_sig_cf->stable->glog->rcnt, decref);
191 #ifdef RTPP_CHECK_LEAKS
192 RTPP_MEMDEB_FIN(rtpproxy);
193 #endif
194 }
195
196 long long
rtpp_rlim_max(struct cfg * cf)197 rtpp_rlim_max(struct cfg *cf)
198 {
199
200 return (long long)(cf->stable->nofile_limit->rlim_max);
201 }
202
203 const static struct option longopts[] = {
204 { "dso", required_argument, NULL, 0 },
205 { NULL, 0, NULL, 0 }
206 };
207
208 static void
handle_longopt(struct rtpp_cfg_stable * cfsp,const char * on,const char * optarg)209 handle_longopt(struct rtpp_cfg_stable *cfsp, const char *on, const char *optarg)
210 {
211
212 if (strcmp(on, "dso") == 0) {
213 if (cfsp->mpath != NULL) {
214 errx(1, "this version of the rtpproxy only supports loading a "
215 "single module");
216 }
217 cfsp->mpath = strdup(optarg);
218 return;
219 }
220 errx(1, "unknown option: --%s", on);
221 }
222
223 static void
init_config(struct cfg * cf,int argc,char ** argv)224 init_config(struct cfg *cf, int argc, char **argv)
225 {
226 int ch, i, umode, stdio_mode;
227 char *bh[2], *bh6[2], *cp, *tp[2];
228 const char *errmsg;
229 struct passwd *pp;
230 struct group *gp;
231 double x, y;
232 struct rtpp_ctrl_sock *ctrl_sock;
233 int option_index;
234
235 bh[0] = bh[1] = bh6[0] = bh6[1] = NULL;
236
237 umode = stdio_mode = 0;
238
239 cf->stable->pid_file = PID_FILE;
240
241 cf->stable->port_min = PORT_MIN;
242 cf->stable->port_max = PORT_MAX;
243 cf->stable->port_ctl = 0;
244
245 cf->stable->advaddr[0] = NULL;
246 cf->stable->advaddr[1] = NULL;
247
248 cf->stable->max_ttl = SESSION_TIMEOUT;
249 cf->stable->tos = TOS;
250 cf->stable->rrtcp = 1;
251 cf->stable->sock_mode = 0;
252 cf->stable->ttl_mode = TTL_UNIFIED;
253 cf->stable->log_level = -1;
254 cf->stable->log_facility = -1;
255 cf->stable->sched_offset = 0.0;
256 cf->stable->sched_hz = rtpp_get_sched_hz();
257 cf->stable->sched_policy = SCHED_OTHER;
258 cf->stable->target_pfreq = MIN(POLL_RATE, cf->stable->sched_hz);
259 #if RTPP_DEBUG
260 fprintf(stderr, "target_pfreq = %f\n", cf->stable->target_pfreq);
261 #endif
262 cf->stable->slowshutdown = 0;
263 cf->stable->fastshutdown = 0;
264
265 cf->stable->rtpp_tnset_cf = rtpp_tnotify_set_ctor();
266 if (cf->stable->rtpp_tnset_cf == NULL) {
267 err(1, "rtpp_tnotify_set_ctor");
268 }
269
270 pthread_mutex_init(&cf->glock, NULL);
271 pthread_mutex_init(&cf->bindaddr_lock, NULL);
272
273 cf->stable->nofile_limit = malloc(sizeof(*cf->stable->nofile_limit));
274 if (cf->stable->nofile_limit == NULL)
275 err(1, "malloc");
276 if (getrlimit(RLIMIT_NOFILE, cf->stable->nofile_limit) != 0)
277 err(1, "getrlimit");
278
279 option_index = -1;
280 while ((ch = getopt_long(argc, argv, "vf2Rl:6:s:S:t:r:p:T:L:m:M:u:Fin:Pad:"
281 "VN:c:A:w:bW:DC", longopts, &option_index)) != -1) {
282 switch (ch) {
283 case 0:
284 RTPP_DBG_ASSERT(option_index >= 0);
285 handle_longopt(cf->stable, longopts[option_index].name, optarg);
286 break;
287
288 case 'c':
289 if (strcmp(optarg, "fifo") == 0) {
290 cf->stable->sched_policy = SCHED_FIFO;
291 break;
292 }
293 if (strcmp(optarg, "rr") == 0) {
294 cf->stable->sched_policy = SCHED_RR;
295 break;
296 }
297 errx(1, "%s: unknown scheduling policy", optarg);
298 break;
299
300 case 'N':
301 if (strcmp(optarg, "random") == 0) {
302 x = getdtime() * 1000000.0;
303 srand48((long)x);
304 cf->stable->sched_offset = drand48();
305 } else {
306 tp[0] = optarg;
307 tp[1] = strchr(tp[0], '/');
308 if (tp[1] == NULL) {
309 errx(1, "%s: -N should be in the format X/Y", optarg);
310 }
311 *tp[1] = '\0';
312 tp[1]++;
313 x = (double)strtol(tp[0], &tp[0], 10);
314 y = (double)strtol(tp[1], &tp[1], 10);
315 cf->stable->sched_offset = x / y;
316 }
317 x = (double)cf->stable->sched_hz / cf->stable->target_pfreq;
318 cf->stable->sched_offset = trunc(x * cf->stable->sched_offset) / x;
319 cf->stable->sched_offset /= cf->stable->target_pfreq;
320 warnx("sched_offset = %f", cf->stable->sched_offset);
321 break;
322
323 case 'f':
324 cf->stable->nodaemon = 1;
325 break;
326
327 case 'l':
328 bh[0] = optarg;
329 bh[1] = strchr(bh[0], '/');
330 if (bh[1] != NULL) {
331 *bh[1] = '\0';
332 bh[1]++;
333 cf->stable->bmode = 1;
334 }
335 break;
336
337 case '6':
338 bh6[0] = optarg;
339 bh6[1] = strchr(bh6[0], '/');
340 if (bh6[1] != NULL) {
341 *bh6[1] = '\0';
342 bh6[1]++;
343 cf->stable->bmode = 1;
344 }
345 break;
346
347 case 'A':
348 if (*optarg == '\0') {
349 errx(1, "first advertised address is invalid");
350 }
351 cf->stable->advaddr[0] = optarg;
352 cp = strchr(optarg, '/');
353 if (cp != NULL) {
354 *cp = '\0';
355 cp++;
356 if (*cp == '\0') {
357 errx(1, "second advertised address is invalid");
358 }
359 }
360 cf->stable->advaddr[1] = cp;
361 break;
362
363 case 's':
364 ctrl_sock = rtpp_ctrl_sock_parse(optarg);
365 if (ctrl_sock == NULL) {
366 errx(1, "can't parse control socket argument");
367 }
368 rtpp_list_append(cf->stable->ctrl_socks, ctrl_sock);
369 if (RTPP_CTRL_ISDG(ctrl_sock)) {
370 umode = 1;
371 } else if (ctrl_sock->type == RTPC_STDIO) {
372 stdio_mode = 1;
373 }
374 break;
375
376 case 't':
377 cf->stable->tos = atoi(optarg);
378 if (cf->stable->tos > 255)
379 errx(1, "%d: TOS is too large", cf->stable->tos);
380 break;
381
382 case '2':
383 cf->stable->dmode = 1;
384 break;
385
386 case 'v':
387 printf("Basic version: %d\n", CPROTOVER);
388 for (i = 1; proto_caps[i].pc_id != NULL; ++i) {
389 printf("Extension %s: %s\n", proto_caps[i].pc_id,
390 proto_caps[i].pc_description);
391 }
392 rtpp_exit(1);
393 break;
394
395 case 'r':
396 cf->stable->rdir = optarg;
397 break;
398
399 case 'S':
400 cf->stable->sdir = optarg;
401 break;
402
403 case 'R':
404 cf->stable->rrtcp = 0;
405 break;
406
407 case 'p':
408 cf->stable->pid_file = optarg;
409 break;
410
411 case 'T':
412 cf->stable->max_ttl = atoi(optarg);
413 break;
414
415 case 'L':
416 cf->stable->nofile_limit->rlim_cur = cf->stable->nofile_limit->rlim_max = atoi(optarg);
417 if (setrlimit(RLIMIT_NOFILE, cf->stable->nofile_limit) != 0)
418 err(1, "setrlimit");
419 if (getrlimit(RLIMIT_NOFILE, cf->stable->nofile_limit) != 0)
420 err(1, "getrlimit");
421 if (cf->stable->nofile_limit->rlim_max < atoi(optarg))
422 warnx("limit allocated by setrlimit (%d) is less than "
423 "requested (%d)", (int) cf->stable->nofile_limit->rlim_max,
424 atoi(optarg));
425 break;
426
427 case 'm':
428 cf->stable->port_min = atoi(optarg);
429 break;
430
431 case 'M':
432 cf->stable->port_max = atoi(optarg);
433 break;
434
435 case 'u':
436 cf->stable->run_uname = optarg;
437 cp = strchr(optarg, ':');
438 if (cp != NULL) {
439 if (cp == optarg)
440 cf->stable->run_uname = NULL;
441 cp[0] = '\0';
442 cp++;
443 }
444 cf->stable->run_gname = cp;
445 cf->stable->run_uid = -1;
446 cf->stable->run_gid = -1;
447 if (cf->stable->run_uname != NULL) {
448 pp = getpwnam(cf->stable->run_uname);
449 if (pp == NULL)
450 err(1, "can't find ID for the user: %s", cf->stable->run_uname);
451 cf->stable->run_uid = pp->pw_uid;
452 if (cf->stable->run_gname == NULL)
453 cf->stable->run_gid = pp->pw_gid;
454 }
455 if (cf->stable->run_gname != NULL) {
456 gp = getgrnam(cf->stable->run_gname);
457 if (gp == NULL)
458 err(1, "can't find ID for the group: %s", cf->stable->run_gname);
459 cf->stable->run_gid = gp->gr_gid;
460 if (cf->stable->sock_mode == 0) {
461 cf->stable->sock_mode = 0755;
462 }
463 }
464 break;
465
466 case 'w':
467 cf->stable->sock_mode = atoi(optarg);
468 break;
469
470 case 'F':
471 cf->stable->no_check = 1;
472 break;
473
474 case 'i':
475 cf->stable->ttl_mode = TTL_INDEPENDENT;
476 break;
477
478 case 'n':
479 if(strlen(optarg) == 0)
480 errx(1, "timeout notification socket name too short");
481 if (CALL_METHOD(cf->stable->rtpp_tnset_cf, append, optarg,
482 &errmsg) != 0) {
483 errx(1, "error adding timeout notification: %s", errmsg);
484 }
485 break;
486
487 case 'P':
488 cf->stable->record_pcap = 1;
489 break;
490
491 case 'a':
492 cf->stable->record_all = 1;
493 break;
494
495 case 'd':
496 cp = strchr(optarg, ':');
497 if (cp != NULL) {
498 cf->stable->log_facility = rtpp_log_str2fac(cp + 1);
499 if (cf->stable->log_facility == -1)
500 errx(1, "%s: invalid log facility", cp + 1);
501 *cp = '\0';
502 }
503 cf->stable->log_level = rtpp_log_str2lvl(optarg);
504 if (cf->stable->log_level == -1)
505 errx(1, "%s: invalid log level", optarg);
506 break;
507
508 case 'V':
509 printf("%s\n", RTPP_SW_VERSION);
510 rtpp_exit(1);
511 break;
512
513 case 'W':
514 cf->stable->max_setup_ttl = atoi(optarg);
515 break;
516
517 case 'b':
518 cf->stable->seq_ports = 1;
519 break;
520
521 case 'D':
522 cf->stable->no_chdir = 1;
523 break;
524
525 case 'C':
526 printf("%s\n", get_mclock_name());
527 rtpp_exit(0);
528 break;
529
530 case '?':
531 default:
532 usage();
533 }
534 }
535
536 if (cf->stable->max_setup_ttl == 0) {
537 cf->stable->max_setup_ttl = cf->stable->max_ttl;
538 }
539
540 /* No control socket has been specified, add a default one */
541 if (RTPP_LIST_IS_EMPTY(cf->stable->ctrl_socks)) {
542 ctrl_sock = rtpp_ctrl_sock_parse(CMD_SOCK);
543 if (ctrl_sock == NULL) {
544 errx(1, "can't parse control socket: \"%s\"", CMD_SOCK);
545 }
546 rtpp_list_append(cf->stable->ctrl_socks, ctrl_sock);
547 }
548
549 if (cf->stable->rdir == NULL && cf->stable->sdir != NULL)
550 errx(1, "-S switch requires -r switch");
551
552 if (cf->stable->nodaemon == 0 && stdio_mode != 0)
553 errx(1, "stdio command mode requires -f switch");
554
555 if (cf->stable->no_check == 0 && getuid() == 0 && cf->stable->run_uname == NULL) {
556 if (umode != 0) {
557 errx(1, "running this program as superuser in a remote control "
558 "mode is strongly not recommended, as it poses serious security "
559 "threat to your system. Use -u option to run as an unprivileged "
560 "user or -F is you want to run as a superuser anyway.");
561 } else {
562 warnx("WARNING!!! Running this program as superuser is strongly "
563 "not recommended, as it may pose serious security threat to "
564 "your system. Use -u option to run as an unprivileged user "
565 "or -F to surpress this warning.");
566 }
567 }
568
569 /* make sure that port_min and port_max are even */
570 if ((cf->stable->port_min % 2) != 0)
571 cf->stable->port_min++;
572 if ((cf->stable->port_max % 2) != 0) {
573 cf->stable->port_max--;
574 } else {
575 /*
576 * If port_max is already even then there is no
577 * "room" for the RTCP port, go back by two ports.
578 */
579 cf->stable->port_max -= 2;
580 }
581
582 if (!IS_VALID_PORT(cf->stable->port_min))
583 errx(1, "invalid value of the port_min argument, "
584 "not in the range 1-65535");
585 if (!IS_VALID_PORT(cf->stable->port_max))
586 errx(1, "invalid value of the port_max argument, "
587 "not in the range 1-65535");
588 if (cf->stable->port_min > cf->stable->port_max)
589 errx(1, "port_min should be less than port_max");
590
591 if (bh[0] == NULL && bh[1] == NULL && bh6[0] == NULL && bh6[1] == NULL) {
592 bh[0] = "*";
593 }
594
595 for (i = 0; i < 2; i++) {
596 if (bh[i] != NULL && *bh[i] == '\0')
597 bh[i] = NULL;
598 if (bh6[i] != NULL && *bh6[i] == '\0')
599 bh6[i] = NULL;
600 }
601
602 i = ((bh[0] == NULL) ? 0 : 1) + ((bh[1] == NULL) ? 0 : 1) +
603 ((bh6[0] == NULL) ? 0 : 1) + ((bh6[1] == NULL) ? 0 : 1);
604 if (cf->stable->bmode != 0) {
605 if (bh[0] != NULL && bh6[0] != NULL)
606 errx(1, "either IPv4 or IPv6 should be configured for external "
607 "interface in bridging mode, not both");
608 if (bh[1] != NULL && bh6[1] != NULL)
609 errx(1, "either IPv4 or IPv6 should be configured for internal "
610 "interface in bridging mode, not both");
611 if (cf->stable->advaddr[0] != NULL && cf->stable->advaddr[1] == NULL)
612 errx(1, "two advertised addresses are required for internal "
613 "and external interfaces in bridging mode");
614 if (i != 2)
615 errx(1, "incomplete configuration of the bridging mode - exactly "
616 "2 listen addresses required, %d provided", i);
617 } else if (i != 1) {
618 errx(1, "exactly 1 listen addresses required, %d provided", i);
619 }
620
621 for (i = 0; i < 2; i++) {
622 cf->stable->bindaddr[i] = NULL;
623 if (bh[i] != NULL) {
624 cf->stable->bindaddr[i] = host2bindaddr(cf, bh[i], AF_INET, &errmsg);
625 if (cf->stable->bindaddr[i] == NULL)
626 errx(1, "host2bindaddr: %s", errmsg);
627 continue;
628 }
629 if (bh6[i] != NULL) {
630 cf->stable->bindaddr[i] = host2bindaddr(cf, bh6[i], AF_INET6, &errmsg);
631 if (cf->stable->bindaddr[i] == NULL)
632 errx(1, "host2bindaddr: %s", errmsg);
633 continue;
634 }
635 }
636 if (cf->stable->bindaddr[0] == NULL) {
637 cf->stable->bindaddr[0] = cf->stable->bindaddr[1];
638 cf->stable->bindaddr[1] = NULL;
639 }
640 }
641
642 static enum rtpp_timed_cb_rvals
update_derived_stats(double dtime,void * argp)643 update_derived_stats(double dtime, void *argp)
644 {
645 struct rtpp_stats *rtpp_stats;
646
647 rtpp_stats = (struct rtpp_stats *)argp;
648 CALL_METHOD(rtpp_stats, update_derived, dtime);
649 return (CB_MORE);
650 }
651
652 int
main(int argc,char ** argv)653 main(int argc, char **argv)
654 {
655 int i, len;
656 double eval, clk;
657 long long ncycles_ref, counter;
658 double eptime;
659 double add_delay;
660 struct cfg cf;
661 char buf[256];
662 struct recfilter loop_error;
663 struct PFD phase_detector;
664 useconds_t usleep_time;
665 struct sched_param sparam;
666 #if RTPP_DEBUG_timers
667 double sleep_time, filter_lastval;
668 #endif
669
670 #ifdef RTPP_CHECK_LEAKS
671 RTPP_MEMDEB_INIT(rtpproxy);
672 #endif
673 if (getdtime() == -1) {
674 err(1, "timer self-test has failed: please check your build configuration");
675 /* NOTREACHED */
676 }
677
678 #ifdef RTPP_CHECK_LEAKS
679 if (rtpp_memdeb_selftest(_rtpproxy_memdeb) != 0) {
680 errx(1, "MEMDEB self-test has failed");
681 /* NOTREACHED */
682 }
683 rtpp_memdeb_approve(_rtpproxy_memdeb, "addr2bindaddr", 100, "Too busy to fix now");
684 #endif
685
686 memset(&cf, 0, sizeof(cf));
687
688 cf.stable = rtpp_zmalloc(sizeof(struct rtpp_cfg_stable));
689 if (cf.stable == NULL) {
690 err(1, "can't allocate memory for the struct rtpp_cfg_stable");
691 /* NOTREACHED */
692 }
693 cf.stable->ctrl_socks = rtpp_zmalloc(sizeof(struct rtpp_list));
694 if (cf.stable->ctrl_socks == NULL) {
695 err(1, "can't allocate memory for the struct rtpp_cfg_stable");
696 /* NOTREACHED */
697 }
698 RTPP_LIST_RESET(cf.stable->ctrl_socks);
699
700 init_config(&cf, argc, argv);
701
702 seedrandom();
703 rtpp_gen_uid_init();
704
705 cf.stable->sessions_ht = rtpp_hash_table_ctor(rtpp_ht_key_str_t, 0);
706 if (cf.stable->sessions_ht == NULL) {
707 err(1, "can't allocate memory for the hash table");
708 /* NOTREACHED */
709 }
710 cf.stable->sessions_wrt = rtpp_weakref_ctor();
711 if (cf.stable->sessions_wrt == NULL) {
712 err(1, "can't allocate memory for the sessions weakref table");
713 /* NOTREACHED */
714 }
715 cf.stable->rtp_streams_wrt = rtpp_weakref_ctor();
716 if (cf.stable->rtp_streams_wrt == NULL) {
717 err(1, "can't allocate memory for the RTP streams weakref table");
718 /* NOTREACHED */
719 }
720 cf.stable->rtcp_streams_wrt = rtpp_weakref_ctor();
721 if (cf.stable->rtcp_streams_wrt == NULL) {
722 err(1, "can't allocate memory for the RTCP streams weakref table");
723 /* NOTREACHED */
724 }
725 cf.stable->servers_wrt = rtpp_weakref_ctor();
726 if (cf.stable->servers_wrt == NULL) {
727 err(1, "can't allocate memory for the servers weakref table");
728 /* NOTREACHED */
729 }
730 cf.stable->sessinfo = rtpp_sessinfo_ctor(cf.stable);
731 if (cf.stable->sessinfo == NULL) {
732 errx(1, "cannot construct rtpp_sessinfo structure");
733 }
734
735 cf.stable->rtpp_stats = rtpp_stats_ctor();
736 if (cf.stable->rtpp_stats == NULL) {
737 err(1, "can't allocate memory for the stats data");
738 /* NOTREACHED */
739 }
740
741 for (i = 0; i <= RTPP_PT_MAX; i++) {
742 cf.stable->port_table[i] = rtpp_port_table_ctor(cf.stable->port_min,
743 cf.stable->port_max, cf.stable->seq_ports, cf.stable->port_ctl);
744 if (cf.stable->port_table[i] == NULL) {
745 err(1, "can't allocate memory for the ports data");
746 /* NOTREACHED */
747 }
748 }
749
750 if (rtpp_controlfd_init(&cf) != 0) {
751 err(1, "can't inilialize control socket%s",
752 cf.stable->ctrl_socks->len > 1 ? "s" : "");
753 }
754
755 if (cf.stable->nodaemon == 0) {
756 if (cf.stable->no_chdir == 0) {
757 cf.stable->cwd_orig = getcwd(NULL, 0);
758 if (cf.stable->cwd_orig == NULL) {
759 err(1, "getcwd");
760 }
761 if (cf.stable->mpath != NULL) {
762 char *mpath_abs;
763
764 asprintf(&mpath_abs, "%s/%s", cf.stable->cwd_orig,
765 cf.stable->mpath);
766 if (mpath_abs == NULL) {
767 err(1, "asprintf");
768 }
769 free(cf.stable->mpath);
770 cf.stable->mpath = mpath_abs;
771 }
772 }
773 if (rtpp_daemon(cf.stable->no_chdir, 0) == -1)
774 err(1, "can't switch into daemon mode");
775 /* NOTREACHED */
776 }
777
778 cf.stable->glog = rtpp_log_ctor(cf.stable, "rtpproxy", NULL, LF_REOPEN);
779 if (cf.stable->glog == NULL) {
780 err(1, "can't inilialize logging subsystem");
781 /* NOTREACHED */
782 }
783
784 #ifdef RTPP_CHECK_LEAKS
785 rtpp_memdeb_setlog(_rtpproxy_memdeb, cf.stable->glog);
786 #endif
787 CALL_METHOD(cf.stable->glog, setlevel, cf.stable->log_level);
788 _sig_cf = &cf;
789 atexit(ehandler);
790 RTPP_LOG(cf.stable->glog, RTPP_LOG_INFO, "rtpproxy started, pid %d", getpid());
791
792 #ifdef RTPP_CHECK_LEAKS
793 rtpp_memdeb_setbaseln(_rtpproxy_memdeb);
794 #endif
795
796 i = open(cf.stable->pid_file, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE);
797 if (i >= 0) {
798 len = sprintf(buf, "%u\n", (unsigned int)getpid());
799 write(i, buf, len);
800 close(i);
801 } else {
802 RTPP_ELOG(cf.stable->glog, RTPP_LOG_ERR, "can't open pidfile for writing");
803 }
804
805 if (cf.stable->sched_policy != SCHED_OTHER) {
806 sparam.sched_priority = sched_get_priority_max(cf.stable->sched_policy);
807 if (sched_setscheduler(0, cf.stable->sched_policy, &sparam) == -1) {
808 RTPP_ELOG(cf.stable->glog, RTPP_LOG_ERR, "sched_setscheduler(SCHED_%s, %d)",
809 (cf.stable->sched_policy == SCHED_FIFO) ? "FIFO" : "RR", sparam.sched_priority);
810 }
811 }
812
813 if (cf.stable->run_uname != NULL || cf.stable->run_gname != NULL) {
814 if (drop_privileges(&cf) != 0) {
815 RTPP_ELOG(cf.stable->glog, RTPP_LOG_ERR,
816 "can't switch to requested user/group");
817 exit(1);
818 }
819 }
820 set_rlimits(&cf);
821
822 cf.stable->rtpp_proc_cf = rtpp_proc_async_ctor(&cf);
823 if (cf.stable->rtpp_proc_cf == NULL) {
824 RTPP_LOG(cf.stable->glog, RTPP_LOG_ERR,
825 "can't init RTP processing subsystem");
826 exit(1);
827 }
828
829 counter = 0;
830 recfilter_init(&loop_error, 0.96, 0.0, 0);
831 PFD_init(&phase_detector, 0.0);
832
833 cf.stable->rtpp_timed_cf = rtpp_timed_ctor(0.1);
834 if (cf.stable->rtpp_timed_cf == NULL) {
835 RTPP_ELOG(cf.stable->glog, RTPP_LOG_ERR,
836 "can't init scheduling subsystem");
837 exit(1);
838 }
839
840 if (CALL_METHOD(cf.stable->rtpp_timed_cf, schedule, 1.0,
841 update_derived_stats, NULL, cf.stable->rtpp_stats) != 0) {
842 RTPP_ELOG(cf.stable->glog, RTPP_LOG_ERR,
843 "can't schedule notification to derive stats");
844 }
845
846 cf.stable->rtpp_notify_cf = rtpp_notify_ctor(cf.stable->glog);
847 if (cf.stable->rtpp_notify_cf == NULL) {
848 RTPP_ELOG(cf.stable->glog, RTPP_LOG_ERR,
849 "can't init timeout notification subsystem");
850 exit(1);
851 }
852
853 #if ENABLE_MODULE_IF
854 if (cf.stable->mpath != NULL) {
855 cf.stable->modules_cf = rtpp_module_if_ctor(cf.stable, cf.stable->glog,
856 cf.stable->mpath);
857 if (cf.stable->modules_cf == NULL) {
858 RTPP_LOG(cf.stable->glog, RTPP_LOG_ERR,
859 "%s: dymanic module load has failed", cf.stable->mpath);
860 exit(1);
861 }
862 }
863 #endif
864
865 cf.stable->rtpp_cmd_cf = rtpp_command_async_ctor(&cf);
866 if (cf.stable->rtpp_cmd_cf == NULL) {
867 RTPP_ELOG(cf.stable->glog, RTPP_LOG_ERR,
868 "can't init command processing subsystem");
869 exit(1);
870 }
871
872 signal(SIGHUP, sighup);
873 signal(SIGINT, fatsignal);
874 signal(SIGKILL, fatsignal);
875 signal(SIGPIPE, SIG_IGN);
876 signal(SIGTERM, fatsignal);
877 signal(SIGXCPU, fatsignal);
878 signal(SIGXFSZ, fatsignal);
879 signal(SIGVTALRM, fatsignal);
880 signal(SIGPROF, fatsignal);
881 signal(SIGUSR1, fatsignal);
882 signal(SIGUSR2, fatsignal);
883 #if RTPP_DEBUG_catchtrace
884 signal(SIGQUIT, rtpp_stacktrace);
885 signal(SIGILL, rtpp_stacktrace);
886 signal(SIGTRAP, rtpp_stacktrace);
887 signal(SIGABRT, rtpp_stacktrace);
888 #if defined(SIGEMT)
889 signal(SIGEMT, rtpp_stacktrace);
890 #endif
891 signal(SIGFPE, rtpp_stacktrace);
892 signal(SIGBUS, rtpp_stacktrace);
893 signal(SIGSEGV, rtpp_stacktrace);
894 signal(SIGSYS, rtpp_stacktrace);
895 #endif
896
897 #ifdef HAVE_SYSTEMD_DAEMON
898 sd_notify(0, "READY=1");
899 #endif
900 for (;;) {
901 eptime = getdtime();
902
903 clk = (eptime + cf.stable->sched_offset) * cf.stable->target_pfreq;
904
905 ncycles_ref = llrint(clk);
906
907 eval = PFD_get_error(&phase_detector, clk);
908
909 #if RTPP_DEBUG_timers
910 filter_lastval = loop_error.lastval;
911 #endif
912
913 if (eval != 0.0) {
914 recfilter_apply(&loop_error, sigmoid(eval));
915 }
916
917 #if RTPP_DEBUG_timers
918 if (counter % (unsigned int)cf.stable->target_pfreq == 0 || counter < 1000) {
919 RTPP_LOG(cf.stable->glog, RTPP_LOG_DBUG, "run %lld ncycles %f raw error1 %f, filter lastval %f, filter nextval %f",
920 counter, clk, eval, filter_lastval, loop_error.lastval);
921 }
922 #endif
923 add_delay = freqoff_to_period(cf.stable->target_pfreq, 1.0, loop_error.lastval);
924 usleep_time = add_delay * 1000000.0;
925 #if RTPP_DEBUG_timers
926 if (counter % (unsigned int)cf.stable->target_pfreq == 0 || counter < 1000) {
927 RTPP_LOG(cf.stable->glog, RTPP_LOG_DBUG, "run %lld filter lastval %f, filter nextval %f, error %f",
928 counter, filter_lastval, loop_error.lastval, sigmoid(eval));
929 RTPP_LOG(cf.stable->glog, RTPP_LOG_DBUG, "run %lld extra sleeping time %llu", counter, usleep_time);
930 }
931 sleep_time = getdtime();
932 #endif
933 CALL_METHOD(cf.stable->rtpp_proc_cf, wakeup, counter, ncycles_ref);
934 usleep(usleep_time);
935 CALL_METHOD(cf.stable->rtpp_timed_cf, wakeup, eptime + add_delay);
936 #if RTPP_DEBUG_timers
937 sleep_time = getdtime() - sleep_time;
938 if (counter % (unsigned int)cf.stable->target_pfreq == 0 || counter < 1000 || sleep_time > add_delay * 2.0) {
939 RTPP_LOG(cf.stable->glog, RTPP_LOG_DBUG, "run %lld sleeping time required %llu sleeping time actual %f, CSV: %f,%f,%f", \
940 counter, usleep_time, sleep_time, (double)counter / cf.stable->target_pfreq, ((double)usleep_time) / 1000.0, sleep_time * 1000.0);
941 }
942 #endif
943 counter += 1;
944 if (cf.stable->fastshutdown != 0) {
945 break;
946 }
947 if (cf.stable->slowshutdown != 0 &&
948 CALL_METHOD(cf.stable->sessions_wrt, get_length) == 0) {
949 RTPP_LOG(cf.stable->glog, RTPP_LOG_INFO,
950 "deorbiting-burn sequence completed, exiting");
951 break;
952 }
953 }
954
955 CALL_METHOD(cf.stable->rtpp_cmd_cf, dtor);
956 #if ENABLE_MODULE_IF
957 if (cf.stable->modules_cf != NULL) {
958 CALL_SMETHOD(cf.stable->modules_cf->rcnt, decref);
959 }
960 #endif
961 CALL_METHOD(cf.stable->rtpp_notify_cf, dtor);
962 CALL_METHOD(cf.stable->rtpp_tnset_cf, dtor);
963 CALL_SMETHOD(cf.stable->rtpp_timed_cf->rcnt, decref);
964 CALL_METHOD(cf.stable->rtpp_proc_cf, dtor);
965 CALL_SMETHOD(cf.stable->sessinfo->rcnt, decref);
966 for (i = 0; i <= RTPP_PT_MAX; i++) {
967 CALL_SMETHOD(cf.stable->port_table[i]->rcnt, decref);
968 }
969 #ifdef HAVE_SYSTEMD_DAEMON
970 sd_notify(0, "STATUS=Exited");
971 #endif
972
973 rtpp_exit(1);
974 }
975