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