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