]> git.proxmox.com Git - mirror_frr.git/blob - lib/libfrr.c
Merge pull request #13649 from donaldsharp/unlock_the_node_or_else
[mirror_frr.git] / lib / libfrr.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * libfrr overall management functions
4 *
5 * Copyright (C) 2016 David Lamparter for NetDEF, Inc.
6 */
7
8 #include <zebra.h>
9 #include <sys/un.h>
10
11 #include <sys/types.h>
12 #include <sys/wait.h>
13
14 #include "libfrr.h"
15 #include "getopt.h"
16 #include "privs.h"
17 #include "vty.h"
18 #include "command.h"
19 #include "lib/version.h"
20 #include "lib_vty.h"
21 #include "log_vty.h"
22 #include "zclient.h"
23 #include "module.h"
24 #include "network.h"
25 #include "lib_errors.h"
26 #include "db.h"
27 #include "northbound_cli.h"
28 #include "northbound_db.h"
29 #include "debug.h"
30 #include "frrcu.h"
31 #include "frr_pthread.h"
32 #include "defaults.h"
33 #include "frrscript.h"
34 #include "systemd.h"
35
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, (), ());
42
43 const char frr_sysconfdir[] = SYSCONFDIR;
44 char frr_vtydir[256];
45 #ifdef HAVE_SQLITE3
46 const char frr_dbdir[] = DAEMON_DB_DIR;
47 #endif
48 const char frr_moduledir[] = MODULE_PATH;
49 const char frr_scriptdir[] = SCRIPT_PATH;
50
51 char frr_protoname[256] = "NONE";
52 char frr_protonameinst[256] = "NONE";
53
54 char config_default[512];
55 char frr_zclientpath[256];
56 static char pidfile_default[1024];
57 #ifdef HAVE_SQLITE3
58 static char dbfile_default[512];
59 #endif
60 static char vtypath_default[512];
61
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;
67
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];
72
73 struct optspec {
74 const char *optstr;
75 const char *helpstr;
76 const struct option *longopts;
77 };
78
79 static void opt_extend(const struct optspec *os)
80 {
81 const struct option *lo;
82
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));
87 }
88
89
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
99
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},
115 {NULL}};
116 static const struct optspec os_always = {
117 "hvdM:F:N:o:",
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",
131 lo_always};
132
133 static bool logging_to_stdout = false; /* set when --log stdout specified */
134
135 static const struct option lo_cfg[] = {
136 {"config_file", required_argument, NULL, 'f'},
137 {"dryrun", no_argument, NULL, 'C'},
138 {NULL}};
139 static const struct optspec os_cfg = {
140 "f:C",
141 " -f, --config_file Set configuration file name\n"
142 " -C, --dryrun Check configuration for validity and exit\n",
143 lo_cfg};
144
145
146 static const struct option lo_fullcli[] = {
147 {"terminal", no_argument, NULL, 't'},
148 {"tcli", no_argument, NULL, OPTION_TCLI},
149 #ifdef HAVE_SQLITE3
150 {"db_file", required_argument, NULL, OPTION_DB_FILE},
151 #endif
152 {NULL}};
153 static const struct optspec os_fullcli = {
154 "t",
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",
158 lo_fullcli};
159
160
161 static const struct option lo_pid[] = {
162 {"pid_file", required_argument, NULL, 'i'},
163 {NULL}};
164 static const struct optspec os_pid = {
165 "i:",
166 " -i, --pid_file Set process identifier file name\n",
167 lo_pid};
168
169
170 static const struct option lo_zclient[] = {
171 {"socket", required_argument, NULL, 'z'},
172 {NULL}};
173 static const struct optspec os_zclient = {
174 "z:", " -z, --socket Set path of zebra socket\n", lo_zclient};
175
176
177 static const struct option lo_vty[] = {
178 {"vty_addr", required_argument, NULL, 'A'},
179 {"vty_port", required_argument, NULL, 'P'},
180 {NULL}};
181 static const struct optspec os_vty = {
182 "A:P:",
183 " -A, --vty_addr Set vty's bind address\n"
184 " -P, --vty_port Set vty's port number\n",
185 lo_vty};
186
187
188 static const struct option lo_user[] = {{"user", required_argument, NULL, 'u'},
189 {"group", required_argument, NULL, 'g'},
190 {NULL}};
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",
194 lo_user};
195
196 bool frr_zclient_addr(struct sockaddr_storage *sa, socklen_t *sa_len,
197 const char *path)
198 {
199 memset(sa, 0, sizeof(*sa));
200
201 if (!path)
202 path = frr_zclientpath;
203
204 if (!strncmp(path, ZAPI_TCP_PATHNAME, strlen(ZAPI_TCP_PATHNAME))) {
205 /* note: this functionality is disabled at bottom */
206 int af;
207 int port = ZEBRA_PORT;
208 char *err = NULL;
209 struct sockaddr_in *sin = NULL;
210 struct sockaddr_in6 *sin6 = NULL;
211
212 path += strlen(ZAPI_TCP_PATHNAME);
213
214 switch (path[0]) {
215 case '4':
216 path++;
217 af = AF_INET;
218 break;
219 case '6':
220 path++;
221 /* fallthrough */
222 default:
223 af = AF_INET6;
224 break;
225 }
226
227 switch (path[0]) {
228 case '\0':
229 break;
230 case ':':
231 path++;
232 port = strtoul(path, &err, 10);
233 if (*err || !*path)
234 return false;
235 break;
236 default:
237 return false;
238 }
239
240 sa->ss_family = af;
241 switch (af) {
242 case AF_INET:
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;
249 #endif
250 break;
251 case AF_INET6:
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);
256 #ifdef SIN6_LEN
257 sin6->sin6_len = *sa_len;
258 #endif
259 break;
260 }
261
262 #if 1
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
267 * domain.
268 *
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));
274 return false;
275 #endif
276 } else {
277 /* "sun" is a #define on solaris */
278 struct sockaddr_un *suna = (struct sockaddr_un *)sa;
279
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);
284 #else
285 *sa_len = sizeof(suna->sun_family) + strlen(suna->sun_path);
286 #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
287 #if 0
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.
291 *
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.)
298 */
299 if (suna->sun_path[0] == '@')
300 suna->sun_path[0] = '\0';
301 #endif
302 }
303 return true;
304 }
305
306 static struct frr_daemon_info *di = NULL;
307
308 void frr_init_vtydir(void)
309 {
310 snprintf(frr_vtydir, sizeof(frr_vtydir), DAEMON_VTY_DIR, "", "");
311 }
312
313 void frr_preinit(struct frr_daemon_info *daemon, int argc, char **argv)
314 {
315 di = daemon;
316 frr_is_after_fork = false;
317
318 /* basename(), opencoded. */
319 char *p = strrchr(argv[0], '/');
320 di->progname = p ? p + 1 : argv[0];
321
322 umask(0027);
323
324 log_args_init(daemon->early_logging);
325
326 opt_extend(&os_always);
327 if (!(di->flags & FRR_NO_SPLIT_CONFIG))
328 opt_extend(&os_cfg);
329 if (!(di->flags & FRR_LIMITED_CLI))
330 opt_extend(&os_fullcli);
331 if (!(di->flags & FRR_NO_PID))
332 opt_extend(&os_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))
338 opt_extend(&os_vty);
339 if (di->flags & FRR_DETACH_LATER)
340 nodetach_daemon = true;
341
342 frr_init_vtydir();
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, "", "");
349 #ifdef HAVE_SQLITE3
350 snprintf(dbfile_default, sizeof(dbfile_default), "%s/%s.db",
351 frr_dbdir, di->name);
352 #endif
353
354 strlcpy(frr_protoname, di->logname, sizeof(frr_protoname));
355 strlcpy(frr_protonameinst, di->logname, sizeof(frr_protonameinst));
356
357 di->cli_mode = FRR_CLI_CLASSIC;
358
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.
363 */
364 startup_fds = 0;
365 for (int i = 0; i < 64; i++) {
366 struct stat st;
367
368 if (fstat(i, &st))
369 continue;
370 if (S_ISDIR(st.st_mode) || S_ISBLK(st.st_mode))
371 continue;
372
373 startup_fds |= UINT64_C(0x1) << (uint64_t)i;
374 }
375
376 /* note this doesn't do anything, it just grabs state, so doing it
377 * early in _preinit is perfect.
378 */
379 systemd_init_env();
380 }
381
382 bool frr_is_startup_fd(int fd)
383 {
384 return !!(startup_fds & (UINT64_C(0x1) << (uint64_t)fd));
385 }
386
387 void frr_opt_add(const char *optstr, const struct option *longopts,
388 const char *helpstr)
389 {
390 const struct optspec main_opts = {optstr, helpstr, longopts};
391 opt_extend(&main_opts);
392 }
393
394 void frr_help_exit(int status)
395 {
396 FILE *target = status ? stderr : stdout;
397
398 if (status != 0)
399 fprintf(stderr, "Invalid options.\n\n");
400
401 if (di->printhelp)
402 di->printhelp(target);
403 else
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);
408 exit(status);
409 }
410
411 struct option_chain {
412 struct option_chain *next;
413 const char *arg;
414 };
415
416 static struct option_chain *modules = NULL, **modnext = &modules;
417 static int errors = 0;
418
419 static int frr_opt(int opt)
420 {
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;
425 size_t arg_len;
426 char *err;
427
428 switch (opt) {
429 case 'h':
430 frr_help_exit(0);
431 case 'v':
432 print_version(di->progname);
433 exit(0);
434 break;
435 case 'd':
436 di->daemon_mode = true;
437 break;
438 case 'M':
439 oc = XMALLOC(MTYPE_TMP, sizeof(*oc));
440 oc->arg = optarg;
441 oc->next = NULL;
442 *modnext = oc;
443 modnext = &oc->next;
444 break;
445 case 'F':
446 if (!frr_defaults_profile_valid(optarg)) {
447 const char **p;
448 FILE *ofd = stderr;
449
450 if (!strcmp(optarg, "help"))
451 ofd = stdout;
452 else
453 fprintf(stderr,
454 "The \"%s\" configuration profile is not valid for this FRR version.\n",
455 optarg);
456
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) ? " " : " * ",
461 *p);
462
463 if (ofd == stdout)
464 exit(0);
465 fprintf(ofd, "\n");
466 errors++;
467 break;
468 }
469 frr_defaults_profile_set(optarg);
470 break;
471 case 'i':
472 if (di->flags & FRR_NO_PID)
473 return 1;
474 di->pid_file = optarg;
475 break;
476 case 'f':
477 if (di->flags & FRR_NO_SPLIT_CONFIG)
478 return 1;
479 di->config_file = optarg;
480 break;
481 case 'N':
482 if (di->pathspace) {
483 fprintf(stderr,
484 "-N/--pathspace option specified more than once!\n");
485 errors++;
486 break;
487 }
488 if (di->zpathspace)
489 fprintf(stderr,
490 "-N option overridden by -z for zebra named socket path\n");
491
492 if (strchr(optarg, '/') || strchr(optarg, '.')) {
493 fprintf(stderr,
494 "slashes or dots are not permitted in the --pathspace option.\n");
495 errors++;
496 break;
497 }
498 di->pathspace = optarg;
499
500 if (!di->zpathspace)
501 snprintf(frr_zclientpath, sizeof(frr_zclientpath),
502 ZEBRA_SERV_PATH, "/", di->pathspace);
503 snprintf(frr_vtydir, sizeof(frr_vtydir), DAEMON_VTY_DIR, "/",
504 di->pathspace);
505 snprintf(pidfile_default, sizeof(pidfile_default), "%s/%s.pid",
506 frr_vtydir, di->name);
507 break;
508 case 'o':
509 vrf_set_default_name(optarg);
510 break;
511 #ifdef HAVE_SQLITE3
512 case OPTION_DB_FILE:
513 if (di->flags & FRR_NO_PID)
514 return 1;
515 di->db_file = optarg;
516 break;
517 #endif
518 case 'C':
519 if (di->flags & FRR_NO_SPLIT_CONFIG)
520 return 1;
521 di->dryrun = true;
522 break;
523 case 't':
524 if (di->flags & FRR_LIMITED_CLI)
525 return 1;
526 di->terminal = true;
527 break;
528 case 'z':
529 di->zpathspace = true;
530 if (di->pathspace)
531 fprintf(stderr,
532 "-z option overrides -N option for zebra named socket path\n");
533 if (di->flags & FRR_NO_ZCLIENT)
534 return 1;
535 strlcpy(frr_zclientpath, optarg, sizeof(frr_zclientpath));
536 break;
537 case 'A':
538 if (di->flags & FRR_NO_TCPVTY)
539 return 1;
540 if (vty_addr_set) {
541 fprintf(stderr,
542 "-A option specified more than once!\n");
543 errors++;
544 break;
545 }
546 vty_addr_set = 1;
547 di->vty_addr = optarg;
548 break;
549 case 'P':
550 if (di->flags & FRR_NO_TCPVTY)
551 return 1;
552 if (vty_port_set) {
553 fprintf(stderr,
554 "-P option specified more than once!\n");
555 errors++;
556 break;
557 }
558 vty_port_set = 1;
559 di->vty_port = strtoul(optarg, &err, 0);
560 if (*err || !*optarg) {
561 fprintf(stderr,
562 "invalid port number \"%s\" for -P option\n",
563 optarg);
564 errors++;
565 break;
566 }
567 break;
568 case OPTION_VTYSOCK:
569 if (di->vty_sock_path) {
570 fprintf(stderr,
571 "--vty_socket option specified more than once!\n");
572 errors++;
573 break;
574 }
575 di->vty_sock_path = optarg;
576 break;
577 case OPTION_MODULEDIR:
578 if (di->module_path) {
579 fprintf(stderr,
580 "----moduledir option specified more than once!\n");
581 errors++;
582 break;
583 }
584 di->module_path = optarg;
585 break;
586 case OPTION_SCRIPTDIR:
587 if (di->script_path) {
588 fprintf(stderr, "--scriptdir option specified more than once!\n");
589 errors++;
590 break;
591 }
592 di->script_path = optarg;
593 break;
594 case OPTION_TCLI:
595 di->cli_mode = FRR_CLI_TRANSACTIONAL;
596 break;
597 case 'u':
598 if (di->flags & FRR_NO_PRIVSEP)
599 return 1;
600 di->privs->user = optarg;
601 break;
602 case 'g':
603 if (di->flags & FRR_NO_PRIVSEP)
604 return 1;
605 di->privs->group = optarg;
606 break;
607 case OPTION_LOG:
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);
612 break;
613 case OPTION_LOGLEVEL:
614 di->early_loglevel = optarg;
615 break;
616 case OPTION_LOGGING:
617 di->log_always = true;
618 break;
619 case OPTION_LIMIT_FDS:
620 di->limit_fds = strtoul(optarg, &err, 0);
621 break;
622 default:
623 return 1;
624 }
625 return 0;
626 }
627
628 int frr_getopt(int argc, char *const argv[], int *longindex)
629 {
630 int opt;
631 int lidx;
632
633 comb_next_lo->name = NULL;
634
635 do {
636 opt = getopt_long(argc, argv, comb_optstr, comb_lo, &lidx);
637 if (frr_opt(opt))
638 break;
639 } while (opt != -1);
640
641 if (opt == -1 && errors)
642 frr_help_exit(1);
643 if (longindex)
644 *longindex = lidx;
645 return opt;
646 }
647
648 static void frr_mkdir(const char *path, bool strip)
649 {
650 char buf[256];
651 mode_t prev;
652 int ret;
653 struct zprivs_ids_t ids;
654
655 if (strip) {
656 char *slash = strrchr(path, '/');
657 size_t plen;
658 if (!slash)
659 return;
660 plen = slash - path;
661 if (plen > sizeof(buf) - 1)
662 return;
663 memcpy(buf, path, plen);
664 buf[plen] = '\0';
665 path = buf;
666 }
667
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.
670 */
671 prev = umask(0022);
672 ret = mkdir(path, 0755);
673 umask(prev);
674
675 if (ret != 0) {
676 /* if EEXIST, return without touching the permissions,
677 * so user-set custom permissions are left in place
678 */
679 if (errno == EEXIST)
680 return;
681
682 flog_err(EC_LIB_SYSTEM_CALL, "failed to mkdir \"%s\": %s", path,
683 strerror(errno));
684 return;
685 }
686
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,
690 strerror(errno));
691 }
692
693 static void _err_print(const void *cookie, const char *errstr)
694 {
695 const char *prefix = (const char *)cookie;
696
697 fprintf(stderr, "%s: %s\n", prefix, errstr);
698 }
699
700 static struct event_loop *master;
701 struct event_loop *frr_init(void)
702 {
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] = "";
708 const char *dir;
709
710 dir = di->module_path ? di->module_path : frr_moduledir;
711
712 srandom(time(NULL));
713 frr_defaults_apply();
714
715 if (di->instance) {
716 snprintf(frr_protonameinst, sizeof(frr_protonameinst), "%s[%u]",
717 di->logname, di->instance);
718 snprintf(p_instance, sizeof(p_instance), "-%d", di->instance);
719 }
720 if (di->pathspace)
721 snprintf(p_pathspace, sizeof(p_pathspace), "%s/",
722 di->pathspace);
723
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);
728 #ifdef HAVE_SQLITE3
729 snprintf(dbfile_default, sizeof(dbfile_default), "%s/%s%s%s.db",
730 frr_dbdir, p_pathspace, di->name, p_instance);
731 #endif
732
733 zprivs_preinit(di->privs);
734 zprivs_get_ids(&ids);
735
736 zlog_init(di->progname, di->logname, di->instance,
737 ids.uid_normal, ids.gid_normal);
738
739 while ((log_arg = log_args_pop(di->early_logging))) {
740 command_setup_early_logging(log_arg->target,
741 di->early_loglevel);
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);
748 }
749
750 if (!frr_zclient_addr(&zclient_addr, &zclient_addr_len,
751 frr_zclientpath)) {
752 fprintf(stderr, "Invalid zserv socket path: %s\n",
753 frr_zclientpath);
754 exit(1);
755 }
756
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);
761 if (di->pid_file)
762 frr_mkdir(di->pid_file, true);
763 if (di->vty_path)
764 frr_mkdir(di->vty_path, true);
765 }
766
767 frrmod_init(di->module);
768 while (modules) {
769 modules = (oc = modules)->next;
770 module = frrmod_load(oc->arg, dir, _err_print, __func__);
771 if (!module)
772 exit(1);
773 XFREE(MTYPE_TMP, oc);
774 }
775
776 zprivs_init(di->privs);
777
778 master = event_master_create(NULL);
779 signal_init(master, di->n_signals, di->signals);
780 hook_call(frr_early_init, master);
781
782 #ifdef HAVE_SQLITE3
783 if (!di->db_file)
784 di->db_file = dbfile_default;
785 db_init("%s", di->db_file);
786 #endif
787
788 if (di->flags & FRR_LIMITED_CLI)
789 cmd_init(-1);
790 else
791 cmd_init(1);
792
793 vty_init(master, di->log_always);
794 lib_cmd_init();
795
796 frr_pthread_init();
797 #ifdef HAVE_SCRIPTING
798 frrscript_init(di->script_path ? di->script_path : frr_scriptdir);
799 #endif
800
801 log_ref_init();
802 log_ref_vty_init();
803 lib_error_init();
804
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",
809 __func__);
810
811 debug_init_cli();
812
813 return master;
814 }
815
816 const char *frr_get_progname(void)
817 {
818 return di ? di->progname : NULL;
819 }
820
821 enum frr_cli_mode frr_get_cli_mode(void)
822 {
823 return di ? di->cli_mode : FRR_CLI_CLASSIC;
824 }
825
826 uint32_t frr_get_fd_limit(void)
827 {
828 return di ? di->limit_fds : 0;
829 }
830
831 static int rcvd_signal = 0;
832
833 static void rcv_signal(int signum)
834 {
835 rcvd_signal = signum;
836 /* poll() is interrupted by the signal; handled below */
837 }
838
839 static void frr_daemon_wait(int fd)
840 {
841 struct pollfd pfd[1];
842 int ret;
843 pid_t exitpid;
844 int exitstat;
845 sigset_t sigs, prevsigs;
846
847 sigemptyset(&sigs);
848 sigaddset(&sigs, SIGTSTP);
849 sigaddset(&sigs, SIGQUIT);
850 sigaddset(&sigs, SIGINT);
851 sigprocmask(SIG_BLOCK, &sigs, &prevsigs);
852
853 struct sigaction sa = {
854 .sa_handler = rcv_signal, .sa_flags = SA_RESETHAND,
855 };
856 sigemptyset(&sa.sa_mask);
857 sigaction(SIGTSTP, &sa, NULL);
858 sigaction(SIGQUIT, &sa, NULL);
859 sigaction(SIGINT, &sa, NULL);
860
861 do {
862 char buf[1];
863 ssize_t nrecv;
864
865 pfd[0].fd = fd;
866 pfd[0].events = POLLIN;
867
868 rcvd_signal = 0;
869
870 #if defined(HAVE_PPOLL)
871 ret = ppoll(pfd, 1, NULL, &prevsigs);
872 #elif defined(HAVE_POLLTS)
873 ret = pollts(pfd, 1, NULL, &prevsigs);
874 #else
875 /* racy -- only used on FreeBSD 9 */
876 sigset_t tmpsigs;
877 sigprocmask(SIG_SETMASK, &prevsigs, &tmpsigs);
878 ret = poll(pfd, 1, -1);
879 sigprocmask(SIG_SETMASK, &tmpsigs, NULL);
880 #endif
881 if (ret < 0 && errno != EINTR && errno != EAGAIN) {
882 perror("poll()");
883 exit(1);
884 }
885 switch (rcvd_signal) {
886 case SIGTSTP:
887 send(fd, "S", 1, 0);
888 do {
889 nrecv = recv(fd, buf, sizeof(buf), 0);
890 } while (nrecv == -1
891 && (errno == EINTR || errno == EAGAIN));
892
893 raise(SIGTSTP);
894 sigaction(SIGTSTP, &sa, NULL);
895 send(fd, "R", 1, 0);
896 break;
897 case SIGINT:
898 send(fd, "I", 1, 0);
899 break;
900 case SIGQUIT:
901 send(fd, "Q", 1, 0);
902 break;
903 }
904 } while (ret <= 0);
905
906 exitpid = waitpid(-1, &exitstat, WNOHANG);
907 if (exitpid == 0)
908 /* child successfully went to main loop & closed socket */
909 exit(0);
910
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 */
914 (void)0;
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,
920 WTERMSIG(exitstat));
921 else
922 fprintf(stderr, "%s failed to start, unknown problem\n",
923 di->name);
924 exit(1);
925 }
926
927 static int daemon_ctl_sock = -1;
928
929 static void frr_daemonize(void)
930 {
931 int fds[2];
932 pid_t pid;
933
934 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds)) {
935 perror("socketpair() for daemon control");
936 exit(1);
937 }
938 set_cloexec(fds[0]);
939 set_cloexec(fds[1]);
940
941 pid = fork();
942 if (pid < 0) {
943 perror("fork()");
944 exit(1);
945 }
946 if (pid == 0) {
947 /* child */
948 close(fds[0]);
949 if (setsid() < 0) {
950 perror("setsid()");
951 exit(1);
952 }
953
954 daemon_ctl_sock = fds[1];
955 return;
956 }
957
958 close(fds[1]);
959 nb_terminate();
960 yang_terminate();
961 frr_daemon_wait(fds[0]);
962 }
963
964 /*
965 * Why is this a thread?
966 *
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.
972 */
973 static void frr_config_read_in(struct event *t)
974 {
975 hook_call(frr_config_pre, master);
976
977 if (!vty_read_config(vty_shared_candidate_config, di->config_file,
978 config_default)
979 && di->backup_config_file) {
980 char *orig = XSTRDUP(MTYPE_TMP, host_config_get());
981
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);
986
987 host_config_set(orig);
988 XFREE(MTYPE_TMP, orig);
989 }
990
991 /*
992 * Automatically commit the candidate configuration after
993 * reading the configuration file.
994 */
995 if (frr_get_cli_mode() == FRR_CLI_TRANSACTIONAL) {
996 struct nb_context context = {};
997 char errmsg[BUFSIZ] = {0};
998 int ret;
999
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)
1005 zlog_err(
1006 "%s: failed to read configuration file: %s (%s)",
1007 __func__, nb_err_name(ret), errmsg);
1008 }
1009
1010 hook_call(frr_config_post, master);
1011 }
1012
1013 void frr_config_fork(void)
1014 {
1015 hook_call(frr_late_init, master);
1016
1017 if (!(di->flags & FRR_NO_SPLIT_CONFIG)) {
1018 /* Don't start execution if we are in dry-run mode */
1019 if (di->dryrun) {
1020 frr_config_read_in(NULL);
1021 exit(0);
1022 }
1023
1024 event_add_event(master, frr_config_read_in, NULL, 0,
1025 &di->read_in);
1026 }
1027
1028 if (di->daemon_mode || di->terminal)
1029 frr_daemonize();
1030
1031 frr_is_after_fork = true;
1032
1033 if (!di->pid_file)
1034 di->pid_file = pidfile_default;
1035 pid_output(di->pid_file);
1036 zlog_tls_buffer_init();
1037 }
1038
1039 void frr_vty_serv_start(void)
1040 {
1041 /* allow explicit override of vty_path in the future
1042 * (not currently set anywhere) */
1043 if (!di->vty_path) {
1044 const char *dir;
1045 char defvtydir[256];
1046
1047 snprintf(defvtydir, sizeof(defvtydir), "%s", frr_vtydir);
1048
1049 dir = di->vty_sock_path ? di->vty_sock_path : defvtydir;
1050
1051 if (di->instance)
1052 snprintf(vtypath_default, sizeof(vtypath_default),
1053 "%s/%s-%d.vty", dir, di->name, di->instance);
1054 else
1055 snprintf(vtypath_default, sizeof(vtypath_default),
1056 "%s/%s.vty", dir, di->name);
1057
1058 di->vty_path = vtypath_default;
1059 }
1060
1061 vty_serv_start(di->vty_addr, di->vty_port, di->vty_path);
1062 }
1063
1064 void frr_vty_serv_stop(void)
1065 {
1066 vty_serv_stop();
1067
1068 if (di->vty_path)
1069 unlink(di->vty_path);
1070 }
1071
1072 static void frr_check_detach(void)
1073 {
1074 if (nodetach_term || nodetach_daemon)
1075 return;
1076
1077 if (daemon_ctl_sock != -1)
1078 close(daemon_ctl_sock);
1079 daemon_ctl_sock = -1;
1080 }
1081
1082 static void frr_terminal_close(int isexit)
1083 {
1084 int nullfd;
1085
1086 nodetach_term = false;
1087 frr_check_detach();
1088
1089 if (!di->daemon_mode || isexit) {
1090 printf("\n%s exiting\n", di->name);
1091 if (!isexit)
1092 raise(SIGINT);
1093 return;
1094 } else {
1095 printf("\n%s daemonizing\n", di->name);
1096 fflush(stdout);
1097 }
1098
1099 nullfd = open("/dev/null", O_RDONLY | O_NOCTTY);
1100 if (nullfd == -1) {
1101 flog_err_sys(EC_LIB_SYSTEM_CALL,
1102 "%s: failed to open /dev/null: %s", __func__,
1103 safe_strerror(errno));
1104 } else {
1105 int fd;
1106 /*
1107 * only redirect stdin, stdout, stderr to null when a tty also
1108 * don't redirect when stdout is set with --log stdout
1109 */
1110 for (fd = 2; fd >= 0; fd--)
1111 if (isatty(fd) &&
1112 (fd != STDOUT_FILENO || !logging_to_stdout))
1113 dup2(nullfd, fd);
1114 close(nullfd);
1115 }
1116 }
1117
1118 static struct event *daemon_ctl_thread = NULL;
1119
1120 static void frr_daemon_ctl(struct event *t)
1121 {
1122 char buf[1];
1123 ssize_t nr;
1124
1125 nr = recv(daemon_ctl_sock, buf, sizeof(buf), 0);
1126 if (nr < 0 && (errno == EINTR || errno == EAGAIN))
1127 goto out;
1128 if (nr <= 0)
1129 return;
1130
1131 switch (buf[0]) {
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 : ""));
1137 break;
1138 case 'R': /* SIGTCNT [implicit] */
1139 vty_stdio_resume();
1140 break;
1141 case 'I': /* SIGINT */
1142 di->daemon_mode = false;
1143 raise(SIGINT);
1144 break;
1145 case 'Q': /* SIGQUIT */
1146 di->daemon_mode = true;
1147 vty_stdio_close();
1148 break;
1149 }
1150
1151 out:
1152 event_add_read(master, frr_daemon_ctl, NULL, daemon_ctl_sock,
1153 &daemon_ctl_thread);
1154 }
1155
1156 void frr_detach(void)
1157 {
1158 nodetach_daemon = false;
1159 frr_check_detach();
1160 }
1161
1162 void frr_run(struct event_loop *master)
1163 {
1164 char instanceinfo[64] = "";
1165
1166 if (!(di->flags & FRR_MANUAL_VTY_START))
1167 frr_vty_serv_start();
1168
1169 if (di->instance)
1170 snprintf(instanceinfo, sizeof(instanceinfo), "instance %u ",
1171 di->instance);
1172
1173 zlog_notice("%s %s starting: %svty@%d%s", di->name, FRR_VERSION,
1174 instanceinfo, di->vty_port, di->startinfo);
1175
1176 if (di->terminal) {
1177 nodetach_term = true;
1178
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);
1184 }
1185 } else if (di->daemon_mode) {
1186 int nullfd = open("/dev/null", O_RDONLY | O_NOCTTY);
1187 if (nullfd == -1) {
1188 flog_err_sys(EC_LIB_SYSTEM_CALL,
1189 "%s: failed to open /dev/null: %s",
1190 __func__, safe_strerror(errno));
1191 } else {
1192 int fd;
1193 /*
1194 * only redirect stdin, stdout, stderr to null when a
1195 * tty also don't redirect when stdout is set with --log
1196 * stdout
1197 */
1198 for (fd = 2; fd >= 0; fd--)
1199 if (isatty(fd) &&
1200 (fd != STDOUT_FILENO || !logging_to_stdout))
1201 dup2(nullfd, fd);
1202 close(nullfd);
1203 }
1204
1205 frr_check_detach();
1206 }
1207
1208 /* end fixed stderr startup logging */
1209 zlog_startup_end();
1210
1211 struct event thread;
1212 while (event_fetch(master, &thread))
1213 event_call(&thread);
1214 }
1215
1216 void frr_early_fini(void)
1217 {
1218 hook_call(frr_early_fini);
1219 }
1220
1221 void frr_fini(void)
1222 {
1223 FILE *fp;
1224 char filename[128];
1225 int have_leftovers = 0;
1226
1227 hook_call(frr_fini);
1228
1229 vty_terminate();
1230 cmd_terminate();
1231 nb_terminate();
1232 yang_terminate();
1233 #ifdef HAVE_SQLITE3
1234 db_close();
1235 #endif
1236 log_ref_fini();
1237
1238 #ifdef HAVE_SCRIPTING
1239 frrscript_fini();
1240 #endif
1241 frr_pthread_finish();
1242 zprivs_terminate(di->privs);
1243 /* signal_init -> nothing needed */
1244 event_master_free(master);
1245 master = NULL;
1246 zlog_tls_buffer_fini();
1247 zlog_fini();
1248 /* frrmod_init -> nothing needed / hooks */
1249 rcu_shutdown();
1250
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);
1254
1255 /* in case we decide at runtime that we want exit-memstats for
1256 * a daemon
1257 * (only do this if we actually have something to print though)
1258 */
1259 if (!debug_memstats_at_exit || !have_leftovers)
1260 return;
1261
1262 snprintf(filename, sizeof(filename), "/tmp/frr-memstats-%s-%llu-%llu",
1263 di->name, (unsigned long long)getpid(),
1264 (unsigned long long)time(NULL));
1265
1266 fp = fopen(filename, "w");
1267 if (fp) {
1268 log_memstats(fp, di->name);
1269 fclose(fp);
1270 }
1271 }
1272
1273 #ifdef INTERP
1274 static const char interp[]
1275 __attribute__((section(".interp"), used)) = INTERP;
1276 #endif
1277 /*
1278 * executable entry point for libfrr.so
1279 *
1280 * note that libc initialization is skipped for this so the set of functions
1281 * that can be called is rather limited
1282 */
1283 extern void _libfrr_version(void)
1284 __attribute__((visibility("hidden"), noreturn));
1285 void _libfrr_version(void)
1286 {
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);
1292 _exit(0);
1293 }