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