1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * libfrr overall management functions
5 * Copyright (C) 2016 David Lamparter for NetDEF, Inc.
11 #include <sys/types.h>
19 #include "lib/version.h"
25 #include "lib_errors.h"
27 #include "northbound_cli.h"
28 #include "northbound_db.h"
31 #include "frr_pthread.h"
33 #include "frrscript.h"
36 DEFINE_HOOK(frr_early_init
, (struct event_loop
* tm
), (tm
));
37 DEFINE_HOOK(frr_late_init
, (struct event_loop
* tm
), (tm
));
38 DEFINE_HOOK(frr_config_pre
, (struct event_loop
* tm
), (tm
));
39 DEFINE_HOOK(frr_config_post
, (struct event_loop
* tm
), (tm
));
40 DEFINE_KOOH(frr_early_fini
, (), ());
41 DEFINE_KOOH(frr_fini
, (), ());
43 const char frr_sysconfdir
[] = SYSCONFDIR
;
46 const char frr_dbdir
[] = DAEMON_DB_DIR
;
48 const char frr_moduledir
[] = MODULE_PATH
;
49 const char frr_scriptdir
[] = SCRIPT_PATH
;
51 char frr_protoname
[256] = "NONE";
52 char frr_protonameinst
[256] = "NONE";
54 char config_default
[512];
55 char frr_zclientpath
[256];
56 static char pidfile_default
[1024];
58 static char dbfile_default
[512];
60 static char vtypath_default
[512];
62 /* cleared in frr_preinit(), then re-set after daemonizing */
63 bool frr_is_after_fork
= true;
64 bool debug_memstats_at_exit
= false;
65 static bool nodetach_term
, nodetach_daemon
;
66 static uint64_t startup_fds
;
68 static char comb_optstr
[256];
69 static struct option comb_lo
[64];
70 static struct option
*comb_next_lo
= &comb_lo
[0];
71 static char comb_helpstr
[4096];
76 const struct option
*longopts
;
79 static void opt_extend(const struct optspec
*os
)
81 const struct option
*lo
;
83 strlcat(comb_optstr
, os
->optstr
, sizeof(comb_optstr
));
84 strlcat(comb_helpstr
, os
->helpstr
, sizeof(comb_helpstr
));
85 for (lo
= os
->longopts
; lo
->name
; lo
++)
86 memcpy(comb_next_lo
++, lo
, sizeof(*lo
));
90 #define OPTION_VTYSOCK 1000
91 #define OPTION_MODULEDIR 1002
92 #define OPTION_LOG 1003
93 #define OPTION_LOGLEVEL 1004
94 #define OPTION_TCLI 1005
95 #define OPTION_DB_FILE 1006
96 #define OPTION_LOGGING 1007
97 #define OPTION_LIMIT_FDS 1008
98 #define OPTION_SCRIPTDIR 1009
100 static const struct option lo_always
[] = {
101 {"help", no_argument
, NULL
, 'h'},
102 {"version", no_argument
, NULL
, 'v'},
103 {"daemon", no_argument
, NULL
, 'd'},
104 {"module", no_argument
, NULL
, 'M'},
105 {"profile", required_argument
, NULL
, 'F'},
106 {"pathspace", required_argument
, NULL
, 'N'},
107 {"vrfdefaultname", required_argument
, NULL
, 'o'},
108 {"vty_socket", required_argument
, NULL
, OPTION_VTYSOCK
},
109 {"moduledir", required_argument
, NULL
, OPTION_MODULEDIR
},
110 {"scriptdir", required_argument
, NULL
, OPTION_SCRIPTDIR
},
111 {"log", required_argument
, NULL
, OPTION_LOG
},
112 {"log-level", required_argument
, NULL
, OPTION_LOGLEVEL
},
113 {"command-log-always", no_argument
, NULL
, OPTION_LOGGING
},
114 {"limit-fds", required_argument
, NULL
, OPTION_LIMIT_FDS
},
116 static const struct optspec os_always
= {
118 " -h, --help Display this help and exit\n"
119 " -v, --version Print program version\n"
120 " -d, --daemon Runs in daemon mode\n"
121 " -M, --module Load specified module\n"
122 " -F, --profile Use specified configuration profile\n"
123 " -N, --pathspace Insert prefix into config & socket paths\n"
124 " -o, --vrfdefaultname Set default VRF name.\n"
125 " --vty_socket Override vty socket path\n"
126 " --moduledir Override modules directory\n"
127 " --scriptdir Override scripts directory\n"
128 " --log Set Logging to stdout, syslog, or file:<name>\n"
129 " --log-level Set Logging Level to use, debug, info, warn, etc\n"
130 " --limit-fds Limit number of fds supported\n",
133 static bool logging_to_stdout
= false; /* set when --log stdout specified */
135 static const struct option lo_cfg
[] = {
136 {"config_file", required_argument
, NULL
, 'f'},
137 {"dryrun", no_argument
, NULL
, 'C'},
139 static const struct optspec os_cfg
= {
141 " -f, --config_file Set configuration file name\n"
142 " -C, --dryrun Check configuration for validity and exit\n",
146 static const struct option lo_fullcli
[] = {
147 {"terminal", no_argument
, NULL
, 't'},
148 {"tcli", no_argument
, NULL
, OPTION_TCLI
},
150 {"db_file", required_argument
, NULL
, OPTION_DB_FILE
},
153 static const struct optspec os_fullcli
= {
155 " --tcli Use transaction-based CLI\n"
156 " -t, --terminal Open terminal session on stdio\n"
157 " -d -t Daemonize after terminal session ends\n",
161 static const struct option lo_pid
[] = {
162 {"pid_file", required_argument
, NULL
, 'i'},
164 static const struct optspec os_pid
= {
166 " -i, --pid_file Set process identifier file name\n",
170 static const struct option lo_zclient
[] = {
171 {"socket", required_argument
, NULL
, 'z'},
173 static const struct optspec os_zclient
= {
174 "z:", " -z, --socket Set path of zebra socket\n", lo_zclient
};
177 static const struct option lo_vty
[] = {
178 {"vty_addr", required_argument
, NULL
, 'A'},
179 {"vty_port", required_argument
, NULL
, 'P'},
181 static const struct optspec os_vty
= {
183 " -A, --vty_addr Set vty's bind address\n"
184 " -P, --vty_port Set vty's port number\n",
188 static const struct option lo_user
[] = {{"user", required_argument
, NULL
, 'u'},
189 {"group", required_argument
, NULL
, 'g'},
191 static const struct optspec os_user
= {"u:g:",
192 " -u, --user User to run as\n"
193 " -g, --group Group to run as\n",
196 bool frr_zclient_addr(struct sockaddr_storage
*sa
, socklen_t
*sa_len
,
199 memset(sa
, 0, sizeof(*sa
));
202 path
= frr_zclientpath
;
204 if (!strncmp(path
, ZAPI_TCP_PATHNAME
, strlen(ZAPI_TCP_PATHNAME
))) {
205 /* note: this functionality is disabled at bottom */
207 int port
= ZEBRA_PORT
;
209 struct sockaddr_in
*sin
= NULL
;
210 struct sockaddr_in6
*sin6
= NULL
;
212 path
+= strlen(ZAPI_TCP_PATHNAME
);
232 port
= strtoul(path
, &err
, 10);
243 sin
= (struct sockaddr_in
*)sa
;
244 sin
->sin_port
= htons(port
);
245 sin
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
246 *sa_len
= sizeof(struct sockaddr_in
);
247 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
248 sin
->sin_len
= *sa_len
;
252 sin6
= (struct sockaddr_in6
*)sa
;
253 sin6
->sin6_port
= htons(port
);
254 inet_pton(AF_INET6
, "::1", &sin6
->sin6_addr
);
255 *sa_len
= sizeof(struct sockaddr_in6
);
257 sin6
->sin6_len
= *sa_len
;
263 /* force-disable this path, because tcp-zebra is a
264 * SECURITY ISSUE. there are no checks at all against
265 * untrusted users on the local system connecting on TCP
266 * and injecting bogus routing data into the entire routing
269 * The functionality is only left here because it may be
270 * useful during development, in order to be able to get
271 * tcpdump or wireshark watching ZAPI as TCP. If you want
272 * to do that, flip the #if 1 above to #if 0. */
273 memset(sa
, 0, sizeof(*sa
));
277 /* "sun" is a #define on solaris */
278 struct sockaddr_un
*suna
= (struct sockaddr_un
*)sa
;
280 suna
->sun_family
= AF_UNIX
;
281 strlcpy(suna
->sun_path
, path
, sizeof(suna
->sun_path
));
282 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
283 *sa_len
= suna
->sun_len
= SUN_LEN(suna
);
285 *sa_len
= sizeof(suna
->sun_family
) + strlen(suna
->sun_path
);
286 #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
288 /* this is left here for future reference; Linux abstract
289 * socket namespace support can be enabled by replacing
290 * above #if 0 with #ifdef GNU_LINUX.
292 * THIS IS A SECURITY ISSUE, the abstract socket namespace
293 * does not have user/group permission control on sockets.
294 * we'd need to implement SCM_CREDENTIALS support first to
295 * check that only proper users can connect to abstract
296 * sockets. (same problem as tcp-zebra, except there is a
297 * fix with SCM_CREDENTIALS. tcp-zebra has no such fix.)
299 if (suna
->sun_path
[0] == '@')
300 suna
->sun_path
[0] = '\0';
306 static struct frr_daemon_info
*di
= NULL
;
308 void frr_init_vtydir(void)
310 snprintf(frr_vtydir
, sizeof(frr_vtydir
), DAEMON_VTY_DIR
, "", "");
313 void frr_preinit(struct frr_daemon_info
*daemon
, int argc
, char **argv
)
316 frr_is_after_fork
= false;
318 /* basename(), opencoded. */
319 char *p
= strrchr(argv
[0], '/');
320 di
->progname
= p
? p
+ 1 : argv
[0];
324 log_args_init(daemon
->early_logging
);
326 opt_extend(&os_always
);
327 if (!(di
->flags
& FRR_NO_SPLIT_CONFIG
))
329 if (!(di
->flags
& FRR_LIMITED_CLI
))
330 opt_extend(&os_fullcli
);
331 if (!(di
->flags
& FRR_NO_PID
))
333 if (!(di
->flags
& FRR_NO_PRIVSEP
))
334 opt_extend(&os_user
);
335 if (!(di
->flags
& FRR_NO_ZCLIENT
))
336 opt_extend(&os_zclient
);
337 if (!(di
->flags
& FRR_NO_TCPVTY
))
339 if (di
->flags
& FRR_DETACH_LATER
)
340 nodetach_daemon
= true;
343 snprintf(config_default
, sizeof(config_default
), "%s/%s.conf",
344 frr_sysconfdir
, di
->name
);
345 snprintf(pidfile_default
, sizeof(pidfile_default
), "%s/%s.pid",
346 frr_vtydir
, di
->name
);
347 snprintf(frr_zclientpath
, sizeof(frr_zclientpath
),
348 ZEBRA_SERV_PATH
, "", "");
350 snprintf(dbfile_default
, sizeof(dbfile_default
), "%s/%s.db",
351 frr_dbdir
, di
->name
);
354 strlcpy(frr_protoname
, di
->logname
, sizeof(frr_protoname
));
355 strlcpy(frr_protonameinst
, di
->logname
, sizeof(frr_protonameinst
));
357 di
->cli_mode
= FRR_CLI_CLASSIC
;
359 /* we may be starting with extra FDs open for whatever purpose,
360 * e.g. logging, some module, etc. Recording them here allows later
361 * checking whether an fd is valid for such extension purposes,
362 * without this we could end up e.g. logging to a BGP session fd.
365 for (int i
= 0; i
< 64; i
++) {
370 if (S_ISDIR(st
.st_mode
) || S_ISBLK(st
.st_mode
))
373 startup_fds
|= UINT64_C(0x1) << (uint64_t)i
;
376 /* note this doesn't do anything, it just grabs state, so doing it
377 * early in _preinit is perfect.
382 bool frr_is_startup_fd(int fd
)
384 return !!(startup_fds
& (UINT64_C(0x1) << (uint64_t)fd
));
387 void frr_opt_add(const char *optstr
, const struct option
*longopts
,
390 const struct optspec main_opts
= {optstr
, helpstr
, longopts
};
391 opt_extend(&main_opts
);
394 void frr_help_exit(int status
)
396 FILE *target
= status
? stderr
: stdout
;
399 fprintf(stderr
, "Invalid options.\n\n");
402 di
->printhelp(target
);
404 fprintf(target
, "Usage: %s [OPTION...]\n\n%s%s%s\n\n%s",
405 di
->progname
, di
->proghelp
, di
->copyright
? "\n\n" : "",
406 di
->copyright
? di
->copyright
: "", comb_helpstr
);
407 fprintf(target
, "\nReport bugs to %s\n", FRR_BUG_ADDRESS
);
411 struct option_chain
{
412 struct option_chain
*next
;
416 static struct option_chain
*modules
= NULL
, **modnext
= &modules
;
417 static int errors
= 0;
419 static int frr_opt(int opt
)
421 static int vty_port_set
= 0;
422 static int vty_addr_set
= 0;
423 struct option_chain
*oc
;
424 struct log_arg
*log_arg
;
432 print_version(di
->progname
);
436 di
->daemon_mode
= true;
439 oc
= XMALLOC(MTYPE_TMP
, sizeof(*oc
));
446 if (!frr_defaults_profile_valid(optarg
)) {
450 if (!strcmp(optarg
, "help"))
454 "The \"%s\" configuration profile is not valid for this FRR version.\n",
457 fprintf(ofd
, "Available profiles are:\n");
458 for (p
= frr_defaults_profiles
; *p
; p
++)
459 fprintf(ofd
, "%s%s\n",
460 strcmp(*p
, DFLT_NAME
) ? " " : " * ",
469 frr_defaults_profile_set(optarg
);
472 if (di
->flags
& FRR_NO_PID
)
474 di
->pid_file
= optarg
;
477 if (di
->flags
& FRR_NO_SPLIT_CONFIG
)
479 di
->config_file
= optarg
;
484 "-N/--pathspace option specified more than once!\n");
490 "-N option overridden by -z for zebra named socket path\n");
492 if (strchr(optarg
, '/') || strchr(optarg
, '.')) {
494 "slashes or dots are not permitted in the --pathspace option.\n");
498 di
->pathspace
= optarg
;
501 snprintf(frr_zclientpath
, sizeof(frr_zclientpath
),
502 ZEBRA_SERV_PATH
, "/", di
->pathspace
);
503 snprintf(frr_vtydir
, sizeof(frr_vtydir
), DAEMON_VTY_DIR
, "/",
505 snprintf(pidfile_default
, sizeof(pidfile_default
), "%s/%s.pid",
506 frr_vtydir
, di
->name
);
509 vrf_set_default_name(optarg
);
513 if (di
->flags
& FRR_NO_PID
)
515 di
->db_file
= optarg
;
519 if (di
->flags
& FRR_NO_SPLIT_CONFIG
)
524 if (di
->flags
& FRR_LIMITED_CLI
)
529 di
->zpathspace
= true;
532 "-z option overrides -N option for zebra named socket path\n");
533 if (di
->flags
& FRR_NO_ZCLIENT
)
535 strlcpy(frr_zclientpath
, optarg
, sizeof(frr_zclientpath
));
538 if (di
->flags
& FRR_NO_TCPVTY
)
542 "-A option specified more than once!\n");
547 di
->vty_addr
= optarg
;
550 if (di
->flags
& FRR_NO_TCPVTY
)
554 "-P option specified more than once!\n");
559 di
->vty_port
= strtoul(optarg
, &err
, 0);
560 if (*err
|| !*optarg
) {
562 "invalid port number \"%s\" for -P option\n",
569 if (di
->vty_sock_path
) {
571 "--vty_socket option specified more than once!\n");
575 di
->vty_sock_path
= optarg
;
577 case OPTION_MODULEDIR
:
578 if (di
->module_path
) {
580 "----moduledir option specified more than once!\n");
584 di
->module_path
= optarg
;
586 case OPTION_SCRIPTDIR
:
587 if (di
->script_path
) {
588 fprintf(stderr
, "--scriptdir option specified more than once!\n");
592 di
->script_path
= optarg
;
595 di
->cli_mode
= FRR_CLI_TRANSACTIONAL
;
598 if (di
->flags
& FRR_NO_PRIVSEP
)
600 di
->privs
->user
= optarg
;
603 if (di
->flags
& FRR_NO_PRIVSEP
)
605 di
->privs
->group
= optarg
;
608 arg_len
= strlen(optarg
) + 1;
609 log_arg
= XCALLOC(MTYPE_TMP
, sizeof(*log_arg
) + arg_len
);
610 memcpy(log_arg
->target
, optarg
, arg_len
);
611 log_args_add_tail(di
->early_logging
, log_arg
);
613 case OPTION_LOGLEVEL
:
614 di
->early_loglevel
= optarg
;
617 di
->log_always
= true;
619 case OPTION_LIMIT_FDS
:
620 di
->limit_fds
= strtoul(optarg
, &err
, 0);
628 int frr_getopt(int argc
, char *const argv
[], int *longindex
)
633 comb_next_lo
->name
= NULL
;
636 opt
= getopt_long(argc
, argv
, comb_optstr
, comb_lo
, &lidx
);
641 if (opt
== -1 && errors
)
648 static void frr_mkdir(const char *path
, bool strip
)
653 struct zprivs_ids_t ids
;
656 char *slash
= strrchr(path
, '/');
661 if (plen
> sizeof(buf
) - 1)
663 memcpy(buf
, path
, plen
);
668 /* o+rx (..5) is needed for the frrvty group to work properly;
669 * without it, users in the frrvty group can't access the vty sockets.
672 ret
= mkdir(path
, 0755);
676 /* if EEXIST, return without touching the permissions,
677 * so user-set custom permissions are left in place
682 flog_err(EC_LIB_SYSTEM_CALL
, "failed to mkdir \"%s\": %s", path
,
687 zprivs_get_ids(&ids
);
688 if (chown(path
, ids
.uid_normal
, ids
.gid_normal
))
689 flog_err(EC_LIB_SYSTEM_CALL
, "failed to chown \"%s\": %s", path
,
693 static void _err_print(const void *cookie
, const char *errstr
)
695 const char *prefix
= (const char *)cookie
;
697 fprintf(stderr
, "%s: %s\n", prefix
, errstr
);
700 static struct event_loop
*master
;
701 struct event_loop
*frr_init(void)
703 struct option_chain
*oc
;
704 struct log_arg
*log_arg
;
705 struct frrmod_runtime
*module
;
706 struct zprivs_ids_t ids
;
707 char p_instance
[16] = "", p_pathspace
[256] = "";
710 dir
= di
->module_path
? di
->module_path
: frr_moduledir
;
713 frr_defaults_apply();
716 snprintf(frr_protonameinst
, sizeof(frr_protonameinst
), "%s[%u]",
717 di
->logname
, di
->instance
);
718 snprintf(p_instance
, sizeof(p_instance
), "-%d", di
->instance
);
721 snprintf(p_pathspace
, sizeof(p_pathspace
), "%s/",
724 snprintf(config_default
, sizeof(config_default
), "%s%s%s%s.conf",
725 frr_sysconfdir
, p_pathspace
, di
->name
, p_instance
);
726 snprintf(pidfile_default
, sizeof(pidfile_default
), "%s/%s%s.pid",
727 frr_vtydir
, di
->name
, p_instance
);
729 snprintf(dbfile_default
, sizeof(dbfile_default
), "%s/%s%s%s.db",
730 frr_dbdir
, p_pathspace
, di
->name
, p_instance
);
733 zprivs_preinit(di
->privs
);
734 zprivs_get_ids(&ids
);
736 zlog_init(di
->progname
, di
->logname
, di
->instance
,
737 ids
.uid_normal
, ids
.gid_normal
);
739 while ((log_arg
= log_args_pop(di
->early_logging
))) {
740 command_setup_early_logging(log_arg
->target
,
742 /* this is a bit of a hack,
743 but need to notice when
744 the target is stdout */
745 if (strcmp(log_arg
->target
, "stdout") == 0)
746 logging_to_stdout
= true;
747 XFREE(MTYPE_TMP
, log_arg
);
750 if (!frr_zclient_addr(&zclient_addr
, &zclient_addr_len
,
752 fprintf(stderr
, "Invalid zserv socket path: %s\n",
757 /* don't mkdir these as root... */
758 if (!(di
->flags
& FRR_NO_PRIVSEP
)) {
759 if (!di
->pid_file
|| !di
->vty_path
)
760 frr_mkdir(frr_vtydir
, false);
762 frr_mkdir(di
->pid_file
, true);
764 frr_mkdir(di
->vty_path
, true);
767 frrmod_init(di
->module
);
769 modules
= (oc
= modules
)->next
;
770 module
= frrmod_load(oc
->arg
, dir
, _err_print
, __func__
);
773 XFREE(MTYPE_TMP
, oc
);
776 zprivs_init(di
->privs
);
778 master
= event_master_create(NULL
);
779 signal_init(master
, di
->n_signals
, di
->signals
);
780 hook_call(frr_early_init
, master
);
784 di
->db_file
= dbfile_default
;
785 db_init("%s", di
->db_file
);
788 if (di
->flags
& FRR_LIMITED_CLI
)
793 vty_init(master
, di
->log_always
);
797 #ifdef HAVE_SCRIPTING
798 frrscript_init(di
->script_path
? di
->script_path
: frr_scriptdir
);
805 nb_init(master
, di
->yang_modules
, di
->n_yang_modules
, true);
806 if (nb_db_init() != NB_OK
)
807 flog_warn(EC_LIB_NB_DATABASE
,
808 "%s: failed to initialize northbound database",
816 const char *frr_get_progname(void)
818 return di
? di
->progname
: NULL
;
821 enum frr_cli_mode
frr_get_cli_mode(void)
823 return di
? di
->cli_mode
: FRR_CLI_CLASSIC
;
826 uint32_t frr_get_fd_limit(void)
828 return di
? di
->limit_fds
: 0;
831 static int rcvd_signal
= 0;
833 static void rcv_signal(int signum
)
835 rcvd_signal
= signum
;
836 /* poll() is interrupted by the signal; handled below */
839 static void frr_daemon_wait(int fd
)
841 struct pollfd pfd
[1];
845 sigset_t sigs
, prevsigs
;
848 sigaddset(&sigs
, SIGTSTP
);
849 sigaddset(&sigs
, SIGQUIT
);
850 sigaddset(&sigs
, SIGINT
);
851 sigprocmask(SIG_BLOCK
, &sigs
, &prevsigs
);
853 struct sigaction sa
= {
854 .sa_handler
= rcv_signal
, .sa_flags
= SA_RESETHAND
,
856 sigemptyset(&sa
.sa_mask
);
857 sigaction(SIGTSTP
, &sa
, NULL
);
858 sigaction(SIGQUIT
, &sa
, NULL
);
859 sigaction(SIGINT
, &sa
, NULL
);
866 pfd
[0].events
= POLLIN
;
870 #if defined(HAVE_PPOLL)
871 ret
= ppoll(pfd
, 1, NULL
, &prevsigs
);
872 #elif defined(HAVE_POLLTS)
873 ret
= pollts(pfd
, 1, NULL
, &prevsigs
);
875 /* racy -- only used on FreeBSD 9 */
877 sigprocmask(SIG_SETMASK
, &prevsigs
, &tmpsigs
);
878 ret
= poll(pfd
, 1, -1);
879 sigprocmask(SIG_SETMASK
, &tmpsigs
, NULL
);
881 if (ret
< 0 && errno
!= EINTR
&& errno
!= EAGAIN
) {
885 switch (rcvd_signal
) {
889 nrecv
= recv(fd
, buf
, sizeof(buf
), 0);
891 && (errno
== EINTR
|| errno
== EAGAIN
));
894 sigaction(SIGTSTP
, &sa
, NULL
);
906 exitpid
= waitpid(-1, &exitstat
, WNOHANG
);
908 /* child successfully went to main loop & closed socket */
911 /* child failed one way or another ... */
912 if (WIFEXITED(exitstat
) && WEXITSTATUS(exitstat
) == 0)
913 /* can happen in --terminal case if exit is fast enough */
915 else if (WIFEXITED(exitstat
))
916 fprintf(stderr
, "%s failed to start, exited %d\n", di
->name
,
917 WEXITSTATUS(exitstat
));
918 else if (WIFSIGNALED(exitstat
))
919 fprintf(stderr
, "%s crashed in startup, signal %d\n", di
->name
,
922 fprintf(stderr
, "%s failed to start, unknown problem\n",
927 static int daemon_ctl_sock
= -1;
929 static void frr_daemonize(void)
934 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, fds
)) {
935 perror("socketpair() for daemon control");
954 daemon_ctl_sock
= fds
[1];
961 frr_daemon_wait(fds
[0]);
965 * Why is this a thread?
967 * The read in of config for integrated config happens *after*
968 * thread execution starts( because it is passed in via a vtysh -b -n )
969 * While if you are not using integrated config we want the ability
970 * to read the config in after thread execution starts, so that
971 * we can match this behavior.
973 static void frr_config_read_in(struct event
*t
)
975 hook_call(frr_config_pre
, master
);
977 if (!vty_read_config(vty_shared_candidate_config
, di
->config_file
,
979 && di
->backup_config_file
) {
980 char *orig
= XSTRDUP(MTYPE_TMP
, host_config_get());
982 zlog_info("Attempting to read backup config file: %s specified",
983 di
->backup_config_file
);
984 vty_read_config(vty_shared_candidate_config
,
985 di
->backup_config_file
, config_default
);
987 host_config_set(orig
);
988 XFREE(MTYPE_TMP
, orig
);
992 * Automatically commit the candidate configuration after
993 * reading the configuration file.
995 if (frr_get_cli_mode() == FRR_CLI_TRANSACTIONAL
) {
996 struct nb_context context
= {};
997 char errmsg
[BUFSIZ
] = {0};
1000 context
.client
= NB_CLIENT_CLI
;
1001 ret
= nb_candidate_commit(context
, vty_shared_candidate_config
,
1002 true, "Read configuration file", NULL
,
1003 errmsg
, sizeof(errmsg
));
1004 if (ret
!= NB_OK
&& ret
!= NB_ERR_NO_CHANGES
)
1006 "%s: failed to read configuration file: %s (%s)",
1007 __func__
, nb_err_name(ret
), errmsg
);
1010 hook_call(frr_config_post
, master
);
1013 void frr_config_fork(void)
1015 hook_call(frr_late_init
, master
);
1017 if (!(di
->flags
& FRR_NO_SPLIT_CONFIG
)) {
1018 /* Don't start execution if we are in dry-run mode */
1020 frr_config_read_in(NULL
);
1024 event_add_event(master
, frr_config_read_in
, NULL
, 0,
1028 if (di
->daemon_mode
|| di
->terminal
)
1031 frr_is_after_fork
= true;
1034 di
->pid_file
= pidfile_default
;
1035 pid_output(di
->pid_file
);
1036 zlog_tls_buffer_init();
1039 void frr_vty_serv_start(void)
1041 /* allow explicit override of vty_path in the future
1042 * (not currently set anywhere) */
1043 if (!di
->vty_path
) {
1045 char defvtydir
[256];
1047 snprintf(defvtydir
, sizeof(defvtydir
), "%s", frr_vtydir
);
1049 dir
= di
->vty_sock_path
? di
->vty_sock_path
: defvtydir
;
1052 snprintf(vtypath_default
, sizeof(vtypath_default
),
1053 "%s/%s-%d.vty", dir
, di
->name
, di
->instance
);
1055 snprintf(vtypath_default
, sizeof(vtypath_default
),
1056 "%s/%s.vty", dir
, di
->name
);
1058 di
->vty_path
= vtypath_default
;
1061 vty_serv_start(di
->vty_addr
, di
->vty_port
, di
->vty_path
);
1064 void frr_vty_serv_stop(void)
1069 unlink(di
->vty_path
);
1072 static void frr_check_detach(void)
1074 if (nodetach_term
|| nodetach_daemon
)
1077 if (daemon_ctl_sock
!= -1)
1078 close(daemon_ctl_sock
);
1079 daemon_ctl_sock
= -1;
1082 static void frr_terminal_close(int isexit
)
1086 nodetach_term
= false;
1089 if (!di
->daemon_mode
|| isexit
) {
1090 printf("\n%s exiting\n", di
->name
);
1095 printf("\n%s daemonizing\n", di
->name
);
1099 nullfd
= open("/dev/null", O_RDONLY
| O_NOCTTY
);
1101 flog_err_sys(EC_LIB_SYSTEM_CALL
,
1102 "%s: failed to open /dev/null: %s", __func__
,
1103 safe_strerror(errno
));
1107 * only redirect stdin, stdout, stderr to null when a tty also
1108 * don't redirect when stdout is set with --log stdout
1110 for (fd
= 2; fd
>= 0; fd
--)
1112 (fd
!= STDOUT_FILENO
|| !logging_to_stdout
))
1118 static struct event
*daemon_ctl_thread
= NULL
;
1120 static void frr_daemon_ctl(struct event
*t
)
1125 nr
= recv(daemon_ctl_sock
, buf
, sizeof(buf
), 0);
1126 if (nr
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1132 case 'S': /* SIGTSTP */
1133 vty_stdio_suspend();
1134 if (send(daemon_ctl_sock
, "s", 1, 0) < 0)
1135 zlog_err("%s send(\"s\") error (SIGTSTP propagation)",
1136 (di
&& di
->name
? di
->name
: ""));
1138 case 'R': /* SIGTCNT [implicit] */
1141 case 'I': /* SIGINT */
1142 di
->daemon_mode
= false;
1145 case 'Q': /* SIGQUIT */
1146 di
->daemon_mode
= true;
1152 event_add_read(master
, frr_daemon_ctl
, NULL
, daemon_ctl_sock
,
1153 &daemon_ctl_thread
);
1156 void frr_detach(void)
1158 nodetach_daemon
= false;
1162 void frr_run(struct event_loop
*master
)
1164 char instanceinfo
[64] = "";
1166 if (!(di
->flags
& FRR_MANUAL_VTY_START
))
1167 frr_vty_serv_start();
1170 snprintf(instanceinfo
, sizeof(instanceinfo
), "instance %u ",
1173 zlog_notice("%s %s starting: %svty@%d%s", di
->name
, FRR_VERSION
,
1174 instanceinfo
, di
->vty_port
, di
->startinfo
);
1177 nodetach_term
= true;
1179 vty_stdio(frr_terminal_close
);
1180 if (daemon_ctl_sock
!= -1) {
1181 set_nonblocking(daemon_ctl_sock
);
1182 event_add_read(master
, frr_daemon_ctl
, NULL
,
1183 daemon_ctl_sock
, &daemon_ctl_thread
);
1185 } else if (di
->daemon_mode
) {
1186 int nullfd
= open("/dev/null", O_RDONLY
| O_NOCTTY
);
1188 flog_err_sys(EC_LIB_SYSTEM_CALL
,
1189 "%s: failed to open /dev/null: %s",
1190 __func__
, safe_strerror(errno
));
1194 * only redirect stdin, stdout, stderr to null when a
1195 * tty also don't redirect when stdout is set with --log
1198 for (fd
= 2; fd
>= 0; fd
--)
1200 (fd
!= STDOUT_FILENO
|| !logging_to_stdout
))
1208 /* end fixed stderr startup logging */
1211 struct event thread
;
1212 while (event_fetch(master
, &thread
))
1213 event_call(&thread
);
1216 void frr_early_fini(void)
1218 hook_call(frr_early_fini
);
1225 int have_leftovers
= 0;
1227 hook_call(frr_fini
);
1238 #ifdef HAVE_SCRIPTING
1241 frr_pthread_finish();
1242 zprivs_terminate(di
->privs
);
1243 /* signal_init -> nothing needed */
1244 event_master_free(master
);
1246 zlog_tls_buffer_fini();
1248 /* frrmod_init -> nothing needed / hooks */
1251 /* also log memstats to stderr when stderr goes to a file*/
1252 if (debug_memstats_at_exit
|| !isatty(STDERR_FILENO
))
1253 have_leftovers
= log_memstats(stderr
, di
->name
);
1255 /* in case we decide at runtime that we want exit-memstats for
1257 * (only do this if we actually have something to print though)
1259 if (!debug_memstats_at_exit
|| !have_leftovers
)
1262 snprintf(filename
, sizeof(filename
), "/tmp/frr-memstats-%s-%llu-%llu",
1263 di
->name
, (unsigned long long)getpid(),
1264 (unsigned long long)time(NULL
));
1266 fp
= fopen(filename
, "w");
1268 log_memstats(fp
, di
->name
);
1274 static const char interp
[]
1275 __attribute__((section(".interp"), used
)) = INTERP
;
1278 * executable entry point for libfrr.so
1280 * note that libc initialization is skipped for this so the set of functions
1281 * that can be called is rather limited
1283 extern void _libfrr_version(void)
1284 __attribute__((visibility("hidden"), noreturn
));
1285 void _libfrr_version(void)
1287 const char banner
[] =
1288 FRR_FULL_NAME
" " FRR_VERSION
".\n"
1289 FRR_COPYRIGHT GIT_INFO
"\n"
1290 "configured with:\n " FRR_CONFIG_ARGS
"\n";
1291 write(1, banner
, sizeof(banner
) - 1);