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