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