]>
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"
39 DEFINE_HOOK(frr_late_init
, (struct thread_master
* tm
), (tm
))
40 DEFINE_KOOH(frr_early_fini
, (), ())
41 DEFINE_KOOH(frr_fini
, (), ())
43 const char frr_sysconfdir
[] = SYSCONFDIR
;
44 const char frr_vtydir
[] = DAEMON_VTY_DIR
;
45 const char frr_moduledir
[] = MODULE_PATH
;
47 char frr_protoname
[256] = "NONE";
48 char frr_protonameinst
[256] = "NONE";
50 char config_default
[256];
51 char frr_zclientpath
[256];
52 static char pidfile_default
[256];
53 static char vtypath_default
[256];
55 bool debug_memstats_at_exit
= 0;
57 static char comb_optstr
[256];
58 static struct option comb_lo
[64];
59 static struct option
*comb_next_lo
= &comb_lo
[0];
60 static char comb_helpstr
[4096];
65 const struct option
*longopts
;
68 static void opt_extend(const struct optspec
*os
)
70 const struct option
*lo
;
72 strcat(comb_optstr
, os
->optstr
);
73 strcat(comb_helpstr
, os
->helpstr
);
74 for (lo
= os
->longopts
; lo
->name
; lo
++)
75 memcpy(comb_next_lo
++, lo
, sizeof(*lo
));
79 #define OPTION_VTYSOCK 1000
80 #define OPTION_MODULEDIR 1002
82 static const struct option lo_always
[] = {
83 {"help", no_argument
, NULL
, 'h'},
84 {"version", no_argument
, NULL
, 'v'},
85 {"daemon", no_argument
, NULL
, 'd'},
86 {"module", no_argument
, NULL
, 'M'},
87 {"vty_socket", required_argument
, NULL
, OPTION_VTYSOCK
},
88 {"moduledir", required_argument
, NULL
, OPTION_MODULEDIR
},
90 static const struct optspec os_always
= {
92 " -h, --help Display this help and exit\n"
93 " -v, --version Print program version\n"
94 " -d, --daemon Runs in daemon mode\n"
95 " -M, --module Load specified module\n"
96 " --vty_socket Override vty socket path\n"
97 " --moduledir Override modules directory\n",
101 static const struct option lo_cfg_pid_dry
[] = {
102 {"pid_file", required_argument
, NULL
, 'i'},
103 {"config_file", required_argument
, NULL
, 'f'},
104 {"pathspace", required_argument
, NULL
, 'N'},
105 {"dryrun", no_argument
, NULL
, 'C'},
106 {"terminal", no_argument
, NULL
, 't'},
108 static const struct optspec os_cfg_pid_dry
= {
110 " -f, --config_file Set configuration file name\n"
111 " -i, --pid_file Set process identifier file name\n"
112 " -N, --pathspace Insert prefix into config & socket paths\n"
113 " -C, --dryrun Check configuration for validity and exit\n"
114 " -t, --terminal Open terminal session on stdio\n"
115 " -d -t Daemonize after terminal session ends\n",
119 static const struct option lo_zclient
[] = {
120 {"socket", required_argument
, NULL
, 'z'},
122 static const struct optspec os_zclient
= {
123 "z:", " -z, --socket Set path of zebra socket\n", lo_zclient
};
126 static const struct option lo_vty
[] = {
127 {"vty_addr", required_argument
, NULL
, 'A'},
128 {"vty_port", required_argument
, NULL
, 'P'},
130 static const struct optspec os_vty
= {
132 " -A, --vty_addr Set vty's bind address\n"
133 " -P, --vty_port Set vty's port number\n",
137 static const struct option lo_user
[] = {{"user", required_argument
, NULL
, 'u'},
138 {"group", required_argument
, NULL
, 'g'},
140 static const struct optspec os_user
= {"u:g:",
141 " -u, --user User to run as\n"
142 " -g, --group Group to run as\n",
146 bool frr_zclient_addr(struct sockaddr_storage
*sa
, socklen_t
*sa_len
,
149 memset(sa
, 0, sizeof(*sa
));
152 path
= ZEBRA_SERV_PATH
;
154 if (!strncmp(path
, ZAPI_TCP_PATHNAME
, strlen(ZAPI_TCP_PATHNAME
))) {
155 /* note: this functionality is disabled at bottom */
157 int port
= ZEBRA_PORT
;
159 struct sockaddr_in
*sin
= NULL
;
160 struct sockaddr_in6
*sin6
= NULL
;
162 path
+= strlen(ZAPI_TCP_PATHNAME
);
182 port
= strtoul(path
, &err
, 10);
193 sin
= (struct sockaddr_in
*)sa
;
194 sin
->sin_port
= htons(port
);
195 sin
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
196 *sa_len
= sizeof(struct sockaddr_in
);
197 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
198 sin
->sin_len
= *sa_len
;
202 sin6
= (struct sockaddr_in6
*)sa
;
203 sin6
->sin6_port
= htons(port
);
204 inet_pton(AF_INET6
, "::1", &sin6
->sin6_addr
);
205 *sa_len
= sizeof(struct sockaddr_in6
);
207 sin6
->sin6_len
= *sa_len
;
213 /* force-disable this path, because tcp-zebra is a
214 * SECURITY ISSUE. there are no checks at all against
215 * untrusted users on the local system connecting on TCP
216 * and injecting bogus routing data into the entire routing
219 * The functionality is only left here because it may be
220 * useful during development, in order to be able to get
221 * tcpdump or wireshark watching ZAPI as TCP. If you want
222 * to do that, flip the #if 1 above to #if 0. */
223 memset(sa
, 0, sizeof(*sa
));
227 /* "sun" is a #define on solaris */
228 struct sockaddr_un
*suna
= (struct sockaddr_un
*)sa
;
230 suna
->sun_family
= AF_UNIX
;
231 strlcpy(suna
->sun_path
, path
, sizeof(suna
->sun_path
));
232 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
233 *sa_len
= suna
->sun_len
= SUN_LEN(suna
);
235 *sa_len
= sizeof(suna
->sun_family
) + strlen(suna
->sun_path
);
236 #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
238 /* this is left here for future reference; Linux abstract
239 * socket namespace support can be enabled by replacing
240 * above #if 0 with #ifdef GNU_LINUX.
242 * THIS IS A SECURITY ISSUE, the abstract socket namespace
243 * does not have user/group permission control on sockets.
244 * we'd need to implement SCM_CREDENTIALS support first to
245 * check that only proper users can connect to abstract
246 * sockets. (same problem as tcp-zebra, except there is a
247 * fix with SCM_CREDENTIALS. tcp-zebra has no such fix.)
249 if (suna
->sun_path
[0] == '@')
250 suna
->sun_path
[0] = '\0';
256 static struct frr_daemon_info
*di
= NULL
;
258 void frr_preinit(struct frr_daemon_info
*daemon
, int argc
, char **argv
)
262 /* basename(), opencoded. */
263 char *p
= strrchr(argv
[0], '/');
264 di
->progname
= p
? p
+ 1 : argv
[0];
268 opt_extend(&os_always
);
269 if (!(di
->flags
& FRR_NO_CFG_PID_DRY
))
270 opt_extend(&os_cfg_pid_dry
);
271 if (!(di
->flags
& FRR_NO_PRIVSEP
))
272 opt_extend(&os_user
);
273 if (!(di
->flags
& FRR_NO_ZCLIENT
))
274 opt_extend(&os_zclient
);
275 if (!(di
->flags
& FRR_NO_TCPVTY
))
278 snprintf(config_default
, sizeof(config_default
), "%s/%s.conf",
279 frr_sysconfdir
, di
->name
);
280 snprintf(pidfile_default
, sizeof(pidfile_default
), "%s/%s.pid",
281 frr_vtydir
, di
->name
);
283 strlcpy(frr_protoname
, di
->logname
, sizeof(frr_protoname
));
284 strlcpy(frr_protonameinst
, di
->logname
, sizeof(frr_protonameinst
));
286 strlcpy(frr_zclientpath
, ZEBRA_SERV_PATH
, sizeof(frr_zclientpath
));
289 void frr_opt_add(const char *optstr
, const struct option
*longopts
,
292 const struct optspec main_opts
= {optstr
, helpstr
, longopts
};
293 opt_extend(&main_opts
);
296 void frr_help_exit(int status
)
298 FILE *target
= status
? stderr
: stdout
;
301 fprintf(stderr
, "Invalid options.\n\n");
304 di
->printhelp(target
);
306 fprintf(target
, "Usage: %s [OPTION...]\n\n%s%s%s\n\n%s",
307 di
->progname
, di
->proghelp
, di
->copyright
? "\n\n" : "",
308 di
->copyright
? di
->copyright
: "", comb_helpstr
);
309 fprintf(target
, "\nReport bugs to %s\n", FRR_BUG_ADDRESS
);
313 struct option_chain
{
314 struct option_chain
*next
;
318 static struct option_chain
*modules
= NULL
, **modnext
= &modules
;
319 static int errors
= 0;
321 static int frr_opt(int opt
)
323 static int vty_port_set
= 0;
324 static int vty_addr_set
= 0;
325 struct option_chain
*oc
;
333 print_version(di
->progname
);
340 oc
= XMALLOC(MTYPE_TMP
, sizeof(*oc
));
347 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
349 di
->pid_file
= optarg
;
352 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
354 di
->config_file
= optarg
;
357 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
361 "-N/--pathspace option specified more than once!\n");
365 if (strchr(optarg
, '/') || strchr(optarg
, '.')) {
367 "slashes or dots are not permitted in the --pathspace option.\n");
371 di
->pathspace
= optarg
;
374 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
379 if (di
->flags
& FRR_NO_CFG_PID_DRY
)
384 if (di
->flags
& FRR_NO_ZCLIENT
)
386 strlcpy(frr_zclientpath
, optarg
, sizeof(frr_zclientpath
));
389 if (di
->flags
& FRR_NO_TCPVTY
)
393 "-A option specified more than once!\n");
398 di
->vty_addr
= optarg
;
401 if (di
->flags
& FRR_NO_TCPVTY
)
405 "-P option specified more than once!\n");
410 di
->vty_port
= strtoul(optarg
, &err
, 0);
411 if (*err
|| !*optarg
) {
413 "invalid port number \"%s\" for -P option\n",
420 if (di
->vty_sock_path
) {
422 "--vty_socket option specified more than once!\n");
426 di
->vty_sock_path
= optarg
;
428 case OPTION_MODULEDIR
:
429 if (di
->module_path
) {
431 "----moduledir option specified more than once!\n");
435 di
->module_path
= optarg
;
438 if (di
->flags
& FRR_NO_PRIVSEP
)
440 di
->privs
->user
= optarg
;
443 if (di
->flags
& FRR_NO_PRIVSEP
)
445 di
->privs
->group
= optarg
;
453 int frr_getopt(int argc
, char *const argv
[], int *longindex
)
458 comb_next_lo
->name
= NULL
;
461 opt
= getopt_long(argc
, argv
, comb_optstr
, comb_lo
, &lidx
);
466 if (opt
== -1 && errors
)
473 static void frr_mkdir(const char *path
, bool strip
)
478 struct zprivs_ids_t ids
;
481 char *slash
= strrchr(path
, '/');
486 if (plen
> sizeof(buf
) - 1)
488 memcpy(buf
, path
, plen
);
493 /* o+rx (..5) is needed for the frrvty group to work properly;
494 * without it, users in the frrvty group can't access the vty sockets.
497 ret
= mkdir(path
, 0755);
501 /* if EEXIST, return without touching the permissions,
502 * so user-set custom permissions are left in place
507 zlog_warn("failed to mkdir \"%s\": %s", path
, strerror(errno
));
511 zprivs_get_ids(&ids
);
512 if (chown(path
, ids
.uid_normal
, ids
.gid_normal
))
513 zlog_warn("failed to chown \"%s\": %s", path
, strerror(errno
));
516 static struct thread_master
*master
;
517 struct thread_master
*frr_init(void)
519 struct option_chain
*oc
;
520 struct frrmod_runtime
*module
;
522 char p_instance
[16] = "", p_pathspace
[256] = "";
524 dir
= di
->module_path
? di
->module_path
: frr_moduledir
;
529 snprintf(frr_protonameinst
, sizeof(frr_protonameinst
), "%s[%u]",
530 di
->logname
, di
->instance
);
531 snprintf(p_instance
, sizeof(p_instance
), "-%d", di
->instance
);
534 snprintf(p_pathspace
, sizeof(p_pathspace
), "/%s",
537 snprintf(config_default
, sizeof(config_default
), "%s%s/%s%s.conf",
538 frr_sysconfdir
, p_pathspace
, di
->name
, p_instance
);
539 snprintf(pidfile_default
, sizeof(pidfile_default
), "%s%s/%s%s.pid",
540 frr_vtydir
, p_pathspace
, di
->name
, p_instance
);
542 zprivs_preinit(di
->privs
);
544 openzlog(di
->progname
, di
->logname
, di
->instance
,
545 LOG_CONS
| LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
546 #if defined(HAVE_CUMULUS)
547 zlog_set_level(ZLOG_DEST_SYSLOG
, zlog_default
->default_lvl
);
550 if (!frr_zclient_addr(&zclient_addr
, &zclient_addr_len
,
552 fprintf(stderr
, "Invalid zserv socket path: %s\n",
557 /* don't mkdir these as root... */
558 if (!(di
->flags
& FRR_NO_PRIVSEP
)) {
559 if (!di
->pid_file
|| !di
->vty_path
)
560 frr_mkdir(frr_vtydir
, false);
562 frr_mkdir(di
->pid_file
, true);
564 frr_mkdir(di
->vty_path
, true);
567 frrmod_init(di
->module
);
569 modules
= (oc
= modules
)->next
;
570 module
= frrmod_load(oc
->arg
, dir
, moderr
, sizeof(moderr
));
572 fprintf(stderr
, "%s\n", moderr
);
575 XFREE(MTYPE_TMP
, oc
);
578 zprivs_init(di
->privs
);
580 master
= thread_master_create(NULL
);
581 signal_init(master
, di
->n_signals
, di
->signals
);
583 if (di
->flags
& FRR_LIMITED_CLI
)
593 static int rcvd_signal
= 0;
595 static void rcv_signal(int signum
)
597 rcvd_signal
= signum
;
598 /* poll() is interrupted by the signal; handled below */
601 static void frr_daemon_wait(int fd
)
603 struct pollfd pfd
[1];
607 sigset_t sigs
, prevsigs
;
610 sigaddset(&sigs
, SIGTSTP
);
611 sigaddset(&sigs
, SIGQUIT
);
612 sigaddset(&sigs
, SIGINT
);
613 sigprocmask(SIG_BLOCK
, &sigs
, &prevsigs
);
615 struct sigaction sa
= {
616 .sa_handler
= rcv_signal
, .sa_flags
= SA_RESETHAND
,
618 sigemptyset(&sa
.sa_mask
);
619 sigaction(SIGTSTP
, &sa
, NULL
);
620 sigaction(SIGQUIT
, &sa
, NULL
);
621 sigaction(SIGINT
, &sa
, NULL
);
628 pfd
[0].events
= POLLIN
;
632 #if defined(HAVE_PPOLL)
633 ret
= ppoll(pfd
, 1, NULL
, &prevsigs
);
634 #elif defined(HAVE_POLLTS)
635 ret
= pollts(pfd
, 1, NULL
, &prevsigs
);
637 /* racy -- only used on FreeBSD 9 */
639 sigprocmask(SIG_SETMASK
, &prevsigs
, &tmpsigs
);
640 ret
= poll(pfd
, 1, -1);
641 sigprocmask(SIG_SETMASK
, &tmpsigs
, NULL
);
643 if (ret
< 0 && errno
!= EINTR
&& errno
!= EAGAIN
) {
647 switch (rcvd_signal
) {
651 nrecv
= recv(fd
, buf
, sizeof(buf
), 0);
653 && (errno
== EINTR
|| errno
== EAGAIN
));
656 sigaction(SIGTSTP
, &sa
, NULL
);
668 exitpid
= waitpid(-1, &exitstat
, WNOHANG
);
670 /* child successfully went to main loop & closed socket */
673 /* child failed one way or another ... */
674 if (WIFEXITED(exitstat
) && WEXITSTATUS(exitstat
) == 0)
675 /* can happen in --terminal case if exit is fast enough */
677 else if (WIFEXITED(exitstat
))
678 fprintf(stderr
, "%s failed to start, exited %d\n", di
->name
,
679 WEXITSTATUS(exitstat
));
680 else if (WIFSIGNALED(exitstat
))
681 fprintf(stderr
, "%s crashed in startup, signal %d\n", di
->name
,
684 fprintf(stderr
, "%s failed to start, unknown problem\n",
689 static int daemon_ctl_sock
= -1;
691 static void frr_daemonize(void)
696 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, fds
)) {
697 perror("socketpair() for daemon control");
716 daemon_ctl_sock
= fds
[1];
721 frr_daemon_wait(fds
[0]);
724 void frr_config_fork(void)
726 hook_call(frr_late_init
, master
);
728 vty_read_config(di
->config_file
, config_default
);
730 /* Don't start execution if we are in dry-run mode */
734 if (di
->daemon_mode
|| di
->terminal
)
738 di
->pid_file
= pidfile_default
;
739 pid_output(di
->pid_file
);
742 void frr_vty_serv(void)
744 /* allow explicit override of vty_path in the future
745 * (not currently set anywhere) */
750 snprintf(defvtydir
, sizeof(defvtydir
), "%s%s%s", frr_vtydir
,
751 di
->pathspace
? "/" : "",
752 di
->pathspace
? di
->pathspace
: "");
754 dir
= di
->vty_sock_path
? di
->vty_sock_path
: defvtydir
;
757 snprintf(vtypath_default
, sizeof(vtypath_default
),
758 "%s/%s-%d.vty", dir
, di
->name
, di
->instance
);
760 snprintf(vtypath_default
, sizeof(vtypath_default
),
761 "%s/%s.vty", dir
, di
->name
);
763 di
->vty_path
= vtypath_default
;
766 vty_serv_sock(di
->vty_addr
, di
->vty_port
, di
->vty_path
);
769 static void frr_terminal_close(int isexit
)
771 if (daemon_ctl_sock
!= -1) {
772 close(daemon_ctl_sock
);
773 daemon_ctl_sock
= -1;
776 if (!di
->daemon_mode
|| isexit
) {
777 printf("\n%s exiting\n", di
->name
);
782 printf("\n%s daemonizing\n", di
->name
);
786 int nullfd
= open("/dev/null", O_RDONLY
| O_NOCTTY
);
793 static struct thread
*daemon_ctl_thread
= NULL
;
795 static int frr_daemon_ctl(struct thread
*t
)
800 nr
= recv(daemon_ctl_sock
, buf
, sizeof(buf
), 0);
801 if (nr
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
807 case 'S': /* SIGTSTP */
809 send(daemon_ctl_sock
, "s", 1, 0);
811 case 'R': /* SIGTCNT [implicit] */
814 case 'I': /* SIGINT */
815 di
->daemon_mode
= false;
818 case 'Q': /* SIGQUIT */
819 di
->daemon_mode
= true;
825 thread_add_read(master
, frr_daemon_ctl
, NULL
, daemon_ctl_sock
,
830 void frr_run(struct thread_master
*master
)
832 char instanceinfo
[64] = "";
837 snprintf(instanceinfo
, sizeof(instanceinfo
), "instance %u ",
840 zlog_notice("%s %s starting: %svty@%d%s", di
->name
, FRR_VERSION
,
841 instanceinfo
, di
->vty_port
, di
->startinfo
);
844 vty_stdio(frr_terminal_close
);
845 if (daemon_ctl_sock
!= -1) {
846 set_nonblocking(daemon_ctl_sock
);
847 thread_add_read(master
, frr_daemon_ctl
, NULL
,
848 daemon_ctl_sock
, &daemon_ctl_thread
);
850 } else if (di
->daemon_mode
) {
851 int nullfd
= open("/dev/null", O_RDONLY
| O_NOCTTY
);
857 if (daemon_ctl_sock
!= -1)
858 close(daemon_ctl_sock
);
859 daemon_ctl_sock
= -1;
862 /* end fixed stderr startup logging */
863 zlog_startup_stderr
= false;
865 struct thread thread
;
866 while (thread_fetch(master
, &thread
))
867 thread_call(&thread
);
870 void frr_early_fini(void)
872 hook_call(frr_early_fini
);
883 /* memory_init -> nothing needed */
886 zprivs_terminate(di
->privs
);
887 /* signal_init -> nothing needed */
888 thread_master_free(master
);
890 /* frrmod_init -> nothing needed / hooks */
892 if (!debug_memstats_at_exit
)
895 have_leftovers
= log_memstats(stderr
, di
->name
);
897 /* in case we decide at runtime that we want exit-memstats for
898 * a daemon, but it has no stderr because it's daemonized
899 * (only do this if we actually have something to print though)
904 snprintf(filename
, sizeof(filename
),
905 "/tmp/frr-memstats-%s-%llu-%llu",
907 (unsigned long long)getpid(),
908 (unsigned long long)time(NULL
));
910 fp
= fopen(filename
, "w");
912 log_memstats(fp
, di
->name
);