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