]> git.proxmox.com Git - mirror_frr.git/blob - lib/libfrr.c
Merge pull request #4393 from donaldsharp/debug_all
[mirror_frr.git] / lib / libfrr.c
1 /*
2 * libfrr overall management functions
3 *
4 * Copyright (C) 2016 David Lamparter for NetDEF, Inc.
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the Free
8 * Software Foundation; either version 2 of the License, or (at your option)
9 * any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 * more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; see the file COPYING; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21 #include <zebra.h>
22 #include <sys/un.h>
23
24 #include <sys/types.h>
25 #include <sys/wait.h>
26
27 #include "libfrr.h"
28 #include "getopt.h"
29 #include "privs.h"
30 #include "vty.h"
31 #include "command.h"
32 #include "version.h"
33 #include "memory_vty.h"
34 #include "zclient.h"
35 #include "log_int.h"
36 #include "module.h"
37 #include "network.h"
38 #include "lib_errors.h"
39 #include "db.h"
40 #include "northbound_cli.h"
41 #include "northbound_db.h"
42 #include "debug.h"
43
44 DEFINE_HOOK(frr_late_init, (struct thread_master * tm), (tm))
45 DEFINE_KOOH(frr_early_fini, (), ())
46 DEFINE_KOOH(frr_fini, (), ())
47
48 const char frr_sysconfdir[] = SYSCONFDIR;
49 const char frr_vtydir[] = DAEMON_VTY_DIR;
50 #ifdef HAVE_SQLITE3
51 const char frr_dbdir[] = DAEMON_DB_DIR;
52 #endif
53 const char frr_moduledir[] = MODULE_PATH;
54
55 char frr_protoname[256] = "NONE";
56 char frr_protonameinst[256] = "NONE";
57
58 char config_default[512];
59 char frr_zclientpath[256];
60 static char pidfile_default[512];
61 #ifdef HAVE_SQLITE3
62 static char dbfile_default[512];
63 #endif
64 static char vtypath_default[256];
65
66 bool debug_memstats_at_exit = false;
67 static bool nodetach_term, nodetach_daemon;
68
69 static char comb_optstr[256];
70 static struct option comb_lo[64];
71 static struct option *comb_next_lo = &comb_lo[0];
72 static char comb_helpstr[4096];
73
74 struct optspec {
75 const char *optstr;
76 const char *helpstr;
77 const struct option *longopts;
78 };
79
80 static void opt_extend(const struct optspec *os)
81 {
82 const struct option *lo;
83
84 strlcat(comb_optstr, os->optstr, sizeof(comb_optstr));
85 strlcat(comb_helpstr, os->helpstr, sizeof(comb_helpstr));
86 for (lo = os->longopts; lo->name; lo++)
87 memcpy(comb_next_lo++, lo, sizeof(*lo));
88 }
89
90
91 #define OPTION_VTYSOCK 1000
92 #define OPTION_MODULEDIR 1002
93 #define OPTION_LOG 1003
94 #define OPTION_LOGLEVEL 1004
95 #define OPTION_TCLI 1005
96 #define OPTION_DB_FILE 1006
97
98 static const struct option lo_always[] = {
99 {"help", no_argument, NULL, 'h'},
100 {"version", no_argument, NULL, 'v'},
101 {"daemon", no_argument, NULL, 'd'},
102 {"module", no_argument, NULL, 'M'},
103 {"vty_socket", required_argument, NULL, OPTION_VTYSOCK},
104 {"moduledir", required_argument, NULL, OPTION_MODULEDIR},
105 {"log", required_argument, NULL, OPTION_LOG},
106 {"log-level", required_argument, NULL, OPTION_LOGLEVEL},
107 {"tcli", no_argument, NULL, OPTION_TCLI},
108 {NULL}};
109 static const struct optspec os_always = {
110 "hvdM:",
111 " -h, --help Display this help and exit\n"
112 " -v, --version Print program version\n"
113 " -d, --daemon Runs in daemon mode\n"
114 " -M, --module Load specified module\n"
115 " --vty_socket Override vty socket path\n"
116 " --moduledir Override modules directory\n"
117 " --log Set Logging to stdout, syslog, or file:<name>\n"
118 " --log-level Set Logging Level to use, debug, info, warn, etc\n"
119 " --tcli Use transaction-based CLI\n",
120 lo_always};
121
122
123 static const struct option lo_cfg_pid_dry[] = {
124 {"pid_file", required_argument, NULL, 'i'},
125 {"config_file", required_argument, NULL, 'f'},
126 #ifdef HAVE_SQLITE3
127 {"db_file", required_argument, NULL, OPTION_DB_FILE},
128 #endif
129 {"pathspace", required_argument, NULL, 'N'},
130 {"dryrun", no_argument, NULL, 'C'},
131 {"terminal", no_argument, NULL, 't'},
132 {NULL}};
133 static const struct optspec os_cfg_pid_dry = {
134 "f:i:CtN:",
135 " -f, --config_file Set configuration file name\n"
136 " -i, --pid_file Set process identifier file name\n"
137 #ifdef HAVE_SQLITE3
138 " --db_file Set database file name\n"
139 #endif
140 " -N, --pathspace Insert prefix into config & socket paths\n"
141 " -C, --dryrun Check configuration for validity and exit\n"
142 " -t, --terminal Open terminal session on stdio\n"
143 " -d -t Daemonize after terminal session ends\n",
144 lo_cfg_pid_dry};
145
146
147 static const struct option lo_zclient[] = {
148 {"socket", required_argument, NULL, 'z'},
149 {NULL}};
150 static const struct optspec os_zclient = {
151 "z:", " -z, --socket Set path of zebra socket\n", lo_zclient};
152
153
154 static const struct option lo_vty[] = {
155 {"vty_addr", required_argument, NULL, 'A'},
156 {"vty_port", required_argument, NULL, 'P'},
157 {NULL}};
158 static const struct optspec os_vty = {
159 "A:P:",
160 " -A, --vty_addr Set vty's bind address\n"
161 " -P, --vty_port Set vty's port number\n",
162 lo_vty};
163
164
165 static const struct option lo_user[] = {{"user", required_argument, NULL, 'u'},
166 {"group", required_argument, NULL, 'g'},
167 {NULL}};
168 static const struct optspec os_user = {"u:g:",
169 " -u, --user User to run as\n"
170 " -g, --group Group to run as\n",
171 lo_user};
172
173
174 bool frr_zclient_addr(struct sockaddr_storage *sa, socklen_t *sa_len,
175 const char *path)
176 {
177 memset(sa, 0, sizeof(*sa));
178
179 if (!path)
180 path = ZEBRA_SERV_PATH;
181
182 if (!strncmp(path, ZAPI_TCP_PATHNAME, strlen(ZAPI_TCP_PATHNAME))) {
183 /* note: this functionality is disabled at bottom */
184 int af;
185 int port = ZEBRA_PORT;
186 char *err = NULL;
187 struct sockaddr_in *sin = NULL;
188 struct sockaddr_in6 *sin6 = NULL;
189
190 path += strlen(ZAPI_TCP_PATHNAME);
191
192 switch (path[0]) {
193 case '4':
194 path++;
195 af = AF_INET;
196 break;
197 case '6':
198 path++;
199 /* fallthrough */
200 default:
201 af = AF_INET6;
202 break;
203 }
204
205 switch (path[0]) {
206 case '\0':
207 break;
208 case ':':
209 path++;
210 port = strtoul(path, &err, 10);
211 if (*err || !*path)
212 return false;
213 break;
214 default:
215 return false;
216 }
217
218 sa->ss_family = af;
219 switch (af) {
220 case AF_INET:
221 sin = (struct sockaddr_in *)sa;
222 sin->sin_port = htons(port);
223 sin->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
224 *sa_len = sizeof(struct sockaddr_in);
225 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
226 sin->sin_len = *sa_len;
227 #endif
228 break;
229 case AF_INET6:
230 sin6 = (struct sockaddr_in6 *)sa;
231 sin6->sin6_port = htons(port);
232 inet_pton(AF_INET6, "::1", &sin6->sin6_addr);
233 *sa_len = sizeof(struct sockaddr_in6);
234 #ifdef SIN6_LEN
235 sin6->sin6_len = *sa_len;
236 #endif
237 break;
238 }
239
240 #if 1
241 /* force-disable this path, because tcp-zebra is a
242 * SECURITY ISSUE. there are no checks at all against
243 * untrusted users on the local system connecting on TCP
244 * and injecting bogus routing data into the entire routing
245 * domain.
246 *
247 * The functionality is only left here because it may be
248 * useful during development, in order to be able to get
249 * tcpdump or wireshark watching ZAPI as TCP. If you want
250 * to do that, flip the #if 1 above to #if 0. */
251 memset(sa, 0, sizeof(*sa));
252 return false;
253 #endif
254 } else {
255 /* "sun" is a #define on solaris */
256 struct sockaddr_un *suna = (struct sockaddr_un *)sa;
257
258 suna->sun_family = AF_UNIX;
259 strlcpy(suna->sun_path, path, sizeof(suna->sun_path));
260 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
261 *sa_len = suna->sun_len = SUN_LEN(suna);
262 #else
263 *sa_len = sizeof(suna->sun_family) + strlen(suna->sun_path);
264 #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
265 #if 0
266 /* this is left here for future reference; Linux abstract
267 * socket namespace support can be enabled by replacing
268 * above #if 0 with #ifdef GNU_LINUX.
269 *
270 * THIS IS A SECURITY ISSUE, the abstract socket namespace
271 * does not have user/group permission control on sockets.
272 * we'd need to implement SCM_CREDENTIALS support first to
273 * check that only proper users can connect to abstract
274 * sockets. (same problem as tcp-zebra, except there is a
275 * fix with SCM_CREDENTIALS. tcp-zebra has no such fix.)
276 */
277 if (suna->sun_path[0] == '@')
278 suna->sun_path[0] = '\0';
279 #endif
280 }
281 return true;
282 }
283
284 static struct frr_daemon_info *di = NULL;
285
286 void frr_preinit(struct frr_daemon_info *daemon, int argc, char **argv)
287 {
288 di = daemon;
289
290 /* basename(), opencoded. */
291 char *p = strrchr(argv[0], '/');
292 di->progname = p ? p + 1 : argv[0];
293
294 umask(0027);
295
296 opt_extend(&os_always);
297 if (!(di->flags & FRR_NO_CFG_PID_DRY))
298 opt_extend(&os_cfg_pid_dry);
299 if (!(di->flags & FRR_NO_PRIVSEP))
300 opt_extend(&os_user);
301 if (!(di->flags & FRR_NO_ZCLIENT))
302 opt_extend(&os_zclient);
303 if (!(di->flags & FRR_NO_TCPVTY))
304 opt_extend(&os_vty);
305 if (di->flags & FRR_DETACH_LATER)
306 nodetach_daemon = true;
307
308 snprintf(config_default, sizeof(config_default), "%s/%s.conf",
309 frr_sysconfdir, di->name);
310 snprintf(pidfile_default, sizeof(pidfile_default), "%s/%s.pid",
311 frr_vtydir, di->name);
312 #ifdef HAVE_SQLITE3
313 snprintf(dbfile_default, sizeof(dbfile_default), "%s/%s.db",
314 frr_dbdir, di->name);
315 #endif
316
317 strlcpy(frr_protoname, di->logname, sizeof(frr_protoname));
318 strlcpy(frr_protonameinst, di->logname, sizeof(frr_protonameinst));
319
320 strlcpy(frr_zclientpath, ZEBRA_SERV_PATH, sizeof(frr_zclientpath));
321
322 di->cli_mode = FRR_CLI_CLASSIC;
323 }
324
325 void frr_opt_add(const char *optstr, const struct option *longopts,
326 const char *helpstr)
327 {
328 const struct optspec main_opts = {optstr, helpstr, longopts};
329 opt_extend(&main_opts);
330 }
331
332 void frr_help_exit(int status)
333 {
334 FILE *target = status ? stderr : stdout;
335
336 if (status != 0)
337 fprintf(stderr, "Invalid options.\n\n");
338
339 if (di->printhelp)
340 di->printhelp(target);
341 else
342 fprintf(target, "Usage: %s [OPTION...]\n\n%s%s%s\n\n%s",
343 di->progname, di->proghelp, di->copyright ? "\n\n" : "",
344 di->copyright ? di->copyright : "", comb_helpstr);
345 fprintf(target, "\nReport bugs to %s\n", FRR_BUG_ADDRESS);
346 exit(status);
347 }
348
349 struct option_chain {
350 struct option_chain *next;
351 const char *arg;
352 };
353
354 static struct option_chain *modules = NULL, **modnext = &modules;
355 static int errors = 0;
356
357 static int frr_opt(int opt)
358 {
359 static int vty_port_set = 0;
360 static int vty_addr_set = 0;
361 struct option_chain *oc;
362 char *err;
363
364 switch (opt) {
365 case 'h':
366 frr_help_exit(0);
367 break;
368 case 'v':
369 print_version(di->progname);
370 exit(0);
371 break;
372 case 'd':
373 di->daemon_mode = 1;
374 break;
375 case 'M':
376 oc = XMALLOC(MTYPE_TMP, sizeof(*oc));
377 oc->arg = optarg;
378 oc->next = NULL;
379 *modnext = oc;
380 modnext = &oc->next;
381 break;
382 case 'i':
383 if (di->flags & FRR_NO_CFG_PID_DRY)
384 return 1;
385 di->pid_file = optarg;
386 break;
387 case 'f':
388 if (di->flags & FRR_NO_CFG_PID_DRY)
389 return 1;
390 di->config_file = optarg;
391 break;
392 case 'N':
393 if (di->flags & FRR_NO_CFG_PID_DRY)
394 return 1;
395 if (di->pathspace) {
396 fprintf(stderr,
397 "-N/--pathspace option specified more than once!\n");
398 errors++;
399 break;
400 }
401 if (strchr(optarg, '/') || strchr(optarg, '.')) {
402 fprintf(stderr,
403 "slashes or dots are not permitted in the --pathspace option.\n");
404 errors++;
405 break;
406 }
407 di->pathspace = optarg;
408 break;
409 #ifdef HAVE_SQLITE3
410 case OPTION_DB_FILE:
411 if (di->flags & FRR_NO_CFG_PID_DRY)
412 return 1;
413 di->db_file = optarg;
414 break;
415 #endif
416 case 'C':
417 if (di->flags & FRR_NO_CFG_PID_DRY)
418 return 1;
419 di->dryrun = 1;
420 break;
421 case 't':
422 if (di->flags & FRR_NO_CFG_PID_DRY)
423 return 1;
424 di->terminal = 1;
425 break;
426 case 'z':
427 if (di->flags & FRR_NO_ZCLIENT)
428 return 1;
429 strlcpy(frr_zclientpath, optarg, sizeof(frr_zclientpath));
430 break;
431 case 'A':
432 if (di->flags & FRR_NO_TCPVTY)
433 return 1;
434 if (vty_addr_set) {
435 fprintf(stderr,
436 "-A option specified more than once!\n");
437 errors++;
438 break;
439 }
440 vty_addr_set = 1;
441 di->vty_addr = optarg;
442 break;
443 case 'P':
444 if (di->flags & FRR_NO_TCPVTY)
445 return 1;
446 if (vty_port_set) {
447 fprintf(stderr,
448 "-P option specified more than once!\n");
449 errors++;
450 break;
451 }
452 vty_port_set = 1;
453 di->vty_port = strtoul(optarg, &err, 0);
454 if (*err || !*optarg) {
455 fprintf(stderr,
456 "invalid port number \"%s\" for -P option\n",
457 optarg);
458 errors++;
459 break;
460 }
461 break;
462 case OPTION_VTYSOCK:
463 if (di->vty_sock_path) {
464 fprintf(stderr,
465 "--vty_socket option specified more than once!\n");
466 errors++;
467 break;
468 }
469 di->vty_sock_path = optarg;
470 break;
471 case OPTION_MODULEDIR:
472 if (di->module_path) {
473 fprintf(stderr,
474 "----moduledir option specified more than once!\n");
475 errors++;
476 break;
477 }
478 di->module_path = optarg;
479 break;
480 case OPTION_TCLI:
481 di->cli_mode = FRR_CLI_TRANSACTIONAL;
482 break;
483 case 'u':
484 if (di->flags & FRR_NO_PRIVSEP)
485 return 1;
486 di->privs->user = optarg;
487 break;
488 case 'g':
489 if (di->flags & FRR_NO_PRIVSEP)
490 return 1;
491 di->privs->group = optarg;
492 break;
493 case OPTION_LOG:
494 di->early_logging = optarg;
495 break;
496 case OPTION_LOGLEVEL:
497 di->early_loglevel = optarg;
498 break;
499 default:
500 return 1;
501 }
502 return 0;
503 }
504
505 int frr_getopt(int argc, char *const argv[], int *longindex)
506 {
507 int opt;
508 int lidx;
509
510 comb_next_lo->name = NULL;
511
512 do {
513 opt = getopt_long(argc, argv, comb_optstr, comb_lo, &lidx);
514 if (frr_opt(opt))
515 break;
516 } while (opt != -1);
517
518 if (opt == -1 && errors)
519 frr_help_exit(1);
520 if (longindex)
521 *longindex = lidx;
522 return opt;
523 }
524
525 static void frr_mkdir(const char *path, bool strip)
526 {
527 char buf[256];
528 mode_t prev;
529 int ret;
530 struct zprivs_ids_t ids;
531
532 if (strip) {
533 char *slash = strrchr(path, '/');
534 size_t plen;
535 if (!slash)
536 return;
537 plen = slash - path;
538 if (plen > sizeof(buf) - 1)
539 return;
540 memcpy(buf, path, plen);
541 buf[plen] = '\0';
542 path = buf;
543 }
544
545 /* o+rx (..5) is needed for the frrvty group to work properly;
546 * without it, users in the frrvty group can't access the vty sockets.
547 */
548 prev = umask(0022);
549 ret = mkdir(path, 0755);
550 umask(prev);
551
552 if (ret != 0) {
553 /* if EEXIST, return without touching the permissions,
554 * so user-set custom permissions are left in place
555 */
556 if (errno == EEXIST)
557 return;
558
559 flog_err(EC_LIB_SYSTEM_CALL, "failed to mkdir \"%s\": %s", path,
560 strerror(errno));
561 return;
562 }
563
564 zprivs_get_ids(&ids);
565 if (chown(path, ids.uid_normal, ids.gid_normal))
566 flog_err(EC_LIB_SYSTEM_CALL, "failed to chown \"%s\": %s", path,
567 strerror(errno));
568 }
569
570 static struct thread_master *master;
571 struct thread_master *frr_init(void)
572 {
573 struct option_chain *oc;
574 struct frrmod_runtime *module;
575 char moderr[256];
576 char p_instance[16] = "", p_pathspace[256] = "";
577 const char *dir;
578 dir = di->module_path ? di->module_path : frr_moduledir;
579
580 srandom(time(NULL));
581
582 if (di->instance) {
583 snprintf(frr_protonameinst, sizeof(frr_protonameinst), "%s[%u]",
584 di->logname, di->instance);
585 snprintf(p_instance, sizeof(p_instance), "-%d", di->instance);
586 }
587 if (di->pathspace)
588 snprintf(p_pathspace, sizeof(p_pathspace), "%s/",
589 di->pathspace);
590
591 snprintf(config_default, sizeof(config_default), "%s%s%s%s.conf",
592 frr_sysconfdir, p_pathspace, di->name, p_instance);
593 snprintf(pidfile_default, sizeof(pidfile_default), "%s/%s%s%s.pid",
594 frr_vtydir, p_pathspace, di->name, p_instance);
595 #ifdef HAVE_SQLITE3
596 snprintf(dbfile_default, sizeof(dbfile_default), "%s/%s%s%s.db",
597 frr_dbdir, p_pathspace, di->name, p_instance);
598 #endif
599
600 zprivs_preinit(di->privs);
601
602 openzlog(di->progname, di->logname, di->instance,
603 LOG_CONS | LOG_NDELAY | LOG_PID, LOG_DAEMON);
604
605 command_setup_early_logging(di->early_logging, di->early_loglevel);
606
607 if (!frr_zclient_addr(&zclient_addr, &zclient_addr_len,
608 frr_zclientpath)) {
609 fprintf(stderr, "Invalid zserv socket path: %s\n",
610 frr_zclientpath);
611 exit(1);
612 }
613
614 /* don't mkdir these as root... */
615 if (!(di->flags & FRR_NO_PRIVSEP)) {
616 if (!di->pid_file || !di->vty_path)
617 frr_mkdir(frr_vtydir, false);
618 if (di->pid_file)
619 frr_mkdir(di->pid_file, true);
620 if (di->vty_path)
621 frr_mkdir(di->vty_path, true);
622 }
623
624 frrmod_init(di->module);
625 while (modules) {
626 modules = (oc = modules)->next;
627 module = frrmod_load(oc->arg, dir, moderr, sizeof(moderr));
628 if (!module) {
629 fprintf(stderr, "%s\n", moderr);
630 exit(1);
631 }
632 XFREE(MTYPE_TMP, oc);
633 }
634
635 zprivs_init(di->privs);
636
637 master = thread_master_create(NULL);
638 signal_init(master, di->n_signals, di->signals);
639
640 #ifdef HAVE_SQLITE3
641 if (!di->db_file)
642 di->db_file = dbfile_default;
643 db_init(di->db_file);
644 #endif
645
646 if (di->flags & FRR_LIMITED_CLI)
647 cmd_init(-1);
648 else
649 cmd_init(1);
650
651 vty_init(master);
652 memory_init();
653
654 log_ref_init();
655 lib_error_init();
656
657 yang_init();
658
659 debug_init_cli();
660
661 nb_init(master, di->yang_modules, di->n_yang_modules);
662 if (nb_db_init() != NB_OK)
663 flog_warn(EC_LIB_NB_DATABASE,
664 "%s: failed to initialize northbound database",
665 __func__);
666
667 return master;
668 }
669
670 const char *frr_get_progname(void)
671 {
672 return di ? di->progname : NULL;
673 }
674
675 enum frr_cli_mode frr_get_cli_mode(void)
676 {
677 return di ? di->cli_mode : FRR_CLI_CLASSIC;
678 }
679
680 static int rcvd_signal = 0;
681
682 static void rcv_signal(int signum)
683 {
684 rcvd_signal = signum;
685 /* poll() is interrupted by the signal; handled below */
686 }
687
688 static void frr_daemon_wait(int fd)
689 {
690 struct pollfd pfd[1];
691 int ret;
692 pid_t exitpid;
693 int exitstat;
694 sigset_t sigs, prevsigs;
695
696 sigemptyset(&sigs);
697 sigaddset(&sigs, SIGTSTP);
698 sigaddset(&sigs, SIGQUIT);
699 sigaddset(&sigs, SIGINT);
700 sigprocmask(SIG_BLOCK, &sigs, &prevsigs);
701
702 struct sigaction sa = {
703 .sa_handler = rcv_signal, .sa_flags = SA_RESETHAND,
704 };
705 sigemptyset(&sa.sa_mask);
706 sigaction(SIGTSTP, &sa, NULL);
707 sigaction(SIGQUIT, &sa, NULL);
708 sigaction(SIGINT, &sa, NULL);
709
710 do {
711 char buf[1];
712 ssize_t nrecv;
713
714 pfd[0].fd = fd;
715 pfd[0].events = POLLIN;
716
717 rcvd_signal = 0;
718
719 #if defined(HAVE_PPOLL)
720 ret = ppoll(pfd, 1, NULL, &prevsigs);
721 #elif defined(HAVE_POLLTS)
722 ret = pollts(pfd, 1, NULL, &prevsigs);
723 #else
724 /* racy -- only used on FreeBSD 9 */
725 sigset_t tmpsigs;
726 sigprocmask(SIG_SETMASK, &prevsigs, &tmpsigs);
727 ret = poll(pfd, 1, -1);
728 sigprocmask(SIG_SETMASK, &tmpsigs, NULL);
729 #endif
730 if (ret < 0 && errno != EINTR && errno != EAGAIN) {
731 perror("poll()");
732 exit(1);
733 }
734 switch (rcvd_signal) {
735 case SIGTSTP:
736 send(fd, "S", 1, 0);
737 do {
738 nrecv = recv(fd, buf, sizeof(buf), 0);
739 } while (nrecv == -1
740 && (errno == EINTR || errno == EAGAIN));
741
742 raise(SIGTSTP);
743 sigaction(SIGTSTP, &sa, NULL);
744 send(fd, "R", 1, 0);
745 break;
746 case SIGINT:
747 send(fd, "I", 1, 0);
748 break;
749 case SIGQUIT:
750 send(fd, "Q", 1, 0);
751 break;
752 }
753 } while (ret <= 0);
754
755 exitpid = waitpid(-1, &exitstat, WNOHANG);
756 if (exitpid == 0)
757 /* child successfully went to main loop & closed socket */
758 exit(0);
759
760 /* child failed one way or another ... */
761 if (WIFEXITED(exitstat) && WEXITSTATUS(exitstat) == 0)
762 /* can happen in --terminal case if exit is fast enough */
763 (void)0;
764 else if (WIFEXITED(exitstat))
765 fprintf(stderr, "%s failed to start, exited %d\n", di->name,
766 WEXITSTATUS(exitstat));
767 else if (WIFSIGNALED(exitstat))
768 fprintf(stderr, "%s crashed in startup, signal %d\n", di->name,
769 WTERMSIG(exitstat));
770 else
771 fprintf(stderr, "%s failed to start, unknown problem\n",
772 di->name);
773 exit(1);
774 }
775
776 static int daemon_ctl_sock = -1;
777
778 static void frr_daemonize(void)
779 {
780 int fds[2];
781 pid_t pid;
782
783 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds)) {
784 perror("socketpair() for daemon control");
785 exit(1);
786 }
787 set_cloexec(fds[0]);
788 set_cloexec(fds[1]);
789
790 pid = fork();
791 if (pid < 0) {
792 perror("fork()");
793 exit(1);
794 }
795 if (pid == 0) {
796 /* child */
797 close(fds[0]);
798 if (setsid() < 0) {
799 perror("setsid()");
800 exit(1);
801 }
802
803 daemon_ctl_sock = fds[1];
804 return;
805 }
806
807 close(fds[1]);
808 frr_daemon_wait(fds[0]);
809 }
810
811 /*
812 * Why is this a thread?
813 *
814 * The read in of config for integrated config happens *after*
815 * thread execution starts( because it is passed in via a vtysh -b -n )
816 * While if you are not using integrated config we want the ability
817 * to read the config in after thread execution starts, so that
818 * we can match this behavior.
819 */
820 static int frr_config_read_in(struct thread *t)
821 {
822 if (!vty_read_config(NULL, di->config_file, config_default) &&
823 di->backup_config_file) {
824 char *orig = XSTRDUP(MTYPE_TMP, host_config_get());
825
826 zlog_info("Attempting to read backup config file: %s specified",
827 di->backup_config_file);
828 vty_read_config(NULL, di->backup_config_file, config_default);
829
830 host_config_set(orig);
831 XFREE(MTYPE_TMP, orig);
832 }
833
834 /*
835 * Update the shared candidate after reading the startup configuration.
836 */
837 pthread_rwlock_rdlock(&running_config->lock);
838 {
839 nb_config_replace(vty_shared_candidate_config, running_config,
840 true);
841 }
842 pthread_rwlock_unlock(&running_config->lock);
843
844 return 0;
845 }
846
847 void frr_config_fork(void)
848 {
849 hook_call(frr_late_init, master);
850
851 if (!(di->flags & FRR_NO_CFG_PID_DRY)) {
852 /* Don't start execution if we are in dry-run mode */
853 if (di->dryrun) {
854 frr_config_read_in(NULL);
855 exit(0);
856 }
857
858 thread_add_event(master, frr_config_read_in, NULL, 0,
859 &di->read_in);
860 }
861
862 if (di->daemon_mode || di->terminal)
863 frr_daemonize();
864
865 if (!di->pid_file)
866 di->pid_file = pidfile_default;
867 pid_output(di->pid_file);
868 }
869
870 static void frr_vty_serv(void)
871 {
872 /* allow explicit override of vty_path in the future
873 * (not currently set anywhere) */
874 if (!di->vty_path) {
875 const char *dir;
876 char defvtydir[256];
877
878 snprintf(defvtydir, sizeof(defvtydir), "%s%s%s", frr_vtydir,
879 di->pathspace ? "/" : "",
880 di->pathspace ? di->pathspace : "");
881
882 dir = di->vty_sock_path ? di->vty_sock_path : defvtydir;
883
884 if (di->instance)
885 snprintf(vtypath_default, sizeof(vtypath_default),
886 "%s/%s-%d.vty", dir, di->name, di->instance);
887 else
888 snprintf(vtypath_default, sizeof(vtypath_default),
889 "%s/%s.vty", dir, di->name);
890
891 di->vty_path = vtypath_default;
892 }
893
894 vty_serv_sock(di->vty_addr, di->vty_port, di->vty_path);
895 }
896
897 static void frr_check_detach(void)
898 {
899 if (nodetach_term || nodetach_daemon)
900 return;
901
902 if (daemon_ctl_sock != -1)
903 close(daemon_ctl_sock);
904 daemon_ctl_sock = -1;
905 }
906
907 static void frr_terminal_close(int isexit)
908 {
909 int nullfd;
910
911 nodetach_term = false;
912 frr_check_detach();
913
914 if (!di->daemon_mode || isexit) {
915 printf("\n%s exiting\n", di->name);
916 if (!isexit)
917 raise(SIGINT);
918 return;
919 } else {
920 printf("\n%s daemonizing\n", di->name);
921 fflush(stdout);
922 }
923
924 nullfd = open("/dev/null", O_RDONLY | O_NOCTTY);
925 if (nullfd == -1) {
926 flog_err_sys(EC_LIB_SYSTEM_CALL,
927 "%s: failed to open /dev/null: %s", __func__,
928 safe_strerror(errno));
929 } else {
930 dup2(nullfd, 0);
931 dup2(nullfd, 1);
932 dup2(nullfd, 2);
933 close(nullfd);
934 }
935 }
936
937 static struct thread *daemon_ctl_thread = NULL;
938
939 static int frr_daemon_ctl(struct thread *t)
940 {
941 char buf[1];
942 ssize_t nr;
943
944 nr = recv(daemon_ctl_sock, buf, sizeof(buf), 0);
945 if (nr < 0 && (errno == EINTR || errno == EAGAIN))
946 goto out;
947 if (nr <= 0)
948 return 0;
949
950 switch (buf[0]) {
951 case 'S': /* SIGTSTP */
952 vty_stdio_suspend();
953 if (send(daemon_ctl_sock, "s", 1, 0) < 0)
954 zlog_err("%s send(\"s\") error (SIGTSTP propagation)",
955 (di && di->name ? di->name : ""));
956 break;
957 case 'R': /* SIGTCNT [implicit] */
958 vty_stdio_resume();
959 break;
960 case 'I': /* SIGINT */
961 di->daemon_mode = false;
962 raise(SIGINT);
963 break;
964 case 'Q': /* SIGQUIT */
965 di->daemon_mode = true;
966 vty_stdio_close();
967 break;
968 }
969
970 out:
971 thread_add_read(master, frr_daemon_ctl, NULL, daemon_ctl_sock,
972 &daemon_ctl_thread);
973 return 0;
974 }
975
976 void frr_detach(void)
977 {
978 nodetach_daemon = false;
979 frr_check_detach();
980 }
981
982 void frr_run(struct thread_master *master)
983 {
984 char instanceinfo[64] = "";
985
986 frr_vty_serv();
987
988 if (di->instance)
989 snprintf(instanceinfo, sizeof(instanceinfo), "instance %u ",
990 di->instance);
991
992 zlog_notice("%s %s starting: %svty@%d%s", di->name, FRR_VERSION,
993 instanceinfo, di->vty_port, di->startinfo);
994
995 if (di->terminal) {
996 nodetach_term = true;
997
998 vty_stdio(frr_terminal_close);
999 if (daemon_ctl_sock != -1) {
1000 set_nonblocking(daemon_ctl_sock);
1001 thread_add_read(master, frr_daemon_ctl, NULL,
1002 daemon_ctl_sock, &daemon_ctl_thread);
1003 }
1004 } else if (di->daemon_mode) {
1005 int nullfd = open("/dev/null", O_RDONLY | O_NOCTTY);
1006 if (nullfd == -1) {
1007 flog_err_sys(EC_LIB_SYSTEM_CALL,
1008 "%s: failed to open /dev/null: %s",
1009 __func__, safe_strerror(errno));
1010 } else {
1011 dup2(nullfd, 0);
1012 dup2(nullfd, 1);
1013 dup2(nullfd, 2);
1014 close(nullfd);
1015 }
1016
1017 frr_check_detach();
1018 }
1019
1020 /* end fixed stderr startup logging */
1021 zlog_startup_stderr = false;
1022
1023 struct thread thread;
1024 while (thread_fetch(master, &thread))
1025 thread_call(&thread);
1026 }
1027
1028 void frr_early_fini(void)
1029 {
1030 hook_call(frr_early_fini);
1031 }
1032
1033 void frr_fini(void)
1034 {
1035 FILE *fp;
1036 char filename[128];
1037 int have_leftovers;
1038
1039 hook_call(frr_fini);
1040
1041 /* memory_init -> nothing needed */
1042 vty_terminate();
1043 cmd_terminate();
1044 nb_terminate();
1045 yang_terminate();
1046 #ifdef HAVE_SQLITE3
1047 db_close();
1048 #endif
1049 log_ref_fini();
1050 zprivs_terminate(di->privs);
1051 /* signal_init -> nothing needed */
1052 thread_master_free(master);
1053 master = NULL;
1054 closezlog();
1055 /* frrmod_init -> nothing needed / hooks */
1056
1057 if (!debug_memstats_at_exit)
1058 return;
1059
1060 have_leftovers = log_memstats(stderr, di->name);
1061
1062 /* in case we decide at runtime that we want exit-memstats for
1063 * a daemon, but it has no stderr because it's daemonized
1064 * (only do this if we actually have something to print though)
1065 */
1066 if (!have_leftovers)
1067 return;
1068
1069 snprintf(filename, sizeof(filename), "/tmp/frr-memstats-%s-%llu-%llu",
1070 di->name, (unsigned long long)getpid(),
1071 (unsigned long long)time(NULL));
1072
1073 fp = fopen(filename, "w");
1074 if (fp) {
1075 log_memstats(fp, di->name);
1076 fclose(fp);
1077 }
1078 }
1079
1080 #ifdef INTERP
1081 static const char interp[]
1082 __attribute__((section(".interp"), used)) = INTERP;
1083 #endif
1084 /*
1085 * executable entry point for libfrr.so
1086 *
1087 * note that libc initialization is skipped for this so the set of functions
1088 * that can be called is rather limited
1089 */
1090 extern void _libfrr_version(void)
1091 __attribute__((visibility("hidden"), noreturn));
1092 void _libfrr_version(void)
1093 {
1094 const char banner[] =
1095 FRR_FULL_NAME " " FRR_VERSION ".\n"
1096 FRR_COPYRIGHT GIT_INFO "\n"
1097 "configured with:\n " FRR_CONFIG_ARGS "\n";
1098 write(1, banner, sizeof(banner) - 1);
1099 _exit(0);
1100 }