]> git.proxmox.com Git - mirror_frr.git/blame - lib/libfrr.c
*: rename ferr_ref -> log_ref
[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"
b66d022e 38#include "lib_errors.h"
eb05883f 39
d62a17ae 40DEFINE_HOOK(frr_late_init, (struct thread_master * tm), (tm))
03951374
DL
41DEFINE_KOOH(frr_early_fini, (), ())
42DEFINE_KOOH(frr_fini, (), ())
a5b38c5b 43
eb05883f
DL
44const char frr_sysconfdir[] = SYSCONFDIR;
45const char frr_vtydir[] = DAEMON_VTY_DIR;
80b4df3b 46const char frr_moduledir[] = MODULE_PATH;
eb05883f 47
4f138a3e
DL
48char frr_protoname[256] = "NONE";
49char frr_protonameinst[256] = "NONE";
b85120bc 50
ff44f570 51char config_default[512];
689f5a8c 52char frr_zclientpath[256];
ff44f570 53static char pidfile_default[512];
eb05883f 54static char vtypath_default[256];
4f04a76b 55
9eed278b
DL
56bool debug_memstats_at_exit = 0;
57
4f04a76b
DL
58static char comb_optstr[256];
59static struct option comb_lo[64];
60static struct option *comb_next_lo = &comb_lo[0];
61static char comb_helpstr[4096];
62
63struct optspec {
64 const char *optstr;
65 const char *helpstr;
66 const struct option *longopts;
67};
68
69static 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
80b4df3b
MW
80#define OPTION_VTYSOCK 1000
81#define OPTION_MODULEDIR 1002
e9b4e74a
DS
82#define OPTION_LOG 1003
83#define OPTION_LOGLEVEL 1004
4f04a76b
DL
84
85static const struct option lo_always[] = {
d62a17ae 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},
f8507817 92 {"log", required_argument, NULL, OPTION_LOG},
e9b4e74a 93 {"log-level", required_argument, NULL, OPTION_LOGLEVEL},
d62a17ae 94 {NULL}};
4f04a76b 95static const struct optspec os_always = {
30771d65 96 "hvdM:",
4f04a76b
DL
97 " -h, --help Display this help and exit\n"
98 " -v, --version Print program version\n"
eb05883f 99 " -d, --daemon Runs in daemon mode\n"
30771d65 100 " -M, --module Load specified module\n"
80b4df3b 101 " --vty_socket Override vty socket path\n"
f8507817 102 " --moduledir Override modules directory\n"
e9b4e74a
DS
103 " --log Set Logging to stdout, syslog, or file:<name>\n"
104 " --log-level Set Logging Level to use, debug, info, warn, etc\n",
d62a17ae 105 lo_always};
4f04a76b
DL
106
107
eb05883f 108static const struct option lo_cfg_pid_dry[] = {
d62a17ae 109 {"pid_file", required_argument, NULL, 'i'},
110 {"config_file", required_argument, NULL, 'f'},
d1b4fc1f 111 {"pathspace", required_argument, NULL, 'N'},
d62a17ae 112 {"dryrun", no_argument, NULL, 'C'},
cff2b211 113 {"terminal", no_argument, NULL, 't'},
d62a17ae 114 {NULL}};
eb05883f 115static const struct optspec os_cfg_pid_dry = {
d1b4fc1f 116 "f:i:CtN:",
eb05883f
DL
117 " -f, --config_file Set configuration file name\n"
118 " -i, --pid_file Set process identifier file name\n"
d1b4fc1f 119 " -N, --pathspace Insert prefix into config & socket paths\n"
cff2b211
DL
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",
d62a17ae 123 lo_cfg_pid_dry};
eb05883f
DL
124
125
126static const struct option lo_zclient[] = {
d62a17ae 127 {"socket", required_argument, NULL, 'z'},
128 {NULL}};
eb05883f 129static const struct optspec os_zclient = {
d62a17ae 130 "z:", " -z, --socket Set path of zebra socket\n", lo_zclient};
eb05883f
DL
131
132
4f04a76b 133static const struct option lo_vty[] = {
d62a17ae 134 {"vty_addr", required_argument, NULL, 'A'},
135 {"vty_port", required_argument, NULL, 'P'},
136 {NULL}};
4f04a76b
DL
137static 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",
d62a17ae 141 lo_vty};
4f04a76b
DL
142
143
d62a17ae 144static const struct option lo_user[] = {{"user", required_argument, NULL, 'u'},
145 {"group", required_argument, NULL, 'g'},
146 {NULL}};
147static 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};
4f04a76b
DL
151
152
689f5a8c
DL
153bool 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))) {
5d13cd09 162 /* note: this functionality is disabled at bottom */
689f5a8c
DL
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++;
996c9314 178 /* fallthrough */
689f5a8c
DL
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 }
5d13cd09
DL
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
689f5a8c
DL
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
4f04a76b
DL
263static struct frr_daemon_info *di = NULL;
264
265void frr_preinit(struct frr_daemon_info *daemon, int argc, char **argv)
266{
267 di = daemon;
268
269 /* basename(), opencoded. */
270 char *p = strrchr(argv[0], '/');
271 di->progname = p ? p + 1 : argv[0];
272
273 umask(0027);
274
275 opt_extend(&os_always);
eb05883f
DL
276 if (!(di->flags & FRR_NO_CFG_PID_DRY))
277 opt_extend(&os_cfg_pid_dry);
4f04a76b
DL
278 if (!(di->flags & FRR_NO_PRIVSEP))
279 opt_extend(&os_user);
eb05883f
DL
280 if (!(di->flags & FRR_NO_ZCLIENT))
281 opt_extend(&os_zclient);
4f04a76b
DL
282 if (!(di->flags & FRR_NO_TCPVTY))
283 opt_extend(&os_vty);
eb05883f
DL
284
285 snprintf(config_default, sizeof(config_default), "%s/%s.conf",
d62a17ae 286 frr_sysconfdir, di->name);
eb05883f 287 snprintf(pidfile_default, sizeof(pidfile_default), "%s/%s.pid",
d62a17ae 288 frr_vtydir, di->name);
b85120bc
DL
289
290 strlcpy(frr_protoname, di->logname, sizeof(frr_protoname));
291 strlcpy(frr_protonameinst, di->logname, sizeof(frr_protonameinst));
689f5a8c
DL
292
293 strlcpy(frr_zclientpath, ZEBRA_SERV_PATH, sizeof(frr_zclientpath));
4f04a76b
DL
294}
295
296void frr_opt_add(const char *optstr, const struct option *longopts,
d62a17ae 297 const char *helpstr)
4f04a76b 298{
d62a17ae 299 const struct optspec main_opts = {optstr, helpstr, longopts};
4f04a76b
DL
300 opt_extend(&main_opts);
301}
302
303void frr_help_exit(int status)
304{
305 FILE *target = status ? stderr : stdout;
306
307 if (status != 0)
308 fprintf(stderr, "Invalid options.\n\n");
309
310 if (di->printhelp)
311 di->printhelp(target);
312 else
313 fprintf(target, "Usage: %s [OPTION...]\n\n%s%s%s\n\n%s",
d62a17ae 314 di->progname, di->proghelp, di->copyright ? "\n\n" : "",
315 di->copyright ? di->copyright : "", comb_helpstr);
4f04a76b
DL
316 fprintf(target, "\nReport bugs to %s\n", FRR_BUG_ADDRESS);
317 exit(status);
318}
319
30771d65
DL
320struct option_chain {
321 struct option_chain *next;
322 const char *arg;
323};
80b4df3b 324
30771d65 325static struct option_chain *modules = NULL, **modnext = &modules;
4f04a76b
DL
326static int errors = 0;
327
328static int frr_opt(int opt)
329{
330 static int vty_port_set = 0;
331 static int vty_addr_set = 0;
30771d65 332 struct option_chain *oc;
4f04a76b
DL
333 char *err;
334
335 switch (opt) {
336 case 'h':
337 frr_help_exit(0);
338 break;
339 case 'v':
340 print_version(di->progname);
341 exit(0);
342 break;
eb05883f
DL
343 case 'd':
344 di->daemon_mode = 1;
345 break;
30771d65
DL
346 case 'M':
347 oc = XMALLOC(MTYPE_TMP, sizeof(*oc));
348 oc->arg = optarg;
349 oc->next = NULL;
350 *modnext = oc;
351 modnext = &oc->next;
352 break;
eb05883f
DL
353 case 'i':
354 if (di->flags & FRR_NO_CFG_PID_DRY)
355 return 1;
356 di->pid_file = optarg;
357 break;
358 case 'f':
359 if (di->flags & FRR_NO_CFG_PID_DRY)
360 return 1;
361 di->config_file = optarg;
362 break;
d1b4fc1f
DL
363 case 'N':
364 if (di->flags & FRR_NO_CFG_PID_DRY)
365 return 1;
366 if (di->pathspace) {
367 fprintf(stderr,
368 "-N/--pathspace option specified more than once!\n");
369 errors++;
370 break;
371 }
372 if (strchr(optarg, '/') || strchr(optarg, '.')) {
373 fprintf(stderr,
374 "slashes or dots are not permitted in the --pathspace option.\n");
375 errors++;
376 break;
377 }
378 di->pathspace = optarg;
379 break;
eb05883f
DL
380 case 'C':
381 if (di->flags & FRR_NO_CFG_PID_DRY)
382 return 1;
383 di->dryrun = 1;
384 break;
cff2b211
DL
385 case 't':
386 if (di->flags & FRR_NO_CFG_PID_DRY)
387 return 1;
388 di->terminal = 1;
389 break;
eb05883f
DL
390 case 'z':
391 if (di->flags & FRR_NO_ZCLIENT)
392 return 1;
689f5a8c 393 strlcpy(frr_zclientpath, optarg, sizeof(frr_zclientpath));
eb05883f 394 break;
4f04a76b
DL
395 case 'A':
396 if (di->flags & FRR_NO_TCPVTY)
397 return 1;
398 if (vty_addr_set) {
d62a17ae 399 fprintf(stderr,
400 "-A option specified more than once!\n");
4f04a76b
DL
401 errors++;
402 break;
403 }
404 vty_addr_set = 1;
405 di->vty_addr = optarg;
406 break;
407 case 'P':
408 if (di->flags & FRR_NO_TCPVTY)
409 return 1;
410 if (vty_port_set) {
d62a17ae 411 fprintf(stderr,
412 "-P option specified more than once!\n");
4f04a76b
DL
413 errors++;
414 break;
415 }
416 vty_port_set = 1;
417 di->vty_port = strtoul(optarg, &err, 0);
418 if (*err || !*optarg) {
d62a17ae 419 fprintf(stderr,
420 "invalid port number \"%s\" for -P option\n",
421 optarg);
4f04a76b
DL
422 errors++;
423 break;
424 }
425 break;
426 case OPTION_VTYSOCK:
427 if (di->vty_sock_path) {
d62a17ae 428 fprintf(stderr,
429 "--vty_socket option specified more than once!\n");
4f04a76b
DL
430 errors++;
431 break;
432 }
433 di->vty_sock_path = optarg;
434 break;
80b4df3b
MW
435 case OPTION_MODULEDIR:
436 if (di->module_path) {
d62a17ae 437 fprintf(stderr,
438 "----moduledir option specified more than once!\n");
80b4df3b
MW
439 errors++;
440 break;
441 }
442 di->module_path = optarg;
443 break;
4f04a76b
DL
444 case 'u':
445 if (di->flags & FRR_NO_PRIVSEP)
446 return 1;
447 di->privs->user = optarg;
448 break;
449 case 'g':
450 if (di->flags & FRR_NO_PRIVSEP)
451 return 1;
452 di->privs->group = optarg;
453 break;
f8507817
DS
454 case OPTION_LOG:
455 di->early_logging = optarg;
456 break;
e9b4e74a
DS
457 case OPTION_LOGLEVEL:
458 di->early_loglevel = optarg;
459 break;
4f04a76b
DL
460 default:
461 return 1;
462 }
463 return 0;
464}
465
d62a17ae 466int frr_getopt(int argc, char *const argv[], int *longindex)
4f04a76b
DL
467{
468 int opt;
469 int lidx;
470
471 comb_next_lo->name = NULL;
472
473 do {
474 opt = getopt_long(argc, argv, comb_optstr, comb_lo, &lidx);
475 if (frr_opt(opt))
476 break;
477 } while (opt != -1);
478
479 if (opt == -1 && errors)
480 frr_help_exit(1);
481 if (longindex)
482 *longindex = lidx;
483 return opt;
484}
485
beaa5470
DL
486static void frr_mkdir(const char *path, bool strip)
487{
488 char buf[256];
489 mode_t prev;
490 int ret;
491 struct zprivs_ids_t ids;
492
493 if (strip) {
494 char *slash = strrchr(path, '/');
495 size_t plen;
496 if (!slash)
497 return;
498 plen = slash - path;
499 if (plen > sizeof(buf) - 1)
500 return;
501 memcpy(buf, path, plen);
502 buf[plen] = '\0';
503 path = buf;
504 }
505
506 /* o+rx (..5) is needed for the frrvty group to work properly;
507 * without it, users in the frrvty group can't access the vty sockets.
508 */
509 prev = umask(0022);
510 ret = mkdir(path, 0755);
511 umask(prev);
512
513 if (ret != 0) {
514 /* if EEXIST, return without touching the permissions,
515 * so user-set custom permissions are left in place
516 */
517 if (errno == EEXIST)
518 return;
519
520 zlog_warn("failed to mkdir \"%s\": %s", path, strerror(errno));
521 return;
522 }
523
524 zprivs_get_ids(&ids);
525 if (chown(path, ids.uid_normal, ids.gid_normal))
526 zlog_warn("failed to chown \"%s\": %s", path, strerror(errno));
527}
528
a5b38c5b 529static struct thread_master *master;
4f04a76b
DL
530struct thread_master *frr_init(void)
531{
30771d65
DL
532 struct option_chain *oc;
533 struct frrmod_runtime *module;
534 char moderr[256];
d1b4fc1f 535 char p_instance[16] = "", p_pathspace[256] = "";
80b4df3b
MW
536 const char *dir;
537 dir = di->module_path ? di->module_path : frr_moduledir;
4f04a76b
DL
538
539 srandom(time(NULL));
540
d1b4fc1f 541 if (di->instance) {
d62a17ae 542 snprintf(frr_protonameinst, sizeof(frr_protonameinst), "%s[%u]",
543 di->logname, di->instance);
d1b4fc1f
DL
544 snprintf(p_instance, sizeof(p_instance), "-%d", di->instance);
545 }
546 if (di->pathspace)
b39404c1 547 snprintf(p_pathspace, sizeof(p_pathspace), "%s/",
d1b4fc1f
DL
548 di->pathspace);
549
36077833 550 snprintf(config_default, sizeof(config_default), "%s%s%s%s.conf",
d1b4fc1f 551 frr_sysconfdir, p_pathspace, di->name, p_instance);
b39404c1 552 snprintf(pidfile_default, sizeof(pidfile_default), "%s/%s%s%s.pid",
d1b4fc1f 553 frr_vtydir, p_pathspace, di->name, p_instance);
b85120bc 554
37a1f2fb
DL
555 zprivs_preinit(di->privs);
556
d62a17ae 557 openzlog(di->progname, di->logname, di->instance,
558 LOG_CONS | LOG_NDELAY | LOG_PID, LOG_DAEMON);
f8507817 559
e9b4e74a 560 command_setup_early_logging(di->early_logging, di->early_loglevel);
4f04a76b 561
689f5a8c
DL
562 if (!frr_zclient_addr(&zclient_addr, &zclient_addr_len,
563 frr_zclientpath)) {
564 fprintf(stderr, "Invalid zserv socket path: %s\n",
565 frr_zclientpath);
566 exit(1);
567 }
568
b8c1fde3
DL
569 /* don't mkdir these as root... */
570 if (!(di->flags & FRR_NO_PRIVSEP)) {
571 if (!di->pid_file || !di->vty_path)
572 frr_mkdir(frr_vtydir, false);
573 if (di->pid_file)
574 frr_mkdir(di->pid_file, true);
575 if (di->vty_path)
576 frr_mkdir(di->vty_path, true);
577 }
beaa5470 578
30771d65
DL
579 frrmod_init(di->module);
580 while (modules) {
581 modules = (oc = modules)->next;
80b4df3b 582 module = frrmod_load(oc->arg, dir, moderr, sizeof(moderr));
30771d65
DL
583 if (!module) {
584 fprintf(stderr, "%s\n", moderr);
585 exit(1);
586 }
587 XFREE(MTYPE_TMP, oc);
588 }
589
4f04a76b
DL
590 zprivs_init(di->privs);
591
972a411c 592 master = thread_master_create(NULL);
4f04a76b
DL
593 signal_init(master, di->n_signals, di->signals);
594
857b5446
DL
595 if (di->flags & FRR_LIMITED_CLI)
596 cmd_init(-1);
597 else
598 cmd_init(1);
599 vty_init(master);
600 memory_init();
601
85cd2f9f 602 log_ref_init();
b66d022e
DS
603 lib_error_init();
604
4f04a76b
DL
605 return master;
606}
607
154b9e8f
DL
608static int rcvd_signal = 0;
609
610static void rcv_signal(int signum)
611{
612 rcvd_signal = signum;
613 /* poll() is interrupted by the signal; handled below */
614}
615
f43fbf83
DL
616static void frr_daemon_wait(int fd)
617{
618 struct pollfd pfd[1];
619 int ret;
620 pid_t exitpid;
621 int exitstat;
154b9e8f
DL
622 sigset_t sigs, prevsigs;
623
624 sigemptyset(&sigs);
625 sigaddset(&sigs, SIGTSTP);
626 sigaddset(&sigs, SIGQUIT);
627 sigaddset(&sigs, SIGINT);
628 sigprocmask(SIG_BLOCK, &sigs, &prevsigs);
629
630 struct sigaction sa = {
631 .sa_handler = rcv_signal, .sa_flags = SA_RESETHAND,
632 };
633 sigemptyset(&sa.sa_mask);
634 sigaction(SIGTSTP, &sa, NULL);
635 sigaction(SIGQUIT, &sa, NULL);
636 sigaction(SIGINT, &sa, NULL);
f43fbf83
DL
637
638 do {
154b9e8f
DL
639 char buf[1];
640 ssize_t nrecv;
641
f43fbf83
DL
642 pfd[0].fd = fd;
643 pfd[0].events = POLLIN;
644
154b9e8f
DL
645 rcvd_signal = 0;
646
996c9314 647#if defined(HAVE_PPOLL)
154b9e8f
DL
648 ret = ppoll(pfd, 1, NULL, &prevsigs);
649#elif defined(HAVE_POLLTS)
650 ret = pollts(pfd, 1, NULL, &prevsigs);
651#else
652 /* racy -- only used on FreeBSD 9 */
653 sigset_t tmpsigs;
654 sigprocmask(SIG_SETMASK, &prevsigs, &tmpsigs);
f43fbf83 655 ret = poll(pfd, 1, -1);
154b9e8f
DL
656 sigprocmask(SIG_SETMASK, &tmpsigs, NULL);
657#endif
f43fbf83
DL
658 if (ret < 0 && errno != EINTR && errno != EAGAIN) {
659 perror("poll()");
660 exit(1);
661 }
154b9e8f
DL
662 switch (rcvd_signal) {
663 case SIGTSTP:
664 send(fd, "S", 1, 0);
665 do {
666 nrecv = recv(fd, buf, sizeof(buf), 0);
667 } while (nrecv == -1
668 && (errno == EINTR || errno == EAGAIN));
669
670 raise(SIGTSTP);
671 sigaction(SIGTSTP, &sa, NULL);
672 send(fd, "R", 1, 0);
673 break;
674 case SIGINT:
675 send(fd, "I", 1, 0);
676 break;
677 case SIGQUIT:
678 send(fd, "Q", 1, 0);
679 break;
680 }
f43fbf83
DL
681 } while (ret <= 0);
682
683 exitpid = waitpid(-1, &exitstat, WNOHANG);
684 if (exitpid == 0)
685 /* child successfully went to main loop & closed socket */
686 exit(0);
687
688 /* child failed one way or another ... */
6bd2b360
DL
689 if (WIFEXITED(exitstat) && WEXITSTATUS(exitstat) == 0)
690 /* can happen in --terminal case if exit is fast enough */
691 (void)0;
692 else if (WIFEXITED(exitstat))
f43fbf83
DL
693 fprintf(stderr, "%s failed to start, exited %d\n", di->name,
694 WEXITSTATUS(exitstat));
695 else if (WIFSIGNALED(exitstat))
696 fprintf(stderr, "%s crashed in startup, signal %d\n", di->name,
697 WTERMSIG(exitstat));
698 else
699 fprintf(stderr, "%s failed to start, unknown problem\n",
700 di->name);
701 exit(1);
702}
703
704static int daemon_ctl_sock = -1;
705
706static void frr_daemonize(void)
707{
708 int fds[2];
709 pid_t pid;
710
711 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds)) {
712 perror("socketpair() for daemon control");
713 exit(1);
714 }
715 set_cloexec(fds[0]);
716 set_cloexec(fds[1]);
717
718 pid = fork();
719 if (pid < 0) {
720 perror("fork()");
721 exit(1);
722 }
723 if (pid == 0) {
724 /* child */
725 close(fds[0]);
726 if (setsid() < 0) {
727 perror("setsid()");
728 exit(1);
729 }
730
731 daemon_ctl_sock = fds[1];
732 return;
733 }
734
735 close(fds[1]);
736 frr_daemon_wait(fds[0]);
737}
738
9e224e60
DS
739/*
740 * Why is this a thread?
741 *
742 * The read in of config for integrated config happens *after*
743 * thread execution starts( because it is passed in via a vtysh -b -n )
744 * While if you are not using integrated config we want the ability
745 * to read the config in after thread execution starts, so that
746 * we can match this behavior.
747 */
748static int frr_config_read_in(struct thread *t)
4f04a76b 749{
573de11f
DS
750 if (!vty_read_config(di->config_file, config_default) &&
751 di->backup_config_file) {
fe64533a
DS
752 char *orig = XSTRDUP(MTYPE_TMP, host_config_get());
753
573de11f
DS
754 zlog_info("Attempting to read backup config file: %s specified",
755 di->backup_config_file);
756 vty_read_config(di->backup_config_file, config_default);
fe64533a
DS
757
758 host_config_set(orig);
759 XFREE(MTYPE_TMP, orig);
573de11f 760 }
9e224e60
DS
761 return 0;
762}
763
764void frr_config_fork(void)
765{
766 hook_call(frr_late_init, master);
eb05883f
DL
767
768 /* Don't start execution if we are in dry-run mode */
9e224e60
DS
769 if (di->dryrun) {
770 frr_config_read_in(NULL);
eb05883f 771 exit(0);
9e224e60
DS
772 }
773
774 thread_add_event(master, frr_config_read_in, NULL, 0, &di->read_in);
eb05883f 775
154b9e8f 776 if (di->daemon_mode || di->terminal)
f43fbf83 777 frr_daemonize();
eb05883f
DL
778
779 if (!di->pid_file)
780 di->pid_file = pidfile_default;
d62a17ae 781 pid_output(di->pid_file);
eb05883f
DL
782}
783
784void frr_vty_serv(void)
785{
d62a17ae 786 /* allow explicit override of vty_path in the future
eb05883f
DL
787 * (not currently set anywhere) */
788 if (!di->vty_path) {
789 const char *dir;
d1b4fc1f
DL
790 char defvtydir[256];
791
792 snprintf(defvtydir, sizeof(defvtydir), "%s%s%s", frr_vtydir,
793 di->pathspace ? "/" : "",
794 di->pathspace ? di->pathspace : "");
795
796 dir = di->vty_sock_path ? di->vty_sock_path : defvtydir;
eb05883f
DL
797
798 if (di->instance)
799 snprintf(vtypath_default, sizeof(vtypath_default),
d62a17ae 800 "%s/%s-%d.vty", dir, di->name, di->instance);
eb05883f
DL
801 else
802 snprintf(vtypath_default, sizeof(vtypath_default),
d62a17ae 803 "%s/%s.vty", dir, di->name);
eb05883f
DL
804
805 di->vty_path = vtypath_default;
806 }
807
808 vty_serv_sock(di->vty_addr, di->vty_port, di->vty_path);
4f04a76b
DL
809}
810
154b9e8f 811static void frr_terminal_close(int isexit)
cff2b211 812{
993bab89
RW
813 int nullfd;
814
154b9e8f
DL
815 if (daemon_ctl_sock != -1) {
816 close(daemon_ctl_sock);
817 daemon_ctl_sock = -1;
818 }
819
820 if (!di->daemon_mode || isexit) {
cff2b211 821 printf("\n%s exiting\n", di->name);
154b9e8f
DL
822 if (!isexit)
823 raise(SIGINT);
824 return;
cff2b211
DL
825 } else {
826 printf("\n%s daemonizing\n", di->name);
827 fflush(stdout);
828 }
829
993bab89
RW
830 nullfd = open("/dev/null", O_RDONLY | O_NOCTTY);
831 if (nullfd == -1) {
af4c2728 832 flog_err(LIB_ERR_SYSTEM_CALL,
8d619fba
DS
833 "%s: failed to open /dev/null: %s", __func__,
834 safe_strerror(errno));
993bab89
RW
835 } else {
836 dup2(nullfd, 0);
837 dup2(nullfd, 1);
838 dup2(nullfd, 2);
839 close(nullfd);
840 }
154b9e8f 841}
cff2b211 842
154b9e8f
DL
843static struct thread *daemon_ctl_thread = NULL;
844
845static int frr_daemon_ctl(struct thread *t)
846{
847 char buf[1];
848 ssize_t nr;
849
850 nr = recv(daemon_ctl_sock, buf, sizeof(buf), 0);
851 if (nr < 0 && (errno == EINTR || errno == EAGAIN))
852 goto out;
853 if (nr <= 0)
854 return 0;
855
856 switch (buf[0]) {
996c9314 857 case 'S': /* SIGTSTP */
154b9e8f 858 vty_stdio_suspend();
e339d7c0 859 if (send(daemon_ctl_sock, "s", 1, 0) < 0)
860 zlog_err("%s send(\"s\") error (SIGTSTP propagation)",
861 (di && di->name ? di->name : ""));
154b9e8f 862 break;
996c9314 863 case 'R': /* SIGTCNT [implicit] */
154b9e8f
DL
864 vty_stdio_resume();
865 break;
996c9314 866 case 'I': /* SIGINT */
154b9e8f
DL
867 di->daemon_mode = false;
868 raise(SIGINT);
869 break;
996c9314 870 case 'Q': /* SIGQUIT */
154b9e8f
DL
871 di->daemon_mode = true;
872 vty_stdio_close();
873 break;
cff2b211 874 }
154b9e8f
DL
875
876out:
877 thread_add_read(master, frr_daemon_ctl, NULL, daemon_ctl_sock,
878 &daemon_ctl_thread);
879 return 0;
cff2b211
DL
880}
881
16077f2f
DL
882void frr_run(struct thread_master *master)
883{
884 char instanceinfo[64] = "";
885
886 frr_vty_serv();
887
888 if (di->instance)
889 snprintf(instanceinfo, sizeof(instanceinfo), "instance %u ",
d62a17ae 890 di->instance);
891
892 zlog_notice("%s %s starting: %svty@%d%s", di->name, FRR_VERSION,
893 instanceinfo, di->vty_port, di->startinfo);
16077f2f 894
cff2b211
DL
895 if (di->terminal) {
896 vty_stdio(frr_terminal_close);
154b9e8f
DL
897 if (daemon_ctl_sock != -1) {
898 set_nonblocking(daemon_ctl_sock);
899 thread_add_read(master, frr_daemon_ctl, NULL,
900 daemon_ctl_sock, &daemon_ctl_thread);
901 }
eef3d030 902 } else if (di->daemon_mode) {
c9c8d0d1 903 int nullfd = open("/dev/null", O_RDONLY | O_NOCTTY);
993bab89 904 if (nullfd == -1) {
af4c2728 905 flog_err(LIB_ERR_SYSTEM_CALL,
8d619fba
DS
906 "%s: failed to open /dev/null: %s", __func__,
907 safe_strerror(errno));
993bab89
RW
908 } else {
909 dup2(nullfd, 0);
910 dup2(nullfd, 1);
911 dup2(nullfd, 2);
912 close(nullfd);
913 }
c9c8d0d1
DL
914
915 if (daemon_ctl_sock != -1)
916 close(daemon_ctl_sock);
f43fbf83
DL
917 daemon_ctl_sock = -1;
918 }
919
d34cb7f0
DL
920 /* end fixed stderr startup logging */
921 zlog_startup_stderr = false;
922
16077f2f
DL
923 struct thread thread;
924 while (thread_fetch(master, &thread))
925 thread_call(&thread);
926}
03951374
DL
927
928void frr_early_fini(void)
929{
930 hook_call(frr_early_fini);
931}
932
933void frr_fini(void)
934{
9eed278b
DL
935 FILE *fp;
936 char filename[128];
937 int have_leftovers;
938
03951374
DL
939 hook_call(frr_fini);
940
941 /* memory_init -> nothing needed */
942 vty_terminate();
943 cmd_terminate();
85cd2f9f 944 log_ref_fini();
03951374
DL
945 zprivs_terminate(di->privs);
946 /* signal_init -> nothing needed */
947 thread_master_free(master);
e5716b16 948 master = NULL;
03951374
DL
949 closezlog();
950 /* frrmod_init -> nothing needed / hooks */
9eed278b
DL
951
952 if (!debug_memstats_at_exit)
953 return;
954
955 have_leftovers = log_memstats(stderr, di->name);
956
957 /* in case we decide at runtime that we want exit-memstats for
958 * a daemon, but it has no stderr because it's daemonized
959 * (only do this if we actually have something to print though)
960 */
961 if (!have_leftovers)
962 return;
963
996c9314
LB
964 snprintf(filename, sizeof(filename), "/tmp/frr-memstats-%s-%llu-%llu",
965 di->name, (unsigned long long)getpid(),
9eed278b
DL
966 (unsigned long long)time(NULL));
967
968 fp = fopen(filename, "w");
969 if (fp) {
970 log_memstats(fp, di->name);
971 fclose(fp);
972 }
03951374 973}