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