]> git.proxmox.com Git - mirror_frr.git/blame - lib/vty.c
zebra: move up prefix2str call in rib dump
[mirror_frr.git] / lib / vty.c
CommitLineData
718e3744 1/*
2 * Virtual terminal [aka TeletYpe] interface routine.
3 * Copyright (C) 1997, 98 Kunihiro Ishiguro
4 *
5 * This file is part of GNU Zebra.
6 *
7 * GNU Zebra is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2, or (at your option) any
10 * later version.
11 *
12 * GNU Zebra is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
896014f4
DL
17 * You should have received a copy of the GNU General Public License along
18 * with this program; see the file COPYING; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
718e3744 20 */
21
22#include <zebra.h>
23
fe6b47b9
QY
24#include <lib/version.h>
25#include <sys/types.h>
beee9b4a
DS
26#include <sys/types.h>
27#ifdef HAVE_LIBPCREPOSIX
28#include <pcreposix.h>
29#else
fe6b47b9 30#include <regex.h>
beee9b4a 31#endif /* HAVE_LIBPCREPOSIX */
6ef6e4f0 32#include <stdio.h>
fe6b47b9 33
718e3744 34#include "linklist.h"
b21b19c5 35#include "thread.h"
718e3744 36#include "buffer.h"
718e3744 37#include "command.h"
38#include "sockunion.h"
718e3744 39#include "memory.h"
718e3744 40#include "log.h"
41#include "prefix.h"
42#include "filter.h"
b21b19c5 43#include "vty.h"
edd7c245 44#include "privs.h"
9fc7ebf1 45#include "network.h"
b85120bc 46#include "libfrr.h"
fe6b47b9 47#include "frrstr.h"
ab99c8e2 48#include "lib_errors.h"
1c2facd1 49#include "northbound_cli.h"
807f5b98 50#include "printfrr.h"
9fc7ebf1 51
52#include <arpa/telnet.h>
b510a06e 53#include <termios.h>
718e3744 54
2950f5da
DS
55#ifndef VTYSH_EXTRACT_PL
56#include "lib/vty_clippy.c"
57#endif
58
d62a17ae 59DEFINE_MTYPE_STATIC(LIB, VTY, "VTY")
4a1ab8e4 60DEFINE_MTYPE_STATIC(LIB, VTY_OUT_BUF, "VTY output buffer")
d62a17ae 61DEFINE_MTYPE_STATIC(LIB, VTY_HIST, "VTY history")
4a1ab8e4 62
718e3744 63/* Vty events */
d62a17ae 64enum event {
65 VTY_SERV,
66 VTY_READ,
67 VTY_WRITE,
68 VTY_TIMEOUT_RESET,
718e3744 69#ifdef VTYSH
d62a17ae 70 VTYSH_SERV,
71 VTYSH_READ,
72 VTYSH_WRITE
718e3744 73#endif /* VTYSH */
74};
75
ab699721
DL
76static void vty_event_serv(enum event event, int sock);
77static void vty_event(enum event, struct vty *);
718e3744 78
79/* Extern host structure from command.c */
80extern struct host host;
6b0655a2 81
718e3744 82/* Vector which store each vty structure. */
83static vector vtyvec;
84
85/* Vty timeout value. */
86static unsigned long vty_timeout_val = VTY_TIMEOUT_DEFAULT;
87
88/* Vty access-class command */
89static char *vty_accesslist_name = NULL;
90
91/* Vty access-calss for IPv6. */
92static char *vty_ipv6_accesslist_name = NULL;
93
94/* VTY server thread. */
677bcbbf 95static vector Vvty_serv_thread;
718e3744 96
97/* Current directory. */
1b3e9a21 98static char vty_cwd[MAXPATHLEN];
718e3744 99
718e3744 100/* Login password check. */
101static int no_password_check = 0;
102
103/* Integrated configuration file path */
c17faa4b 104static char integrate_default[] = SYSCONFDIR INTEGRATE_DEFAULT_CONFIG;
718e3744 105
2950f5da
DS
106static bool do_log_commands;
107static bool do_log_commands_perm;
6b0655a2 108
2071aa0e
DL
109void vty_frame(struct vty *vty, const char *format, ...)
110{
111 va_list args;
112
113 va_start(args, format);
c7179009
DL
114 vsnprintfrr(vty->frame + vty->frame_pos,
115 sizeof(vty->frame) - vty->frame_pos, format, args);
2071aa0e
DL
116 vty->frame_pos = strlen(vty->frame);
117 va_end(args);
118}
119
120void vty_endframe(struct vty *vty, const char *endtext)
121{
122 if (vty->frame_pos == 0 && endtext)
123 vty_out(vty, "%s", endtext);
124 vty->frame_pos = 0;
125}
126
fe6b47b9
QY
127bool vty_set_include(struct vty *vty, const char *regexp)
128{
129 int errcode;
130 bool ret = true;
131 char errbuf[256];
132
8224c6cf 133 if (!regexp) {
134 if (vty->filter) {
135 regfree(&vty->include);
136 vty->filter = false;
137 }
fe6b47b9
QY
138 return true;
139 }
140
141 errcode = regcomp(&vty->include, regexp,
142 REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
143 if (errcode) {
144 ret = false;
511942ba
IR
145 regerror(errcode, &vty->include, errbuf, sizeof(errbuf));
146 vty_out(vty, "%% Regex compilation error: %s\n", errbuf);
fe6b47b9
QY
147 } else {
148 vty->filter = true;
149 }
150
151 return ret;
152}
153
83eba583 154/* VTY standard output function. */
d62a17ae 155int vty_out(struct vty *vty, const char *format, ...)
156{
157 va_list args;
807f5b98 158 ssize_t len;
d62a17ae 159 char buf[1024];
fa3bf3a2 160 char *p = NULL;
fe6b47b9 161 char *filtered;
d62a17ae 162
2071aa0e
DL
163 if (vty->frame_pos) {
164 vty->frame_pos = 0;
165 vty_out(vty, "%s", vty->frame);
166 }
167
2cddf2ff 168 va_start(args, format);
807f5b98 169 p = vasnprintfrr(MTYPE_VTY_OUT_BUF, buf, sizeof(buf), format, args);
2cddf2ff 170 va_end(args);
d62a17ae 171
807f5b98 172 len = strlen(p);
2cddf2ff
QY
173
174 /* filter buffer */
175 if (vty->filter) {
0b42d81a
QY
176 vector lines = frrstr_split_vec(p, "\n");
177
178 /* Place first value in the cache */
179 char *firstline = vector_slot(lines, 0);
180 buffer_put(vty->lbuf, (uint8_t *) firstline, strlen(firstline));
181
182 /* If our split returned more than one entry, time to filter */
183 if (vector_active(lines) > 1) {
184 /*
185 * returned string is MTYPE_TMP so it matches the MTYPE
186 * of everything else in the vector
187 */
188 char *bstr = buffer_getstr(vty->lbuf);
189 buffer_reset(vty->lbuf);
190 XFREE(MTYPE_TMP, lines->index[0]);
191 vector_set_index(lines, 0, bstr);
192 frrstr_filter_vec(lines, &vty->include);
193 vector_compact(lines);
194 /*
195 * Consider the string "foo\n". If the regex is an empty string
196 * and the line ended with a newline, then the vector will look
197 * like:
198 *
199 * [0]: 'foo'
200 * [1]: ''
201 *
202 * If the regex isn't empty, the vector will look like:
203 *
204 * [0]: 'foo'
205 *
206 * In this case we'd like to preserve the newline, so we add
207 * the empty string [1] as in the first example.
208 */
209 if (p[strlen(p) - 1] == '\n' && vector_active(lines) > 0
210 && strlen(vector_slot(lines, vector_active(lines) - 1)))
211 vector_set(lines, XSTRDUP(MTYPE_TMP, ""));
212
213 filtered = frrstr_join_vec(lines, "\n");
214 }
215 else {
216 filtered = NULL;
217 }
5d806ec6 218
2cddf2ff 219 frrstr_strvec_free(lines);
0b42d81a 220
2cddf2ff
QY
221 } else {
222 filtered = p;
223 }
d62a17ae 224
0b42d81a
QY
225 if (!filtered)
226 goto done;
227
2cddf2ff
QY
228 switch (vty->type) {
229 case VTY_TERM:
230 /* print with crlf replacement */
231 buffer_put_crlf(vty->obuf, (uint8_t *)filtered,
232 strlen(filtered));
233 break;
234 case VTY_SHELL:
9934e1c9 235 if (vty->of) {
236 fprintf(vty->of, "%s", filtered);
237 fflush(vty->of);
238 } else if (vty->of_saved) {
239 fprintf(vty->of_saved, "%s", filtered);
240 fflush(vty->of_saved);
241 }
2cddf2ff
QY
242 break;
243 case VTY_SHELL_SERV:
244 case VTY_FILE:
245 default:
246 /* print without crlf replacement */
247 buffer_put(vty->obuf, (uint8_t *)filtered, strlen(filtered));
248 break;
d62a17ae 249 }
250
0b42d81a
QY
251done:
252
253 if (vty->filter && filtered)
2cddf2ff
QY
254 XFREE(MTYPE_TMP, filtered);
255
256 /* If p is not different with buf, it is allocated buffer. */
257 if (p != buf)
258 XFREE(MTYPE_VTY_OUT_BUF, p);
259
d62a17ae 260 return len;
261}
262
263static int vty_log_out(struct vty *vty, const char *level,
807f5b98
DL
264 const char *proto_str, const char *msg,
265 struct timestamp_control *ctl)
d62a17ae 266{
267 int ret;
268 int len;
269 char buf[1024];
270
271 if (!ctl->already_rendered) {
272 ctl->len = quagga_timestamp(ctl->precision, ctl->buf,
273 sizeof(ctl->buf));
274 ctl->already_rendered = 1;
275 }
276 if (ctl->len + 1 >= sizeof(buf))
277 return -1;
278 memcpy(buf, ctl->buf, len = ctl->len);
279 buf[len++] = ' ';
280 buf[len] = '\0';
281
282 if (level)
283 ret = snprintf(buf + len, sizeof(buf) - len, "%s: %s: ", level,
284 proto_str);
285 else
286 ret = snprintf(buf + len, sizeof(buf) - len, "%s: ", proto_str);
287 if ((ret < 0) || ((size_t)(len += ret) >= sizeof(buf)))
288 return -1;
289
807f5b98 290 if (((ret = snprintf(buf + len, sizeof(buf) - len, "%s", msg)) < 0)
d62a17ae 291 || ((size_t)((len += ret) + 2) > sizeof(buf)))
292 return -1;
293
294 buf[len++] = '\r';
295 buf[len++] = '\n';
296
297 if (write(vty->wfd, buf, len) < 0) {
298 if (ERRNO_IO_RETRY(errno))
299 /* Kernel buffer is full, probably too much debugging
300 output, so just
301 drop the data and ignore. */
302 return -1;
303 /* Fatal I/O error. */
304 vty->monitor =
305 0; /* disable monitoring to avoid infinite recursion */
450971aa 306 flog_err(EC_LIB_SOCKET,
34699016
DS
307 "%s: write failed to vty client fd %d, closing: %s",
308 __func__, vty->fd, safe_strerror(errno));
d62a17ae 309 buffer_reset(vty->obuf);
0b42d81a 310 buffer_reset(vty->lbuf);
d62a17ae 311 /* cannot call vty_close, because a parent routine may still try
312 to access the vty struct */
313 vty->status = VTY_CLOSE;
314 shutdown(vty->fd, SHUT_RDWR);
315 return -1;
316 }
317 return 0;
718e3744 318}
319
320/* Output current time to the vty. */
d62a17ae 321void vty_time_print(struct vty *vty, int cr)
718e3744 322{
d62a17ae 323 char buf[QUAGGA_TIMESTAMP_LEN];
d0bfb22c 324
d62a17ae 325 if (quagga_timestamp(0, buf, sizeof(buf)) == 0) {
326 zlog_info("quagga_timestamp error");
327 return;
328 }
329 if (cr)
330 vty_out(vty, "%s\n", buf);
331 else
332 vty_out(vty, "%s ", buf);
718e3744 333
d62a17ae 334 return;
718e3744 335}
336
337/* Say hello to vty interface. */
d62a17ae 338void vty_hello(struct vty *vty)
339{
340 if (host.motdfile) {
341 FILE *f;
342 char buf[4096];
343
344 f = fopen(host.motdfile, "r");
345 if (f) {
346 while (fgets(buf, sizeof(buf), f)) {
347 char *s;
348 /* work backwards to ignore trailling isspace()
349 */
350 for (s = buf + strlen(buf);
fefa5e0f
DL
351 (s > buf) && isspace((unsigned char)s[-1]);
352 s--)
d62a17ae 353 ;
354 *s = '\0';
355 vty_out(vty, "%s\n", buf);
356 }
357 fclose(f);
358 } else
359 vty_out(vty, "MOTD file not found\n");
360 } else if (host.motd)
361 vty_out(vty, "%s", host.motd);
718e3744 362}
363
364/* Put out prompt and wait input from user. */
d62a17ae 365static void vty_prompt(struct vty *vty)
718e3744 366{
d62a17ae 367 if (vty->type == VTY_TERM) {
60466a63 368 vty_out(vty, cmd_prompt(vty->node), cmd_hostname_get());
d62a17ae 369 }
718e3744 370}
371
372/* Send WILL TELOPT_ECHO to remote server. */
d62a17ae 373static void vty_will_echo(struct vty *vty)
718e3744 374{
d62a17ae 375 unsigned char cmd[] = {IAC, WILL, TELOPT_ECHO, '\0'};
376 vty_out(vty, "%s", cmd);
718e3744 377}
378
379/* Make suppress Go-Ahead telnet option. */
d62a17ae 380static void vty_will_suppress_go_ahead(struct vty *vty)
718e3744 381{
d62a17ae 382 unsigned char cmd[] = {IAC, WILL, TELOPT_SGA, '\0'};
383 vty_out(vty, "%s", cmd);
718e3744 384}
385
386/* Make don't use linemode over telnet. */
d62a17ae 387static void vty_dont_linemode(struct vty *vty)
718e3744 388{
d62a17ae 389 unsigned char cmd[] = {IAC, DONT, TELOPT_LINEMODE, '\0'};
390 vty_out(vty, "%s", cmd);
718e3744 391}
392
393/* Use window size. */
d62a17ae 394static void vty_do_window_size(struct vty *vty)
718e3744 395{
d62a17ae 396 unsigned char cmd[] = {IAC, DO, TELOPT_NAWS, '\0'};
397 vty_out(vty, "%s", cmd);
718e3744 398}
399
718e3744 400/* Authentication of vty */
d62a17ae 401static void vty_auth(struct vty *vty, char *buf)
402{
403 char *passwd = NULL;
404 enum node_type next_node = 0;
405 int fail;
406 char *crypt(const char *, const char *);
407
408 switch (vty->node) {
409 case AUTH_NODE:
410 if (host.encrypt)
411 passwd = host.password_encrypt;
412 else
413 passwd = host.password;
414 if (host.advanced)
415 next_node = host.enable ? VIEW_NODE : ENABLE_NODE;
416 else
417 next_node = VIEW_NODE;
418 break;
419 case AUTH_ENABLE_NODE:
420 if (host.encrypt)
421 passwd = host.enable_encrypt;
422 else
423 passwd = host.enable;
424 next_node = ENABLE_NODE;
425 break;
426 }
427
428 if (passwd) {
429 if (host.encrypt)
430 fail = strcmp(crypt(buf, passwd), passwd);
431 else
432 fail = strcmp(buf, passwd);
433 } else
434 fail = 1;
435
436 if (!fail) {
437 vty->fail = 0;
438 vty->node = next_node; /* Success ! */
439 } else {
440 vty->fail++;
441 if (vty->fail >= 3) {
442 if (vty->node == AUTH_NODE) {
443 vty_out(vty,
444 "%% Bad passwords, too many failures!\n");
445 vty->status = VTY_CLOSE;
446 } else {
447 /* AUTH_ENABLE_NODE */
448 vty->fail = 0;
449 vty_out(vty,
450 "%% Bad enable passwords, too many failures!\n");
451 vty->status = VTY_CLOSE;
452 }
453 }
454 }
718e3744 455}
456
457/* Command execution over the vty interface. */
d62a17ae 458static int vty_command(struct vty *vty, char *buf)
459{
460 int ret;
d62a17ae 461 const char *protocolname;
462 char *cp = NULL;
463
b575a12c
A
464 assert(vty);
465
d62a17ae 466 /*
467 * Log non empty command lines
468 */
469 if (do_log_commands)
470 cp = buf;
471 if (cp != NULL) {
472 /* Skip white spaces. */
fefa5e0f 473 while (isspace((unsigned char)*cp) && *cp != '\0')
d62a17ae 474 cp++;
475 }
476 if (cp != NULL && *cp != '\0') {
477 unsigned i;
478 char vty_str[VTY_BUFSIZ];
479 char prompt_str[VTY_BUFSIZ];
480
481 /* format the base vty info */
482 snprintf(vty_str, sizeof(vty_str), "vty[??]@%s", vty->address);
b575a12c
A
483
484 for (i = 0; i < vector_active(vtyvec); i++)
485 if (vty == vector_slot(vtyvec, i)) {
486 snprintf(vty_str, sizeof(vty_str), "vty[%d]@%s",
487 i, vty->address);
488 break;
489 }
d62a17ae 490
491 /* format the prompt */
492 snprintf(prompt_str, sizeof(prompt_str), cmd_prompt(vty->node),
493 vty_str);
494
495 /* now log the command */
3ec8b5b8 496 zlog_notice("%s%s", prompt_str, buf);
d62a17ae 497 }
718e3744 498
924b9229 499#ifdef CONSUMED_TIME_CHECK
d62a17ae 500 {
501 RUSAGE_T before;
502 RUSAGE_T after;
503 unsigned long realtime, cputime;
924b9229 504
d62a17ae 505 GETRUSAGE(&before);
924b9229 506#endif /* CONSUMED_TIME_CHECK */
507
fe6b47b9 508 ret = cmd_execute(vty, buf, NULL, 0);
718e3744 509
d62a17ae 510 /* Get the name of the protocol if any */
511 protocolname = frr_protoname;
d0bfb22c 512
924b9229 513#ifdef CONSUMED_TIME_CHECK
d62a17ae 514 GETRUSAGE(&after);
515 if ((realtime = thread_consumed_time(&after, &before, &cputime))
516 > CONSUMED_TIME_CHECK)
517 /* Warn about CPU hog that must be fixed. */
34699016 518 flog_warn(
450971aa 519 EC_LIB_SLOW_THREAD,
d62a17ae 520 "SLOW COMMAND: command took %lums (cpu time %lums): %s",
521 realtime / 1000, cputime / 1000, buf);
522 }
924b9229 523#endif /* CONSUMED_TIME_CHECK */
524
d62a17ae 525 if (ret != CMD_SUCCESS)
526 switch (ret) {
527 case CMD_WARNING:
528 if (vty->type == VTY_FILE)
529 vty_out(vty, "Warning...\n");
530 break;
531 case CMD_ERR_AMBIGUOUS:
532 vty_out(vty, "%% Ambiguous command.\n");
533 break;
534 case CMD_ERR_NO_MATCH:
535 vty_out(vty, "%% [%s] Unknown command: %s\n",
536 protocolname, buf);
537 break;
538 case CMD_ERR_INCOMPLETE:
539 vty_out(vty, "%% Command incomplete.\n");
540 break;
541 }
d62a17ae 542
543 return ret;
718e3744 544}
6b0655a2 545
9fc7ebf1 546static const char telnet_backward_char = 0x08;
547static const char telnet_space_char = ' ';
718e3744 548
549/* Basic function to write buffer to vty. */
d62a17ae 550static void vty_write(struct vty *vty, const char *buf, size_t nbytes)
718e3744 551{
d62a17ae 552 if ((vty->node == AUTH_NODE) || (vty->node == AUTH_ENABLE_NODE))
553 return;
718e3744 554
d62a17ae 555 /* Should we do buffering here ? And make vty_flush (vty) ? */
556 buffer_put(vty->obuf, buf, nbytes);
718e3744 557}
558
718e3744 559/* Basic function to insert character into vty. */
d62a17ae 560static void vty_self_insert(struct vty *vty, char c)
718e3744 561{
d62a17ae 562 int i;
563 int length;
718e3744 564
d62a17ae 565 if (vty->length + 1 >= VTY_BUFSIZ)
566 return;
2af38873 567
d62a17ae 568 length = vty->length - vty->cp;
569 memmove(&vty->buf[vty->cp + 1], &vty->buf[vty->cp], length);
570 vty->buf[vty->cp] = c;
718e3744 571
d62a17ae 572 vty_write(vty, &vty->buf[vty->cp], length + 1);
573 for (i = 0; i < length; i++)
574 vty_write(vty, &telnet_backward_char, 1);
718e3744 575
d62a17ae 576 vty->cp++;
577 vty->length++;
d1e4a518 578
d62a17ae 579 vty->buf[vty->length] = '\0';
718e3744 580}
581
582/* Self insert character 'c' in overwrite mode. */
d62a17ae 583static void vty_self_insert_overwrite(struct vty *vty, char c)
718e3744 584{
d62a17ae 585 if (vty->cp == vty->length) {
586 vty_self_insert(vty, c);
587 return;
588 }
718e3744 589
d62a17ae 590 vty->buf[vty->cp++] = c;
591 vty_write(vty, &c, 1);
718e3744 592}
593
2af38873
QY
594/**
595 * Insert a string into vty->buf at the current cursor position.
596 *
597 * If the resultant string would be larger than VTY_BUFSIZ it is
598 * truncated to fit.
599 */
d62a17ae 600static void vty_insert_word_overwrite(struct vty *vty, char *str)
718e3744 601{
d62a17ae 602 if (vty->cp == VTY_BUFSIZ)
603 return;
d1e4a518 604
d62a17ae 605 size_t nwrite = MIN((int)strlen(str), VTY_BUFSIZ - vty->cp - 1);
606 memcpy(&vty->buf[vty->cp], str, nwrite);
607 vty->cp += nwrite;
608 vty->length = MAX(vty->cp, vty->length);
609 vty->buf[vty->length] = '\0';
610 vty_write(vty, str, nwrite);
718e3744 611}
612
613/* Forward character. */
d62a17ae 614static void vty_forward_char(struct vty *vty)
718e3744 615{
d62a17ae 616 if (vty->cp < vty->length) {
617 vty_write(vty, &vty->buf[vty->cp], 1);
618 vty->cp++;
619 }
718e3744 620}
621
622/* Backward character. */
d62a17ae 623static void vty_backward_char(struct vty *vty)
718e3744 624{
d62a17ae 625 if (vty->cp > 0) {
626 vty->cp--;
627 vty_write(vty, &telnet_backward_char, 1);
628 }
718e3744 629}
630
631/* Move to the beginning of the line. */
d62a17ae 632static void vty_beginning_of_line(struct vty *vty)
718e3744 633{
d62a17ae 634 while (vty->cp)
635 vty_backward_char(vty);
718e3744 636}
637
638/* Move to the end of the line. */
d62a17ae 639static void vty_end_of_line(struct vty *vty)
718e3744 640{
d62a17ae 641 while (vty->cp < vty->length)
642 vty_forward_char(vty);
718e3744 643}
644
d62a17ae 645static void vty_kill_line_from_beginning(struct vty *);
646static void vty_redraw_line(struct vty *);
718e3744 647
648/* Print command line history. This function is called from
649 vty_next_line and vty_previous_line. */
d62a17ae 650static void vty_history_print(struct vty *vty)
718e3744 651{
d62a17ae 652 int length;
718e3744 653
d62a17ae 654 vty_kill_line_from_beginning(vty);
718e3744 655
d62a17ae 656 /* Get previous line from history buffer */
657 length = strlen(vty->hist[vty->hp]);
658 memcpy(vty->buf, vty->hist[vty->hp], length);
659 vty->cp = vty->length = length;
660 vty->buf[vty->length] = '\0';
718e3744 661
d62a17ae 662 /* Redraw current line */
663 vty_redraw_line(vty);
718e3744 664}
665
666/* Show next command line history. */
d62a17ae 667static void vty_next_line(struct vty *vty)
718e3744 668{
d62a17ae 669 int try_index;
718e3744 670
d62a17ae 671 if (vty->hp == vty->hindex)
672 return;
718e3744 673
d62a17ae 674 /* Try is there history exist or not. */
675 try_index = vty->hp;
676 if (try_index == (VTY_MAXHIST - 1))
677 try_index = 0;
678 else
679 try_index++;
718e3744 680
d62a17ae 681 /* If there is not history return. */
682 if (vty->hist[try_index] == NULL)
683 return;
684 else
685 vty->hp = try_index;
718e3744 686
d62a17ae 687 vty_history_print(vty);
718e3744 688}
689
690/* Show previous command line history. */
d62a17ae 691static void vty_previous_line(struct vty *vty)
718e3744 692{
d62a17ae 693 int try_index;
718e3744 694
d62a17ae 695 try_index = vty->hp;
696 if (try_index == 0)
697 try_index = VTY_MAXHIST - 1;
698 else
699 try_index--;
718e3744 700
d62a17ae 701 if (vty->hist[try_index] == NULL)
702 return;
703 else
704 vty->hp = try_index;
718e3744 705
d62a17ae 706 vty_history_print(vty);
718e3744 707}
708
709/* This function redraw all of the command line character. */
d62a17ae 710static void vty_redraw_line(struct vty *vty)
718e3744 711{
d62a17ae 712 vty_write(vty, vty->buf, vty->length);
713 vty->cp = vty->length;
718e3744 714}
715
716/* Forward word. */
d62a17ae 717static void vty_forward_word(struct vty *vty)
718e3744 718{
d62a17ae 719 while (vty->cp != vty->length && vty->buf[vty->cp] != ' ')
720 vty_forward_char(vty);
d0bfb22c 721
d62a17ae 722 while (vty->cp != vty->length && vty->buf[vty->cp] == ' ')
723 vty_forward_char(vty);
718e3744 724}
725
726/* Backward word without skipping training space. */
d62a17ae 727static void vty_backward_pure_word(struct vty *vty)
718e3744 728{
d62a17ae 729 while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
730 vty_backward_char(vty);
718e3744 731}
732
733/* Backward word. */
d62a17ae 734static void vty_backward_word(struct vty *vty)
718e3744 735{
d62a17ae 736 while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ')
737 vty_backward_char(vty);
718e3744 738
d62a17ae 739 while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
740 vty_backward_char(vty);
718e3744 741}
742
743/* When '^D' is typed at the beginning of the line we move to the down
744 level. */
d62a17ae 745static void vty_down_level(struct vty *vty)
718e3744 746{
d62a17ae 747 vty_out(vty, "\n");
748 cmd_exit(vty);
749 vty_prompt(vty);
750 vty->cp = 0;
718e3744 751}
752
753/* When '^Z' is received from vty, move down to the enable mode. */
d62a17ae 754static void vty_end_config(struct vty *vty)
755{
756 vty_out(vty, "\n");
757
cf09d3ca 758 if (vty->config) {
f344c66e 759 vty_config_exit(vty);
d62a17ae 760 vty->node = ENABLE_NODE;
d62a17ae 761 }
762
763 vty_prompt(vty);
764 vty->cp = 0;
718e3744 765}
766
767/* Delete a charcter at the current point. */
d62a17ae 768static void vty_delete_char(struct vty *vty)
718e3744 769{
d62a17ae 770 int i;
771 int size;
718e3744 772
d62a17ae 773 if (vty->length == 0) {
774 vty_down_level(vty);
775 return;
776 }
718e3744 777
d62a17ae 778 if (vty->cp == vty->length)
779 return; /* completion need here? */
718e3744 780
d62a17ae 781 size = vty->length - vty->cp;
718e3744 782
d62a17ae 783 vty->length--;
784 memmove(&vty->buf[vty->cp], &vty->buf[vty->cp + 1], size - 1);
785 vty->buf[vty->length] = '\0';
d0bfb22c 786
d62a17ae 787 if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE)
788 return;
718e3744 789
d62a17ae 790 vty_write(vty, &vty->buf[vty->cp], size - 1);
791 vty_write(vty, &telnet_space_char, 1);
718e3744 792
d62a17ae 793 for (i = 0; i < size; i++)
794 vty_write(vty, &telnet_backward_char, 1);
718e3744 795}
796
797/* Delete a character before the point. */
d62a17ae 798static void vty_delete_backward_char(struct vty *vty)
718e3744 799{
d62a17ae 800 if (vty->cp == 0)
801 return;
718e3744 802
d62a17ae 803 vty_backward_char(vty);
804 vty_delete_char(vty);
718e3744 805}
806
807/* Kill rest of line from current point. */
d62a17ae 808static void vty_kill_line(struct vty *vty)
718e3744 809{
d62a17ae 810 int i;
811 int size;
718e3744 812
d62a17ae 813 size = vty->length - vty->cp;
d0bfb22c 814
d62a17ae 815 if (size == 0)
816 return;
718e3744 817
d62a17ae 818 for (i = 0; i < size; i++)
819 vty_write(vty, &telnet_space_char, 1);
820 for (i = 0; i < size; i++)
821 vty_write(vty, &telnet_backward_char, 1);
718e3744 822
d62a17ae 823 memset(&vty->buf[vty->cp], 0, size);
824 vty->length = vty->cp;
718e3744 825}
826
827/* Kill line from the beginning. */
d62a17ae 828static void vty_kill_line_from_beginning(struct vty *vty)
718e3744 829{
d62a17ae 830 vty_beginning_of_line(vty);
831 vty_kill_line(vty);
718e3744 832}
833
834/* Delete a word before the point. */
d62a17ae 835static void vty_forward_kill_word(struct vty *vty)
718e3744 836{
d62a17ae 837 while (vty->cp != vty->length && vty->buf[vty->cp] == ' ')
838 vty_delete_char(vty);
839 while (vty->cp != vty->length && vty->buf[vty->cp] != ' ')
840 vty_delete_char(vty);
718e3744 841}
842
843/* Delete a word before the point. */
d62a17ae 844static void vty_backward_kill_word(struct vty *vty)
718e3744 845{
d62a17ae 846 while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ')
847 vty_delete_backward_char(vty);
848 while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
849 vty_delete_backward_char(vty);
718e3744 850}
851
852/* Transpose chars before or at the point. */
d62a17ae 853static void vty_transpose_chars(struct vty *vty)
718e3744 854{
d62a17ae 855 char c1, c2;
718e3744 856
d62a17ae 857 /* If length is short or point is near by the beginning of line then
858 return. */
859 if (vty->length < 2 || vty->cp < 1)
860 return;
718e3744 861
d62a17ae 862 /* In case of point is located at the end of the line. */
863 if (vty->cp == vty->length) {
864 c1 = vty->buf[vty->cp - 1];
865 c2 = vty->buf[vty->cp - 2];
718e3744 866
d62a17ae 867 vty_backward_char(vty);
868 vty_backward_char(vty);
869 vty_self_insert_overwrite(vty, c1);
870 vty_self_insert_overwrite(vty, c2);
871 } else {
872 c1 = vty->buf[vty->cp];
873 c2 = vty->buf[vty->cp - 1];
718e3744 874
d62a17ae 875 vty_backward_char(vty);
876 vty_self_insert_overwrite(vty, c1);
877 vty_self_insert_overwrite(vty, c2);
878 }
718e3744 879}
880
881/* Do completion at vty interface. */
d62a17ae 882static void vty_complete_command(struct vty *vty)
883{
884 int i;
885 int ret;
886 char **matched = NULL;
887 vector vline;
888
889 if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE)
890 return;
891
892 vline = cmd_make_strvec(vty->buf);
893 if (vline == NULL)
894 return;
895
896 /* In case of 'help \t'. */
fefa5e0f 897 if (isspace((unsigned char)vty->buf[vty->length - 1]))
d62a17ae 898 vector_set(vline, NULL);
899
900 matched = cmd_complete_command(vline, vty, &ret);
901
902 cmd_free_strvec(vline);
903
904 vty_out(vty, "\n");
905 switch (ret) {
906 case CMD_ERR_AMBIGUOUS:
907 vty_out(vty, "%% Ambiguous command.\n");
908 vty_prompt(vty);
909 vty_redraw_line(vty);
910 break;
911 case CMD_ERR_NO_MATCH:
912 /* vty_out (vty, "%% There is no matched command.\n"); */
913 vty_prompt(vty);
914 vty_redraw_line(vty);
915 break;
916 case CMD_COMPLETE_FULL_MATCH:
917 if (!matched[0]) {
918 /* 2016-11-28 equinox -- need to debug, SEGV here */
919 vty_out(vty, "%% CLI BUG: FULL_MATCH with NULL str\n");
920 vty_prompt(vty);
921 vty_redraw_line(vty);
922 break;
923 }
924 vty_prompt(vty);
925 vty_redraw_line(vty);
926 vty_backward_pure_word(vty);
927 vty_insert_word_overwrite(vty, matched[0]);
928 vty_self_insert(vty, ' ');
929 XFREE(MTYPE_COMPLETION, matched[0]);
930 break;
931 case CMD_COMPLETE_MATCH:
932 vty_prompt(vty);
933 vty_redraw_line(vty);
934 vty_backward_pure_word(vty);
935 vty_insert_word_overwrite(vty, matched[0]);
936 XFREE(MTYPE_COMPLETION, matched[0]);
937 break;
938 case CMD_COMPLETE_LIST_MATCH:
939 for (i = 0; matched[i] != NULL; i++) {
940 if (i != 0 && ((i % 6) == 0))
941 vty_out(vty, "\n");
942 vty_out(vty, "%-10s ", matched[i]);
943 XFREE(MTYPE_COMPLETION, matched[i]);
944 }
945 vty_out(vty, "\n");
946
947 vty_prompt(vty);
948 vty_redraw_line(vty);
949 break;
950 case CMD_ERR_NOTHING_TODO:
951 vty_prompt(vty);
952 vty_redraw_line(vty);
953 break;
954 default:
955 break;
956 }
0a22ddfb 957 XFREE(MTYPE_TMP, matched);
d62a17ae 958}
959
960static void vty_describe_fold(struct vty *vty, int cmd_width,
961 unsigned int desc_width, struct cmd_token *token)
962{
963 char *buf;
964 const char *cmd, *p;
965 int pos;
966
967 cmd = token->text;
968
969 if (desc_width <= 0) {
970 vty_out(vty, " %-*s %s\n", cmd_width, cmd, token->desc);
971 return;
972 }
973
974 buf = XCALLOC(MTYPE_TMP, strlen(token->desc) + 1);
975
976 for (p = token->desc; strlen(p) > desc_width; p += pos + 1) {
977 for (pos = desc_width; pos > 0; pos--)
978 if (*(p + pos) == ' ')
979 break;
980
981 if (pos == 0)
982 break;
983
fcb072cd 984 memcpy(buf, p, pos);
d62a17ae 985 buf[pos] = '\0';
986 vty_out(vty, " %-*s %s\n", cmd_width, cmd, buf);
987
988 cmd = "";
989 }
990
991 vty_out(vty, " %-*s %s\n", cmd_width, cmd, p);
992
993 XFREE(MTYPE_TMP, buf);
718e3744 994}
995
996/* Describe matched command function. */
d62a17ae 997static void vty_describe_command(struct vty *vty)
998{
999 int ret;
1000 vector vline;
1001 vector describe;
1002 unsigned int i, width, desc_width;
1003 struct cmd_token *token, *token_cr = NULL;
1004
1005 vline = cmd_make_strvec(vty->buf);
1006
1007 /* In case of '> ?'. */
1008 if (vline == NULL) {
1009 vline = vector_init(1);
1010 vector_set(vline, NULL);
fefa5e0f 1011 } else if (isspace((unsigned char)vty->buf[vty->length - 1]))
d62a17ae 1012 vector_set(vline, NULL);
1013
1014 describe = cmd_describe_command(vline, vty, &ret);
1015
1016 vty_out(vty, "\n");
1017
1018 /* Ambiguous error. */
1019 switch (ret) {
1020 case CMD_ERR_AMBIGUOUS:
1021 vty_out(vty, "%% Ambiguous command.\n");
1022 goto out;
1023 break;
1024 case CMD_ERR_NO_MATCH:
1025 vty_out(vty, "%% There is no matched command.\n");
1026 goto out;
1027 break;
1028 }
1029
1030 /* Get width of command string. */
1031 width = 0;
1032 for (i = 0; i < vector_active(describe); i++)
1033 if ((token = vector_slot(describe, i)) != NULL) {
1034 unsigned int len;
1035
1036 if (token->text[0] == '\0')
1037 continue;
1038
1039 len = strlen(token->text);
1040
1041 if (width < len)
1042 width = len;
1043 }
1044
1045 /* Get width of description string. */
1046 desc_width = vty->width - (width + 6);
1047
1048 /* Print out description. */
1049 for (i = 0; i < vector_active(describe); i++)
1050 if ((token = vector_slot(describe, i)) != NULL) {
1051 if (token->text[0] == '\0')
1052 continue;
1053
1054 if (strcmp(token->text, CMD_CR_TEXT) == 0) {
1055 token_cr = token;
1056 continue;
1057 }
1058
1059 if (!token->desc)
1060 vty_out(vty, " %-s\n", token->text);
1061 else if (desc_width >= strlen(token->desc))
1062 vty_out(vty, " %-*s %s\n", width, token->text,
1063 token->desc);
1064 else
1065 vty_describe_fold(vty, width, desc_width,
1066 token);
1067
1068 if (IS_VARYING_TOKEN(token->type)) {
1069 const char *ref = vector_slot(
1070 vline, vector_active(vline) - 1);
1071
1072 vector varcomps = vector_init(VECTOR_MIN_SIZE);
1073 cmd_variable_complete(token, ref, varcomps);
1074
1075 if (vector_active(varcomps) > 0) {
1076 char *ac = cmd_variable_comp2str(
1077 varcomps, vty->width);
1078 vty_out(vty, "%s\n", ac);
1079 XFREE(MTYPE_TMP, ac);
1080 }
1081
1082 vector_free(varcomps);
1083 }
d62a17ae 1084 }
1085
1086 if ((token = token_cr)) {
1087 if (!token->desc)
1088 vty_out(vty, " %-s\n", token->text);
1089 else if (desc_width >= strlen(token->desc))
1090 vty_out(vty, " %-*s %s\n", width, token->text,
1091 token->desc);
1092 else
1093 vty_describe_fold(vty, width, desc_width, token);
1094 }
718e3744 1095
2fe8aba3 1096out:
d62a17ae 1097 cmd_free_strvec(vline);
1098 if (describe)
1099 vector_free(describe);
718e3744 1100
d62a17ae 1101 vty_prompt(vty);
1102 vty_redraw_line(vty);
718e3744 1103}
1104
d62a17ae 1105static void vty_clear_buf(struct vty *vty)
718e3744 1106{
d62a17ae 1107 memset(vty->buf, 0, vty->max);
718e3744 1108}
1109
1110/* ^C stop current input and do not add command line to the history. */
d62a17ae 1111static void vty_stop_input(struct vty *vty)
1112{
1113 vty->cp = vty->length = 0;
1114 vty_clear_buf(vty);
1115 vty_out(vty, "\n");
1116
cf09d3ca 1117 if (vty->config) {
f344c66e 1118 vty_config_exit(vty);
d62a17ae 1119 vty->node = ENABLE_NODE;
d62a17ae 1120 }
cf09d3ca 1121
d62a17ae 1122 vty_prompt(vty);
1123
1124 /* Set history pointer to the latest one. */
1125 vty->hp = vty->hindex;
718e3744 1126}
1127
1128/* Add current command line to the history buffer. */
d62a17ae 1129static void vty_hist_add(struct vty *vty)
718e3744 1130{
d62a17ae 1131 int index;
718e3744 1132
d62a17ae 1133 if (vty->length == 0)
1134 return;
718e3744 1135
d62a17ae 1136 index = vty->hindex ? vty->hindex - 1 : VTY_MAXHIST - 1;
718e3744 1137
d62a17ae 1138 /* Ignore the same string as previous one. */
1139 if (vty->hist[index])
1140 if (strcmp(vty->buf, vty->hist[index]) == 0) {
1141 vty->hp = vty->hindex;
1142 return;
1143 }
718e3744 1144
d62a17ae 1145 /* Insert history entry. */
0a22ddfb 1146 XFREE(MTYPE_VTY_HIST, vty->hist[vty->hindex]);
d62a17ae 1147 vty->hist[vty->hindex] = XSTRDUP(MTYPE_VTY_HIST, vty->buf);
718e3744 1148
d62a17ae 1149 /* History index rotation. */
1150 vty->hindex++;
1151 if (vty->hindex == VTY_MAXHIST)
1152 vty->hindex = 0;
718e3744 1153
d62a17ae 1154 vty->hp = vty->hindex;
718e3744 1155}
1156
1157/* #define TELNET_OPTION_DEBUG */
1158
1159/* Get telnet window size. */
d62a17ae 1160static int vty_telnet_option(struct vty *vty, unsigned char *buf, int nbytes)
718e3744 1161{
1162#ifdef TELNET_OPTION_DEBUG
d62a17ae 1163 int i;
1164
1165 for (i = 0; i < nbytes; i++) {
1166 switch (buf[i]) {
1167 case IAC:
1168 vty_out(vty, "IAC ");
1169 break;
1170 case WILL:
1171 vty_out(vty, "WILL ");
1172 break;
1173 case WONT:
1174 vty_out(vty, "WONT ");
1175 break;
1176 case DO:
1177 vty_out(vty, "DO ");
1178 break;
1179 case DONT:
1180 vty_out(vty, "DONT ");
1181 break;
1182 case SB:
1183 vty_out(vty, "SB ");
1184 break;
1185 case SE:
1186 vty_out(vty, "SE ");
1187 break;
1188 case TELOPT_ECHO:
1189 vty_out(vty, "TELOPT_ECHO \n");
1190 break;
1191 case TELOPT_SGA:
1192 vty_out(vty, "TELOPT_SGA \n");
1193 break;
1194 case TELOPT_NAWS:
1195 vty_out(vty, "TELOPT_NAWS \n");
1196 break;
1197 default:
1198 vty_out(vty, "%x ", buf[i]);
1199 break;
1200 }
1201 }
1202 vty_out(vty, "\n");
718e3744 1203
1204#endif /* TELNET_OPTION_DEBUG */
1205
d62a17ae 1206 switch (buf[0]) {
1207 case SB:
1208 vty->sb_len = 0;
1209 vty->iac_sb_in_progress = 1;
1210 return 0;
d62a17ae 1211 case SE: {
1212 if (!vty->iac_sb_in_progress)
1213 return 0;
1214
1215 if ((vty->sb_len == 0) || (vty->sb_buf[0] == '\0')) {
1216 vty->iac_sb_in_progress = 0;
1217 return 0;
1218 }
1219 switch (vty->sb_buf[0]) {
1220 case TELOPT_NAWS:
1221 if (vty->sb_len != TELNET_NAWS_SB_LEN)
34699016 1222 flog_err(
450971aa 1223 EC_LIB_SYSTEM_CALL,
3efd0893 1224 "RFC 1073 violation detected: telnet NAWS option should send %d characters, but we received %lu",
d62a17ae 1225 TELNET_NAWS_SB_LEN,
d7c0a89a 1226 (unsigned long)vty->sb_len);
d62a17ae 1227 else if (sizeof(vty->sb_buf) < TELNET_NAWS_SB_LEN)
af4c2728 1228 flog_err(
450971aa 1229 EC_LIB_DEVELOPMENT,
472878dc 1230 "Bug detected: sizeof(vty->sb_buf) %lu < %d, too small to handle the telnet NAWS option",
d7c0a89a 1231 (unsigned long)sizeof(vty->sb_buf),
d62a17ae 1232 TELNET_NAWS_SB_LEN);
1233 else {
1234 vty->width = ((vty->sb_buf[1] << 8)
1235 | vty->sb_buf[2]);
1236 vty->height = ((vty->sb_buf[3] << 8)
1237 | vty->sb_buf[4]);
9fc7ebf1 1238#ifdef TELNET_OPTION_DEBUG
d62a17ae 1239 vty_out(vty,
3efd0893 1240 "TELNET NAWS window size negotiation completed: width %d, height %d\n",
d62a17ae 1241 vty->width, vty->height);
9fc7ebf1 1242#endif
d62a17ae 1243 }
1244 break;
1245 }
1246 vty->iac_sb_in_progress = 0;
1247 return 0;
d62a17ae 1248 }
1249 default:
1250 break;
1251 }
1252 return 1;
718e3744 1253}
1254
1255/* Execute current command line. */
d62a17ae 1256static int vty_execute(struct vty *vty)
718e3744 1257{
d62a17ae 1258 int ret;
718e3744 1259
d62a17ae 1260 ret = CMD_SUCCESS;
718e3744 1261
d62a17ae 1262 switch (vty->node) {
1263 case AUTH_NODE:
1264 case AUTH_ENABLE_NODE:
1265 vty_auth(vty, vty->buf);
1266 break;
1267 default:
1268 ret = vty_command(vty, vty->buf);
1269 if (vty->type == VTY_TERM)
1270 vty_hist_add(vty);
1271 break;
1272 }
718e3744 1273
d62a17ae 1274 /* Clear command line buffer. */
1275 vty->cp = vty->length = 0;
1276 vty_clear_buf(vty);
718e3744 1277
d62a17ae 1278 if (vty->status != VTY_CLOSE)
1279 vty_prompt(vty);
718e3744 1280
d62a17ae 1281 return ret;
718e3744 1282}
1283
1284#define CONTROL(X) ((X) - '@')
1285#define VTY_NORMAL 0
1286#define VTY_PRE_ESCAPE 1
1287#define VTY_ESCAPE 2
e0a5979d 1288#define VTY_CR 3
718e3744 1289
1290/* Escape character command map. */
d62a17ae 1291static void vty_escape_map(unsigned char c, struct vty *vty)
1292{
1293 switch (c) {
1294 case ('A'):
1295 vty_previous_line(vty);
1296 break;
1297 case ('B'):
1298 vty_next_line(vty);
1299 break;
1300 case ('C'):
1301 vty_forward_char(vty);
1302 break;
1303 case ('D'):
1304 vty_backward_char(vty);
1305 break;
1306 default:
1307 break;
1308 }
1309
1310 /* Go back to normal mode. */
1311 vty->escape = VTY_NORMAL;
718e3744 1312}
1313
1314/* Quit print out to the buffer. */
d62a17ae 1315static void vty_buffer_reset(struct vty *vty)
718e3744 1316{
d62a17ae 1317 buffer_reset(vty->obuf);
0b42d81a 1318 buffer_reset(vty->lbuf);
d62a17ae 1319 vty_prompt(vty);
1320 vty_redraw_line(vty);
718e3744 1321}
1322
1323/* Read data via vty socket. */
d62a17ae 1324static int vty_read(struct thread *thread)
1325{
1326 int i;
1327 int nbytes;
1328 unsigned char buf[VTY_READ_BUFSIZ];
1329
d62a17ae 1330 struct vty *vty = THREAD_ARG(thread);
d62a17ae 1331
1332 /* Read raw data from socket */
1333 if ((nbytes = read(vty->fd, buf, VTY_READ_BUFSIZ)) <= 0) {
1334 if (nbytes < 0) {
1335 if (ERRNO_IO_RETRY(errno)) {
ab699721 1336 vty_event(VTY_READ, vty);
d62a17ae 1337 return 0;
1338 }
1339 vty->monitor = 0; /* disable monitoring to avoid
1340 infinite recursion */
34699016 1341 flog_err(
450971aa 1342 EC_LIB_SOCKET,
d62a17ae 1343 "%s: read error on vty client fd %d, closing: %s",
1344 __func__, vty->fd, safe_strerror(errno));
1345 buffer_reset(vty->obuf);
0b42d81a 1346 buffer_reset(vty->lbuf);
d62a17ae 1347 }
1348 vty->status = VTY_CLOSE;
1349 }
1350
1351 for (i = 0; i < nbytes; i++) {
1352 if (buf[i] == IAC) {
1353 if (!vty->iac) {
1354 vty->iac = 1;
1355 continue;
1356 } else {
1357 vty->iac = 0;
1358 }
1359 }
1360
1361 if (vty->iac_sb_in_progress && !vty->iac) {
1362 if (vty->sb_len < sizeof(vty->sb_buf))
1363 vty->sb_buf[vty->sb_len] = buf[i];
1364 vty->sb_len++;
1365 continue;
1366 }
1367
1368 if (vty->iac) {
1369 /* In case of telnet command */
1370 int ret = 0;
1371 ret = vty_telnet_option(vty, buf + i, nbytes - i);
1372 vty->iac = 0;
1373 i += ret;
1374 continue;
1375 }
1376
1377
1378 if (vty->status == VTY_MORE) {
1379 switch (buf[i]) {
1380 case CONTROL('C'):
1381 case 'q':
1382 case 'Q':
1383 vty_buffer_reset(vty);
1384 break;
d62a17ae 1385 default:
1386 break;
1387 }
1388 continue;
1389 }
1390
1391 /* Escape character. */
1392 if (vty->escape == VTY_ESCAPE) {
1393 vty_escape_map(buf[i], vty);
1394 continue;
1395 }
1396
1397 /* Pre-escape status. */
1398 if (vty->escape == VTY_PRE_ESCAPE) {
1399 switch (buf[i]) {
1400 case '[':
1401 vty->escape = VTY_ESCAPE;
1402 break;
1403 case 'b':
1404 vty_backward_word(vty);
1405 vty->escape = VTY_NORMAL;
1406 break;
1407 case 'f':
1408 vty_forward_word(vty);
1409 vty->escape = VTY_NORMAL;
1410 break;
1411 case 'd':
1412 vty_forward_kill_word(vty);
1413 vty->escape = VTY_NORMAL;
1414 break;
1415 case CONTROL('H'):
1416 case 0x7f:
1417 vty_backward_kill_word(vty);
1418 vty->escape = VTY_NORMAL;
1419 break;
1420 default:
1421 vty->escape = VTY_NORMAL;
1422 break;
1423 }
1424 continue;
1425 }
1426
e0a5979d
DL
1427 if (vty->escape == VTY_CR) {
1428 /* if we get CR+NL, the NL results in an extra empty
1429 * prompt line being printed without this; just drop
1430 * the NL if it immediately follows CR.
1431 */
1432 vty->escape = VTY_NORMAL;
1433
1434 if (buf[i] == '\n')
1435 continue;
1436 }
1437
d62a17ae 1438 switch (buf[i]) {
1439 case CONTROL('A'):
1440 vty_beginning_of_line(vty);
1441 break;
1442 case CONTROL('B'):
1443 vty_backward_char(vty);
1444 break;
1445 case CONTROL('C'):
1446 vty_stop_input(vty);
1447 break;
1448 case CONTROL('D'):
1449 vty_delete_char(vty);
1450 break;
1451 case CONTROL('E'):
1452 vty_end_of_line(vty);
1453 break;
1454 case CONTROL('F'):
1455 vty_forward_char(vty);
1456 break;
1457 case CONTROL('H'):
1458 case 0x7f:
1459 vty_delete_backward_char(vty);
1460 break;
1461 case CONTROL('K'):
1462 vty_kill_line(vty);
1463 break;
1464 case CONTROL('N'):
1465 vty_next_line(vty);
1466 break;
1467 case CONTROL('P'):
1468 vty_previous_line(vty);
1469 break;
1470 case CONTROL('T'):
1471 vty_transpose_chars(vty);
1472 break;
1473 case CONTROL('U'):
1474 vty_kill_line_from_beginning(vty);
1475 break;
1476 case CONTROL('W'):
1477 vty_backward_kill_word(vty);
1478 break;
1479 case CONTROL('Z'):
1480 vty_end_config(vty);
1481 break;
d62a17ae 1482 case '\r':
e0a5979d
DL
1483 vty->escape = VTY_CR;
1484 /* fallthru */
1485 case '\n':
d62a17ae 1486 vty_out(vty, "\n");
ab699721 1487 buffer_flush_available(vty->obuf, vty->wfd);
d62a17ae 1488 vty_execute(vty);
1489 break;
1490 case '\t':
1491 vty_complete_command(vty);
1492 break;
1493 case '?':
1494 if (vty->node == AUTH_NODE
1495 || vty->node == AUTH_ENABLE_NODE)
1496 vty_self_insert(vty, buf[i]);
1497 else
1498 vty_describe_command(vty);
1499 break;
1500 case '\033':
1501 if (i + 1 < nbytes && buf[i + 1] == '[') {
1502 vty->escape = VTY_ESCAPE;
1503 i++;
1504 } else
1505 vty->escape = VTY_PRE_ESCAPE;
1506 break;
1507 default:
1508 if (buf[i] > 31 && buf[i] < 127)
1509 vty_self_insert(vty, buf[i]);
1510 break;
1511 }
1512 }
1513
1514 /* Check status. */
1515 if (vty->status == VTY_CLOSE)
1516 vty_close(vty);
1517 else {
ab699721
DL
1518 vty_event(VTY_WRITE, vty);
1519 vty_event(VTY_READ, vty);
d62a17ae 1520 }
1521 return 0;
718e3744 1522}
1523
1524/* Flush buffer to the vty. */
d62a17ae 1525static int vty_flush(struct thread *thread)
1526{
1527 int erase;
1528 buffer_status_t flushrc;
d62a17ae 1529 struct vty *vty = THREAD_ARG(thread);
1530
d62a17ae 1531 /* Tempolary disable read thread. */
43b8ca99
DS
1532 if (vty->lines == 0)
1533 THREAD_OFF(vty->t_read);
d62a17ae 1534
1535 /* Function execution continue. */
1536 erase = ((vty->status == VTY_MORE || vty->status == VTY_MORELINE));
1537
1538 /* N.B. if width is 0, that means we don't know the window size. */
1539 if ((vty->lines == 0) || (vty->width == 0) || (vty->height == 0))
ab699721 1540 flushrc = buffer_flush_available(vty->obuf, vty->wfd);
d62a17ae 1541 else if (vty->status == VTY_MORELINE)
ab699721 1542 flushrc = buffer_flush_window(vty->obuf, vty->wfd, vty->width,
d62a17ae 1543 1, erase, 0);
1544 else
1545 flushrc = buffer_flush_window(
ab699721 1546 vty->obuf, vty->wfd, vty->width,
d62a17ae 1547 vty->lines >= 0 ? vty->lines : vty->height, erase, 0);
1548 switch (flushrc) {
1549 case BUFFER_ERROR:
1550 vty->monitor =
1551 0; /* disable monitoring to avoid infinite recursion */
ab699721
DL
1552 zlog_info("buffer_flush failed on vty client fd %d/%d, closing",
1553 vty->fd, vty->wfd);
0b42d81a 1554 buffer_reset(vty->lbuf);
d62a17ae 1555 buffer_reset(vty->obuf);
1556 vty_close(vty);
1557 return 0;
1558 case BUFFER_EMPTY:
1559 if (vty->status == VTY_CLOSE)
1560 vty_close(vty);
1561 else {
1562 vty->status = VTY_NORMAL;
1563 if (vty->lines == 0)
ab699721 1564 vty_event(VTY_READ, vty);
d62a17ae 1565 }
1566 break;
1567 case BUFFER_PENDING:
1568 /* There is more data waiting to be written. */
1569 vty->status = VTY_MORE;
1570 if (vty->lines == 0)
ab699721 1571 vty_event(VTY_WRITE, vty);
d62a17ae 1572 break;
1573 }
1574
1575 return 0;
718e3744 1576}
1577
2cddf2ff 1578/* Allocate new vty struct. */
4d762f26 1579struct vty *vty_new(void)
2cddf2ff
QY
1580{
1581 struct vty *new = XCALLOC(MTYPE_VTY, sizeof(struct vty));
1582
1583 new->fd = new->wfd = -1;
6ef6e4f0 1584 new->of = stdout;
0b42d81a 1585 new->lbuf = buffer_new(0);
2cddf2ff
QY
1586 new->obuf = buffer_new(0); /* Use default buffer size. */
1587 new->buf = XCALLOC(MTYPE_VTY, VTY_BUFSIZ);
2cddf2ff
QY
1588 new->max = VTY_BUFSIZ;
1589
1590 return new;
1591}
1592
1593
b7642925 1594/* allocate and initialise vty */
d62a17ae 1595static struct vty *vty_new_init(int vty_sock)
1596{
1597 struct vty *vty;
1598
1599 vty = vty_new();
1600 vty->fd = vty_sock;
1601 vty->wfd = vty_sock;
1602 vty->type = VTY_TERM;
1603 vty->node = AUTH_NODE;
1604 vty->fail = 0;
1605 vty->cp = 0;
1606 vty_clear_buf(vty);
1607 vty->length = 0;
1608 memset(vty->hist, 0, sizeof(vty->hist));
1609 vty->hp = 0;
1610 vty->hindex = 0;
1c2facd1
RW
1611 vty->xpath_index = 0;
1612 memset(vty->xpath, 0, sizeof(vty->xpath));
1613 vty->private_config = false;
1614 vty->candidate_config = vty_shared_candidate_config;
d62a17ae 1615 vector_set_index(vtyvec, vty_sock, vty);
1616 vty->status = VTY_NORMAL;
1617 vty->lines = -1;
1618 vty->iac = 0;
1619 vty->iac_sb_in_progress = 0;
1620 vty->sb_len = 0;
1621
1622 return vty;
b7642925
DL
1623}
1624
718e3744 1625/* Create new vty structure. */
d62a17ae 1626static struct vty *vty_create(int vty_sock, union sockunion *su)
1627{
1628 char buf[SU_ADDRSTRLEN];
1629 struct vty *vty;
1630
1631 sockunion2str(su, buf, SU_ADDRSTRLEN);
1632
1633 /* Allocate new vty structure and set up default values. */
1634 vty = vty_new_init(vty_sock);
1635
1636 /* configurable parameters not part of basic init */
1637 vty->v_timeout = vty_timeout_val;
9f73d2c9 1638 strlcpy(vty->address, buf, sizeof(vty->address));
d62a17ae 1639 if (no_password_check) {
1640 if (host.advanced)
1641 vty->node = ENABLE_NODE;
1642 else
1643 vty->node = VIEW_NODE;
1644 }
1645 if (host.lines >= 0)
1646 vty->lines = host.lines;
1647
1648 if (!no_password_check) {
1649 /* Vty is not available if password isn't set. */
1650 if (host.password == NULL && host.password_encrypt == NULL) {
1651 vty_out(vty, "Vty password is not set.\n");
1652 vty->status = VTY_CLOSE;
1653 vty_close(vty);
1654 return NULL;
1655 }
1656 }
1657
1658 /* Say hello to the world. */
1659 vty_hello(vty);
1660 if (!no_password_check)
1661 vty_out(vty, "\nUser Access Verification\n\n");
1662
1663 /* Setting up terminal. */
1664 vty_will_echo(vty);
1665 vty_will_suppress_go_ahead(vty);
1666
1667 vty_dont_linemode(vty);
1668 vty_do_window_size(vty);
1669 /* vty_dont_lflow_ahead (vty); */
1670
1671 vty_prompt(vty);
1672
1673 /* Add read/write thread. */
ab699721
DL
1674 vty_event(VTY_WRITE, vty);
1675 vty_event(VTY_READ, vty);
d62a17ae 1676
1677 return vty;
718e3744 1678}
1679
b7642925 1680/* create vty for stdio */
b510a06e
DL
1681static struct termios stdio_orig_termios;
1682static struct vty *stdio_vty = NULL;
154b9e8f
DL
1683static bool stdio_termios = false;
1684static void (*stdio_vty_atclose)(int isexit);
b510a06e 1685
154b9e8f 1686static void vty_stdio_reset(int isexit)
b510a06e 1687{
d62a17ae 1688 if (stdio_vty) {
154b9e8f
DL
1689 if (stdio_termios)
1690 tcsetattr(0, TCSANOW, &stdio_orig_termios);
1691 stdio_termios = false;
1692
d62a17ae 1693 stdio_vty = NULL;
dbf78092 1694
d62a17ae 1695 if (stdio_vty_atclose)
154b9e8f 1696 stdio_vty_atclose(isexit);
d62a17ae 1697 stdio_vty_atclose = NULL;
1698 }
b510a06e
DL
1699}
1700
154b9e8f
DL
1701static void vty_stdio_atexit(void)
1702{
1703 vty_stdio_reset(1);
1704}
1705
1706void vty_stdio_suspend(void)
1707{
1708 if (!stdio_vty)
1709 return;
1710
43b8ca99
DS
1711 THREAD_OFF(stdio_vty->t_write);
1712 THREAD_OFF(stdio_vty->t_read);
1713 THREAD_OFF(stdio_vty->t_timeout);
154b9e8f
DL
1714
1715 if (stdio_termios)
1716 tcsetattr(0, TCSANOW, &stdio_orig_termios);
1717 stdio_termios = false;
1718}
1719
1720void vty_stdio_resume(void)
1721{
1722 if (!stdio_vty)
1723 return;
1724
1725 if (!tcgetattr(0, &stdio_orig_termios)) {
1726 struct termios termios;
1727
1728 termios = stdio_orig_termios;
1729 termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR
1730 | IGNCR | ICRNL | IXON);
154b9e8f
DL
1731 termios.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
1732 termios.c_cflag &= ~(CSIZE | PARENB);
1733 termios.c_cflag |= CS8;
1734 tcsetattr(0, TCSANOW, &termios);
1735 stdio_termios = true;
1736 }
1737
1738 vty_prompt(stdio_vty);
1739
1740 /* Add read/write thread. */
ab699721
DL
1741 vty_event(VTY_WRITE, stdio_vty);
1742 vty_event(VTY_READ, stdio_vty);
154b9e8f
DL
1743}
1744
1745void vty_stdio_close(void)
1746{
1747 if (!stdio_vty)
1748 return;
1749 vty_close(stdio_vty);
1750}
1751
1752struct vty *vty_stdio(void (*atclose)(int isexit))
b7642925 1753{
d62a17ae 1754 struct vty *vty;
b7642925 1755
d62a17ae 1756 /* refuse creating two vtys on stdio */
1757 if (stdio_vty)
1758 return NULL;
b510a06e 1759
d62a17ae 1760 vty = stdio_vty = vty_new_init(0);
1761 stdio_vty_atclose = atclose;
1762 vty->wfd = 1;
b7642925 1763
d62a17ae 1764 /* always have stdio vty in a known _unchangeable_ state, don't want
1765 * config
1766 * to have any effect here to make sure scripting this works as intended
1767 */
1768 vty->node = ENABLE_NODE;
1769 vty->v_timeout = 0;
9f73d2c9 1770 strlcpy(vty->address, "console", sizeof(vty->address));
b7642925 1771
154b9e8f 1772 vty_stdio_resume();
d62a17ae 1773 return vty;
b7642925
DL
1774}
1775
718e3744 1776/* Accept connection from the network. */
d62a17ae 1777static int vty_accept(struct thread *thread)
1778{
1779 int vty_sock;
1780 union sockunion su;
1781 int ret;
1782 unsigned int on;
1783 int accept_sock;
1784 struct prefix p;
1785 struct access_list *acl = NULL;
d62a17ae 1786
1787 accept_sock = THREAD_FD(thread);
1788
1789 /* We continue hearing vty socket. */
ab699721 1790 vty_event_serv(VTY_SERV, accept_sock);
d62a17ae 1791
1792 memset(&su, 0, sizeof(union sockunion));
1793
1794 /* We can handle IPv4 or IPv6 socket. */
1795 vty_sock = sockunion_accept(accept_sock, &su);
1796 if (vty_sock < 0) {
450971aa 1797 flog_err(EC_LIB_SOCKET, "can't accept vty socket : %s",
34699016 1798 safe_strerror(errno));
d62a17ae 1799 return -1;
1800 }
1801 set_nonblocking(vty_sock);
1802 set_cloexec(vty_sock);
1803
0154d8ce 1804 if (!sockunion2hostprefix(&su, &p)) {
07d4bb8b 1805 close(vty_sock);
a0ee6f32
DS
1806 zlog_info("Vty unable to convert prefix from sockunion %pSU",
1807 &su);
0154d8ce
DS
1808 return -1;
1809 }
d62a17ae 1810
1811 /* VTY's accesslist apply. */
1812 if (p.family == AF_INET && vty_accesslist_name) {
1813 if ((acl = access_list_lookup(AFI_IP, vty_accesslist_name))
1814 && (access_list_apply(acl, &p) == FILTER_DENY)) {
a0ee6f32 1815 zlog_info("Vty connection refused from %pSU", &su);
d62a17ae 1816 close(vty_sock);
1817
1818 /* continue accepting connections */
ab699721 1819 vty_event_serv(VTY_SERV, accept_sock);
d62a17ae 1820
1821 return 0;
1822 }
1823 }
1824
1825 /* VTY's ipv6 accesslist apply. */
1826 if (p.family == AF_INET6 && vty_ipv6_accesslist_name) {
1827 if ((acl = access_list_lookup(AFI_IP6,
1828 vty_ipv6_accesslist_name))
1829 && (access_list_apply(acl, &p) == FILTER_DENY)) {
a0ee6f32 1830 zlog_info("Vty connection refused from %pSU", &su);
d62a17ae 1831 close(vty_sock);
1832
1833 /* continue accepting connections */
ab699721 1834 vty_event_serv(VTY_SERV, accept_sock);
d62a17ae 1835
1836 return 0;
1837 }
1838 }
1839
1840 on = 1;
1841 ret = setsockopt(vty_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&on,
1842 sizeof(on));
1843 if (ret < 0)
1844 zlog_info("can't set sockopt to vty_sock : %s",
1845 safe_strerror(errno));
1846
a0ee6f32 1847 zlog_info("Vty connection from %pSU", &su);
d62a17ae 1848
1849 vty_create(vty_sock, &su);
1850
1851 return 0;
1852}
1853
1854static void vty_serv_sock_addrinfo(const char *hostname, unsigned short port)
1855{
1856 int ret;
1857 struct addrinfo req;
1858 struct addrinfo *ainfo;
1859 struct addrinfo *ainfo_save;
1860 int sock;
1861 char port_str[BUFSIZ];
1862
1863 memset(&req, 0, sizeof(struct addrinfo));
1864 req.ai_flags = AI_PASSIVE;
1865 req.ai_family = AF_UNSPEC;
1866 req.ai_socktype = SOCK_STREAM;
772270f3 1867 snprintf(port_str, sizeof(port_str), "%d", port);
d62a17ae 1868 port_str[sizeof(port_str) - 1] = '\0';
1869
1870 ret = getaddrinfo(hostname, port_str, &req, &ainfo);
1871
1872 if (ret != 0) {
450971aa 1873 flog_err_sys(EC_LIB_SYSTEM_CALL, "getaddrinfo failed: %s",
09c866e3 1874 gai_strerror(ret));
d62a17ae 1875 exit(1);
1876 }
1877
1878 ainfo_save = ainfo;
1879
1880 do {
1881 if (ainfo->ai_family != AF_INET && ainfo->ai_family != AF_INET6)
1882 continue;
1883
1884 sock = socket(ainfo->ai_family, ainfo->ai_socktype,
1885 ainfo->ai_protocol);
1886 if (sock < 0)
1887 continue;
718e3744 1888
d62a17ae 1889 sockopt_v6only(ainfo->ai_family, sock);
1890 sockopt_reuseaddr(sock);
1891 sockopt_reuseport(sock);
1892 set_cloexec(sock);
1893
1894 ret = bind(sock, ainfo->ai_addr, ainfo->ai_addrlen);
1895 if (ret < 0) {
1896 close(sock); /* Avoid sd leak. */
1897 continue;
1898 }
1899
1900 ret = listen(sock, 3);
1901 if (ret < 0) {
1902 close(sock); /* Avoid sd leak. */
1903 continue;
1904 }
1905
ab699721 1906 vty_event_serv(VTY_SERV, sock);
d62a17ae 1907 } while ((ainfo = ainfo->ai_next) != NULL);
1908
1909 freeaddrinfo(ainfo_save);
718e3744 1910}
718e3744 1911
1912#ifdef VTYSH
1913/* For sockaddr_un. */
1914#include <sys/un.h>
1915
1916/* VTY shell UNIX domain socket. */
d62a17ae 1917static void vty_serv_un(const char *path)
1918{
1919 int ret;
1920 int sock, len;
1921 struct sockaddr_un serv;
1922 mode_t old_mask;
1923 struct zprivs_ids_t ids;
1924
1925 /* First of all, unlink existing socket */
1926 unlink(path);
1927
1928 /* Set umask */
1929 old_mask = umask(0007);
1930
1931 /* Make UNIX domain socket. */
1932 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1933 if (sock < 0) {
450971aa 1934 flog_err_sys(EC_LIB_SOCKET,
09c866e3
QY
1935 "Cannot create unix stream socket: %s",
1936 safe_strerror(errno));
d62a17ae 1937 return;
1938 }
1939
1940 /* Make server socket. */
1941 memset(&serv, 0, sizeof(struct sockaddr_un));
1942 serv.sun_family = AF_UNIX;
1943 strlcpy(serv.sun_path, path, sizeof(serv.sun_path));
6f0e3f6e 1944#ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
d62a17ae 1945 len = serv.sun_len = SUN_LEN(&serv);
718e3744 1946#else
d62a17ae 1947 len = sizeof(serv.sun_family) + strlen(serv.sun_path);
6f0e3f6e 1948#endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
718e3744 1949
d62a17ae 1950 set_cloexec(sock);
2da59394 1951
d62a17ae 1952 ret = bind(sock, (struct sockaddr *)&serv, len);
1953 if (ret < 0) {
450971aa 1954 flog_err_sys(EC_LIB_SOCKET, "Cannot bind path %s: %s", path,
09c866e3 1955 safe_strerror(errno));
d62a17ae 1956 close(sock); /* Avoid sd leak. */
1957 return;
1958 }
718e3744 1959
d62a17ae 1960 ret = listen(sock, 5);
1961 if (ret < 0) {
450971aa 1962 flog_err_sys(EC_LIB_SOCKET, "listen(fd %d) failed: %s", sock,
09c866e3 1963 safe_strerror(errno));
d62a17ae 1964 close(sock); /* Avoid sd leak. */
1965 return;
1966 }
718e3744 1967
d62a17ae 1968 umask(old_mask);
718e3744 1969
d62a17ae 1970 zprivs_get_ids(&ids);
d0bfb22c 1971
d62a17ae 1972 /* Hack: ids.gid_vty is actually a uint, but we stored -1 in it
1973 earlier for the case when we don't need to chown the file
1974 type casting it here to make a compare */
1975 if ((int)ids.gid_vty > 0) {
1976 /* set group of socket */
1977 if (chown(path, -1, ids.gid_vty)) {
450971aa 1978 flog_err_sys(EC_LIB_SYSTEM_CALL,
09c866e3
QY
1979 "vty_serv_un: could chown socket, %s",
1980 safe_strerror(errno));
d62a17ae 1981 }
1982 }
edd7c245 1983
ab699721 1984 vty_event_serv(VTYSH_SERV, sock);
718e3744 1985}
1986
1987/* #define VTYSH_DEBUG 1 */
1988
d62a17ae 1989static int vtysh_accept(struct thread *thread)
718e3744 1990{
d62a17ae 1991 int accept_sock;
1992 int sock;
1993 int client_len;
1994 struct sockaddr_un client;
1995 struct vty *vty;
d0bfb22c 1996
d62a17ae 1997 accept_sock = THREAD_FD(thread);
718e3744 1998
ab699721 1999 vty_event_serv(VTYSH_SERV, accept_sock);
718e3744 2000
d62a17ae 2001 memset(&client, 0, sizeof(struct sockaddr_un));
2002 client_len = sizeof(struct sockaddr_un);
718e3744 2003
d62a17ae 2004 sock = accept(accept_sock, (struct sockaddr *)&client,
2005 (socklen_t *)&client_len);
718e3744 2006
d62a17ae 2007 if (sock < 0) {
450971aa 2008 flog_err(EC_LIB_SOCKET, "can't accept vty socket : %s",
34699016 2009 safe_strerror(errno));
d62a17ae 2010 return -1;
2011 }
718e3744 2012
d62a17ae 2013 if (set_nonblocking(sock) < 0) {
34699016 2014 flog_err(
450971aa 2015 EC_LIB_SOCKET,
34699016 2016 "vtysh_accept: could not set vty socket %d to non-blocking, %s, closing",
d62a17ae 2017 sock, safe_strerror(errno));
2018 close(sock);
2019 return -1;
2020 }
2021 set_cloexec(sock);
2da59394 2022
718e3744 2023#ifdef VTYSH_DEBUG
d62a17ae 2024 printf("VTY shell accept\n");
718e3744 2025#endif /* VTYSH_DEBUG */
2026
d62a17ae 2027 vty = vty_new();
2028 vty->fd = sock;
2029 vty->wfd = sock;
2030 vty->type = VTY_SHELL_SERV;
2031 vty->node = VIEW_NODE;
2032
ab699721 2033 vty_event(VTYSH_READ, vty);
d62a17ae 2034
2035 return 0;
2036}
2037
2038static int vtysh_flush(struct vty *vty)
2039{
2040 switch (buffer_flush_available(vty->obuf, vty->wfd)) {
2041 case BUFFER_PENDING:
ab699721 2042 vty_event(VTYSH_WRITE, vty);
d62a17ae 2043 break;
2044 case BUFFER_ERROR:
2045 vty->monitor =
2046 0; /* disable monitoring to avoid infinite recursion */
450971aa 2047 flog_err(EC_LIB_SOCKET, "%s: write error to fd %d, closing",
34699016 2048 __func__, vty->fd);
0b42d81a 2049 buffer_reset(vty->lbuf);
d62a17ae 2050 buffer_reset(vty->obuf);
2051 vty_close(vty);
2052 return -1;
d62a17ae 2053 case BUFFER_EMPTY:
2054 break;
2055 }
2056 return 0;
2057}
2058
2059static int vtysh_read(struct thread *thread)
2060{
2061 int ret;
2062 int sock;
2063 int nbytes;
2064 struct vty *vty;
2065 unsigned char buf[VTY_READ_BUFSIZ];
2066 unsigned char *p;
d7c0a89a 2067 uint8_t header[4] = {0, 0, 0, 0};
d62a17ae 2068
2069 sock = THREAD_FD(thread);
2070 vty = THREAD_ARG(thread);
d62a17ae 2071
2072 if ((nbytes = read(sock, buf, VTY_READ_BUFSIZ)) <= 0) {
2073 if (nbytes < 0) {
2074 if (ERRNO_IO_RETRY(errno)) {
ab699721 2075 vty_event(VTYSH_READ, vty);
d62a17ae 2076 return 0;
2077 }
2078 vty->monitor = 0; /* disable monitoring to avoid
2079 infinite recursion */
34699016 2080 flog_err(
450971aa 2081 EC_LIB_SOCKET,
d62a17ae 2082 "%s: read failed on vtysh client fd %d, closing: %s",
2083 __func__, sock, safe_strerror(errno));
2084 }
0b42d81a 2085 buffer_reset(vty->lbuf);
d62a17ae 2086 buffer_reset(vty->obuf);
2087 vty_close(vty);
718e3744 2088#ifdef VTYSH_DEBUG
d62a17ae 2089 printf("close vtysh\n");
718e3744 2090#endif /* VTYSH_DEBUG */
d62a17ae 2091 return 0;
2092 }
718e3744 2093
2094#ifdef VTYSH_DEBUG
d62a17ae 2095 printf("line: %.*s\n", nbytes, buf);
718e3744 2096#endif /* VTYSH_DEBUG */
2097
d62a17ae 2098 if (vty->length + nbytes >= VTY_BUFSIZ) {
2099 /* Clear command line buffer. */
2100 vty->cp = vty->length = 0;
2101 vty_clear_buf(vty);
2102 vty_out(vty, "%% Command is too long.\n");
2103 } else {
2104 for (p = buf; p < buf + nbytes; p++) {
2105 vty->buf[vty->length++] = *p;
2106 if (*p == '\0') {
2107 /* Pass this line to parser. */
2108 ret = vty_execute(vty);
2109/* Note that vty_execute clears the command buffer and resets
2110 vty->length to 0. */
2111
2112/* Return result. */
718e3744 2113#ifdef VTYSH_DEBUG
d62a17ae 2114 printf("result: %d\n", ret);
2115 printf("vtysh node: %d\n", vty->node);
718e3744 2116#endif /* VTYSH_DEBUG */
2117
d62a17ae 2118 /* hack for asynchronous "write integrated"
2119 * - other commands in "buf" will be ditched
2120 * - input during pending config-write is
2121 * "unsupported" */
2122 if (ret == CMD_SUSPEND)
2123 break;
95c4aff2 2124
d62a17ae 2125 /* warning: watchfrr hardcodes this result write
2126 */
2127 header[3] = ret;
2128 buffer_put(vty->obuf, header, 4);
9fc7ebf1 2129
d62a17ae 2130 if (!vty->t_write && (vtysh_flush(vty) < 0))
2131 /* Try to flush results; exit if a write
2132 * error occurs. */
2133 return 0;
2134 }
2135 }
2136 }
718e3744 2137
d62a17ae 2138 if (vty->status == VTY_CLOSE)
2139 vty_close(vty);
2140 else
ab699721 2141 vty_event(VTYSH_READ, vty);
718e3744 2142
d62a17ae 2143 return 0;
718e3744 2144}
49ff6d9d 2145
d62a17ae 2146static int vtysh_write(struct thread *thread)
49ff6d9d 2147{
d62a17ae 2148 struct vty *vty = THREAD_ARG(thread);
49ff6d9d 2149
d62a17ae 2150 vtysh_flush(vty);
2151 return 0;
49ff6d9d 2152}
2153
718e3744 2154#endif /* VTYSH */
2155
2156/* Determine address family to bind. */
d62a17ae 2157void vty_serv_sock(const char *addr, unsigned short port, const char *path)
718e3744 2158{
d62a17ae 2159 /* If port is set to 0, do not listen on TCP/IP at all! */
2160 if (port)
2161 vty_serv_sock_addrinfo(addr, port);
718e3744 2162
2163#ifdef VTYSH
d62a17ae 2164 vty_serv_un(path);
718e3744 2165#endif /* VTYSH */
2166}
2167
7ab57d19
DS
2168static void vty_error_delete(void *arg)
2169{
2170 struct vty_error *ve = arg;
2171
2172 XFREE(MTYPE_TMP, ve);
2173}
2174
9d0a3260
AS
2175/* Close vty interface. Warning: call this only from functions that
2176 will be careful not to access the vty afterwards (since it has
2177 now been freed). This is safest from top-level functions (called
2178 directly by the thread dispatcher). */
d62a17ae 2179void vty_close(struct vty *vty)
718e3744 2180{
d62a17ae 2181 int i;
2182 bool was_stdio = false;
718e3744 2183
791ded4a
DL
2184 /* Drop out of configure / transaction if needed. */
2185 vty_config_exit(vty);
2186
d62a17ae 2187 /* Cancel threads.*/
43b8ca99
DS
2188 THREAD_OFF(vty->t_read);
2189 THREAD_OFF(vty->t_write);
2190 THREAD_OFF(vty->t_timeout);
718e3744 2191
d62a17ae 2192 /* Flush buffer. */
2193 buffer_flush_all(vty->obuf, vty->wfd);
718e3744 2194
d62a17ae 2195 /* Free input buffer. */
2196 buffer_free(vty->obuf);
0b42d81a 2197 buffer_free(vty->lbuf);
718e3744 2198
d62a17ae 2199 /* Free command history. */
0a22ddfb
QY
2200 for (i = 0; i < VTY_MAXHIST; i++) {
2201 XFREE(MTYPE_VTY_HIST, vty->hist[i]);
2202 }
718e3744 2203
d62a17ae 2204 /* Unset vector. */
10b8a9c0
DL
2205 if (vty->fd != -1)
2206 vector_unset(vtyvec, vty->fd);
718e3744 2207
d62a17ae 2208 if (vty->wfd > 0 && vty->type == VTY_FILE)
2209 fsync(vty->wfd);
056cfe49 2210
10b8a9c0
DL
2211 /* Close socket.
2212 * note check is for fd > STDERR_FILENO, not fd != -1.
2213 * We never close stdin/stdout/stderr here, because we may be
2214 * running in foreground mode with logging to stdout. Also,
2215 * additionally, we'd need to replace these fds with /dev/null. */
2216 if (vty->wfd > STDERR_FILENO && vty->wfd != vty->fd)
2217 close(vty->wfd);
572e2644 2218 if (vty->fd > STDERR_FILENO)
d62a17ae 2219 close(vty->fd);
572e2644 2220 if (vty->fd == STDIN_FILENO)
d62a17ae 2221 was_stdio = true;
718e3744 2222
0a22ddfb 2223 XFREE(MTYPE_VTY, vty->buf);
718e3744 2224
7ab57d19
DS
2225 if (vty->error) {
2226 vty->error->del = vty_error_delete;
2227 list_delete(&vty->error);
2228 }
5689fe5f 2229
d62a17ae 2230 /* OK free vty. */
2231 XFREE(MTYPE_VTY, vty);
dd03f8ca 2232
d62a17ae 2233 if (was_stdio)
154b9e8f 2234 vty_stdio_reset(0);
718e3744 2235}
2236
2237/* When time out occur output message then close connection. */
d62a17ae 2238static int vty_timeout(struct thread *thread)
718e3744 2239{
d62a17ae 2240 struct vty *vty;
718e3744 2241
d62a17ae 2242 vty = THREAD_ARG(thread);
d62a17ae 2243 vty->v_timeout = 0;
718e3744 2244
d62a17ae 2245 /* Clear buffer*/
0b42d81a 2246 buffer_reset(vty->lbuf);
d62a17ae 2247 buffer_reset(vty->obuf);
2248 vty_out(vty, "\nVty connection is timed out.\n");
718e3744 2249
d62a17ae 2250 /* Close connection. */
2251 vty->status = VTY_CLOSE;
2252 vty_close(vty);
718e3744 2253
d62a17ae 2254 return 0;
718e3744 2255}
2256
2257/* Read up configuration file from file_name. */
1c2facd1 2258static void vty_read_file(struct nb_config *config, FILE *confp)
d62a17ae 2259{
2260 int ret;
2261 struct vty *vty;
7ab57d19
DS
2262 struct vty_error *ve;
2263 struct listnode *node;
d62a17ae 2264 unsigned int line_num = 0;
2265
2266 vty = vty_new();
10b8a9c0
DL
2267 /* vty_close won't close stderr; if some config command prints
2268 * something it'll end up there. (not ideal; it'd be beter if output
2269 * from a file-load went to logging instead. Also note that if this
2270 * function is called after daemonizing, stderr will be /dev/null.)
2271 *
2272 * vty->fd will be -1 from vty_new()
2273 */
2274 vty->wfd = STDERR_FILENO;
d62a17ae 2275 vty->type = VTY_FILE;
2276 vty->node = CONFIG_NODE;
eaf6705d 2277 vty->config = true;
1c2facd1
RW
2278 if (config)
2279 vty->candidate_config = config;
2280 else {
2281 vty->private_config = true;
2282 vty->candidate_config = nb_config_new(NULL);
2283 }
d62a17ae 2284
2285 /* Execute configuration file */
2286 ret = config_from_file(vty, confp, &line_num);
2287
2288 /* Flush any previous errors before printing messages below */
10b8a9c0 2289 buffer_flush_all(vty->obuf, vty->wfd);
d62a17ae 2290
2291 if (!((ret == CMD_SUCCESS) || (ret == CMD_ERR_NOTHING_TODO))) {
2292 const char *message = NULL;
b4fa7c95
DL
2293 char *nl;
2294
d62a17ae 2295 switch (ret) {
2296 case CMD_ERR_AMBIGUOUS:
b4fa7c95 2297 message = "Ambiguous command";
d62a17ae 2298 break;
2299 case CMD_ERR_NO_MATCH:
b4fa7c95 2300 message = "No such command";
d62a17ae 2301 break;
c539c389
DS
2302 case CMD_WARNING:
2303 message = "Command returned Warning";
2304 break;
2305 case CMD_WARNING_CONFIG_FAILED:
2306 message = "Command returned Warning Config Failed";
2307 break;
2308 case CMD_ERR_INCOMPLETE:
2309 message = "Command returned Incomplete";
2310 break;
2311 case CMD_ERR_EXEED_ARGC_MAX:
996c9314
LB
2312 message =
2313 "Command exceeded maximum number of Arguments";
c539c389
DS
2314 break;
2315 default:
2316 message = "Command returned unhandled error message";
2317 break;
d62a17ae 2318 }
b4fa7c95 2319
7ab57d19
DS
2320 for (ALL_LIST_ELEMENTS_RO(vty->error, node, ve)) {
2321 nl = strchr(ve->error_buf, '\n');
2322 if (nl)
2323 *nl = '\0';
2324 flog_err(EC_LIB_VTY, "ERROR: %s on config line %u: %s",
2325 message, ve->line_num, ve->error_buf);
2326 }
d62a17ae 2327 }
2328
1c2facd1
RW
2329 /*
2330 * Automatically commit the candidate configuration after
2331 * reading the configuration file.
2332 */
91f9fd78 2333 if (config == NULL) {
13d6b9c1 2334 struct nb_context context = {};
df5eda3d 2335 char errmsg[BUFSIZ] = {0};
13d6b9c1
RW
2336
2337 context.client = NB_CLIENT_CLI;
2338 context.user = vty;
2339 ret = nb_candidate_commit(&context, vty->candidate_config, true,
df5eda3d
RW
2340 "Read configuration file", NULL,
2341 errmsg, sizeof(errmsg));
1c2facd1 2342 if (ret != NB_OK && ret != NB_ERR_NO_CHANGES)
df5eda3d
RW
2343 zlog_err(
2344 "%s: failed to read configuration file: %s (%s)",
2345 __func__, nb_err_name(ret), errmsg);
1c2facd1
RW
2346 }
2347
d62a17ae 2348 vty_close(vty);
2349}
2350
2351static FILE *vty_use_backup_config(const char *fullpath)
2352{
2353 char *fullpath_sav, *fullpath_tmp;
2354 FILE *ret = NULL;
2355 int tmp, sav;
2356 int c;
2357 char buffer[512];
2358
9f73d2c9
QY
2359 size_t fullpath_sav_sz = strlen(fullpath) + strlen(CONF_BACKUP_EXT) + 1;
2360 fullpath_sav = malloc(fullpath_sav_sz);
2361 strlcpy(fullpath_sav, fullpath, fullpath_sav_sz);
2362 strlcat(fullpath_sav, CONF_BACKUP_EXT, fullpath_sav_sz);
d62a17ae 2363
2364 sav = open(fullpath_sav, O_RDONLY);
2365 if (sav < 0) {
2366 free(fullpath_sav);
2367 return NULL;
2368 }
2369
2370 fullpath_tmp = malloc(strlen(fullpath) + 8);
fc746f1c 2371 snprintf(fullpath_tmp, strlen(fullpath) + 8, "%s.XXXXXX", fullpath);
d62a17ae 2372
2373 /* Open file to configuration write. */
2374 tmp = mkstemp(fullpath_tmp);
2375 if (tmp < 0)
2376 goto out_close_sav;
2377
2378 if (fchmod(tmp, CONFIGFILE_MASK) != 0)
2379 goto out_close;
2380
2381 while ((c = read(sav, buffer, 512)) > 0) {
2382 if (write(tmp, buffer, c) <= 0)
2383 goto out_close;
2384 }
2385 close(sav);
2386 close(tmp);
2387
2388 if (rename(fullpath_tmp, fullpath) == 0)
2389 ret = fopen(fullpath, "r");
2390 else
2391 unlink(fullpath_tmp);
2392
2393 if (0) {
2394 out_close:
2395 close(tmp);
2396 unlink(fullpath_tmp);
2397 out_close_sav:
2398 close(sav);
2399 }
2400
2401 free(fullpath_sav);
2402 free(fullpath_tmp);
2403 return ret;
718e3744 2404}
2405
2406/* Read up configuration file from file_name. */
1c2facd1
RW
2407bool vty_read_config(struct nb_config *config, const char *config_file,
2408 char *config_default_dir)
d62a17ae 2409{
2410 char cwd[MAXPATHLEN];
2411 FILE *confp = NULL;
2412 const char *fullpath;
2413 char *tmp = NULL;
5ede5e4e 2414 bool read_success = false;
d62a17ae 2415
2416 /* If -f flag specified. */
2417 if (config_file != NULL) {
2418 if (!IS_DIRECTORY_SEP(config_file[0])) {
2419 if (getcwd(cwd, MAXPATHLEN) == NULL) {
09c866e3 2420 flog_err_sys(
450971aa 2421 EC_LIB_SYSTEM_CALL,
1c2facd1
RW
2422 "%s: failure to determine Current Working Directory %d!",
2423 __func__, errno);
2424 goto tmp_free_and_out;
d62a17ae 2425 }
7533cad7
QY
2426 size_t tmp_len = strlen(cwd) + strlen(config_file) + 2;
2427 tmp = XMALLOC(MTYPE_TMP, tmp_len);
2428 snprintf(tmp, tmp_len, "%s/%s", cwd, config_file);
d62a17ae 2429 fullpath = tmp;
2430 } else
2431 fullpath = config_file;
2432
2433 confp = fopen(fullpath, "r");
2434
2435 if (confp == NULL) {
34699016 2436 flog_warn(
450971aa 2437 EC_LIB_BACKUP_CONFIG,
34699016
DS
2438 "%s: failed to open configuration file %s: %s, checking backup",
2439 __func__, fullpath, safe_strerror(errno));
d62a17ae 2440
2441 confp = vty_use_backup_config(fullpath);
2442 if (confp)
a0ee6f32
DS
2443 flog_warn(EC_LIB_BACKUP_CONFIG,
2444 "using backup configuration file!");
d62a17ae 2445 else {
1c2facd1
RW
2446 flog_err(
2447 EC_LIB_VTY,
2448 "%s: can't open configuration file [%s]",
2449 __func__, config_file);
2450 goto tmp_free_and_out;
d62a17ae 2451 }
2452 }
2453 } else {
2454
2455 host_config_set(config_default_dir);
a7222276 2456
718e3744 2457#ifdef VTYSH
d62a17ae 2458 int ret;
2459 struct stat conf_stat;
2460
2461 /* !!!!PLEASE LEAVE!!!!
2462 * This is NEEDED for use with vtysh -b, or else you can get
2463 * a real configuration food fight with a lot garbage in the
2464 * merged configuration file it creates coming from the per
2465 * daemon configuration files. This also allows the daemons
2466 * to start if there default configuration file is not
2467 * present or ignore them, as needed when using vtysh -b to
2468 * configure the daemons at boot - MAG
2469 */
2470
2471 /* Stat for vtysh Zebra.conf, if found startup and wait for
2472 * boot configuration
2473 */
2474
2475 if (strstr(config_default_dir, "vtysh") == NULL) {
2476 ret = stat(integrate_default, &conf_stat);
5ede5e4e
DS
2477 if (ret >= 0) {
2478 read_success = true;
d62a17ae 2479 goto tmp_free_and_out;
5ede5e4e 2480 }
d62a17ae 2481 }
a7222276 2482#endif /* VTYSH */
d62a17ae 2483 confp = fopen(config_default_dir, "r");
2484 if (confp == NULL) {
34699016 2485 flog_err(
450971aa 2486 EC_LIB_SYSTEM_CALL,
34699016
DS
2487 "%s: failed to open configuration file %s: %s, checking backup",
2488 __func__, config_default_dir,
2489 safe_strerror(errno));
d62a17ae 2490
2491 confp = vty_use_backup_config(config_default_dir);
2492 if (confp) {
a0ee6f32
DS
2493 flog_warn(EC_LIB_BACKUP_CONFIG,
2494 "using backup configuration file!");
d62a17ae 2495 fullpath = config_default_dir;
2496 } else {
450971aa 2497 flog_err(EC_LIB_VTY,
1c50c1c0
QY
2498 "can't open configuration file [%s]",
2499 config_default_dir);
d62a17ae 2500 goto tmp_free_and_out;
2501 }
2502 } else
2503 fullpath = config_default_dir;
2504 }
2505
1c2facd1 2506 vty_read_file(config, confp);
5ede5e4e 2507 read_success = true;
d62a17ae 2508
2509 fclose(confp);
2510
2511 host_config_set(fullpath);
6eda6425
DS
2512
2513tmp_free_and_out:
0a22ddfb 2514 XFREE(MTYPE_TMP, tmp);
5ede5e4e
DS
2515
2516 return read_success;
718e3744 2517}
2518
2519/* Small utility function which output log to the VTY. */
807f5b98
DL
2520void vty_log(const char *level, const char *proto_str, const char *msg,
2521 struct timestamp_control *ctl)
718e3744 2522{
d62a17ae 2523 unsigned int i;
2524 struct vty *vty;
d0bfb22c 2525
d62a17ae 2526 if (!vtyvec)
2527 return;
718e3744 2528
d62a17ae 2529 for (i = 0; i < vector_active(vtyvec); i++)
2530 if ((vty = vector_slot(vtyvec, i)) != NULL)
807f5b98
DL
2531 if (vty->monitor)
2532 vty_log_out(vty, level, proto_str, msg, ctl);
718e3744 2533}
2534
274a4a44 2535/* Async-signal-safe version of vty_log for fixed strings. */
d62a17ae 2536void vty_log_fixed(char *buf, size_t len)
274a4a44 2537{
d62a17ae 2538 unsigned int i;
2539 struct iovec iov[2];
2540 char crlf[4] = "\r\n";
9fc7ebf1 2541
d62a17ae 2542 /* vty may not have been initialised */
2543 if (!vtyvec)
2544 return;
d0bfb22c 2545
d62a17ae 2546 iov[0].iov_base = buf;
2547 iov[0].iov_len = len;
2548 iov[1].iov_base = crlf;
2549 iov[1].iov_len = 2;
274a4a44 2550
d62a17ae 2551 for (i = 0; i < vector_active(vtyvec); i++) {
2552 struct vty *vty;
2553 if (((vty = vector_slot(vtyvec, i)) != NULL) && vty->monitor)
2554 /* N.B. We don't care about the return code, since
2555 process is
2556 most likely just about to die anyway. */
2557 if (writev(vty->wfd, iov, 2) == -1) {
2558 fprintf(stderr, "Failure to writev: %d\n",
2559 errno);
2560 exit(-1);
2561 }
2562 }
274a4a44 2563}
2564
f344c66e 2565int vty_config_enter(struct vty *vty, bool private_config, bool exclusive)
718e3744 2566{
364ad673
RW
2567 if (exclusive && nb_running_lock(NB_CLIENT_CLI, vty)) {
2568 vty_out(vty, "%% Configuration is locked by other client\n");
f344c66e 2569 return CMD_WARNING;
d62a17ae 2570 }
f344c66e
RW
2571
2572 vty->node = CONFIG_NODE;
2573 vty->config = true;
2574 vty->private_config = private_config;
41e195d4 2575 vty->xpath_index = 0;
f344c66e 2576
8685be73
RW
2577 if (private_config) {
2578 vty->candidate_config = nb_config_dup(running_config);
2579 vty->candidate_config_base = nb_config_dup(running_config);
2580 vty_out(vty,
2581 "Warning: uncommitted changes will be discarded on exit.\n\n");
2582 } else {
2583 vty->candidate_config = vty_shared_candidate_config;
2584 if (frr_get_cli_mode() == FRR_CLI_TRANSACTIONAL)
f344c66e
RW
2585 vty->candidate_config_base =
2586 nb_config_dup(running_config);
2587 }
2588
2589 return CMD_SUCCESS;
718e3744 2590}
2591
f344c66e 2592void vty_config_exit(struct vty *vty)
718e3744 2593{
24389580
DL
2594 enum node_type node = vty->node;
2595 struct cmd_node *cnode;
2596
2597 /* unlock and jump up to ENABLE_NODE if -and only if- we're
2598 * somewhere below CONFIG_NODE */
2599 while (node && node != CONFIG_NODE) {
2600 cnode = vector_lookup(cmdvec, node);
2601 node = cnode->parent_node;
2602 }
791ded4a
DL
2603 if (node != CONFIG_NODE)
2604 /* called outside config, e.g. vty_close() in ENABLE_NODE */
24389580 2605 return;
24389580
DL
2606
2607 while (vty->node != ENABLE_NODE)
791ded4a 2608 /* will call vty_config_node_exit() below */
24389580 2609 cmd_exit(vty);
791ded4a
DL
2610}
2611
2612int vty_config_node_exit(struct vty *vty)
2613{
2614 vty->xpath_index = 0;
24389580 2615
b855e95f
RW
2616 /* Perform pending commit if any. */
2617 nb_cli_pending_commit_check(vty);
2618
fbdc1c0a
RW
2619 /* Check if there's a pending confirmed commit. */
2620 if (vty->t_confirmed_commit_timeout) {
2621 vty_out(vty,
a0ee6f32 2622 "exiting with a pending confirmed commit. Rolling back to previous configuration.\n\n");
fbdc1c0a
RW
2623 nb_cli_confirmed_commit_rollback(vty);
2624 nb_cli_confirmed_commit_clean(vty);
2625 }
2626
364ad673 2627 (void)nb_running_unlock(NB_CLIENT_CLI, vty);
1c2facd1
RW
2628
2629 if (vty->candidate_config) {
2630 if (vty->private_config)
2631 nb_config_free(vty->candidate_config);
2632 vty->candidate_config = NULL;
2633 }
2634 if (vty->candidate_config_base) {
2635 nb_config_free(vty->candidate_config_base);
2636 vty->candidate_config_base = NULL;
2637 }
cf09d3ca
RW
2638
2639 vty->config = false;
791ded4a 2640 return 1;
cc933ef9
DL
2641}
2642
718e3744 2643/* Master of the threads. */
79159516 2644static struct thread_master *vty_master;
718e3744 2645
ab699721 2646static void vty_event_serv(enum event event, int sock)
718e3744 2647{
d62a17ae 2648 struct thread *vty_serv_thread = NULL;
d8182598 2649
d62a17ae 2650 switch (event) {
2651 case VTY_SERV:
ab699721
DL
2652 vty_serv_thread = thread_add_read(vty_master, vty_accept,
2653 NULL, sock, NULL);
d62a17ae 2654 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2655 break;
718e3744 2656#ifdef VTYSH
d62a17ae 2657 case VTYSH_SERV:
ab699721
DL
2658 vty_serv_thread = thread_add_read(vty_master, vtysh_accept,
2659 NULL, sock, NULL);
d62a17ae 2660 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2661 break;
ab699721
DL
2662#endif /* VTYSH */
2663 default:
2664 assert(!"vty_event_serv() called incorrectly");
2665 }
2666}
2667
2668static void vty_event(enum event event, struct vty *vty)
2669{
2670 switch (event) {
2671#ifdef VTYSH
d62a17ae 2672 case VTYSH_READ:
ab699721 2673 thread_add_read(vty_master, vtysh_read, vty, vty->fd,
d62a17ae 2674 &vty->t_read);
2675 break;
2676 case VTYSH_WRITE:
ab699721 2677 thread_add_write(vty_master, vtysh_write, vty, vty->wfd,
d62a17ae 2678 &vty->t_write);
2679 break;
718e3744 2680#endif /* VTYSH */
d62a17ae 2681 case VTY_READ:
ab699721
DL
2682 thread_add_read(vty_master, vty_read, vty, vty->fd,
2683 &vty->t_read);
d62a17ae 2684
2685 /* Time out treatment. */
2686 if (vty->v_timeout) {
43b8ca99 2687 THREAD_OFF(vty->t_timeout);
d62a17ae 2688 thread_add_timer(vty_master, vty_timeout, vty,
2689 vty->v_timeout, &vty->t_timeout);
2690 }
2691 break;
2692 case VTY_WRITE:
ab699721 2693 thread_add_write(vty_master, vty_flush, vty, vty->wfd,
d62a17ae 2694 &vty->t_write);
2695 break;
2696 case VTY_TIMEOUT_RESET:
43b8ca99
DS
2697 THREAD_OFF(vty->t_timeout);
2698 if (vty->v_timeout)
d62a17ae 2699 thread_add_timer(vty_master, vty_timeout, vty,
2700 vty->v_timeout, &vty->t_timeout);
d62a17ae 2701 break;
ab699721
DL
2702 default:
2703 assert(!"vty_event() called incorrectly");
d62a17ae 2704 }
718e3744 2705}
6b0655a2 2706
505e5056 2707DEFUN_NOSH (config_who,
718e3744 2708 config_who_cmd,
2709 "who",
2710 "Display who is on vty\n")
2711{
d62a17ae 2712 unsigned int i;
2713 struct vty *v;
718e3744 2714
d62a17ae 2715 for (i = 0; i < vector_active(vtyvec); i++)
2716 if ((v = vector_slot(vtyvec, i)) != NULL)
2717 vty_out(vty, "%svty[%d] connected from %s.\n",
2718 v->config ? "*" : " ", i, v->address);
2719 return CMD_SUCCESS;
718e3744 2720}
2721
2722/* Move to vty configuration mode. */
505e5056 2723DEFUN_NOSH (line_vty,
718e3744 2724 line_vty_cmd,
2725 "line vty",
2726 "Configure a terminal line\n"
2727 "Virtual terminal\n")
2728{
d62a17ae 2729 vty->node = VTY_NODE;
2730 return CMD_SUCCESS;
718e3744 2731}
2732
2733/* Set time out value. */
d62a17ae 2734static int exec_timeout(struct vty *vty, const char *min_str,
2735 const char *sec_str)
718e3744 2736{
d62a17ae 2737 unsigned long timeout = 0;
718e3744 2738
d62a17ae 2739 /* min_str and sec_str are already checked by parser. So it must be
2740 all digit string. */
2741 if (min_str) {
2742 timeout = strtol(min_str, NULL, 10);
2743 timeout *= 60;
2744 }
2745 if (sec_str)
2746 timeout += strtol(sec_str, NULL, 10);
718e3744 2747
d62a17ae 2748 vty_timeout_val = timeout;
2749 vty->v_timeout = timeout;
ab699721 2750 vty_event(VTY_TIMEOUT_RESET, vty);
718e3744 2751
2752
d62a17ae 2753 return CMD_SUCCESS;
718e3744 2754}
2755
2756DEFUN (exec_timeout_min,
2757 exec_timeout_min_cmd,
aa1c90a4 2758 "exec-timeout (0-35791)",
718e3744 2759 "Set timeout value\n"
2760 "Timeout value in minutes\n")
2761{
d62a17ae 2762 int idx_number = 1;
2763 return exec_timeout(vty, argv[idx_number]->arg, NULL);
718e3744 2764}
2765
2766DEFUN (exec_timeout_sec,
2767 exec_timeout_sec_cmd,
aa1c90a4 2768 "exec-timeout (0-35791) (0-2147483)",
718e3744 2769 "Set the EXEC timeout\n"
2770 "Timeout in minutes\n"
2771 "Timeout in seconds\n")
2772{
d62a17ae 2773 int idx_number = 1;
2774 int idx_number_2 = 2;
2775 return exec_timeout(vty, argv[idx_number]->arg,
2776 argv[idx_number_2]->arg);
718e3744 2777}
2778
2779DEFUN (no_exec_timeout,
2780 no_exec_timeout_cmd,
2781 "no exec-timeout",
2782 NO_STR
2783 "Set the EXEC timeout\n")
2784{
d62a17ae 2785 return exec_timeout(vty, NULL, NULL);
718e3744 2786}
2787
2788/* Set vty access class. */
2789DEFUN (vty_access_class,
2790 vty_access_class_cmd,
2791 "access-class WORD",
2792 "Filter connections based on an IP access list\n"
2793 "IP access list\n")
2794{
d62a17ae 2795 int idx_word = 1;
2796 if (vty_accesslist_name)
2797 XFREE(MTYPE_VTY, vty_accesslist_name);
718e3744 2798
d62a17ae 2799 vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
718e3744 2800
d62a17ae 2801 return CMD_SUCCESS;
718e3744 2802}
2803
2804/* Clear vty access class. */
2805DEFUN (no_vty_access_class,
2806 no_vty_access_class_cmd,
2807 "no access-class [WORD]",
2808 NO_STR
2809 "Filter connections based on an IP access list\n"
2810 "IP access list\n")
2811{
d62a17ae 2812 int idx_word = 2;
2813 const char *accesslist = (argc == 3) ? argv[idx_word]->arg : NULL;
2814 if (!vty_accesslist_name
2815 || (argc == 3 && strcmp(vty_accesslist_name, accesslist))) {
2816 vty_out(vty, "Access-class is not currently applied to vty\n");
2817 return CMD_WARNING_CONFIG_FAILED;
2818 }
718e3744 2819
d62a17ae 2820 XFREE(MTYPE_VTY, vty_accesslist_name);
718e3744 2821
d62a17ae 2822 vty_accesslist_name = NULL;
718e3744 2823
d62a17ae 2824 return CMD_SUCCESS;
718e3744 2825}
2826
718e3744 2827/* Set vty access class. */
2828DEFUN (vty_ipv6_access_class,
2829 vty_ipv6_access_class_cmd,
2830 "ipv6 access-class WORD",
2831 IPV6_STR
2832 "Filter connections based on an IP access list\n"
2833 "IPv6 access list\n")
2834{
d62a17ae 2835 int idx_word = 2;
2836 if (vty_ipv6_accesslist_name)
2837 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
718e3744 2838
d62a17ae 2839 vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
718e3744 2840
d62a17ae 2841 return CMD_SUCCESS;
718e3744 2842}
2843
2844/* Clear vty access class. */
2845DEFUN (no_vty_ipv6_access_class,
2846 no_vty_ipv6_access_class_cmd,
2847 "no ipv6 access-class [WORD]",
2848 NO_STR
2849 IPV6_STR
2850 "Filter connections based on an IP access list\n"
2851 "IPv6 access list\n")
2852{
d62a17ae 2853 int idx_word = 3;
2854 const char *accesslist = (argc == 4) ? argv[idx_word]->arg : NULL;
aa1c90a4 2855
d62a17ae 2856 if (!vty_ipv6_accesslist_name
2857 || (argc == 4 && strcmp(vty_ipv6_accesslist_name, accesslist))) {
2858 vty_out(vty,
2859 "IPv6 access-class is not currently applied to vty\n");
2860 return CMD_WARNING_CONFIG_FAILED;
2861 }
718e3744 2862
d62a17ae 2863 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
718e3744 2864
d62a17ae 2865 vty_ipv6_accesslist_name = NULL;
718e3744 2866
d62a17ae 2867 return CMD_SUCCESS;
718e3744 2868}
718e3744 2869
2870/* vty login. */
2871DEFUN (vty_login,
2872 vty_login_cmd,
2873 "login",
2874 "Enable password checking\n")
2875{
d62a17ae 2876 no_password_check = 0;
2877 return CMD_SUCCESS;
718e3744 2878}
2879
2880DEFUN (no_vty_login,
2881 no_vty_login_cmd,
2882 "no login",
2883 NO_STR
2884 "Enable password checking\n")
2885{
d62a17ae 2886 no_password_check = 1;
2887 return CMD_SUCCESS;
718e3744 2888}
2889
2890DEFUN (service_advanced_vty,
2891 service_advanced_vty_cmd,
2892 "service advanced-vty",
2893 "Set up miscellaneous service\n"
2894 "Enable advanced mode vty interface\n")
2895{
d62a17ae 2896 host.advanced = 1;
2897 return CMD_SUCCESS;
718e3744 2898}
2899
2900DEFUN (no_service_advanced_vty,
2901 no_service_advanced_vty_cmd,
2902 "no service advanced-vty",
2903 NO_STR
2904 "Set up miscellaneous service\n"
2905 "Enable advanced mode vty interface\n")
2906{
d62a17ae 2907 host.advanced = 0;
2908 return CMD_SUCCESS;
718e3744 2909}
2910
505e5056 2911DEFUN_NOSH (terminal_monitor,
718e3744 2912 terminal_monitor_cmd,
2913 "terminal monitor",
2914 "Set terminal line parameters\n"
2915 "Copy debug output to the current terminal line\n")
2916{
d62a17ae 2917 vty->monitor = 1;
2918 return CMD_SUCCESS;
718e3744 2919}
2920
505e5056 2921DEFUN_NOSH (terminal_no_monitor,
718e3744 2922 terminal_no_monitor_cmd,
2923 "terminal no monitor",
2924 "Set terminal line parameters\n"
2925 NO_STR
2926 "Copy debug output to the current terminal line\n")
2927{
d62a17ae 2928 vty->monitor = 0;
2929 return CMD_SUCCESS;
718e3744 2930}
2931
505e5056 2932DEFUN_NOSH (no_terminal_monitor,
789f78ac 2933 no_terminal_monitor_cmd,
2934 "no terminal monitor",
2935 NO_STR
2936 "Set terminal line parameters\n"
2937 "Copy debug output to the current terminal line\n")
f667a580 2938{
d62a17ae 2939 return terminal_no_monitor(self, vty, argc, argv);
f667a580
QY
2940}
2941
789f78ac 2942
505e5056 2943DEFUN_NOSH (show_history,
718e3744 2944 show_history_cmd,
2945 "show history",
2946 SHOW_STR
2947 "Display the session command history\n")
2948{
d62a17ae 2949 int index;
718e3744 2950
d62a17ae 2951 for (index = vty->hindex + 1; index != vty->hindex;) {
2952 if (index == VTY_MAXHIST) {
2953 index = 0;
2954 continue;
2955 }
718e3744 2956
d62a17ae 2957 if (vty->hist[index] != NULL)
2958 vty_out(vty, " %s\n", vty->hist[index]);
718e3744 2959
d62a17ae 2960 index++;
2961 }
718e3744 2962
d62a17ae 2963 return CMD_SUCCESS;
718e3744 2964}
2965
da688ecd 2966/* vty login. */
2950f5da 2967DEFPY (log_commands,
da688ecd 2968 log_commands_cmd,
2950f5da
DS
2969 "[no] log commands",
2970 NO_STR
da688ecd 2971 "Logging control\n"
2950f5da 2972 "Log all commands\n")
da688ecd 2973{
2950f5da
DS
2974 if (no) {
2975 if (do_log_commands_perm) {
2976 vty_out(vty,
2977 "Daemon started with permanent logging turned on for commands, ignoring\n");
2978 return CMD_WARNING;
2979 }
2980
2981 do_log_commands = false;
2982 } else
2983 do_log_commands = true;
2984
d62a17ae 2985 return CMD_SUCCESS;
da688ecd
LB
2986}
2987
718e3744 2988/* Display current configuration. */
d62a17ae 2989static int vty_config_write(struct vty *vty)
718e3744 2990{
d62a17ae 2991 vty_out(vty, "line vty\n");
718e3744 2992
d62a17ae 2993 if (vty_accesslist_name)
2994 vty_out(vty, " access-class %s\n", vty_accesslist_name);
718e3744 2995
d62a17ae 2996 if (vty_ipv6_accesslist_name)
2997 vty_out(vty, " ipv6 access-class %s\n",
2998 vty_ipv6_accesslist_name);
718e3744 2999
d62a17ae 3000 /* exec-timeout */
3001 if (vty_timeout_val != VTY_TIMEOUT_DEFAULT)
3002 vty_out(vty, " exec-timeout %ld %ld\n", vty_timeout_val / 60,
3003 vty_timeout_val % 60);
718e3744 3004
d62a17ae 3005 /* login */
3006 if (no_password_check)
3007 vty_out(vty, " no login\n");
da688ecd 3008
d62a17ae 3009 if (do_log_commands)
3010 vty_out(vty, "log commands\n");
d0bfb22c 3011
d62a17ae 3012 vty_out(vty, "!\n");
718e3744 3013
d62a17ae 3014 return CMD_SUCCESS;
718e3744 3015}
3016
612c2c15 3017static int vty_config_write(struct vty *vty);
d62a17ae 3018struct cmd_node vty_node = {
f4b8291f 3019 .name = "vty",
62b346ee 3020 .node = VTY_NODE,
24389580 3021 .parent_node = CONFIG_NODE,
62b346ee 3022 .prompt = "%s(config-line)# ",
612c2c15 3023 .config_write = vty_config_write,
718e3744 3024};
3025
3026/* Reset all VTY status. */
4d762f26 3027void vty_reset(void)
d62a17ae 3028{
3029 unsigned int i;
3030 struct vty *vty;
3031 struct thread *vty_serv_thread;
3032
3033 for (i = 0; i < vector_active(vtyvec); i++)
3034 if ((vty = vector_slot(vtyvec, i)) != NULL) {
0b42d81a 3035 buffer_reset(vty->lbuf);
d62a17ae 3036 buffer_reset(vty->obuf);
3037 vty->status = VTY_CLOSE;
3038 vty_close(vty);
3039 }
3040
3041 for (i = 0; i < vector_active(Vvty_serv_thread); i++)
3042 if ((vty_serv_thread = vector_slot(Vvty_serv_thread, i))
3043 != NULL) {
43b8ca99 3044 THREAD_OFF(vty_serv_thread);
d62a17ae 3045 vector_slot(Vvty_serv_thread, i) = NULL;
3046 close(i);
3047 }
3048
3049 vty_timeout_val = VTY_TIMEOUT_DEFAULT;
3050
e1b36e13
QY
3051 XFREE(MTYPE_VTY, vty_accesslist_name);
3052 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
718e3744 3053}
3054
d62a17ae 3055static void vty_save_cwd(void)
718e3744 3056{
d62a17ae 3057 char *c;
79ad2798 3058
daeb97e9 3059 c = getcwd(vty_cwd, sizeof(vty_cwd));
718e3744 3060
d62a17ae 3061 if (!c) {
3062 /*
3063 * At this point if these go wrong, more than likely
3064 * the whole world is coming down around us
3065 * Hence not worrying about it too much.
3066 */
3067 if (!chdir(SYSCONFDIR)) {
450971aa 3068 flog_err_sys(EC_LIB_SYSTEM_CALL,
09c866e3
QY
3069 "Failure to chdir to %s, errno: %d",
3070 SYSCONFDIR, errno);
d62a17ae 3071 exit(-1);
3072 }
daeb97e9 3073 if (getcwd(vty_cwd, sizeof(vty_cwd)) == NULL) {
450971aa 3074 flog_err_sys(EC_LIB_SYSTEM_CALL,
09c866e3 3075 "Failure to getcwd, errno: %d", errno);
d62a17ae 3076 exit(-1);
3077 }
3078 }
718e3744 3079}
3080
4d762f26 3081char *vty_get_cwd(void)
718e3744 3082{
d62a17ae 3083 return vty_cwd;
718e3744 3084}
3085
d62a17ae 3086int vty_shell(struct vty *vty)
718e3744 3087{
d62a17ae 3088 return vty->type == VTY_SHELL ? 1 : 0;
718e3744 3089}
3090
d62a17ae 3091int vty_shell_serv(struct vty *vty)
718e3744 3092{
d62a17ae 3093 return vty->type == VTY_SHELL_SERV ? 1 : 0;
718e3744 3094}
3095
4d762f26 3096void vty_init_vtysh(void)
718e3744 3097{
d62a17ae 3098 vtyvec = vector_init(VECTOR_MIN_SIZE);
718e3744 3099}
3100
3101/* Install vty's own commands like `who' command. */
2950f5da 3102void vty_init(struct thread_master *master_thread, bool do_command_logging)
d62a17ae 3103{
3104 /* For further configuration read, preserve current directory. */
3105 vty_save_cwd();
3106
3107 vtyvec = vector_init(VECTOR_MIN_SIZE);
3108
3109 vty_master = master_thread;
3110
154b9e8f 3111 atexit(vty_stdio_atexit);
d62a17ae 3112
3113 /* Initilize server thread vector. */
3114 Vvty_serv_thread = vector_init(VECTOR_MIN_SIZE);
3115
3116 /* Install bgp top node. */
612c2c15 3117 install_node(&vty_node);
d62a17ae 3118
3119 install_element(VIEW_NODE, &config_who_cmd);
3120 install_element(VIEW_NODE, &show_history_cmd);
3121 install_element(CONFIG_NODE, &line_vty_cmd);
3122 install_element(CONFIG_NODE, &service_advanced_vty_cmd);
3123 install_element(CONFIG_NODE, &no_service_advanced_vty_cmd);
3124 install_element(CONFIG_NODE, &show_history_cmd);
3125 install_element(CONFIG_NODE, &log_commands_cmd);
2950f5da
DS
3126
3127 if (do_command_logging) {
3128 do_log_commands = true;
3129 do_log_commands_perm = true;
3130 }
3131
d62a17ae 3132 install_element(ENABLE_NODE, &terminal_monitor_cmd);
3133 install_element(ENABLE_NODE, &terminal_no_monitor_cmd);
3134 install_element(ENABLE_NODE, &no_terminal_monitor_cmd);
3135
3136 install_default(VTY_NODE);
3137 install_element(VTY_NODE, &exec_timeout_min_cmd);
3138 install_element(VTY_NODE, &exec_timeout_sec_cmd);
3139 install_element(VTY_NODE, &no_exec_timeout_cmd);
3140 install_element(VTY_NODE, &vty_access_class_cmd);
3141 install_element(VTY_NODE, &no_vty_access_class_cmd);
3142 install_element(VTY_NODE, &vty_login_cmd);
3143 install_element(VTY_NODE, &no_vty_login_cmd);
3144 install_element(VTY_NODE, &vty_ipv6_access_class_cmd);
3145 install_element(VTY_NODE, &no_vty_ipv6_access_class_cmd);
3146}
3147
3148void vty_terminate(void)
3149{
daeb97e9 3150 memset(vty_cwd, 0x00, sizeof(vty_cwd));
d62a17ae 3151
3152 if (vtyvec && Vvty_serv_thread) {
3153 vty_reset();
3154 vector_free(vtyvec);
3155 vector_free(Vvty_serv_thread);
3156 vtyvec = NULL;
3157 Vvty_serv_thread = NULL;
3158 }
228da428 3159}