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