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