]> git.proxmox.com Git - mirror_frr.git/blob - vtysh/vtysh_main.c
Merge pull request #8627 from volta-networks/fix_pceplib_scan_build
[mirror_frr.git] / vtysh / vtysh_main.c
1 /* Virtual terminal interface shell.
2 * Copyright (C) 2000 Kunihiro Ishiguro
3 *
4 * This file is part of GNU Zebra.
5 *
6 * GNU Zebra 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
8 * Free Software Foundation; either version 2, or (at your option) any
9 * later version.
10 *
11 * GNU Zebra is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
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
19 */
20
21 #include <zebra.h>
22
23 #include <sys/un.h>
24 #include <setjmp.h>
25 #include <sys/wait.h>
26 #include <pwd.h>
27 #include <sys/file.h>
28 #include <unistd.h>
29
30 #include <readline/readline.h>
31 #include <readline/history.h>
32
33 /*
34 * The append_history function only appears in newer versions
35 * of the readline library it appears like. Since we don't
36 * need this just silently ignore the code on these
37 * ancient platforms.
38 */
39 #if !defined HAVE_APPEND_HISTORY
40 #define append_history(A, B)
41 #endif
42
43 #include <lib/version.h>
44 #include "getopt.h"
45 #include "command.h"
46 #include "memory.h"
47 #include "linklist.h"
48 #include "libfrr.h"
49 #include "ferr.h"
50 #include "lib_errors.h"
51
52 #include "vtysh/vtysh.h"
53 #include "vtysh/vtysh_user.h"
54
55 /* VTY shell program name. */
56 char *progname;
57
58 /* SUID mode */
59 static uid_t elevuid, realuid;
60 static gid_t elevgid, realgid;
61
62 #define VTYSH_CONFIG_NAME "vtysh.conf"
63 #define FRR_CONFIG_NAME "frr.conf"
64
65 /* Configuration file name and directory. */
66 static char vtysh_config[MAXPATHLEN * 3];
67 char frr_config[MAXPATHLEN * 3];
68 char vtydir[MAXPATHLEN];
69 static char history_file[MAXPATHLEN];
70
71 /* Flag for indicate executing child command. */
72 int execute_flag = 0;
73
74 /* Flag to indicate if in user/unprivileged mode. */
75 int user_mode;
76
77 /* For sigsetjmp() & siglongjmp(). */
78 static sigjmp_buf jmpbuf;
79
80 /* Flag for avoid recursive siglongjmp() call. */
81 static int jmpflag = 0;
82
83 /* A static variable for holding the line. */
84 static char *line_read;
85
86 /* Master of threads. */
87 struct thread_master *master;
88
89 /* Command logging */
90 FILE *logfile;
91
92 /* SIGTSTP handler. This function care user's ^Z input. */
93 static void sigtstp(int sig)
94 {
95 /* Execute "end" command. */
96 vtysh_execute("end");
97
98 /* Initialize readline. */
99 rl_initialize();
100 printf("\n");
101
102 /* Check jmpflag for duplicate siglongjmp(). */
103 if (!jmpflag)
104 return;
105
106 jmpflag = 0;
107
108 /* Back to main command loop. */
109 siglongjmp(jmpbuf, 1);
110 }
111
112 /* SIGINT handler. This function care user's ^Z input. */
113 static void sigint(int sig)
114 {
115 /* Check this process is not child process. */
116 if (!execute_flag) {
117 rl_initialize();
118 printf("\n");
119 rl_forced_update_display();
120 }
121 }
122
123 /* Signale wrapper for vtysh. We don't use sigevent because
124 * vtysh doesn't use threads. TODO */
125 static void vtysh_signal_set(int signo, void (*func)(int))
126 {
127 struct sigaction sig;
128 struct sigaction osig;
129
130 sig.sa_handler = func;
131 sigemptyset(&sig.sa_mask);
132 sig.sa_flags = 0;
133 #ifdef SA_RESTART
134 sig.sa_flags |= SA_RESTART;
135 #endif /* SA_RESTART */
136
137 sigaction(signo, &sig, &osig);
138 }
139
140 /* Initialization of signal handles. */
141 static void vtysh_signal_init(void)
142 {
143 vtysh_signal_set(SIGINT, sigint);
144 vtysh_signal_set(SIGTSTP, sigtstp);
145 vtysh_signal_set(SIGPIPE, SIG_IGN);
146 }
147
148 /* Help information display. */
149 static void usage(int status)
150 {
151 if (status != 0)
152 fprintf(stderr, "Try `%s --help' for more information.\n",
153 progname);
154 else
155 printf("Usage : %s [OPTION...]\n\n"
156 "Integrated shell for FRR (version " FRR_VERSION
157 "). \n"
158 "Configured with:\n " FRR_CONFIG_ARGS
159 "\n\n"
160 "-b, --boot Execute boot startup configuration\n"
161 "-c, --command Execute argument as command\n"
162 "-d, --daemon Connect only to the specified daemon\n"
163 "-f, --inputfile Execute commands from specific file and exit\n"
164 "-E, --echo Echo prompt and command in -c mode\n"
165 "-C, --dryrun Check configuration for validity and exit\n"
166 "-m, --markfile Mark input file with context end\n"
167 " --vty_socket Override vty socket path\n"
168 " --config_dir Override config directory path\n"
169 "-N --pathspace Insert prefix into config & socket paths\n"
170 "-u --user Run as an unprivileged user\n"
171 "-w, --writeconfig Write integrated config (frr.conf) and exit\n"
172 "-H, --histfile Override history file\n"
173 "-h, --help Display this help and exit\n\n"
174 "Note that multiple commands may be executed from the command\n"
175 "line by passing multiple -c args, or by embedding linefeed\n"
176 "characters in one or more of the commands.\n\n"
177 "Report bugs to %s\n",
178 progname, FRR_BUG_ADDRESS);
179
180 exit(status);
181 }
182
183 /* VTY shell options, we use GNU getopt library. */
184 #define OPTION_VTYSOCK 1000
185 #define OPTION_CONFDIR 1001
186 struct option longopts[] = {
187 {"boot", no_argument, NULL, 'b'},
188 /* For compatibility with older zebra/quagga versions */
189 {"eval", required_argument, NULL, 'e'},
190 {"command", required_argument, NULL, 'c'},
191 {"daemon", required_argument, NULL, 'd'},
192 {"vty_socket", required_argument, NULL, OPTION_VTYSOCK},
193 {"config_dir", required_argument, NULL, OPTION_CONFDIR},
194 {"inputfile", required_argument, NULL, 'f'},
195 {"histfile", required_argument, NULL, 'H'},
196 {"echo", no_argument, NULL, 'E'},
197 {"dryrun", no_argument, NULL, 'C'},
198 {"help", no_argument, NULL, 'h'},
199 {"noerror", no_argument, NULL, 'n'},
200 {"mark", no_argument, NULL, 'm'},
201 {"writeconfig", no_argument, NULL, 'w'},
202 {"pathspace", required_argument, NULL, 'N'},
203 {"user", no_argument, NULL, 'u'},
204 {0}};
205
206 /* Read a string, and return a pointer to it. Returns NULL on EOF. */
207 static char *vtysh_rl_gets(void)
208 {
209 HIST_ENTRY *last;
210 /* If the buffer has already been allocated, return the memory
211 * to the free pool. */
212 if (line_read) {
213 free(line_read);
214 line_read = NULL;
215 }
216
217 /* Get a line from the user. Change prompt according to node. XXX. */
218 line_read = readline(vtysh_prompt());
219
220 /* If the line has any text in it, save it on the history. But only if
221 * last command in history isn't the same one. */
222 if (line_read && *line_read) {
223 using_history();
224 last = previous_history();
225 if (!last || strcmp(last->line, line_read) != 0) {
226 add_history(line_read);
227 append_history(1, history_file);
228 }
229 }
230
231 return (line_read);
232 }
233
234 static void log_it(const char *line)
235 {
236 time_t t = time(NULL);
237 struct tm tmp;
238 const char *user = getenv("USER");
239 char tod[64];
240
241 localtime_r(&t, &tmp);
242 if (!user)
243 user = "boot";
244
245 strftime(tod, sizeof(tod), "%Y%m%d-%H:%M.%S", &tmp);
246
247 fprintf(logfile, "%s:%s %s\n", tod, user, line);
248 }
249
250 static int flock_fd;
251
252 static void vtysh_flock_config(const char *flock_file)
253 {
254 int count = 0;
255
256 flock_fd = open(flock_file, O_RDONLY, 0644);
257 if (flock_fd < 0) {
258 fprintf(stderr, "Unable to create lock file: %s, %s\n",
259 flock_file, safe_strerror(errno));
260 return;
261 }
262
263 while (count < 400 && (flock(flock_fd, LOCK_EX | LOCK_NB) < 0)) {
264 count++;
265 usleep(500000);
266 }
267
268 if (count >= 400)
269 fprintf(stderr,
270 "Flock of %s failed, continuing this may cause issues\n",
271 flock_file);
272 }
273
274 static void vtysh_unflock_config(void)
275 {
276 flock(flock_fd, LOCK_UN);
277 close(flock_fd);
278 }
279
280 void suid_on(void)
281 {
282 if (elevuid != realuid && seteuid(elevuid)) {
283 perror("seteuid(on)");
284 exit(1);
285 }
286 if (elevgid != realgid && setegid(elevgid)) {
287 perror("setegid(on)");
288 exit(1);
289 }
290 }
291
292 void suid_off(void)
293 {
294 if (elevuid != realuid && seteuid(realuid)) {
295 perror("seteuid(off)");
296 exit(1);
297 }
298 if (elevgid != realgid && setegid(realgid)) {
299 perror("setegid(off)");
300 exit(1);
301 }
302 }
303
304 /* VTY shell main routine. */
305 int main(int argc, char **argv, char **env)
306 {
307 char *p;
308 int opt;
309 int dryrun = 0;
310 int boot_flag = 0;
311 const char *daemon_name = NULL;
312 const char *inputfile = NULL;
313 struct cmd_rec {
314 char *line;
315 struct cmd_rec *next;
316 } *cmd = NULL;
317 struct cmd_rec *tail = NULL;
318 int echo_command = 0;
319 int no_error = 0;
320 int markfile = 0;
321 int writeconfig = 0;
322 int ret = 0;
323 char *homedir = NULL;
324 int ditch_suid = 0;
325 char sysconfdir[MAXPATHLEN];
326 const char *pathspace_arg = NULL;
327 char pathspace[MAXPATHLEN] = "";
328 const char *histfile = NULL;
329
330 /* SUID: drop down to calling user & go back up when needed */
331 elevuid = geteuid();
332 elevgid = getegid();
333 realuid = getuid();
334 realgid = getgid();
335 suid_off();
336
337 user_mode = 0; /* may be set in options processing */
338
339 /* Preserve name of myself. */
340 progname = ((p = strrchr(argv[0], '/')) ? ++p : argv[0]);
341
342 strlcpy(sysconfdir, frr_sysconfdir, sizeof(sysconfdir));
343
344 frr_init_vtydir();
345 strlcpy(vtydir, frr_vtydir, sizeof(vtydir));
346
347 /* Option handling. */
348 while (1) {
349 opt = getopt_long(argc, argv, "be:c:d:nf:H:mEhCwN:u", longopts,
350 0);
351
352 if (opt == EOF)
353 break;
354
355 switch (opt) {
356 case 0:
357 break;
358 case 'b':
359 boot_flag = 1;
360 break;
361 case 'e':
362 case 'c': {
363 struct cmd_rec *cr;
364 cr = XMALLOC(MTYPE_TMP, sizeof(*cr));
365 cr->line = optarg;
366 cr->next = NULL;
367 if (tail)
368 tail->next = cr;
369 else
370 cmd = cr;
371 tail = cr;
372 } break;
373 case OPTION_VTYSOCK:
374 ditch_suid = 1; /* option disables SUID */
375 strlcpy(vtydir, optarg, sizeof(vtydir));
376 break;
377 case OPTION_CONFDIR:
378 ditch_suid = 1; /* option disables SUID */
379 snprintf(sysconfdir, sizeof(sysconfdir), "%s/", optarg);
380 break;
381 case 'N':
382 if (strchr(optarg, '/') || strchr(optarg, '.')) {
383 fprintf(stderr,
384 "slashes or dots are not permitted in the --pathspace option.\n");
385 exit(1);
386 }
387 pathspace_arg = optarg;
388 snprintf(pathspace, sizeof(pathspace), "%s/", optarg);
389 break;
390 case 'd':
391 daemon_name = optarg;
392 break;
393 case 'f':
394 inputfile = optarg;
395 break;
396 case 'm':
397 markfile = 1;
398 break;
399 case 'n':
400 no_error = 1;
401 break;
402 case 'E':
403 echo_command = 1;
404 break;
405 case 'C':
406 dryrun = 1;
407 break;
408 case 'u':
409 user_mode = 1;
410 break;
411 case 'w':
412 writeconfig = 1;
413 break;
414 case 'h':
415 usage(0);
416 break;
417 case 'H':
418 histfile = optarg;
419 break;
420 default:
421 usage(1);
422 break;
423 }
424 }
425
426 if (ditch_suid) {
427 elevuid = realuid;
428 elevgid = realgid;
429 }
430
431 if (markfile + writeconfig + dryrun + boot_flag > 1) {
432 fprintf(stderr,
433 "Invalid combination of arguments. Please specify at most one of:\n\t-b, -C, -m, -w\n");
434 return 1;
435 }
436 if (inputfile && (writeconfig || boot_flag)) {
437 fprintf(stderr,
438 "WARNING: Combinining the -f option with -b or -w is NOT SUPPORTED since its\nresults are inconsistent!\n");
439 }
440
441 snprintf(vtysh_config, sizeof(vtysh_config), "%s%s%s", sysconfdir,
442 pathspace, VTYSH_CONFIG_NAME);
443 snprintf(frr_config, sizeof(frr_config), "%s%s%s", sysconfdir,
444 pathspace, FRR_CONFIG_NAME);
445
446 if (pathspace_arg) {
447 strlcat(vtydir, "/", sizeof(vtydir));
448 strlcat(vtydir, pathspace_arg, sizeof(vtydir));
449 }
450
451 /* Initialize user input buffer. */
452 line_read = NULL;
453 setlinebuf(stdout);
454
455 /* Signal and others. */
456 vtysh_signal_init();
457
458 /* Make vty structure and register commands. */
459 vtysh_init_vty();
460 vtysh_init_cmd();
461 vtysh_user_init();
462 vtysh_config_init();
463
464 vty_init_vtysh();
465
466 if (!user_mode) {
467 /* Read vtysh configuration file before connecting to daemons.
468 * (file may not be readable to calling user in SUID mode) */
469 suid_on();
470 vtysh_read_config(vtysh_config, dryrun);
471 suid_off();
472 }
473 /* Error code library system */
474 log_ref_init();
475 lib_error_init();
476
477 if (markfile) {
478 if (!inputfile) {
479 fprintf(stderr,
480 "-f option MUST be specified with -m option\n");
481 return 1;
482 }
483 return (vtysh_mark_file(inputfile));
484 }
485
486 /* Start execution only if not in dry-run mode */
487 if (dryrun && !cmd) {
488 if (inputfile) {
489 ret = vtysh_read_config(inputfile, dryrun);
490 } else {
491 ret = vtysh_read_config(frr_config, dryrun);
492 }
493
494 exit(ret);
495 }
496
497 if (dryrun && cmd && cmd->line) {
498 if (!user_mode)
499 vtysh_execute("enable");
500 while (cmd) {
501 struct cmd_rec *cr;
502 char *cmdnow = cmd->line, *next;
503 do {
504 next = strchr(cmdnow, '\n');
505 if (next)
506 *next++ = '\0';
507
508 if (echo_command)
509 printf("%s%s\n", vtysh_prompt(),
510 cmdnow);
511
512 ret = vtysh_execute_no_pager(cmdnow);
513 if (!no_error
514 && !(ret == CMD_SUCCESS
515 || ret == CMD_SUCCESS_DAEMON
516 || ret == CMD_WARNING))
517 exit(1);
518 } while ((cmdnow = next) != NULL);
519
520 cr = cmd;
521 cmd = cmd->next;
522 XFREE(MTYPE_TMP, cr);
523 }
524 exit(ret);
525 }
526
527 /* Ignore error messages */
528 if (no_error) {
529 if (freopen("/dev/null", "w", stdout) == NULL) {
530 fprintf(stderr,
531 "Exiting: Failed to duplicate stdout with -n option");
532 exit(1);
533 }
534 }
535
536 /* SUID: go back up elevated privs */
537 suid_on();
538
539 /* Make sure we pass authentication before proceeding. */
540 vtysh_auth();
541
542 /* Do not connect until we have passed authentication. */
543 if (vtysh_connect_all(daemon_name) <= 0) {
544 fprintf(stderr, "Exiting: failed to connect to any daemons.\n");
545 if (geteuid() != 0)
546 fprintf(stderr,
547 "Hint: if this seems wrong, try running me as a privileged user!\n");
548 if (no_error)
549 exit(0);
550 else
551 exit(1);
552 }
553
554 /* SUID: back down, don't need privs further on */
555 suid_off();
556
557 if (writeconfig) {
558 if (user_mode) {
559 fprintf(stderr,
560 "writeconfig cannot be used when running as an unprivileged user.\n");
561 if (no_error)
562 exit(0);
563 else
564 exit(1);
565 }
566 vtysh_execute("enable");
567 return vtysh_write_config_integrated();
568 }
569
570 if (inputfile) {
571 vtysh_flock_config(inputfile);
572 ret = vtysh_read_config(inputfile, dryrun);
573 vtysh_unflock_config();
574 exit(ret);
575 }
576
577 /*
578 * Setup history file for use by both -c and regular input
579 * If we can't find the home directory, then don't store
580 * the history information.
581 * VTYSH_HISTFILE is prefered over command line
582 * argument (-H/--histfile).
583 */
584 if (getenv("VTYSH_HISTFILE")) {
585 const char *file = getenv("VTYSH_HISTFILE");
586
587 strlcpy(history_file, file, sizeof(history_file));
588 } else if (histfile) {
589 strlcpy(history_file, histfile, sizeof(history_file));
590 } else {
591 homedir = vtysh_get_home();
592 if (homedir)
593 snprintf(history_file, sizeof(history_file),
594 "%s/.history_frr", homedir);
595 }
596
597 if (strlen(history_file) > 0) {
598 if (read_history(history_file) != 0) {
599 int fp;
600
601 fp = open(history_file, O_CREAT | O_EXCL,
602 S_IRUSR | S_IWUSR);
603 if (fp != -1)
604 close(fp);
605
606 read_history(history_file);
607 }
608 }
609
610 if (getenv("VTYSH_LOG")) {
611 const char *logpath = getenv("VTYSH_LOG");
612
613 logfile = fopen(logpath, "a");
614 if (!logfile) {
615 fprintf(stderr, "Failed to open logfile (%s): %s\n",
616 logpath, strerror(errno));
617 exit(1);
618 }
619 }
620
621 /* If eval mode. */
622 if (cmd && cmd->line) {
623 /* Enter into enable node. */
624 if (!user_mode)
625 vtysh_execute("enable");
626
627 while (cmd != NULL) {
628 char *eol;
629
630 while ((eol = strchr(cmd->line, '\n')) != NULL) {
631 *eol = '\0';
632
633 add_history(cmd->line);
634 append_history(1, history_file);
635
636 if (echo_command)
637 printf("%s%s\n", vtysh_prompt(),
638 cmd->line);
639
640 if (logfile)
641 log_it(cmd->line);
642
643 ret = vtysh_execute_no_pager(cmd->line);
644 if (!no_error
645 && !(ret == CMD_SUCCESS
646 || ret == CMD_SUCCESS_DAEMON
647 || ret == CMD_WARNING))
648 exit(1);
649
650 cmd->line = eol + 1;
651 }
652
653 add_history(cmd->line);
654 append_history(1, history_file);
655
656 if (echo_command)
657 printf("%s%s\n", vtysh_prompt(), cmd->line);
658
659 if (logfile)
660 log_it(cmd->line);
661
662 /*
663 * Parsing logic for regular commands will be different
664 * than for those commands requiring further
665 * processing, such as cli instructions terminating
666 * with question-mark character.
667 */
668 if (!vtysh_execute_command_questionmark(cmd->line))
669 ret = CMD_SUCCESS;
670 else
671 ret = vtysh_execute_no_pager(cmd->line);
672
673 if (!no_error
674 && !(ret == CMD_SUCCESS || ret == CMD_SUCCESS_DAEMON
675 || ret == CMD_WARNING))
676 exit(1);
677
678 {
679 struct cmd_rec *cr;
680 cr = cmd;
681 cmd = cmd->next;
682 XFREE(MTYPE_TMP, cr);
683 }
684 }
685
686 history_truncate_file(history_file, 1000);
687 exit(0);
688 }
689
690 /* Boot startup configuration file. */
691 if (boot_flag) {
692 vtysh_flock_config(frr_config);
693 ret = vtysh_read_config(frr_config, dryrun);
694 vtysh_unflock_config();
695 if (ret) {
696 fprintf(stderr,
697 "Configuration file[%s] processing failure: %d\n",
698 frr_config, ret);
699 if (no_error)
700 exit(0);
701 else
702 exit(ret);
703 } else
704 exit(0);
705 }
706
707 vtysh_readline_init();
708
709 vty_hello(vty);
710
711 /* Enter into enable node. */
712 if (!user_mode)
713 vtysh_execute("enable");
714
715 /* Preparation for longjmp() in sigtstp(). */
716 sigsetjmp(jmpbuf, 1);
717 jmpflag = 1;
718
719 /* Main command loop. */
720 while (vtysh_rl_gets())
721 vtysh_execute(line_read);
722
723 vtysh_uninit();
724
725 history_truncate_file(history_file, 1000);
726 printf("\n");
727
728 /* Rest in peace. */
729 exit(0);
730 }