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