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