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