]>
git.proxmox.com Git - mirror_frr.git/blob - lib/libfrr.c
2 * libfrr overall management functions
4 * Copyright (C) 2016 David Lamparter for NetDEF, Inc.
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)
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
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
24 #include <sys/types.h>
33 #include "memory_vty.h"
38 #include "lib_errors.h"
40 DEFINE_HOOK(frr_late_init
, (struct thread_master
* tm
), (tm
))
41 DEFINE_KOOH(frr_early_fini
, (), ())
42 DEFINE_KOOH(frr_fini
, (), ())
44 const char frr_sysconfdir
[] = SYSCONFDIR
;
45 const char frr_vtydir
[] = DAEMON_VTY_DIR
;
46 const char frr_moduledir
[] = MODULE_PATH
;
48 char frr_protoname
[256] = "NONE";
49 char frr_protonameinst
[256] = "NONE";
51 char config_default
[512];
52 char frr_zclientpath
[256];
53 static char pidfile_default
[512];
54 static char vtypath_default
[256];
56 bool debug_memstats_at_exit
= 0;
58 static char comb_optstr
[256];
59 static struct option comb_lo
[64];
60 static struct option
*comb_next_lo
= &comb_lo
[0];
61 static char comb_helpstr
[4096];
66 const struct option
*longopts
;
69 static void opt_extend(const struct optspec
*os
)
71 const struct option
*lo
;
73 strcat(comb_optstr
, os
->optstr
);
74 strcat(comb_helpstr
, os
->helpstr
);
75 for (lo
= os
->longopts
; lo
->name
; lo
++)
76 memcpy(comb_next_lo
++, lo
, sizeof(*lo
));
80 #define OPTION_VTYSOCK 1000
81 #define OPTION_MODULEDIR 1002
82 #define OPTION_LOG 1003
83 #define OPTION_LOGLEVEL 1004
85 static const struct option lo_always
[] = {
86 {"help", no_argument
, NULL
, 'h'},
87 {"version", no_argument
, NULL
, 'v'},
88 {"daemon", no_argument
, NULL
, 'd'},
89 {"module", no_argument
, NULL
, 'M'},
90 {"vty_socket", required_argument
, NULL
, OPTION_VTYSOCK
},
91 {"moduledir", required_argument
, NULL
, OPTION_MODULEDIR
},
92 {"log", required_argument
, NULL
, OPTION_LOG
},
93 {"log-level", required_argument
, NULL
, OPTION_LOGLEVEL
},
95 static const struct optspec os_always
= {
97 " -h, --help Display this help and exit\n"
98 " -v, --version Print program version\n"
99 " -d, --daemon Runs in daemon mode\n"
100 " -M, --module Load specified module\n"
101 " --vty_socket Override vty socket path\n"
102 " --moduledir Override modules directory\n"
103 " --log Set Logging to stdout, syslog, or file:<name>\n"
104 " --log-level Set Logging Level to use, debug, info, warn, etc\n",
108 static const struct option lo_cfg_pid_dry
[] = {
109 {"pid_file", required_argument
, NULL
, 'i'},
110 {"config_file", required_argument
, NULL
, 'f'},
111 {"pathspace", required_argument
, NULL
, 'N'},
112 {"dryrun", no_argument
, NULL
, 'C'},
113 {"terminal", no_argument
, NULL
, 't'},
115 static const struct optspec os_cfg_pid_dry
= {
117 " -f, --config_file Set configuration file name\n"
118 " -i, --pid_file Set process identifier file name\n"
119 " -N, --pathspace Insert prefix into config & socket paths\n"
120 " -C, --dryrun Check configuration for validity and exit\n"
121 " -t, --terminal Open terminal session on stdio\n"
122 " -d -t Daemonize after terminal session ends\n",
126 static const struct option lo_zclient
[] = {
127 {"socket", required_argument
, NULL
, 'z'},
129 static const struct optspec os_zclient
= {
130 "z:", " -z, --socket Set path of zebra socket\n", lo_zclient
};
133 static const struct option lo_vty
[] = {
134 {"vty_addr", required_argument
, NULL
, 'A'},
135 {"vty_port", required_argument
, NULL
, 'P'},
137 static const struct optspec os_vty
= {
139 " -A, --vty_addr Set vty's bind address\n"
140 " -P, --vty_port Set vty's port number\n",
144 static const struct option lo_user
[] = {{"user", required_argument
, NULL
, 'u'},
145 {"group", required_argument
, NULL
, 'g'},
147 static const struct optspec os_user
= {"u:g:",
148 " -u, --user User to run as\n"
149 " -g, --group Group to run as\n",
153 bool frr_zclient_addr(struct sockaddr_storage
*sa
, socklen_t
*sa_len
,
156 memset(sa
, 0, sizeof(*sa
));
159 path
= ZEBRA_SERV_PATH
;
161 if (!strncmp(path
, ZAPI_TCP_PATHNAME
, strlen(ZAPI_TCP_PATHNAME
))) {
162 /* note: this functionality is disabled at bottom */
164 int port
= ZEBRA_PORT
;
166 struct sockaddr_in
*sin
= NULL
;
167 struct sockaddr_in6
*sin6
= NULL
;
169 path
+= strlen(ZAPI_TCP_PATHNAME
);
189 port
= strtoul(path
, &err
, 10);
200 sin
= (struct sockaddr_in
*)sa
;
201 sin
->sin_port
= htons(port
);
202 sin
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
203 *sa_len
= sizeof(struct sockaddr_in
);
204 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
205 sin
->sin_len
= *sa_len
;
209 sin6
= (struct sockaddr_in6
*)sa
;
210 sin6
->sin6_port
= htons(port
);
211 inet_pton(AF_INET6
, "::1", &sin6
->sin6_addr
);
212 *sa_len
= sizeof(struct sockaddr_in6
);
214 sin6
->sin6_len
= *sa_len
;
220 /* force-disable this path, because tcp-zebra is a
221 * SECURITY ISSUE. there are no checks at all against
222 * untrusted users on the local system connecting on TCP
223 * and injecting bogus routing data into the entire routing
226 * The functionality is only left here because it may be
227 * useful during development, in order to be able to get
228 * tcpdump or wireshark watching ZAPI as TCP. If you want
229 * to do that, flip the #if 1 above to #if 0. */
230 memset(sa
, 0, sizeof(*sa
));
234 /* "sun" is a #define on solaris */
235 struct sockaddr_un
*suna
= (struct sockaddr_un
*)sa
;
237 suna
->sun_family
= AF_UNIX
;
238 strlcpy(suna
->sun_path
, path
, sizeof(suna
->sun_path
));
239 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
240 *sa_len
= suna
->sun_len
= SUN_LEN(suna
);
242 *sa_len
= sizeof(suna
->sun_family
) + strlen(suna
->sun_path
);
243 #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
245 /* this is left here for future reference; Linux abstract
246 * socket namespace support can be enabled by replacing
247 * above #if 0 with #ifdef GNU_LINUX.
249 * THIS IS A SECURITY ISSUE, the abstract socket namespace
250 * does not have user/group permission control on sockets.
251 * we'd need to implement SCM_CREDENTIALS support first to
252 * check that only proper users can connect to abstract
253 * sockets. (same problem as tcp-zebra, except there is a
254 * fix with SCM_CREDENTIALS. tcp-zebra has no such fix.)
256 if (suna
->sun_path
[0] == '@')
257 suna
->sun_path
[0] = '\0';
263 static struct frr_daemon_info
*di
= NULL
;
265 void frr_preinit(struct frr_daemon_info
*daemon
, int argc
, char **argv
)
269 /* basename(), opencoded. */
270 char *p
= strrchr(argv
[0], '/');
271 di
->progname
= p
? p
+ 1 : argv
[0];
275 opt_extend(&os_always
);
276 if (!(di
->flags
& FRR_NO_CFG_PID_DRY
))
277 opt_extend(&os_cfg_pid_dry
);
278 if (!(di
->flags
& FRR_NO_PRIVSEP
))
279 opt_extend(&os_user
);
280 if (!(di
->flags
& FRR_NO_ZCLIENT
))
281 opt_extend(&os_zclient
);
282 if (!(di
->flags
& FRR_NO_TCPVTY
))
285 snprintf(config_default
, sizeof(config_default
), "%s/%s.conf",
286 frr_sysconfdir
, di
->name
);
287 snprintf(pidfile_default
, sizeof(pidfile_default
), "%s/%s.pid",
288 frr_vtydir
, di
->name
);
290 strlcpy(frr_protoname
, di
->logname
, sizeof(frr_protoname
));
291 strlcpy(frr_protonameinst
, di
->logname
, sizeof(frr_protonameinst
));
293 strlcpy(frr_zclientpath
, ZEBRA_SERV_PATH
, sizeof(frr_zclientpath
));
296 void frr_opt_add(const char *optstr
, const struct option
*longopts
,
299 const struct optspec main_opts
= {optstr
, helpstr
, longopts
};
300 opt_extend(&main_opts
);
303 void frr_help_exit(int status
)
305 FILE *target
= status
? stderr
: stdout
;
308 fprintf(stderr
, "Invalid options.\n\n");
311 di
->printhelp(target
);
313 fprintf(target
, "Usage: %s [OPTION...]\n\n%s%s%s\n\n%s",
314 di
->progname
, di
->proghelp
, di
->copyright
? "\n\n" : "",
315 di
->copyright
? di
->copyright
: "", comb_helpstr
);
316 fprintf(target
, "\nReport bugs to %s\n", FRR_BUG_ADDRESS
);
320 struct option_chain
{
321 struct option_chain
*next
;
325 static struct option_chain
*modules
= NULL
, **modnext
= &modules
;
326 static int errors
= 0;
328 static int frr_opt(int opt
)
330 static int vty_port_set
= 0;
331 static int vty_addr_set
= 0;
332 struct option_chain
*oc
;
340 print_version(di
->progname
);
347 oc
= XMALLOC(MTYPE_TMP
, sizeof(*oc
));
354 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
356 di
->pid_file
= optarg
;
359 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
361 di
->config_file
= optarg
;
364 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
368 "-N/--pathspace option specified more than once!\n");
372 if (strchr(optarg
, '/') || strchr(optarg
, '.')) {
374 "slashes or dots are not permitted in the --pathspace option.\n");
378 di
->pathspace
= optarg
;
381 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
386 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
391 if (di
->flags
& FRR_NO_ZCLIENT
)
393 strlcpy(frr_zclientpath
, optarg
, sizeof(frr_zclientpath
));
396 if (di
->flags
& FRR_NO_TCPVTY
)
400 "-A option specified more than once!\n");
405 di
->vty_addr
= optarg
;
408 if (di
->flags
& FRR_NO_TCPVTY
)
412 "-P option specified more than once!\n");
417 di
->vty_port
= strtoul(optarg
, &err
, 0);
418 if (*err
|| !*optarg
) {
420 "invalid port number \"%s\" for -P option\n",
427 if (di
->vty_sock_path
) {
429 "--vty_socket option specified more than once!\n");
433 di
->vty_sock_path
= optarg
;
435 case OPTION_MODULEDIR
:
436 if (di
->module_path
) {
438 "----moduledir option specified more than once!\n");
442 di
->module_path
= optarg
;
445 if (di
->flags
& FRR_NO_PRIVSEP
)
447 di
->privs
->user
= optarg
;
450 if (di
->flags
& FRR_NO_PRIVSEP
)
452 di
->privs
->group
= optarg
;
455 di
->early_logging
= optarg
;
457 case OPTION_LOGLEVEL
:
458 di
->early_loglevel
= optarg
;
466 int frr_getopt(int argc
, char *const argv
[], int *longindex
)
471 comb_next_lo
->name
= NULL
;
474 opt
= getopt_long(argc
, argv
, comb_optstr
, comb_lo
, &lidx
);
479 if (opt
== -1 && errors
)
486 static void frr_mkdir(const char *path
, bool strip
)
491 struct zprivs_ids_t ids
;
494 char *slash
= strrchr(path
, '/');
499 if (plen
> sizeof(buf
) - 1)
501 memcpy(buf
, path
, plen
);
506 /* o+rx (..5) is needed for the frrvty group to work properly;
507 * without it, users in the frrvty group can't access the vty sockets.
510 ret
= mkdir(path
, 0755);
514 /* if EEXIST, return without touching the permissions,
515 * so user-set custom permissions are left in place
520 flog_err(EC_LIB_SYSTEM_CALL
, "failed to mkdir \"%s\": %s", path
,
525 zprivs_get_ids(&ids
);
526 if (chown(path
, ids
.uid_normal
, ids
.gid_normal
))
527 flog_err(EC_LIB_SYSTEM_CALL
, "failed to chown \"%s\": %s", path
,
531 static struct thread_master
*master
;
532 struct thread_master
*frr_init(void)
534 struct option_chain
*oc
;
535 struct frrmod_runtime
*module
;
537 char p_instance
[16] = "", p_pathspace
[256] = "";
539 dir
= di
->module_path
? di
->module_path
: frr_moduledir
;
544 snprintf(frr_protonameinst
, sizeof(frr_protonameinst
), "%s[%u]",
545 di
->logname
, di
->instance
);
546 snprintf(p_instance
, sizeof(p_instance
), "-%d", di
->instance
);
549 snprintf(p_pathspace
, sizeof(p_pathspace
), "%s/",
552 snprintf(config_default
, sizeof(config_default
), "%s%s%s%s.conf",
553 frr_sysconfdir
, p_pathspace
, di
->name
, p_instance
);
554 snprintf(pidfile_default
, sizeof(pidfile_default
), "%s/%s%s%s.pid",
555 frr_vtydir
, p_pathspace
, di
->name
, p_instance
);
557 zprivs_preinit(di
->privs
);
559 openzlog(di
->progname
, di
->logname
, di
->instance
,
560 LOG_CONS
| LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
562 command_setup_early_logging(di
->early_logging
, di
->early_loglevel
);
564 if (!frr_zclient_addr(&zclient_addr
, &zclient_addr_len
,
566 fprintf(stderr
, "Invalid zserv socket path: %s\n",
571 /* don't mkdir these as root... */
572 if (!(di
->flags
& FRR_NO_PRIVSEP
)) {
573 if (!di
->pid_file
|| !di
->vty_path
)
574 frr_mkdir(frr_vtydir
, false);
576 frr_mkdir(di
->pid_file
, true);
578 frr_mkdir(di
->vty_path
, true);
581 frrmod_init(di
->module
);
583 modules
= (oc
= modules
)->next
;
584 module
= frrmod_load(oc
->arg
, dir
, moderr
, sizeof(moderr
));
586 fprintf(stderr
, "%s\n", moderr
);
589 XFREE(MTYPE_TMP
, oc
);
592 zprivs_init(di
->privs
);
594 master
= thread_master_create(NULL
);
595 signal_init(master
, di
->n_signals
, di
->signals
);
597 if (di
->flags
& FRR_LIMITED_CLI
)
610 static int rcvd_signal
= 0;
612 static void rcv_signal(int signum
)
614 rcvd_signal
= signum
;
615 /* poll() is interrupted by the signal; handled below */
618 static void frr_daemon_wait(int fd
)
620 struct pollfd pfd
[1];
624 sigset_t sigs
, prevsigs
;
627 sigaddset(&sigs
, SIGTSTP
);
628 sigaddset(&sigs
, SIGQUIT
);
629 sigaddset(&sigs
, SIGINT
);
630 sigprocmask(SIG_BLOCK
, &sigs
, &prevsigs
);
632 struct sigaction sa
= {
633 .sa_handler
= rcv_signal
, .sa_flags
= SA_RESETHAND
,
635 sigemptyset(&sa
.sa_mask
);
636 sigaction(SIGTSTP
, &sa
, NULL
);
637 sigaction(SIGQUIT
, &sa
, NULL
);
638 sigaction(SIGINT
, &sa
, NULL
);
645 pfd
[0].events
= POLLIN
;
649 #if defined(HAVE_PPOLL)
650 ret
= ppoll(pfd
, 1, NULL
, &prevsigs
);
651 #elif defined(HAVE_POLLTS)
652 ret
= pollts(pfd
, 1, NULL
, &prevsigs
);
654 /* racy -- only used on FreeBSD 9 */
656 sigprocmask(SIG_SETMASK
, &prevsigs
, &tmpsigs
);
657 ret
= poll(pfd
, 1, -1);
658 sigprocmask(SIG_SETMASK
, &tmpsigs
, NULL
);
660 if (ret
< 0 && errno
!= EINTR
&& errno
!= EAGAIN
) {
664 switch (rcvd_signal
) {
668 nrecv
= recv(fd
, buf
, sizeof(buf
), 0);
670 && (errno
== EINTR
|| errno
== EAGAIN
));
673 sigaction(SIGTSTP
, &sa
, NULL
);
685 exitpid
= waitpid(-1, &exitstat
, WNOHANG
);
687 /* child successfully went to main loop & closed socket */
690 /* child failed one way or another ... */
691 if (WIFEXITED(exitstat
) && WEXITSTATUS(exitstat
) == 0)
692 /* can happen in --terminal case if exit is fast enough */
694 else if (WIFEXITED(exitstat
))
695 fprintf(stderr
, "%s failed to start, exited %d\n", di
->name
,
696 WEXITSTATUS(exitstat
));
697 else if (WIFSIGNALED(exitstat
))
698 fprintf(stderr
, "%s crashed in startup, signal %d\n", di
->name
,
701 fprintf(stderr
, "%s failed to start, unknown problem\n",
706 static int daemon_ctl_sock
= -1;
708 static void frr_daemonize(void)
713 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, fds
)) {
714 perror("socketpair() for daemon control");
733 daemon_ctl_sock
= fds
[1];
738 frr_daemon_wait(fds
[0]);
742 * Why is this a thread?
744 * The read in of config for integrated config happens *after*
745 * thread execution starts( because it is passed in via a vtysh -b -n )
746 * While if you are not using integrated config we want the ability
747 * to read the config in after thread execution starts, so that
748 * we can match this behavior.
750 static int frr_config_read_in(struct thread
*t
)
752 if (!vty_read_config(di
->config_file
, config_default
) &&
753 di
->backup_config_file
) {
754 char *orig
= XSTRDUP(MTYPE_TMP
, host_config_get());
756 zlog_info("Attempting to read backup config file: %s specified",
757 di
->backup_config_file
);
758 vty_read_config(di
->backup_config_file
, config_default
);
760 host_config_set(orig
);
761 XFREE(MTYPE_TMP
, orig
);
766 void frr_config_fork(void)
768 hook_call(frr_late_init
, master
);
770 /* Don't start execution if we are in dry-run mode */
772 frr_config_read_in(NULL
);
776 thread_add_event(master
, frr_config_read_in
, NULL
, 0, &di
->read_in
);
778 if (di
->daemon_mode
|| di
->terminal
)
782 di
->pid_file
= pidfile_default
;
783 pid_output(di
->pid_file
);
786 void frr_vty_serv(void)
788 /* allow explicit override of vty_path in the future
789 * (not currently set anywhere) */
794 snprintf(defvtydir
, sizeof(defvtydir
), "%s%s%s", frr_vtydir
,
795 di
->pathspace
? "/" : "",
796 di
->pathspace
? di
->pathspace
: "");
798 dir
= di
->vty_sock_path
? di
->vty_sock_path
: defvtydir
;
801 snprintf(vtypath_default
, sizeof(vtypath_default
),
802 "%s/%s-%d.vty", dir
, di
->name
, di
->instance
);
804 snprintf(vtypath_default
, sizeof(vtypath_default
),
805 "%s/%s.vty", dir
, di
->name
);
807 di
->vty_path
= vtypath_default
;
810 vty_serv_sock(di
->vty_addr
, di
->vty_port
, di
->vty_path
);
813 static void frr_terminal_close(int isexit
)
817 if (daemon_ctl_sock
!= -1) {
818 close(daemon_ctl_sock
);
819 daemon_ctl_sock
= -1;
822 if (!di
->daemon_mode
|| isexit
) {
823 printf("\n%s exiting\n", di
->name
);
828 printf("\n%s daemonizing\n", di
->name
);
832 nullfd
= open("/dev/null", O_RDONLY
| O_NOCTTY
);
834 flog_err_sys(EC_LIB_SYSTEM_CALL
,
835 "%s: failed to open /dev/null: %s", __func__
,
836 safe_strerror(errno
));
845 static struct thread
*daemon_ctl_thread
= NULL
;
847 static int frr_daemon_ctl(struct thread
*t
)
852 nr
= recv(daemon_ctl_sock
, buf
, sizeof(buf
), 0);
853 if (nr
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
859 case 'S': /* SIGTSTP */
861 if (send(daemon_ctl_sock
, "s", 1, 0) < 0)
862 zlog_err("%s send(\"s\") error (SIGTSTP propagation)",
863 (di
&& di
->name
? di
->name
: ""));
865 case 'R': /* SIGTCNT [implicit] */
868 case 'I': /* SIGINT */
869 di
->daemon_mode
= false;
872 case 'Q': /* SIGQUIT */
873 di
->daemon_mode
= true;
879 thread_add_read(master
, frr_daemon_ctl
, NULL
, daemon_ctl_sock
,
884 void frr_run(struct thread_master
*master
)
886 char instanceinfo
[64] = "";
891 snprintf(instanceinfo
, sizeof(instanceinfo
), "instance %u ",
894 zlog_notice("%s %s starting: %svty@%d%s", di
->name
, FRR_VERSION
,
895 instanceinfo
, di
->vty_port
, di
->startinfo
);
898 vty_stdio(frr_terminal_close
);
899 if (daemon_ctl_sock
!= -1) {
900 set_nonblocking(daemon_ctl_sock
);
901 thread_add_read(master
, frr_daemon_ctl
, NULL
,
902 daemon_ctl_sock
, &daemon_ctl_thread
);
904 } else if (di
->daemon_mode
) {
905 int nullfd
= open("/dev/null", O_RDONLY
| O_NOCTTY
);
907 flog_err_sys(EC_LIB_SYSTEM_CALL
,
908 "%s: failed to open /dev/null: %s",
909 __func__
, safe_strerror(errno
));
917 if (daemon_ctl_sock
!= -1)
918 close(daemon_ctl_sock
);
919 daemon_ctl_sock
= -1;
922 /* end fixed stderr startup logging */
923 zlog_startup_stderr
= false;
925 struct thread thread
;
926 while (thread_fetch(master
, &thread
))
927 thread_call(&thread
);
930 void frr_early_fini(void)
932 hook_call(frr_early_fini
);
943 /* memory_init -> nothing needed */
947 zprivs_terminate(di
->privs
);
948 /* signal_init -> nothing needed */
949 thread_master_free(master
);
952 /* frrmod_init -> nothing needed / hooks */
954 if (!debug_memstats_at_exit
)
957 have_leftovers
= log_memstats(stderr
, di
->name
);
959 /* in case we decide at runtime that we want exit-memstats for
960 * a daemon, but it has no stderr because it's daemonized
961 * (only do this if we actually have something to print though)
966 snprintf(filename
, sizeof(filename
), "/tmp/frr-memstats-%s-%llu-%llu",
967 di
->name
, (unsigned long long)getpid(),
968 (unsigned long long)time(NULL
));
970 fp
= fopen(filename
, "w");
972 log_memstats(fp
, di
->name
);