]> git.proxmox.com Git - mirror_frr.git/blob - vtysh/vtysh_main.c
vtysh: Have help dump the how FRR was built
[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 "). \n"
157 "Configured with:\n " FRR_CONFIG_ARGS "\n\n"
158 "-b, --boot Execute boot startup configuration\n"
159 "-c, --command Execute argument as command\n"
160 "-d, --daemon Connect only to the specified daemon\n"
161 "-f, --inputfile Execute commands from specific file and exit\n"
162 "-E, --echo Echo prompt and command in -c mode\n"
163 "-C, --dryrun Check configuration for validity and exit\n"
164 "-m, --markfile Mark input file with context end\n"
165 " --vty_socket Override vty socket path\n"
166 " --config_dir Override config directory path\n"
167 "-N --pathspace Insert prefix into config & socket paths\n"
168 "-u --user Run as an unprivileged user\n"
169 "-w, --writeconfig Write integrated config (frr.conf) and exit\n"
170 "-h, --help Display this help and exit\n\n"
171 "Note that multiple commands may be executed from the command\n"
172 "line by passing multiple -c args, or by embedding linefeed\n"
173 "characters in one or more of the commands.\n\n"
174 "Report bugs to %s\n",
175 progname, FRR_BUG_ADDRESS);
176
177 exit(status);
178 }
179
180 /* VTY shell options, we use GNU getopt library. */
181 #define OPTION_VTYSOCK 1000
182 #define OPTION_CONFDIR 1001
183 struct option longopts[] = {
184 {"boot", no_argument, NULL, 'b'},
185 /* For compatibility with older zebra/quagga versions */
186 {"eval", required_argument, NULL, 'e'},
187 {"command", required_argument, NULL, 'c'},
188 {"daemon", required_argument, NULL, 'd'},
189 {"vty_socket", required_argument, NULL, OPTION_VTYSOCK},
190 {"config_dir", required_argument, NULL, OPTION_CONFDIR},
191 {"inputfile", required_argument, NULL, 'f'},
192 {"echo", no_argument, NULL, 'E'},
193 {"dryrun", no_argument, NULL, 'C'},
194 {"help", no_argument, NULL, 'h'},
195 {"noerror", no_argument, NULL, 'n'},
196 {"mark", no_argument, NULL, 'm'},
197 {"writeconfig", no_argument, NULL, 'w'},
198 {"pathspace", required_argument, NULL, 'N'},
199 {"user", no_argument, NULL, 'u'},
200 {0}};
201
202 /* Read a string, and return a pointer to it. Returns NULL on EOF. */
203 static char *vtysh_rl_gets(void)
204 {
205 HIST_ENTRY *last;
206 /* If the buffer has already been allocated, return the memory
207 * to the free pool. */
208 if (line_read) {
209 free(line_read);
210 line_read = NULL;
211 }
212
213 /* Get a line from the user. Change prompt according to node. XXX. */
214 line_read = readline(vtysh_prompt());
215
216 /* If the line has any text in it, save it on the history. But only if
217 * last command in history isn't the same one. */
218 if (line_read && *line_read) {
219 using_history();
220 last = previous_history();
221 if (!last || strcmp(last->line, line_read) != 0) {
222 add_history(line_read);
223 append_history(1, history_file);
224 }
225 }
226
227 return (line_read);
228 }
229
230 static void log_it(const char *line)
231 {
232 time_t t = time(NULL);
233 struct tm tmp;
234 const char *user = getenv("USER");
235 char tod[64];
236
237 localtime_r(&t, &tmp);
238 if (!user)
239 user = "boot";
240
241 strftime(tod, sizeof(tod), "%Y%m%d-%H:%M.%S", &tmp);
242
243 fprintf(logfile, "%s:%s %s\n", tod, user, line);
244 }
245
246 static int flock_fd;
247
248 static void vtysh_flock_config(const char *flock_file)
249 {
250 int count = 0;
251
252 flock_fd = open(flock_file, O_RDONLY, 0644);
253 if (flock_fd < 0) {
254 fprintf(stderr, "Unable to create lock file: %s, %s\n",
255 flock_file, safe_strerror(errno));
256 return;
257 }
258
259 while (count < 400 && (flock(flock_fd, LOCK_EX | LOCK_NB) < 0)) {
260 count++;
261 usleep(500000);
262 }
263
264 if (count >= 400)
265 fprintf(stderr,
266 "Flock of %s failed, continuing this may cause issues\n",
267 flock_file);
268 }
269
270 static void vtysh_unflock_config(void)
271 {
272 flock(flock_fd, LOCK_UN);
273 close(flock_fd);
274 }
275
276 void suid_on(void)
277 {
278 if (elevuid != realuid && seteuid(elevuid)) {
279 perror("seteuid(on)");
280 exit(1);
281 }
282 if (elevgid != realgid && setegid(elevgid)) {
283 perror("setegid(on)");
284 exit(1);
285 }
286 }
287
288 void suid_off(void)
289 {
290 if (elevuid != realuid && seteuid(realuid)) {
291 perror("seteuid(off)");
292 exit(1);
293 }
294 if (elevgid != realgid && setegid(realgid)) {
295 perror("setegid(off)");
296 exit(1);
297 }
298 }
299
300 /* VTY shell main routine. */
301 int main(int argc, char **argv, char **env)
302 {
303 char *p;
304 int opt;
305 int dryrun = 0;
306 int boot_flag = 0;
307 const char *daemon_name = NULL;
308 const char *inputfile = NULL;
309 struct cmd_rec {
310 char *line;
311 struct cmd_rec *next;
312 } *cmd = NULL;
313 struct cmd_rec *tail = NULL;
314 int echo_command = 0;
315 int no_error = 0;
316 int markfile = 0;
317 int writeconfig = 0;
318 int ret = 0;
319 char *homedir = NULL;
320 int ditch_suid = 0;
321 char sysconfdir[MAXPATHLEN];
322 const char *pathspace_arg = NULL;
323 char pathspace[MAXPATHLEN] = "";
324
325 /* SUID: drop down to calling user & go back up when needed */
326 elevuid = geteuid();
327 elevgid = getegid();
328 realuid = getuid();
329 realgid = getgid();
330 suid_off();
331
332 user_mode = 0; /* may be set in options processing */
333
334 /* Preserve name of myself. */
335 progname = ((p = strrchr(argv[0], '/')) ? ++p : argv[0]);
336
337 strlcpy(sysconfdir, frr_sysconfdir, sizeof(sysconfdir));
338
339 frr_init_vtydir();
340 strlcpy(vtydir, frr_vtydir, sizeof(vtydir));
341
342 /* Option handling. */
343 while (1) {
344 opt = getopt_long(argc, argv, "be:c:d:nf:mEhCwN:u",
345 longopts, 0);
346
347 if (opt == EOF)
348 break;
349
350 switch (opt) {
351 case 0:
352 break;
353 case 'b':
354 boot_flag = 1;
355 break;
356 case 'e':
357 case 'c': {
358 struct cmd_rec *cr;
359 cr = XMALLOC(MTYPE_TMP, sizeof(*cr));
360 cr->line = optarg;
361 cr->next = NULL;
362 if (tail)
363 tail->next = cr;
364 else
365 cmd = cr;
366 tail = cr;
367 } break;
368 case OPTION_VTYSOCK:
369 ditch_suid = 1; /* option disables SUID */
370 strlcpy(vtydir, optarg, sizeof(vtydir));
371 break;
372 case OPTION_CONFDIR:
373 ditch_suid = 1; /* option disables SUID */
374 snprintf(sysconfdir, sizeof(sysconfdir), "%s/", optarg);
375 break;
376 case 'N':
377 if (strchr(optarg, '/') || strchr(optarg, '.')) {
378 fprintf(stderr,
379 "slashes or dots are not permitted in the --pathspace option.\n");
380 exit(1);
381 }
382 pathspace_arg = optarg;
383 snprintf(pathspace, sizeof(pathspace), "%s/", optarg);
384 break;
385 case 'd':
386 daemon_name = optarg;
387 break;
388 case 'f':
389 inputfile = optarg;
390 break;
391 case 'm':
392 markfile = 1;
393 break;
394 case 'n':
395 no_error = 1;
396 break;
397 case 'E':
398 echo_command = 1;
399 break;
400 case 'C':
401 dryrun = 1;
402 break;
403 case 'u':
404 user_mode = 1;
405 break;
406 case 'w':
407 writeconfig = 1;
408 break;
409 case 'h':
410 usage(0);
411 break;
412 default:
413 usage(1);
414 break;
415 }
416 }
417
418 if (ditch_suid) {
419 elevuid = realuid;
420 elevgid = realgid;
421 }
422
423 if (markfile + writeconfig + dryrun + boot_flag > 1) {
424 fprintf(stderr,
425 "Invalid combination of arguments. Please specify at most one of:\n\t-b, -C, -m, -w\n");
426 return 1;
427 }
428 if (inputfile && (writeconfig || boot_flag)) {
429 fprintf(stderr,
430 "WARNING: Combinining the -f option with -b or -w is NOT SUPPORTED since its\nresults are inconsistent!\n");
431 }
432
433 snprintf(vtysh_config, sizeof(vtysh_config), "%s%s%s", sysconfdir,
434 pathspace, VTYSH_CONFIG_NAME);
435 snprintf(frr_config, sizeof(frr_config), "%s%s%s", sysconfdir,
436 pathspace, FRR_CONFIG_NAME);
437
438 if (pathspace_arg) {
439 strlcat(vtydir, "/", sizeof(vtydir));
440 strlcat(vtydir, pathspace_arg, sizeof(vtydir));
441 }
442
443 /* Initialize user input buffer. */
444 line_read = NULL;
445 setlinebuf(stdout);
446
447 /* Signal and others. */
448 vtysh_signal_init();
449
450 /* Make vty structure and register commands. */
451 vtysh_init_vty();
452 vtysh_init_cmd();
453 vtysh_user_init();
454 vtysh_config_init();
455
456 vty_init_vtysh();
457
458 if (!user_mode) {
459 /* Read vtysh configuration file before connecting to daemons.
460 * (file may not be readable to calling user in SUID mode) */
461 suid_on();
462 vtysh_read_config(vtysh_config);
463 suid_off();
464 }
465 /* Error code library system */
466 log_ref_init();
467 lib_error_init();
468
469 if (markfile) {
470 if (!inputfile) {
471 fprintf(stderr,
472 "-f option MUST be specified with -m option\n");
473 return 1;
474 }
475 return (vtysh_mark_file(inputfile));
476 }
477
478 /* Start execution only if not in dry-run mode */
479 if (dryrun && !cmd) {
480 if (inputfile) {
481 ret = vtysh_read_config(inputfile);
482 } else {
483 ret = vtysh_read_config(frr_config);
484 }
485
486 exit(ret);
487 }
488
489 if (dryrun && cmd && cmd->line) {
490 if (!user_mode)
491 vtysh_execute("enable");
492 while (cmd) {
493 struct cmd_rec *cr;
494 char *cmdnow = cmd->line, *next;
495 do {
496 next = strchr(cmdnow, '\n');
497 if (next)
498 *next++ = '\0';
499
500 if (echo_command)
501 printf("%s%s\n", vtysh_prompt(),
502 cmdnow);
503
504 ret = vtysh_execute_no_pager(cmdnow);
505 if (!no_error
506 && !(ret == CMD_SUCCESS
507 || ret == CMD_SUCCESS_DAEMON
508 || ret == CMD_WARNING))
509 exit(1);
510 } while ((cmdnow = next) != NULL);
511
512 cr = cmd;
513 cmd = cmd->next;
514 XFREE(MTYPE_TMP, cr);
515 }
516 exit(ret);
517 }
518
519 /* Ignore error messages */
520 if (no_error) {
521 if (freopen("/dev/null", "w", stdout) == NULL) {
522 fprintf(stderr,
523 "Exiting: Failed to duplicate stdout with -n option");
524 exit(1);
525 }
526 }
527
528 /* SUID: go back up elevated privs */
529 suid_on();
530
531 /* Make sure we pass authentication before proceeding. */
532 vtysh_auth();
533
534 /* Do not connect until we have passed authentication. */
535 if (vtysh_connect_all(daemon_name) <= 0) {
536 fprintf(stderr, "Exiting: failed to connect to any daemons.\n");
537 if (geteuid() != 0)
538 fprintf(stderr,
539 "Hint: if this seems wrong, try running me as a privileged user!\n");
540 if (no_error)
541 exit(0);
542 else
543 exit(1);
544 }
545
546 /* SUID: back down, don't need privs further on */
547 suid_off();
548
549 if (writeconfig) {
550 if (user_mode) {
551 fprintf(stderr,
552 "writeconfig cannot be used when running as an unprivileged user.\n");
553 if (no_error)
554 exit(0);
555 else
556 exit(1);
557 }
558 vtysh_execute("enable");
559 return vtysh_write_config_integrated();
560 }
561
562 if (inputfile) {
563 vtysh_flock_config(inputfile);
564 ret = vtysh_read_config(inputfile);
565 vtysh_unflock_config();
566 exit(ret);
567 }
568
569 /*
570 * Setup history file for use by both -c and regular input
571 * If we can't find the home directory, then don't store
572 * the history information
573 */
574 homedir = vtysh_get_home();
575 if (homedir) {
576 snprintf(history_file, sizeof(history_file), "%s/.history_frr",
577 homedir);
578 if (read_history(history_file) != 0) {
579 int fp;
580
581 fp = open(history_file, O_CREAT | O_EXCL,
582 S_IRUSR | S_IWUSR);
583 if (fp != -1)
584 close(fp);
585
586 read_history(history_file);
587 }
588 }
589
590 if (getenv("VTYSH_LOG")) {
591 const char *logpath = getenv("VTYSH_LOG");
592
593 logfile = fopen(logpath, "a");
594 if (!logfile) {
595 fprintf(stderr, "Failed to open logfile (%s): %s\n",
596 logpath, strerror(errno));
597 exit(1);
598 }
599 }
600
601 /* If eval mode. */
602 if (cmd && cmd->line) {
603 /* Enter into enable node. */
604 if (!user_mode)
605 vtysh_execute("enable");
606
607 while (cmd != NULL) {
608 char *eol;
609
610 while ((eol = strchr(cmd->line, '\n')) != NULL) {
611 *eol = '\0';
612
613 add_history(cmd->line);
614 append_history(1, history_file);
615
616 if (echo_command)
617 printf("%s%s\n", vtysh_prompt(),
618 cmd->line);
619
620 if (logfile)
621 log_it(cmd->line);
622
623 ret = vtysh_execute_no_pager(cmd->line);
624 if (!no_error
625 && !(ret == CMD_SUCCESS
626 || ret == CMD_SUCCESS_DAEMON
627 || ret == CMD_WARNING))
628 exit(1);
629
630 cmd->line = eol + 1;
631 }
632
633 add_history(cmd->line);
634 append_history(1, history_file);
635
636 if (echo_command)
637 printf("%s%s\n", vtysh_prompt(), cmd->line);
638
639 if (logfile)
640 log_it(cmd->line);
641
642 /*
643 * Parsing logic for regular commands will be different
644 * than for those commands requiring further
645 * processing, such as cli instructions terminating
646 * with question-mark character.
647 */
648 if (!vtysh_execute_command_questionmark(cmd->line))
649 ret = CMD_SUCCESS;
650 else
651 ret = vtysh_execute_no_pager(cmd->line);
652
653 if (!no_error
654 && !(ret == CMD_SUCCESS || ret == CMD_SUCCESS_DAEMON
655 || ret == CMD_WARNING))
656 exit(1);
657
658 {
659 struct cmd_rec *cr;
660 cr = cmd;
661 cmd = cmd->next;
662 XFREE(MTYPE_TMP, cr);
663 }
664 }
665
666 history_truncate_file(history_file, 1000);
667 exit(0);
668 }
669
670 /* Boot startup configuration file. */
671 if (boot_flag) {
672 vtysh_flock_config(frr_config);
673 ret = vtysh_read_config(frr_config);
674 vtysh_unflock_config();
675 if (ret) {
676 fprintf(stderr,
677 "Configuration file[%s] processing failure: %d\n",
678 frr_config, ret);
679 if (no_error)
680 exit(0);
681 else
682 exit(ret);
683 } else
684 exit(0);
685 }
686
687 vtysh_readline_init();
688
689 vty_hello(vty);
690
691 /* Enter into enable node. */
692 if (!user_mode)
693 vtysh_execute("enable");
694
695 /* Preparation for longjmp() in sigtstp(). */
696 sigsetjmp(jmpbuf, 1);
697 jmpflag = 1;
698
699 /* Main command loop. */
700 while (vtysh_rl_gets())
701 vtysh_execute(line_read);
702
703 vtysh_uninit();
704
705 history_truncate_file(history_file, 1000);
706 printf("\n");
707
708 /* Rest in peace. */
709 exit(0);
710 }