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