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