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