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