5136da516fc7ce33a685baba31fd1ae4117e6833
[vpp.git] / vlib / vlib / unix / cli.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16  * cli.c: Unix stdin/socket CLI.
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39 /**
40  * @file vlib/vlib/unix/cli.c
41  * @brief Unix stdin/socket command line interface.
42  * Provides a command line interface so humans can interact with VPP.
43  * This is predominantly a debugging and testing mechanism.
44  */
45
46 #include <vlib/vlib.h>
47 #include <vlib/unix/unix.h>
48 #include <vppinfra/timer.h>
49
50 #include <ctype.h>
51 #include <fcntl.h>
52 #include <sys/stat.h>
53 #include <termios.h>
54 #include <signal.h>
55 #include <unistd.h>
56 #include <arpa/telnet.h>
57 #include <sys/ioctl.h>
58
59 /** ANSI escape code. */
60 #define ESC "\x1b"
61
62 /** ANSI Control Sequence Introducer. */
63 #define CSI ESC "["
64
65 /** ANSI clear screen. */
66 #define ANSI_CLEAR      CSI "2J" CSI "1;1H"
67 /** ANSI reset color settings. */
68 #define ANSI_RESET      CSI "0m"
69 /** ANSI Start bold text. */
70 #define ANSI_BOLD       CSI "1m"
71 /** ANSI Stop bold text. */
72 #define ANSI_DIM        CSI "2m"
73 /** ANSI Start dark red text. */
74 #define ANSI_DRED       ANSI_DIM CSI "31m"
75 /** ANSI Start bright red text. */
76 #define ANSI_BRED       ANSI_BOLD CSI "31m"
77 /** ANSI clear line cursor is on. */
78 #define ANSI_CLEARLINE  CSI "2K"
79 /** ANSI scroll screen down one line. */
80 #define ANSI_SCROLLDN   CSI "1T"
81 /** ANSI save cursor position. */
82 #define ANSI_SAVECURSOR CSI "s"
83 /** ANSI restore cursor position if previously saved. */
84 #define ANSI_RESTCURSOR CSI "u"
85
86 /** Maximum depth into a byte stream from which to compile a Telnet
87  * protocol message. This is a saftey measure. */
88 #define UNIX_CLI_MAX_DEPTH_TELNET 24
89
90 /** Unix standard in */
91 #define UNIX_CLI_STDIN_FD 0
92
93
94 /** A CLI banner line. */
95 typedef struct {
96   u8 * line;    /**< The line to print. */
97   u32 length;   /**< The length of the line without terminating NUL. */
98 } unix_cli_banner_t;
99
100 #define _(a) { .line = (u8 *)(a), .length = sizeof(a) - 1 }
101 /** Plain welcome banner. */
102 static unix_cli_banner_t unix_cli_banner[] = {
103 _("    _______    _        _   _____  ___ \n"),
104 _(" __/ __/ _ \\  (_)__    | | / / _ \\/ _ \\\n"),
105 _(" _/ _// // / / / _ \\   | |/ / ___/ ___/\n"),
106 _(" /_/ /____(_)_/\\___/   |___/_/  /_/    \n"),
107 _("\n")
108 };
109 /** ANSI color welcome banner. */
110 static unix_cli_banner_t unix_cli_banner_color[] = {
111 _(ANSI_BRED "    _______    _     " ANSI_RESET "   _   _____  ___ \n"),
112 _(ANSI_BRED " __/ __/ _ \\  (_)__ " ANSI_RESET "   | | / / _ \\/ _ \\\n"),
113 _(ANSI_BRED " _/ _// // / / / _ \\" ANSI_RESET "   | |/ / ___/ ___/\n"),
114 _(ANSI_BRED " /_/ /____(_)_/\\___/" ANSI_RESET "   |___/_/  /_/    \n"),
115 _("\n")
116 };
117 #undef _
118
119 /** Pager line index */
120 typedef struct {
121   /** Index into pager_vector */
122   u32 line;
123
124   /** Offset of the string in the line */
125   u32 offset;
126
127   /** Length of the string in the line */
128   u32 length;
129 } unix_cli_pager_index_t;
130
131
132 /** Unix CLI session. */
133 typedef struct {
134   /** The file index held by unix.c */
135   u32 unix_file_index;
136
137   /** Vector of output pending write to file descriptor. */
138   u8 * output_vector;
139
140   /** Vector of input saved by Unix input node to be processed by
141      CLI process. */
142   u8 * input_vector;
143
144   u8 has_history;
145   u8 ** command_history;
146   u8 * current_command;
147   i32 excursion;
148
149   /** Maximum number of history entries this session will store. */
150   u32 history_limit;
151
152   /** Current command line counter */
153   u32 command_number;
154
155   u8 * search_key;
156   int search_mode;
157
158   /** Position of the insert cursor on the current input line */
159   u32 cursor;
160
161   /** Line mode or char mode */
162   u8 line_mode;
163
164   /** Set if the CRLF mode wants CR + LF */
165   u8 crlf_mode;
166
167   /** Can we do ANSI output? */
168   u8 ansi_capable;
169
170   /** Has the session started? */
171   u8 started;
172
173   /** Disable the pager? */
174   u8 no_pager;
175
176   /** Pager buffer */
177   u8 ** pager_vector;
178
179   /** Index of line fragments in the pager buffer */
180   unix_cli_pager_index_t * pager_index;
181
182   /** Line number of top of page */
183   u32 pager_start;
184
185   /** Terminal width */
186   u32 width;
187
188   /** Terminal height */
189   u32 height;
190
191   /** Process node identifier */
192   u32 process_node_index;
193 } unix_cli_file_t;
194
195 /** Resets the pager buffer and other data.
196  * @param f The CLI session whose pager needs to be reset.
197  */
198 always_inline void
199 unix_cli_pager_reset (unix_cli_file_t *f)
200 {
201   u8 ** p;
202
203   f->pager_start = 0;
204
205   vec_free (f->pager_index);
206   f->pager_index = 0;
207
208   vec_foreach (p, f->pager_vector)
209     {
210       vec_free (*p);
211     }
212   vec_free (f->pager_vector);
213   f->pager_vector = 0;
214 }
215
216 /** Release storage used by a CLI session.
217  * @param f The CLI session whose storage needs to be released.
218  */
219 always_inline void
220 unix_cli_file_free (unix_cli_file_t * f)
221 {
222   vec_free (f->output_vector);
223   vec_free (f->input_vector);
224   unix_cli_pager_reset (f);
225 }
226
227 /** CLI actions */
228 typedef enum {
229   UNIX_CLI_PARSE_ACTION_NOACTION = 0,  /**< No action */
230   UNIX_CLI_PARSE_ACTION_CRLF,          /**< Carriage return, newline or enter */
231   UNIX_CLI_PARSE_ACTION_TAB,           /**< Tab key */
232   UNIX_CLI_PARSE_ACTION_ERASE,         /**< Erase cursor left */
233   UNIX_CLI_PARSE_ACTION_ERASERIGHT,    /**< Erase cursor right */
234   UNIX_CLI_PARSE_ACTION_UP,            /**< Up arrow */
235   UNIX_CLI_PARSE_ACTION_DOWN,          /**< Down arrow */
236   UNIX_CLI_PARSE_ACTION_LEFT,
237   UNIX_CLI_PARSE_ACTION_RIGHT,
238   UNIX_CLI_PARSE_ACTION_HOME,
239   UNIX_CLI_PARSE_ACTION_END,
240   UNIX_CLI_PARSE_ACTION_WORDLEFT,
241   UNIX_CLI_PARSE_ACTION_WORDRIGHT,
242   UNIX_CLI_PARSE_ACTION_ERASELINELEFT,
243   UNIX_CLI_PARSE_ACTION_ERASELINERIGHT,
244   UNIX_CLI_PARSE_ACTION_CLEAR,
245   UNIX_CLI_PARSE_ACTION_REVSEARCH,
246   UNIX_CLI_PARSE_ACTION_FWDSEARCH,
247   UNIX_CLI_PARSE_ACTION_YANK,
248   UNIX_CLI_PARSE_ACTION_TELNETIAC,
249
250   UNIX_CLI_PARSE_ACTION_PAGER_CRLF,
251   UNIX_CLI_PARSE_ACTION_PAGER_QUIT,
252   UNIX_CLI_PARSE_ACTION_PAGER_NEXT,
253   UNIX_CLI_PARSE_ACTION_PAGER_DN,
254   UNIX_CLI_PARSE_ACTION_PAGER_UP,
255   UNIX_CLI_PARSE_ACTION_PAGER_TOP,
256   UNIX_CLI_PARSE_ACTION_PAGER_BOTTOM,
257   UNIX_CLI_PARSE_ACTION_PAGER_PGDN,
258   UNIX_CLI_PARSE_ACTION_PAGER_PGUP,
259   UNIX_CLI_PARSE_ACTION_PAGER_REDRAW,
260   UNIX_CLI_PARSE_ACTION_PAGER_SEARCH,
261
262   UNIX_CLI_PARSE_ACTION_PARTIALMATCH,
263   UNIX_CLI_PARSE_ACTION_NOMATCH
264 } unix_cli_parse_action_t;
265
266 /** \brief Mapping of input buffer strings to action values.
267  * @note This won't work as a hash since we need to be able to do
268  *       partial matches on the string.
269  */
270 typedef struct {
271   u8 *input;                        /**< Input string to match. */
272   u32 len;                          /**< Length of input without final NUL. */
273   unix_cli_parse_action_t action;   /**< Action to take when matched. */
274 } unix_cli_parse_actions_t;
275
276 /** @brief Given a capital ASCII letter character return a @c NUL terminated
277  * string with the control code for that letter.
278  *
279  * @param c An ASCII character.
280  * @return A @c NUL terminated string of type @c u8[].
281  *
282  * @par Example
283  *     @c CTL('A') returns <code>{ 0x01, 0x00 }</code> as a @c u8[].
284  */
285 #define CTL(c) (u8[]){ (c) - '@', 0 }
286
287 #define _(a,b) { .input = (u8 *)(a), .len = sizeof(a) - 1, .action = (b) }
288 /**
289  * Patterns to match on a CLI input stream.
290  * @showinitializer
291  */
292 static unix_cli_parse_actions_t unix_cli_parse_strings[] = {
293  /* Line handling */
294  _( "\r\n",   UNIX_CLI_PARSE_ACTION_CRLF ),       /* Must be before '\r' */
295  _( "\n",     UNIX_CLI_PARSE_ACTION_CRLF ),
296  _( "\r\0",   UNIX_CLI_PARSE_ACTION_CRLF ),       /* Telnet does this */
297  _( "\r",     UNIX_CLI_PARSE_ACTION_CRLF ),
298
299  /* Unix shell control codes */
300  _( CTL('B'), UNIX_CLI_PARSE_ACTION_LEFT ),
301  _( CTL('F'), UNIX_CLI_PARSE_ACTION_RIGHT ),
302  _( CTL('P'), UNIX_CLI_PARSE_ACTION_UP ),
303  _( CTL('N'), UNIX_CLI_PARSE_ACTION_DOWN ),
304  _( CTL('A'), UNIX_CLI_PARSE_ACTION_HOME ),
305  _( CTL('E'), UNIX_CLI_PARSE_ACTION_END ),
306  _( CTL('D'), UNIX_CLI_PARSE_ACTION_ERASERIGHT ),
307  _( CTL('U'), UNIX_CLI_PARSE_ACTION_ERASELINELEFT ),
308  _( CTL('K'), UNIX_CLI_PARSE_ACTION_ERASELINERIGHT ),
309  _( CTL('Y'), UNIX_CLI_PARSE_ACTION_YANK ),
310  _( CTL('L'), UNIX_CLI_PARSE_ACTION_CLEAR ),
311  _( ESC "b",  UNIX_CLI_PARSE_ACTION_WORDLEFT ),   /* Alt-B */
312  _( ESC "f",  UNIX_CLI_PARSE_ACTION_WORDRIGHT ),  /* Alt-F */
313  _( "\b",     UNIX_CLI_PARSE_ACTION_ERASE ),      /* ^H */
314  _( "\x7f",   UNIX_CLI_PARSE_ACTION_ERASE ),      /* Backspace */
315  _( "\t",     UNIX_CLI_PARSE_ACTION_TAB ),        /* ^I */
316
317  /* VT100 Normal mode - Broadest support */
318  _( CSI "A",  UNIX_CLI_PARSE_ACTION_UP ),
319  _( CSI "B",  UNIX_CLI_PARSE_ACTION_DOWN ),
320  _( CSI "C",  UNIX_CLI_PARSE_ACTION_RIGHT ),
321  _( CSI "D",  UNIX_CLI_PARSE_ACTION_LEFT ),
322  _( CSI "H",  UNIX_CLI_PARSE_ACTION_HOME ),
323  _( CSI "F",  UNIX_CLI_PARSE_ACTION_END ),
324  _( CSI "3~", UNIX_CLI_PARSE_ACTION_ERASERIGHT ), /* Delete */
325  _( CSI "1;5D", UNIX_CLI_PARSE_ACTION_WORDLEFT ), /* C-Left */
326  _( CSI "1;5C", UNIX_CLI_PARSE_ACTION_WORDRIGHT ),/* C-Right */
327
328   /* VT100 Application mode - Some Gnome Terminal functions use these */
329  _( ESC "OA", UNIX_CLI_PARSE_ACTION_UP ),
330  _( ESC "OB", UNIX_CLI_PARSE_ACTION_DOWN ),
331  _( ESC "OC", UNIX_CLI_PARSE_ACTION_RIGHT ),
332  _( ESC "OD", UNIX_CLI_PARSE_ACTION_LEFT ),
333  _( ESC "OH", UNIX_CLI_PARSE_ACTION_HOME ),
334  _( ESC "OF", UNIX_CLI_PARSE_ACTION_END ),
335
336  /* ANSI X3.41-1974 - sent by Microsoft Telnet and PuTTY */
337  _( CSI "1~", UNIX_CLI_PARSE_ACTION_HOME ),
338  _( CSI "4~", UNIX_CLI_PARSE_ACTION_END ),
339
340  /* Emacs-ish history search */
341  _( CTL('S'), UNIX_CLI_PARSE_ACTION_FWDSEARCH ),
342  _( CTL('R'), UNIX_CLI_PARSE_ACTION_REVSEARCH ),
343
344  /* Other protocol things */
345  _( "\xff",   UNIX_CLI_PARSE_ACTION_TELNETIAC ),  /* IAC */
346  _( "\0",     UNIX_CLI_PARSE_ACTION_NOACTION ),   /* NUL */
347  _( NULL,     UNIX_CLI_PARSE_ACTION_NOMATCH )
348 };
349
350 /**
351  * Patterns to match when a CLI session is in the pager.
352  * @showinitializer
353  */
354 static unix_cli_parse_actions_t unix_cli_parse_pager[] = {
355  /* Line handling */
356  _( "\r\n",   UNIX_CLI_PARSE_ACTION_PAGER_CRLF ),       /* Must be before '\r' */
357  _( "\n",     UNIX_CLI_PARSE_ACTION_PAGER_CRLF ),
358  _( "\r\0",   UNIX_CLI_PARSE_ACTION_PAGER_CRLF ),       /* Telnet does this */
359  _( "\r",     UNIX_CLI_PARSE_ACTION_PAGER_CRLF ),
360
361  /* Pager commands */
362  _( " ",      UNIX_CLI_PARSE_ACTION_PAGER_NEXT ),
363  _( "q",      UNIX_CLI_PARSE_ACTION_PAGER_QUIT ),
364  _( CTL('L'), UNIX_CLI_PARSE_ACTION_PAGER_REDRAW ),
365  _( CTL('R'), UNIX_CLI_PARSE_ACTION_PAGER_REDRAW ),
366  _( "/",      UNIX_CLI_PARSE_ACTION_PAGER_SEARCH ),
367
368  /* VT100 */
369  _( CSI "A",  UNIX_CLI_PARSE_ACTION_PAGER_UP ),
370  _( CSI "B",  UNIX_CLI_PARSE_ACTION_PAGER_DN ),
371  _( CSI "H",  UNIX_CLI_PARSE_ACTION_PAGER_TOP ),
372  _( CSI "F",  UNIX_CLI_PARSE_ACTION_PAGER_BOTTOM ),
373
374  /* VT100 Application mode */
375  _( ESC "OA", UNIX_CLI_PARSE_ACTION_PAGER_UP ),
376  _( ESC "OB", UNIX_CLI_PARSE_ACTION_PAGER_DN ),
377  _( ESC "OH", UNIX_CLI_PARSE_ACTION_PAGER_TOP ),
378  _( ESC "OF", UNIX_CLI_PARSE_ACTION_PAGER_BOTTOM ),
379
380  /* ANSI X3.41-1974 */
381  _( CSI "1~", UNIX_CLI_PARSE_ACTION_PAGER_TOP ),
382  _( CSI "4~", UNIX_CLI_PARSE_ACTION_PAGER_BOTTOM ),
383  _( CSI "5~", UNIX_CLI_PARSE_ACTION_PAGER_PGUP ),
384  _( CSI "6~", UNIX_CLI_PARSE_ACTION_PAGER_PGDN ),
385
386  /* Other protocol things */
387  _( "\xff",   UNIX_CLI_PARSE_ACTION_TELNETIAC ),  /* IAC */
388  _( "\0",     UNIX_CLI_PARSE_ACTION_NOACTION ),   /* NUL */
389  _( NULL,     UNIX_CLI_PARSE_ACTION_NOMATCH )
390 };
391 #undef _
392
393 /** CLI session events. */
394 typedef enum {
395   UNIX_CLI_PROCESS_EVENT_READ_READY,  /**< A file descriptor has data to be read. */
396   UNIX_CLI_PROCESS_EVENT_QUIT,        /**< A CLI session wants to close. */
397 } unix_cli_process_event_type_t;
398
399 /** CLI global state. */
400 typedef struct {
401   /** Prompt string for CLI. */
402   u8 * cli_prompt;
403
404   /** Vec pool of CLI sessions. */
405   unix_cli_file_t * cli_file_pool;
406
407   /** Vec pool of unused session indices. */
408   u32 * unused_cli_process_node_indices;
409
410   /** The session index of the stdin cli */
411   u32 stdin_cli_file_index;
412
413   /** File pool index of current input. */
414   u32 current_input_file_index;
415 } unix_cli_main_t;
416
417 /** CLI global state */
418 static unix_cli_main_t unix_cli_main;
419
420 /**
421  * \brief Search for a byte sequence in the action list.
422  *
423  * Searches the @ref unix_cli_parse_actions_t list in @a a for a match with
424  * the bytes in @a input of maximum length @a ilen bytes.
425  * When a match is made @a *matched indicates how many bytes were matched.
426  * Returns a value from the enum @ref unix_cli_parse_action_t to indicate
427  * whether no match was found, a partial match was found or a complete
428  * match was found and what action, if any, should be taken.
429  *
430  * @param[in]  a        Actions list to search within.
431  * @param[in]  input    String fragment to search for.
432  * @param[in]  ilen     Length of the string in 'input'.
433  * @param[out] matched  Pointer to an integer that will contain the number
434  *                      of bytes matched when a complete match is found.
435  *
436  * @return Action from @ref unix_cli_parse_action_t that the string fragment
437  *         matches.
438  *         @ref UNIX_CLI_PARSE_ACTION_PARTIALMATCH is returned when the
439  *         whole input string matches the start of at least one action.
440  *         @ref UNIX_CLI_PARSE_ACTION_NOMATCH is returned when there is no
441  *         match at all.
442  */
443 static unix_cli_parse_action_t
444 unix_cli_match_action(unix_cli_parse_actions_t *a,
445           u8 *input, u32 ilen, i32 *matched)
446 {
447   u8 partial = 0;
448
449   while (a->input)
450     {
451         if (ilen >= a->len)
452           {
453             /* see if the start of the input buffer exactly matches the current
454              * action string. */
455             if (memcmp(input, a->input, a->len) == 0)
456               {
457                 *matched = a->len;
458                 return a->action;
459               }
460           }
461         else
462           {
463             /* if the first ilen characters match, flag this as a partial -
464              * meaning keep collecting bytes in case of a future match */
465             if (memcmp(input, a->input, ilen) == 0)
466                 partial = 1;
467           }
468
469         /* check next action */
470         a ++;
471     }
472
473   return partial ?
474         UNIX_CLI_PARSE_ACTION_PARTIALMATCH :
475         UNIX_CLI_PARSE_ACTION_NOMATCH;
476 }
477
478
479 static void
480 unix_cli_add_pending_output (unix_file_t * uf,
481                              unix_cli_file_t * cf,
482                              u8 * buffer,
483                              uword buffer_bytes)
484 {
485   unix_main_t * um = &unix_main;
486
487   vec_add (cf->output_vector, buffer, buffer_bytes);
488   if (vec_len (cf->output_vector) > 0)
489     {
490       int skip_update = 0 != (uf->flags & UNIX_FILE_DATA_AVAILABLE_TO_WRITE);
491       uf->flags |= UNIX_FILE_DATA_AVAILABLE_TO_WRITE;
492       if (! skip_update)
493         um->file_update (uf, UNIX_FILE_UPDATE_MODIFY);
494     }
495 }
496
497 static void
498 unix_cli_del_pending_output (unix_file_t * uf,
499                              unix_cli_file_t * cf,
500                              uword n_bytes)
501 {
502   unix_main_t * um = &unix_main;
503
504   vec_delete (cf->output_vector, n_bytes, 0);
505   if (vec_len (cf->output_vector) <= 0)
506     {
507       int skip_update = 0 == (uf->flags & UNIX_FILE_DATA_AVAILABLE_TO_WRITE);
508       uf->flags &= ~UNIX_FILE_DATA_AVAILABLE_TO_WRITE;
509       if (! skip_update)
510         um->file_update (uf, UNIX_FILE_UPDATE_MODIFY);
511     }
512 }
513
514 /** \brief A bit like strchr with a buffer length limit.
515  * Search a buffer for the first instance of a character up to the limit of
516  * the buffer length. If found then return the position of that character.
517  *
518  * The key departure from strchr is that if the character is not found then
519  * return the buffer length.
520  *
521  * @param chr The byte value to search for.
522  * @param str The buffer in which to search for the value.
523  * @param len The depth into the buffer to search.
524  *
525  * @return The index of the first occurence of \c chr. If \c chr is not
526  *          found then \c len instead.
527  */
528 always_inline word unix_vlib_findchr(u8 chr, u8 *str, word len)
529 {
530     word i = 0;
531     for (i = 0; i < len; i++, str++)
532       {
533         if (*str == chr)
534           return i;
535       }
536     return len;
537 }
538
539 /** \brief Send a buffer to the CLI stream if possible, enqueue it otherwise.
540  * Attempts to write given buffer to the file descriptor of the given
541  * Unix CLI session. If that session already has data in the output buffer
542  * or if the write attempt tells us to try again later then the given buffer
543  * is appended to the pending output buffer instead.
544  *
545  * This is typically called only from \c unix_vlib_cli_output_cooked since
546  * that is where CRLF handling occurs or from places where we explicitly do
547  * not want cooked handling.
548  *
549  * @param cf Unix CLI session of the desired stream to write to.
550  * @param uf The Unix file structure of the desired stream to write to.
551  * @param buffer Pointer to the buffer that needs to be written.
552  * @param buffer_bytes The number of bytes from \c buffer to write.
553  */
554 static void unix_vlib_cli_output_raw(unix_cli_file_t * cf,
555           unix_file_t * uf,
556           u8 * buffer,
557           uword buffer_bytes)
558 {
559   int n = 0;
560
561   if (vec_len (cf->output_vector) == 0)
562       n = write (uf->file_descriptor, buffer, buffer_bytes);
563
564   if (n < 0 && errno != EAGAIN)
565     {
566       clib_unix_warning ("write");
567     }
568   else if ((word) n < (word) buffer_bytes)
569     {
570       /* We got EAGAIN or we already have stuff in the buffer;
571        * queue up whatever didn't get sent for later. */
572       if (n < 0) n = 0;
573       unix_cli_add_pending_output (uf, cf, buffer + n, buffer_bytes - n);
574     }
575 }
576
577 /** \brief Process a buffer for CRLF handling before outputting it to the CLI.
578  *
579  * @param cf Unix CLI session of the desired stream to write to.
580  * @param uf The Unix file structure of the desired stream to write to.
581  * @param buffer Pointer to the buffer that needs to be written.
582  * @param buffer_bytes The number of bytes from \c buffer to write.
583  */
584 static void unix_vlib_cli_output_cooked(unix_cli_file_t * cf,
585           unix_file_t * uf,
586           u8 * buffer,
587           uword buffer_bytes)
588 {
589   word end = 0, start = 0;
590
591   while (end < buffer_bytes)
592     {
593       if (cf->crlf_mode)
594         {
595           /* iterate the line on \n's so we can insert a \r before it */
596           end = unix_vlib_findchr('\n',
597                                   buffer + start,
598                                   buffer_bytes - start) + start;
599         }
600       else
601         {
602           /* otherwise just send the whole buffer */
603           end = buffer_bytes;
604         }
605
606       unix_vlib_cli_output_raw(cf, uf, buffer + start, end - start);
607
608       if (cf->crlf_mode)
609         {
610           if (end < buffer_bytes)
611             {
612               unix_vlib_cli_output_raw(cf, uf, (u8 *)"\r\n", 2);
613               end ++; /* skip the \n that we already sent */
614             }
615           start = end;
616         }
617     }
618 }
619
620 /** \brief Output the CLI prompt */
621 static void unix_cli_cli_prompt(unix_cli_file_t * cf, unix_file_t * uf)
622 {
623   unix_cli_main_t * cm = &unix_cli_main;
624
625   unix_vlib_cli_output_raw (cf, uf, cm->cli_prompt, vec_len (cm->cli_prompt));
626 }
627
628 /** \brief Output a pager prompt and show number of buffered lines */
629 static void unix_cli_pager_prompt(unix_cli_file_t * cf, unix_file_t * uf)
630 {
631   u8 * prompt;
632   u32 h;
633
634   h = cf->pager_start + (cf->height - 1);
635   if (h > vec_len (cf->pager_index))
636     h = vec_len (cf->pager_index);
637
638   prompt = format(0, "\r%s-- more -- (%d-%d/%d)%s",
639     cf->ansi_capable ? ANSI_BOLD : "",
640     cf->pager_start + 1,
641     h,
642     vec_len (cf->pager_index),
643     cf->ansi_capable ? ANSI_RESET: "");
644
645   unix_vlib_cli_output_cooked(cf, uf, prompt, vec_len(prompt));
646
647   vec_free(prompt);
648 }
649
650 /** \brief Output a pager "skipping" message */
651 static void unix_cli_pager_message(unix_cli_file_t * cf, unix_file_t * uf,
652     char *message, char *postfix)
653 {
654   u8 * prompt;
655
656   prompt = format(0, "\r%s-- %s --%s%s",
657     cf->ansi_capable ? ANSI_BOLD : "",
658     message,
659     cf->ansi_capable ? ANSI_RESET: "",
660     postfix);
661
662   unix_vlib_cli_output_cooked(cf, uf, prompt, vec_len(prompt));
663
664   vec_free(prompt);
665 }
666
667 /** \brief Erase the printed pager prompt */
668 static void unix_cli_pager_prompt_erase(unix_cli_file_t * cf, unix_file_t * uf)
669 {
670   if (cf->ansi_capable)
671     {
672       unix_vlib_cli_output_cooked(cf, uf, (u8 *)"\r", 1);
673       unix_vlib_cli_output_cooked(cf, uf,
674           (u8 *)ANSI_CLEARLINE, sizeof(ANSI_CLEARLINE) - 1);
675     }
676   else
677     {
678       int i;
679
680       unix_vlib_cli_output_cooked(cf, uf, (u8 *)"\r", 1);
681       for (i = 0; i < cf->width - 1; i ++)
682         unix_vlib_cli_output_cooked(cf, uf, (u8 *)" ", 1);
683       unix_vlib_cli_output_cooked(cf, uf, (u8 *)"\r", 1);
684     }
685 }
686
687 /** \brief Uses an ANSI escape sequence to move the cursor */
688 static void unix_cli_ansi_cursor(unix_cli_file_t * cf, unix_file_t * uf,
689       u16 x, u16 y)
690 {
691   u8 * str;
692
693   str = format(0, "%s%d;%dH", CSI, y, x);
694
695   unix_vlib_cli_output_cooked(cf, uf, str, vec_len(str));
696
697   vec_free(str);
698 }
699
700 /** Redraw the currently displayed page of text.
701  * @param cf CLI session to redraw the pager buffer of.
702  * @param uf Unix file of the CLI session.
703  */
704 static void unix_cli_pager_redraw(unix_cli_file_t * cf, unix_file_t * uf)
705 {
706   unix_cli_pager_index_t * pi = NULL;
707   u8 * line = NULL;
708   word i;
709
710   /* No active pager? Do nothing. */
711   if (!vec_len (cf->pager_index))
712     return;
713
714   if (cf->ansi_capable)
715     {
716       /* If we have ANSI, send the clear screen sequence */
717       unix_vlib_cli_output_cooked (cf, uf,
718           (u8 *)ANSI_CLEAR, sizeof(ANSI_CLEAR) - 1);
719     }
720   else
721     {
722       /* Otherwise make sure we're on a blank line */
723       unix_cli_pager_prompt_erase (cf, uf);
724     }
725
726   /* (Re-)send the current page of content */
727   for (i = 0; i < cf->height - 1 &&
728           i + cf->pager_start < vec_len (cf->pager_index);
729           i ++)
730     {
731       pi = &cf->pager_index[cf->pager_start + i];
732       line = cf->pager_vector[pi->line] + pi->offset;
733
734       unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
735     }
736   /* if the last line didn't end in newline, add a newline */
737   if (pi && line[pi->length - 1] != '\n')
738     unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
739
740   unix_cli_pager_prompt (cf, uf);
741 }
742
743 /** @brief Process and add a line to the pager index.
744  * In normal operation this function will take the given character string
745  * found in @c line and with length @c len_or_index and iterates the over the
746  * contents, adding each line of text discovered within it to the
747  * pager index. Lines are identified by newlines ("<code>\\n</code>") and by
748  * strings longer than the width of the terminal.
749  *
750  * If instead @c line is @c NULL then @c len_or_index is taken to mean the
751  * index of an existing line in the pager buffer; this simply means that the
752  * input line does not need to be cloned since we alreayd have it. This is
753  * typical if we are reindexing the pager buffer.
754  *
755  * @param cf           The CLI session whose pager we are adding to.
756  * @param line         The string of text to be indexed into the pager buffer.
757  *                     If @c line is @c NULL then the mode of operation
758  *                     changes slightly; see the description above.
759  * @param len_or_index If @c line is a pointer to a string then this parameter
760  *                     indicates the length of that string; Otherwise this
761  *                     value provides the index in the pager buffer of an
762  *                     existing string to be indexed.
763  */
764 static void unix_cli_pager_add_line (unix_cli_file_t * cf,
765                                      u8 * line,
766                                      word len_or_index)
767 {
768   u8 * p;
769   word i, j, k;
770   word line_index, len;
771   u32 width = cf->width;
772   unix_cli_pager_index_t * pi;
773
774   if (line == NULL)
775     {
776       /* Use a line already in the pager buffer */
777       line_index = len_or_index;
778       p = cf->pager_vector[line_index];
779       len = vec_len (p);
780     }
781   else
782     {
783       len = len_or_index;
784       /* Add a copy of the raw string to the pager buffer */
785       p = vec_new (u8, len);
786       clib_memcpy (p, line, len);
787
788       /* store in pager buffer */
789       line_index = vec_len (cf->pager_vector);
790       vec_add1 (cf->pager_vector, p);
791     }
792
793   i = 0;
794   while (i < len)
795     {
796       /* Find the next line, or run to terminal width, or run to EOL */
797       int l = len - i;
798       j = unix_vlib_findchr((u8)'\n', p, l < width ? l : width);
799
800       if (j < l && p[j] == '\n') /* incl \n */
801         j ++;
802
803       /* Add the line to the index */
804       k = vec_len (cf->pager_index);
805       vec_validate (cf->pager_index, k);
806       pi = &cf->pager_index[k];
807
808       pi->line = line_index;
809       pi->offset = i;
810       pi->length = j;
811
812       i += j;
813       p += j;
814     }
815 }
816
817 /** @brief Reindex entire pager buffer.
818  * Resets the current pager index and then re-adds the lines in the pager
819  * buffer to the index.
820  *
821  * Additionally this function attempts to retain the current page start
822  * line offset by searching for the same top-of-screen line in the new index.
823  *
824  * @param cf The CLI session whose pager buffer should be reindexed.
825  */
826 static void unix_cli_pager_reindex (unix_cli_file_t * cf)
827 {
828   word i, old_line, old_offset;
829   unix_cli_pager_index_t * pi;
830
831   /* If there is nothing in the pager buffer then make sure the index
832    * is empty and move on.
833    */
834   if (cf->pager_vector == 0)
835     {
836       vec_reset_length (cf->pager_index);
837       return;
838     }
839
840   /* Retain a pointer to the current page start line so we can
841    * find it later
842    */
843   pi = &cf->pager_index[cf->pager_start];
844   old_line = pi->line;
845   old_offset = pi->offset;
846
847   /* Re-add the buffered lines to the index */
848   vec_reset_length (cf->pager_index);
849   vec_foreach_index(i, cf->pager_vector)
850     {
851       unix_cli_pager_add_line(cf, NULL, i);
852     }
853
854   /* Attempt to re-locate the previously stored page start line */
855   vec_foreach_index(i, cf->pager_index)
856     {
857       pi = &cf->pager_index[i];
858
859       if (pi->line == old_line &&
860             (pi->offset <= old_offset ||
861              pi->offset + pi->length > old_offset))
862         {
863           /* Found it! */
864           cf->pager_start = i;
865           break;
866         }
867     }
868
869   /* In case the start line was not found (rare), ensure the pager start
870    * index is within bounds
871    */
872   if (cf->pager_start >= vec_len (cf->pager_index))
873     {
874       if (!cf->height || vec_len (cf->pager_index) < (cf->height - 1))
875         cf->pager_start = 0;
876       else
877         cf->pager_start = vec_len (cf->pager_index) - (cf->height - 1);
878     }
879 }
880
881 /** VLIB CLI output function.
882  *
883  * If the terminal has a pager configured then this function takes care
884  * of collating output into the pager buffer; ensuring only the first page
885  * is displayed and any lines in excess of the first page are buffered.
886  *
887  * If the maximum number of index lines in the buffer is exceeded then the
888  * pager is cancelled and the contents of the current buffer are sent to the
889  * terminal.
890  *
891  * If there is no pager configured then the output is sent directly to the
892  * terminal.
893  *
894  * @param cli_file_index Index of the CLI session where this output is
895  *                       directed.
896  * @param buffer         String of printabe bytes to be output.
897  * @param buffer_bytes   The number of bytes in @c buffer to be output.
898  */
899 static void unix_vlib_cli_output (uword cli_file_index,
900                                   u8 * buffer,
901                                   uword buffer_bytes)
902 {
903   unix_main_t * um = &unix_main;
904   unix_cli_main_t * cm = &unix_cli_main;
905   unix_cli_file_t * cf;
906   unix_file_t * uf;
907
908   cf = pool_elt_at_index (cm->cli_file_pool, cli_file_index);
909   uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
910
911   if (cf->no_pager || um->cli_pager_buffer_limit == 0 || cf->height == 0)
912     {
913       unix_vlib_cli_output_cooked (cf, uf, buffer, buffer_bytes);
914     }
915   else
916     {
917       word row = vec_len (cf->pager_index);
918       u8 * line;
919       unix_cli_pager_index_t * pi;
920
921       /* Index and add the output lines to the pager buffer. */
922       unix_cli_pager_add_line (cf, buffer, buffer_bytes);
923
924       /* Now iterate what was added to display the lines.
925        * If we reach the bottom of the page, display a prompt.
926        */
927       while (row < vec_len (cf->pager_index))
928         {
929           if (row < cf->height - 1)
930             {
931               /* output this line */
932               pi = &cf->pager_index[row];
933               line = cf->pager_vector[pi->line] + pi->offset;
934               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
935
936               /* if the last line didn't end in newline, and we're at the
937                * bottom of the page, add a newline */
938               if (line[pi->length - 1] != '\n' && row == cf->height - 2)
939                 unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
940             }
941           else
942             {
943               /* Display the pager prompt every 10 lines */
944               if (!(row % 10))
945                 unix_cli_pager_prompt(cf, uf);
946             }
947           row ++;
948         }
949
950       /* Check if we went over the pager buffer limit */
951       if (vec_len (cf->pager_index) > um->cli_pager_buffer_limit)
952         {
953           /* Stop using the pager for the remainder of this CLI command */
954           cf->no_pager = 2;
955
956           /* If we likely printed the prompt, erase it */
957           if (vec_len (cf->pager_index) > cf->height - 1)
958             unix_cli_pager_prompt_erase (cf, uf);
959
960           /* Dump out the contents of the buffer */
961           for (row = cf->pager_start + (cf->height - 1);
962                         row < vec_len (cf->pager_index); row ++)
963             {
964               pi = &cf->pager_index[row];
965               line = cf->pager_vector[pi->line] + pi->offset;
966               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
967             }
968
969           unix_cli_pager_reset (cf);
970         }
971     }
972 }
973
974 /** Identify whether a terminal type is ANSI capable.
975  *
976  * Compares the string given in @term with a list of terminal types known
977  * to support ANSI escape sequences.
978  *
979  * This list contains, for example, @c xterm, @c screen and @c ansi.
980  *
981  * @param term A string with a terminal type in it.
982  * @param len The length of the string in @term.
983  *
984  * @return @c 1 if the terminal type is recognized as supporting ANSI
985  *         terminal sequences; @c 0 otherwise.
986  */
987 static u8 unix_cli_terminal_type(u8 * term, uword len)
988 {
989   /* This may later be better done as a hash of some sort. */
990 #define _(a) do { \
991     if (strncasecmp(a, (char *)term, (size_t)len) == 0) return 1; \
992   } while(0)
993
994   _("xterm");
995   _("xterm-color");
996   _("xterm-256color"); /* iTerm on Mac */
997   _("screen");
998   _("ansi"); /* Microsoft Telnet */
999 #undef _
1000
1001   return 0;
1002 }
1003
1004 /** \brief Emit initial welcome banner and prompt on a connection. */
1005 static void unix_cli_file_welcome(unix_cli_main_t * cm, unix_cli_file_t * cf)
1006 {
1007   unix_main_t * um = &unix_main;
1008   unix_file_t * uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
1009   unix_cli_banner_t *banner;
1010   int i, len;
1011
1012   /*
1013    * Put the first bytes directly into the buffer so that further output is
1014    * queued until everything is ready. (oterwise initial prompt can appear
1015    * mid way through VPP initialization)
1016    */
1017   unix_cli_add_pending_output (uf, cf, (u8 *)"\r", 1);
1018
1019   if (!um->cli_no_banner)
1020     {
1021       if (cf->ansi_capable)
1022         {
1023           banner = unix_cli_banner_color;
1024           len = ARRAY_LEN(unix_cli_banner_color);
1025         }
1026       else
1027         {
1028           banner = unix_cli_banner;
1029           len = ARRAY_LEN(unix_cli_banner);
1030         }
1031
1032       for (i = 0; i < len; i++)
1033         {
1034           unix_vlib_cli_output_cooked(cf, uf,
1035             banner[i].line,
1036             banner[i].length);
1037         }
1038       }
1039
1040   /* Prompt. */
1041   unix_cli_cli_prompt (cf, uf);
1042
1043   cf->started = 1;
1044 }
1045
1046 /** \brief A failsafe triggered on a timer to ensure we send the prompt
1047  * to telnet sessions that fail to negotiate the terminal type. */
1048 static void unix_cli_file_welcome_timer(any arg, f64 delay)
1049 {
1050   unix_cli_main_t * cm = &unix_cli_main;
1051   unix_cli_file_t * cf;
1052   (void)delay;
1053
1054   /* Check the connection didn't close already */
1055   if (pool_is_free_index (cm->cli_file_pool, (uword)arg))
1056     return;
1057
1058   cf = pool_elt_at_index (cm->cli_file_pool, (uword)arg);
1059
1060   if (!cf->started)
1061     unix_cli_file_welcome(cm, cf);
1062 }
1063
1064 /** \brief A mostly no-op Telnet state machine.
1065  * Process Telnet command bytes in a way that ensures we're mostly
1066  * transparent to the Telnet protocol. That is, it's mostly a no-op.
1067  *
1068  * @return -1 if we need more bytes, otherwise a positive integer number of
1069  *          bytes to consume from the input_vector, not including the initial
1070  *          IAC byte.
1071  */
1072 static i32 unix_cli_process_telnet(unix_main_t * um,
1073         unix_cli_file_t * cf,
1074         unix_file_t * uf,
1075         u8 * input_vector,
1076         uword len)
1077 {
1078   /* Input_vector starts at IAC byte.
1079    * See if we have a complete message; if not, return -1 so we wait for more.
1080    * if we have a complete message, consume those bytes from the vector.
1081    */
1082   i32 consume = 0;
1083
1084   if (len == 1)
1085     return -1; /* want more bytes */
1086
1087   switch (input_vector[1])
1088     {
1089       case IAC:
1090         /* two IAC's in a row means to pass through 0xff.
1091          * since that makes no sense here, just consume it.
1092          */
1093         consume = 1;
1094         break;
1095
1096       case WILL:
1097       case WONT:
1098       case DO:
1099       case DONT:
1100         /* Expect 3 bytes */
1101         if (vec_len(input_vector) < 3)
1102           return -1; /* want more bytes */
1103
1104         consume = 2;
1105         break;
1106
1107       case SB:
1108         {
1109           /* Sub option - search ahead for IAC SE to end it */
1110           i32 i;
1111           for (i = 3; i < len && i < UNIX_CLI_MAX_DEPTH_TELNET; i++)
1112             {
1113               if (input_vector[i - 1] == IAC && input_vector[i] == SE)
1114                 {
1115                   /* We have a complete message; see if we care about it */
1116                   switch (input_vector[2])
1117                     {
1118                       case TELOPT_TTYPE:
1119                         if (input_vector[3] != 0)
1120                           break;
1121                         /* See if the terminal type is ANSI capable */
1122                         cf->ansi_capable =
1123                             unix_cli_terminal_type(input_vector + 4, i - 5);
1124                         /* If session not started, we can release the pause */
1125                         if (!cf->started)
1126                           /* Send the welcome banner and initial prompt */
1127                           unix_cli_file_welcome(&unix_cli_main, cf);
1128                         break;
1129
1130                       case TELOPT_NAWS:
1131                         /* Window size */
1132                         if (i != 8) /* check message is correct size */
1133                           break;
1134                         cf->width = clib_net_to_host_u16(*((u16 *)(input_vector + 3)));
1135                         cf->height = clib_net_to_host_u16(*((u16 *)(input_vector + 5)));
1136                         /* reindex pager buffer */
1137                         unix_cli_pager_reindex (cf);
1138                         /* redraw page */
1139                         unix_cli_pager_redraw (cf, uf);
1140                         break;
1141
1142                       default:
1143                         break;
1144                     }
1145                   /* Consume it all */
1146                   consume = i;
1147                   break;
1148                 }
1149             }
1150
1151           if (i == UNIX_CLI_MAX_DEPTH_TELNET)
1152             consume = 1; /* hit max search depth, advance one byte */
1153
1154           if (consume == 0)
1155             return -1; /* want more bytes */
1156
1157           break;
1158         }
1159
1160       case GA:
1161       case EL:
1162       case EC:
1163       case AO:
1164       case IP:
1165       case BREAK:
1166       case DM:
1167       case NOP:
1168       case SE:
1169       case EOR:
1170       case ABORT:
1171       case SUSP:
1172       case xEOF:
1173         /* Simple one-byte messages */
1174         consume = 1;
1175         break;
1176
1177       case AYT:
1178         /* Are You There - trigger a visible response */
1179         consume = 1;
1180         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "fd.io VPP\n", 10);
1181         break;
1182
1183       default:
1184         /* Unknown command! Eat the IAC byte */
1185         break;
1186     }
1187
1188     return consume;
1189 }
1190
1191 /** \brief Process actionable input.
1192  * Based on the \c action process the input; this typically involves
1193  * searching the command history or editing the current command line.
1194  */
1195 static int unix_cli_line_process_one(unix_cli_main_t * cm,
1196         unix_main_t * um,
1197         unix_cli_file_t * cf,
1198         unix_file_t * uf,
1199         u8 input,
1200         unix_cli_parse_action_t action)
1201 {
1202   u8 * prev;
1203   int j, delta;
1204
1205   switch (action)
1206     {
1207     case UNIX_CLI_PARSE_ACTION_NOACTION:
1208       break;
1209
1210     case UNIX_CLI_PARSE_ACTION_REVSEARCH:
1211     case UNIX_CLI_PARSE_ACTION_FWDSEARCH:
1212       if (!cf->has_history || !cf->history_limit)
1213         break;
1214       if (cf->search_mode == 0)
1215         {
1216           /* Erase the current command (if any) */
1217           for (j = 0; j < (vec_len (cf->current_command)); j++)
1218               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b \b", 3);
1219
1220           vec_reset_length (cf->search_key);
1221           vec_reset_length (cf->current_command);
1222           if (action == UNIX_CLI_PARSE_ACTION_REVSEARCH)
1223               cf->search_mode = -1;
1224           else
1225               cf->search_mode = 1;
1226           cf->cursor = 0;
1227         }
1228       else
1229         {
1230           if (action == UNIX_CLI_PARSE_ACTION_REVSEARCH)
1231             cf->search_mode = -1;
1232           else
1233             cf->search_mode = 1;
1234
1235           cf->excursion += cf->search_mode;
1236           goto search_again;
1237         }
1238       break;
1239
1240     case UNIX_CLI_PARSE_ACTION_ERASELINELEFT:
1241       /* Erase the command from the cursor to the start */
1242
1243       /* Shimmy forwards to the new end of line position */
1244       delta = vec_len (cf->current_command) - cf->cursor;
1245       for (j = cf->cursor; j > delta; j--)
1246         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1247       /* Zap from here to the end of what is currently displayed */
1248       for (; j < (vec_len (cf->current_command)); j++)
1249         unix_vlib_cli_output_cooked (cf, uf, (u8 *) " ", 1);
1250       /* Get back to the start of the line */
1251       for (j = 0; j < (vec_len (cf->current_command)); j++)
1252         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1253
1254       j = vec_len(cf->current_command) - cf->cursor;
1255       memmove(cf->current_command,
1256               cf->current_command + cf->cursor,
1257               j);
1258       _vec_len(cf->current_command) = j;
1259
1260       /* Print the new contents */
1261       unix_vlib_cli_output_cooked (cf, uf, cf->current_command, j);
1262       /* Shimmy back to the start */
1263       for (j = 0; j < (vec_len (cf->current_command)); j++)
1264         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1265       cf->cursor = 0;
1266
1267       cf->search_mode = 0;
1268       break;
1269
1270     case UNIX_CLI_PARSE_ACTION_ERASELINERIGHT:
1271       /* Erase the command from the cursor to the end */
1272
1273       /* Zap from cursor to end of what is currently displayed */
1274       for (j = cf->cursor; j < (vec_len (cf->current_command)); j++)
1275         unix_vlib_cli_output_cooked (cf, uf, (u8 *) " ", 1);
1276       /* Get back to where we were */
1277       for (j = cf->cursor; j < (vec_len (cf->current_command)); j++)
1278         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1279
1280       /* Truncate the line at the cursor */
1281       _vec_len(cf->current_command) = cf->cursor;
1282
1283       cf->search_mode = 0;
1284       break;
1285
1286     case UNIX_CLI_PARSE_ACTION_LEFT:
1287       if (cf->cursor > 0)
1288         {
1289           unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1290           cf->cursor --;
1291         }
1292
1293       cf->search_mode = 0;
1294       break;
1295
1296     case UNIX_CLI_PARSE_ACTION_RIGHT:
1297       if (cf->cursor < vec_len(cf->current_command))
1298         {
1299           /* have to emit the character under the cursor */
1300           unix_vlib_cli_output_cooked (cf, uf, cf->current_command + cf->cursor, 1);
1301           cf->cursor ++;
1302         }
1303
1304       cf->search_mode = 0;
1305       break;
1306
1307     case UNIX_CLI_PARSE_ACTION_UP:
1308     case UNIX_CLI_PARSE_ACTION_DOWN:
1309       if (!cf->has_history || !cf->history_limit)
1310         break;
1311       cf->search_mode = 0;
1312       /* Erase the command */
1313       for (j = cf->cursor; j < (vec_len (cf->current_command)); j++)
1314         unix_vlib_cli_output_cooked (cf, uf, (u8 *) " ", 1);
1315       for (j = 0; j < (vec_len (cf->current_command)); j++)
1316         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b \b", 3);
1317       vec_reset_length (cf->current_command);
1318       if (vec_len (cf->command_history))
1319         {
1320           if (action == UNIX_CLI_PARSE_ACTION_UP)
1321             delta = -1;
1322           else
1323             delta = 1;
1324
1325           cf->excursion += delta;
1326
1327           if (cf->excursion == vec_len (cf->command_history))
1328             {
1329               /* down-arrowed to last entry - want a blank line */
1330               _vec_len (cf->current_command) = 0;
1331             }
1332           else if (cf->excursion < 0)
1333             {
1334               /* up-arrowed over the start to the end, want a blank line */
1335               cf->excursion = vec_len (cf->command_history);
1336               _vec_len (cf->current_command) = 0;
1337             }
1338           else
1339             {
1340               if (cf->excursion > (i32) vec_len (cf->command_history) -1)
1341                 /* down-arrowed past end - wrap to start */
1342                 cf->excursion = 0;
1343
1344               /* Print the command at the current position */
1345               prev = cf->command_history [cf->excursion];
1346               vec_validate (cf->current_command, vec_len(prev)-1);
1347
1348               clib_memcpy (cf->current_command, prev, vec_len(prev));
1349               _vec_len (cf->current_command) = vec_len(prev);
1350               unix_vlib_cli_output_cooked (cf, uf, cf->current_command,
1351                                            vec_len (cf->current_command));
1352             }
1353           cf->cursor = vec_len(cf->current_command);
1354
1355           break;
1356         }
1357       break;
1358
1359     case UNIX_CLI_PARSE_ACTION_HOME:
1360       if (vec_len (cf->current_command) && cf->cursor > 0)
1361         {
1362           while (cf->cursor)
1363             {
1364               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1365               cf->cursor --;
1366             }
1367         }
1368
1369       cf->search_mode = 0;
1370       break;
1371
1372     case UNIX_CLI_PARSE_ACTION_END:
1373       if (vec_len (cf->current_command) &&
1374               cf->cursor < vec_len(cf->current_command))
1375         {
1376           unix_vlib_cli_output_cooked (cf, uf,
1377                 cf->current_command + cf->cursor,
1378                 vec_len(cf->current_command) - cf->cursor);
1379           cf->cursor = vec_len(cf->current_command);
1380         }
1381
1382       cf->search_mode = 0;
1383       break;
1384
1385     case UNIX_CLI_PARSE_ACTION_WORDLEFT:
1386       if (vec_len (cf->current_command) && cf->cursor > 0)
1387         {
1388           j = cf->cursor;
1389
1390           unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1391           j --;
1392
1393           while (j && isspace(cf->current_command[j]))
1394             {
1395               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1396               j --;
1397             }
1398           while (j && !isspace(cf->current_command[j]))
1399             {
1400               if (isspace(cf->current_command[j - 1]))
1401                 break;
1402               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1403               j --;
1404             }
1405
1406           cf->cursor = j;
1407         }
1408
1409       cf->search_mode = 0;
1410       break;
1411
1412     case UNIX_CLI_PARSE_ACTION_WORDRIGHT:
1413       if (vec_len (cf->current_command) &&
1414               cf->cursor < vec_len(cf->current_command))
1415         {
1416           int e = vec_len(cf->current_command);
1417           j = cf->cursor;
1418           while (j < e && !isspace(cf->current_command[j]))
1419             j ++;
1420           while (j < e && isspace(cf->current_command[j]))
1421             j ++;
1422           unix_vlib_cli_output_cooked (cf, uf,
1423                 cf->current_command + cf->cursor,
1424                 j - cf->cursor);
1425           cf->cursor = j;
1426         }
1427
1428       cf->search_mode = 0;
1429       break;
1430
1431
1432     case UNIX_CLI_PARSE_ACTION_ERASE:
1433       if (vec_len (cf->current_command))
1434         {
1435           if (cf->cursor == vec_len(cf->current_command))
1436             {
1437               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b \b", 3);
1438               _vec_len (cf->current_command)--;
1439               cf->cursor --;
1440             }
1441           else if (cf->cursor > 0)
1442             {
1443               /* shift everything at & to the right of the cursor left by 1 */
1444               j = vec_len (cf->current_command) - cf->cursor;
1445               memmove (cf->current_command + cf->cursor - 1,
1446                 cf->current_command + cf->cursor,
1447                 j);
1448               _vec_len (cf->current_command)--;
1449               cf->cursor --;
1450               /* redraw the rest of the line */
1451               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1452               unix_vlib_cli_output_cooked (cf, uf,
1453                     cf->current_command + cf->cursor, j);
1454               unix_vlib_cli_output_cooked (cf, uf, (u8 *) " \b\b", 3);
1455               /* and shift the terminal cursor back where it should be */
1456               while (-- j)
1457                 unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1458             }
1459         }
1460       cf->search_mode = 0;
1461       cf->excursion = 0;
1462       vec_reset_length (cf->search_key);
1463       break;
1464
1465     case UNIX_CLI_PARSE_ACTION_ERASERIGHT:
1466       if (vec_len (cf->current_command))
1467         {
1468           if (cf->cursor < vec_len(cf->current_command))
1469             {
1470               /* shift everything to the right of the cursor left by 1 */
1471               j = vec_len (cf->current_command) - cf->cursor - 1;
1472               memmove (cf->current_command + cf->cursor,
1473                 cf->current_command + cf->cursor + 1,
1474                 j);
1475               _vec_len (cf->current_command)--;
1476               /* redraw the rest of the line */
1477               unix_vlib_cli_output_cooked (cf, uf,
1478                     cf->current_command + cf->cursor, j);
1479               unix_vlib_cli_output_cooked (cf, uf, (u8 *) " \b", 2);
1480               /* and shift the terminal cursor back where it should be */
1481               if (j)
1482                 {
1483                   unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1484                   while (-- j)
1485                     unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1486                 }
1487             }
1488         }
1489       else if (input == 'D' - '@')
1490         {
1491           /* ^D with no command entered = quit */
1492           unix_vlib_cli_output_cooked (cf, uf, (u8 *) "quit\n", 5);
1493           vlib_process_signal_event (um->vlib_main,
1494                 vlib_current_process (um->vlib_main),
1495                 UNIX_CLI_PROCESS_EVENT_QUIT,
1496                 cf - cm->cli_file_pool);
1497         }
1498       cf->search_mode = 0;
1499       cf->excursion = 0;
1500       vec_reset_length (cf->search_key);
1501       break;
1502
1503     case UNIX_CLI_PARSE_ACTION_CLEAR:
1504       /* If we're in ANSI mode, clear the screen.
1505        * Then redraw the prompt and any existing command input, then put
1506        * the cursor back where it was in that line.
1507        */
1508       if (cf->ansi_capable)
1509           unix_vlib_cli_output_cooked (cf, uf,
1510                     (u8 *) ANSI_CLEAR,
1511                     sizeof(ANSI_CLEAR)-1);
1512       else
1513           unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\n", 1);
1514
1515       unix_vlib_cli_output_raw (cf, uf,
1516                 cm->cli_prompt,
1517                 vec_len (cm->cli_prompt));
1518       unix_vlib_cli_output_raw (cf, uf,
1519                 cf->current_command,
1520                 vec_len (cf->current_command));
1521       for (j = cf->cursor; j < vec_len(cf->current_command); j++)
1522          unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1523
1524       break;
1525
1526     case UNIX_CLI_PARSE_ACTION_TAB:
1527     case UNIX_CLI_PARSE_ACTION_YANK:
1528       /* TODO */
1529       break;
1530
1531
1532     case UNIX_CLI_PARSE_ACTION_PAGER_QUIT:
1533     pager_quit:
1534       unix_cli_pager_prompt_erase (cf, uf);
1535       unix_cli_pager_reset (cf);
1536       unix_cli_cli_prompt (cf, uf);
1537       break;
1538
1539     case UNIX_CLI_PARSE_ACTION_PAGER_NEXT:
1540     case UNIX_CLI_PARSE_ACTION_PAGER_PGDN:
1541       /* show next page of the buffer */
1542       if (cf->height + cf->pager_start < vec_len (cf->pager_index))
1543         {
1544           u8 * line = NULL;
1545           unix_cli_pager_index_t * pi = NULL;
1546
1547           int m = cf->pager_start + (cf->height - 1);
1548           unix_cli_pager_prompt_erase (cf, uf);
1549           for (j = m;
1550                 j < vec_len (cf->pager_index) && cf->pager_start < m;
1551                 j ++, cf->pager_start ++)
1552             {
1553               pi = &cf->pager_index[j];
1554               line = cf->pager_vector[pi->line] + pi->offset;
1555               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1556             }
1557             /* if the last line didn't end in newline, add a newline */
1558             if (pi && line[pi->length - 1] != '\n')
1559               unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1560           unix_cli_pager_prompt (cf, uf);
1561         }
1562       else
1563         {
1564           if (action == UNIX_CLI_PARSE_ACTION_PAGER_NEXT)
1565             /* no more in buffer, exit, but only if it was <space> */
1566             goto pager_quit;
1567         }
1568       break;
1569
1570     case UNIX_CLI_PARSE_ACTION_PAGER_DN:
1571     case UNIX_CLI_PARSE_ACTION_PAGER_CRLF:
1572       /* display the next line of the buffer */
1573       if (cf->pager_start < vec_len (cf->pager_index) - (cf->height - 1))
1574         {
1575           u8 * line;
1576           unix_cli_pager_index_t * pi;
1577
1578           unix_cli_pager_prompt_erase (cf, uf);
1579           pi = &cf->pager_index[cf->pager_start + (cf->height - 1)];
1580           line = cf->pager_vector[pi->line] + pi->offset;
1581           unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1582           cf->pager_start ++;
1583           /* if the last line didn't end in newline, add a newline */
1584           if (line[pi->length - 1] != '\n')
1585             unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1586           unix_cli_pager_prompt (cf, uf);
1587         }
1588       else
1589         {
1590           if (action == UNIX_CLI_PARSE_ACTION_PAGER_CRLF)
1591             /* no more in buffer, exit, but only if it was <enter> */
1592             goto pager_quit;
1593         }
1594
1595       break;
1596
1597     case UNIX_CLI_PARSE_ACTION_PAGER_UP:
1598       /* scroll the page back one line */
1599       if (cf->pager_start > 0)
1600         {
1601           u8 * line = NULL;
1602           unix_cli_pager_index_t * pi = NULL;
1603
1604           cf->pager_start --;
1605           if (cf->ansi_capable)
1606             {
1607               pi = &cf->pager_index[cf->pager_start];
1608               line = cf->pager_vector[pi->line] + pi->offset;
1609               unix_cli_pager_prompt_erase (cf, uf);
1610               unix_vlib_cli_output_cooked (cf, uf, (u8 *)ANSI_SCROLLDN, sizeof(ANSI_SCROLLDN) - 1);
1611               unix_vlib_cli_output_cooked (cf, uf, (u8 *)ANSI_SAVECURSOR, sizeof(ANSI_SAVECURSOR) - 1);
1612               unix_cli_ansi_cursor(cf, uf, 1, 1);
1613               unix_vlib_cli_output_cooked (cf, uf, (u8 *)ANSI_CLEARLINE, sizeof(ANSI_CLEARLINE) - 1);
1614               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1615               unix_vlib_cli_output_cooked (cf, uf, (u8 *)ANSI_RESTCURSOR, sizeof(ANSI_RESTCURSOR) - 1);
1616               unix_cli_pager_prompt_erase (cf, uf);
1617               unix_cli_pager_prompt (cf, uf);
1618             }
1619           else
1620             {
1621               int m = cf->pager_start + (cf->height - 1);
1622               unix_cli_pager_prompt_erase (cf, uf);
1623               for (j = cf->pager_start; j < vec_len (cf->pager_index) && j < m; j ++)
1624                 {
1625                   pi = &cf->pager_index[j];
1626                   line = cf->pager_vector[pi->line] + pi->offset;
1627                   unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1628                 }
1629               /* if the last line didn't end in newline, add a newline */
1630               if (pi && line[pi->length - 1] != '\n')
1631                 unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1632               unix_cli_pager_prompt (cf, uf);
1633             }
1634         }
1635       break;
1636
1637     case UNIX_CLI_PARSE_ACTION_PAGER_TOP:
1638       /* back to the first page of the buffer */
1639       if (cf->pager_start > 0)
1640         {
1641           u8 * line = NULL;
1642           unix_cli_pager_index_t * pi = NULL;
1643
1644           cf->pager_start = 0;
1645           int m = cf->pager_start + (cf->height - 1);
1646           unix_cli_pager_prompt_erase (cf, uf);
1647           for (j = cf->pager_start; j < vec_len (cf->pager_index) && j < m; j ++)
1648             {
1649               pi = &cf->pager_index[j];
1650               line = cf->pager_vector[pi->line] + pi->offset;
1651               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1652             }
1653           /* if the last line didn't end in newline, add a newline */
1654           if (pi && line[pi->length - 1] != '\n')
1655             unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1656           unix_cli_pager_prompt (cf, uf);
1657         }
1658       break;
1659
1660     case UNIX_CLI_PARSE_ACTION_PAGER_BOTTOM:
1661       /* skip to the last page of the buffer */
1662       if (cf->pager_start < vec_len (cf->pager_index) - (cf->height - 1))
1663         {
1664           u8 * line = NULL;
1665           unix_cli_pager_index_t * pi = NULL;
1666
1667           cf->pager_start = vec_len (cf->pager_index) - (cf->height - 1);
1668           unix_cli_pager_prompt_erase (cf, uf);
1669           unix_cli_pager_message (cf, uf, "skipping", "\n");
1670           for (j = cf->pager_start; j < vec_len (cf->pager_index); j ++)
1671             {
1672               pi = &cf->pager_index[j];
1673               line = cf->pager_vector[pi->line] + pi->offset;
1674               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1675             }
1676           /* if the last line didn't end in newline, add a newline */
1677           if (pi && line[pi->length - 1] != '\n')
1678             unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1679           unix_cli_pager_prompt (cf, uf);
1680         }
1681       break;
1682
1683     case UNIX_CLI_PARSE_ACTION_PAGER_PGUP:
1684       /* wander back one page in the buffer */
1685       if (cf->pager_start > 0)
1686         {
1687           u8 * line = NULL;
1688           unix_cli_pager_index_t * pi = NULL;
1689           int m;
1690
1691           if (cf->pager_start >= cf->height)
1692             cf->pager_start -= cf->height - 1;
1693           else
1694             cf->pager_start = 0;
1695           m = cf->pager_start + cf->height - 1;
1696           unix_cli_pager_prompt_erase (cf, uf);
1697           for (j = cf->pager_start; j < vec_len (cf->pager_index) && j < m; j ++)
1698             {
1699               pi = &cf->pager_index[j];
1700               line = cf->pager_vector[pi->line] + pi->offset;
1701               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1702             }
1703           /* if the last line didn't end in newline, add a newline */
1704           if (pi && line[pi->length - 1] != '\n')
1705             unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1706           unix_cli_pager_prompt (cf, uf);
1707         }
1708       break;
1709
1710     case UNIX_CLI_PARSE_ACTION_PAGER_REDRAW:
1711       /* Redraw the current pager screen */
1712       unix_cli_pager_redraw (cf, uf);
1713       break;
1714
1715     case UNIX_CLI_PARSE_ACTION_PAGER_SEARCH:
1716       /* search forwards in the buffer */
1717       break;
1718
1719
1720     case UNIX_CLI_PARSE_ACTION_CRLF:
1721     crlf:
1722       unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\n", 1);
1723
1724       if (cf->has_history && cf->history_limit)
1725         {
1726           if (cf->command_history && vec_len(cf->command_history) >= cf->history_limit)
1727             {
1728               vec_free (cf->command_history[0]);
1729               vec_delete (cf->command_history, 1, 0);
1730             }
1731           /* Don't add blank lines to the cmd history */
1732           if (vec_len (cf->current_command))
1733             {
1734               /* Don't duplicate the previous command */
1735               j = vec_len(cf->command_history);
1736               if (j == 0 ||
1737                 (vec_len (cf->current_command) != vec_len (cf->command_history[j - 1]) ||
1738                     memcmp(cf->current_command, cf->command_history[j - 1],
1739                            vec_len (cf->current_command)) != 0))
1740                 {
1741                   /* copy the command to the history */
1742                   u8 * c = 0;
1743                   vec_append(c, cf->current_command);
1744                   vec_add1 (cf->command_history, c);
1745                   cf->command_number ++;
1746                 }
1747             }
1748           cf->excursion = vec_len (cf->command_history);
1749         }
1750
1751       cf->search_mode = 0;
1752       vec_reset_length (cf->search_key);
1753       cf->cursor = 0;
1754
1755       return 0;
1756
1757     case UNIX_CLI_PARSE_ACTION_PARTIALMATCH:
1758     case UNIX_CLI_PARSE_ACTION_NOMATCH:
1759       if (vec_len (cf->pager_index))
1760         {
1761           /* no-op for now */
1762         }
1763       else if (cf->has_history && cf->search_mode && isprint(input))
1764         {
1765           int k, limit, offset;
1766           u8 * item;
1767
1768           vec_add1 (cf->search_key, input);
1769
1770         search_again:
1771           for (j = 0; j < vec_len(cf->command_history); j++)
1772             {
1773               if (cf->excursion > (i32) vec_len (cf->command_history) -1)
1774                 cf->excursion = 0;
1775               else if (cf->excursion < 0)
1776                 cf->excursion = vec_len (cf->command_history) -1;
1777
1778               item = cf->command_history[cf->excursion];
1779
1780               limit = (vec_len(cf->search_key) > vec_len (item)) ?
1781                 vec_len(item) : vec_len (cf->search_key);
1782
1783               for (offset = 0; offset <= vec_len(item) - limit; offset++)
1784                 {
1785                   for (k = 0; k < limit; k++)
1786                     {
1787                       if (item[k+offset] != cf->search_key[k])
1788                         goto next_offset;
1789                     }
1790                   goto found_at_offset;
1791
1792                 next_offset:
1793                   ;
1794                 }
1795               goto next;
1796
1797             found_at_offset:
1798               for (j = 0; j < vec_len (cf->current_command); j++)
1799                 unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b \b", 3);
1800
1801               vec_validate (cf->current_command, vec_len(item)-1);
1802               clib_memcpy (cf->current_command, item, vec_len(item));
1803               _vec_len (cf->current_command) = vec_len(item);
1804
1805               unix_vlib_cli_output_cooked (cf, uf, cf->current_command,
1806                                            vec_len (cf->current_command));
1807               cf->cursor = vec_len (cf->current_command);
1808               goto found;
1809
1810             next:
1811               cf->excursion += cf->search_mode;
1812             }
1813
1814           unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\nNo match...", 12);
1815           vec_reset_length (cf->search_key);
1816           vec_reset_length (cf->current_command);
1817           cf->search_mode = 0;
1818           cf->cursor = 0;
1819           goto crlf;
1820         }
1821       else if (isprint(input)) /* skip any errant control codes */
1822         {
1823           if (cf->cursor == vec_len(cf->current_command))
1824             {
1825               /* Append to end */
1826               vec_add1 (cf->current_command, input);
1827               cf->cursor ++;
1828
1829               /* Echo the character back to the client */
1830               unix_vlib_cli_output_raw (cf, uf, &input, 1);
1831             }
1832           else
1833             {
1834               /* Insert at cursor: resize +1 byte, move everything over */
1835               j = vec_len (cf->current_command) - cf->cursor;
1836               vec_add1 (cf->current_command, (u8)'A');
1837               memmove (cf->current_command + cf->cursor + 1,
1838                 cf->current_command + cf->cursor,
1839                 j);
1840               cf->current_command[cf->cursor] = input;
1841               /* Redraw the line */
1842               j ++;
1843               unix_vlib_cli_output_raw (cf, uf,
1844                     cf->current_command + cf->cursor, j);
1845               /* Put terminal cursor back */
1846               while (-- j)
1847                 unix_vlib_cli_output_raw (cf, uf, (u8 *)"\b", 1);
1848               cf->cursor ++;
1849             }
1850         }
1851       else
1852         {
1853           /* no-op - not printable or otherwise not actionable */
1854         }
1855
1856     found:
1857
1858       break;
1859
1860     case UNIX_CLI_PARSE_ACTION_TELNETIAC:
1861       break;
1862     }
1863     return 1;
1864 }
1865
1866 /** \brief Process input bytes on a stream to provide line editing and
1867  * command history in the CLI. */
1868 static int unix_cli_line_edit (unix_cli_main_t * cm,
1869                       unix_main_t * um,
1870                       unix_cli_file_t * cf)
1871 {
1872   unix_file_t * uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
1873   int i;
1874
1875   for (i = 0; i < vec_len (cf->input_vector); i++)
1876     {
1877       unix_cli_parse_action_t action;
1878       i32 matched = 0;
1879       unix_cli_parse_actions_t *a;
1880
1881       /* If we're in the pager mode, search the pager actions */
1882       a = vec_len (cf->pager_index) ? unix_cli_parse_pager : unix_cli_parse_strings;
1883
1884       /* See if the input buffer is some sort of control code */
1885       action = unix_cli_match_action(a, &cf->input_vector[i],
1886         vec_len (cf->input_vector) - i, &matched);
1887
1888       switch (action)
1889         {
1890         case UNIX_CLI_PARSE_ACTION_PARTIALMATCH:
1891           if (i)
1892             {
1893               /* There was a partial match which means we need more bytes
1894                * than the input buffer currently has.
1895                * Since the bytes before here have been processed, shift
1896                * the remaining contents to the start of the input buffer.
1897                */
1898               vec_delete (cf->input_vector, i, 0);
1899             }
1900           return 1; /* wait for more */
1901
1902         case UNIX_CLI_PARSE_ACTION_TELNETIAC:
1903           /* process telnet options */
1904           matched = unix_cli_process_telnet(um, cf, uf,
1905                 cf->input_vector + i, vec_len(cf->input_vector) - i);
1906           if (matched < 0)
1907             {
1908               if (i)
1909                 {
1910                   /* There was a partial match which means we need more bytes
1911                    * than the input buffer currently has.
1912                    * Since the bytes before here have been processed, shift
1913                    * the remaining contents to the start of the input buffer.
1914                    */
1915                   vec_delete (cf->input_vector, i, 0);
1916                 }
1917               return 1; /* wait for more */
1918             }
1919           break;
1920
1921         default:
1922           /* process the action */
1923           if (!unix_cli_line_process_one(cm, um, cf, uf,
1924                 cf->input_vector[i], action))
1925             {
1926               /* CRLF found. Consume the bytes from the input_vector */
1927               vec_delete (cf->input_vector, i + matched, 0);
1928               /* And tell our caller to execute cf->input_command */
1929               return 0;
1930             }
1931         }
1932
1933       i += matched;
1934     }
1935
1936   vec_reset_length(cf->input_vector);
1937   return 1;
1938 }
1939
1940 /** \brief Process input to a CLI session. */
1941 static void unix_cli_process_input (unix_cli_main_t * cm,
1942                         uword cli_file_index)
1943 {
1944   unix_main_t * um = &unix_main;
1945   unix_file_t * uf;
1946   unix_cli_file_t * cf = pool_elt_at_index (cm->cli_file_pool, cli_file_index);
1947   unformat_input_t input;
1948   int vlib_parse_eval (u8 *);
1949
1950 more:
1951   /* Try vlibplex first.  Someday... */
1952   if (0 && vlib_parse_eval (cf->input_vector) == 0)
1953       goto done;
1954
1955   if (cf->line_mode)
1956     {
1957       /* just treat whatever we got as a complete line of input */
1958       cf->current_command = cf->input_vector;
1959     }
1960   else
1961     {
1962       /* Line edit, echo, etc. */
1963       if (unix_cli_line_edit (cm, um, cf))
1964         /* want more input */
1965         return;
1966     }
1967
1968   if (um->log_fd)
1969     {
1970       static u8 * lv;
1971       vec_reset_length (lv);
1972       lv = format (lv, "%U[%d]: %v", 
1973                    format_timeval,
1974                    0 /* current bat-time */,
1975                    0 /* current bat-format */,
1976                    cli_file_index,
1977                    cf->input_vector);
1978       {
1979         int rv __attribute__((unused)) = 
1980           write (um->log_fd, lv, vec_len(lv));
1981       }
1982     }
1983
1984   /* Copy our input command to a new string */
1985   unformat_init_vector (&input, cf->current_command);
1986
1987   /* Remove leading white space from input. */
1988   (void) unformat (&input, "");
1989
1990   cm->current_input_file_index = cli_file_index;
1991   cf->pager_start = 0; /* start a new pager session */
1992
1993   if (unformat_check_input (&input) != UNFORMAT_END_OF_INPUT)
1994     vlib_cli_input (um->vlib_main, &input, unix_vlib_cli_output, cli_file_index);
1995
1996   /* Zero buffer since otherwise unformat_free will call vec_free on it. */
1997   input.buffer = 0;
1998
1999   unformat_free (&input);
2000
2001   /* Re-fetch pointer since pool may have moved. */
2002   cf = pool_elt_at_index (cm->cli_file_pool, cli_file_index);
2003   uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
2004
2005 done:
2006   /* reset vector; we'll re-use it later  */
2007   if (cf->line_mode)
2008     vec_reset_length (cf->input_vector);
2009   else
2010     vec_reset_length (cf->current_command);
2011
2012   if (cf->no_pager == 2)
2013     {
2014       /* Pager was programmatically disabled */
2015       unix_cli_pager_message (cf, uf, "pager buffer overflowed", "\n");
2016       cf->no_pager = um->cli_no_pager;
2017     }
2018
2019   if (vec_len (cf->pager_index) == 0 || vec_len (cf->pager_index) < cf->height)
2020     {
2021       /* There was no need for the pager */
2022       unix_cli_pager_reset (cf);
2023
2024       /* Prompt. */
2025       unix_cli_cli_prompt (cf, uf);
2026     }
2027   else
2028     {
2029       /* Display the pager prompt */
2030       unix_cli_pager_prompt(cf, uf);
2031     }
2032
2033     /* Any residual data in the input vector? */
2034     if (vec_len (cf->input_vector))
2035       goto more;
2036 }
2037
2038 static void unix_cli_kill (unix_cli_main_t * cm, uword cli_file_index)
2039 {
2040   unix_main_t * um = &unix_main;
2041   unix_cli_file_t * cf;
2042   unix_file_t * uf;
2043   int i;
2044
2045   cf = pool_elt_at_index (cm->cli_file_pool, cli_file_index);
2046   uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
2047
2048   /* Quit/EOF on stdin means quit program. */
2049   if (uf->file_descriptor == UNIX_CLI_STDIN_FD)
2050     clib_longjmp (&um->vlib_main->main_loop_exit, VLIB_MAIN_LOOP_EXIT_CLI);
2051
2052   vec_free (cf->current_command);
2053   vec_free (cf->search_key);
2054
2055   for (i = 0; i < vec_len (cf->command_history); i++)
2056       vec_free (cf->command_history[i]);
2057
2058   vec_free (cf->command_history);
2059
2060   unix_file_del (um, uf);
2061
2062   unix_cli_file_free (cf);
2063   pool_put (cm->cli_file_pool, cf);
2064 }
2065
2066 static uword
2067 unix_cli_process (vlib_main_t * vm,
2068                   vlib_node_runtime_t * rt,
2069                   vlib_frame_t * f)
2070 {
2071   unix_cli_main_t * cm = &unix_cli_main;
2072   uword i, * data = 0;
2073
2074   while (1)
2075     {
2076       unix_cli_process_event_type_t event_type;
2077       vlib_process_wait_for_event (vm);
2078       event_type = vlib_process_get_events (vm, &data);
2079
2080       switch (event_type)
2081         {
2082         case UNIX_CLI_PROCESS_EVENT_READ_READY:
2083           for (i = 0; i < vec_len (data); i++)
2084             unix_cli_process_input (cm, data[i]);
2085           break;
2086
2087         case UNIX_CLI_PROCESS_EVENT_QUIT:
2088           /* Kill this process. */
2089           for (i = 0; i < vec_len (data); i++)
2090             unix_cli_kill (cm, data[i]);
2091           goto done;
2092         }
2093
2094       if (data)
2095         _vec_len (data) = 0;
2096     }
2097
2098  done:
2099   vec_free (data);
2100
2101   vlib_node_set_state (vm, rt->node_index, VLIB_NODE_STATE_DISABLED);
2102
2103   /* Add node index so we can re-use this process later. */
2104   vec_add1 (cm->unused_cli_process_node_indices, rt->node_index);
2105
2106   return 0;
2107 }
2108
2109 static clib_error_t * unix_cli_write_ready (unix_file_t * uf)
2110 {
2111   unix_cli_main_t * cm = &unix_cli_main;
2112   unix_cli_file_t * cf;
2113   int n;
2114
2115   cf = pool_elt_at_index (cm->cli_file_pool, uf->private_data);
2116
2117   /* Flush output vector. */
2118   n = write (uf->file_descriptor,
2119              cf->output_vector, vec_len (cf->output_vector));
2120
2121   if (n < 0 && errno != EAGAIN)
2122     return clib_error_return_unix (0, "write");
2123
2124   else if (n > 0)
2125     unix_cli_del_pending_output (uf, cf, n);
2126
2127   return /* no error */ 0;
2128 }
2129
2130 static clib_error_t * unix_cli_read_ready (unix_file_t * uf)
2131 {
2132   unix_main_t * um = &unix_main;
2133   unix_cli_main_t * cm = &unix_cli_main;
2134   unix_cli_file_t * cf;
2135   uword l;
2136   int n, n_read, n_try;
2137
2138   cf = pool_elt_at_index (cm->cli_file_pool, uf->private_data);
2139
2140   n = n_try = 4096;
2141   while (n == n_try) {
2142       l = vec_len (cf->input_vector);
2143       vec_resize (cf->input_vector, l + n_try);
2144
2145       n = read (uf->file_descriptor, cf->input_vector + l, n_try);
2146
2147       /* Error? */
2148       if (n < 0 && errno != EAGAIN)
2149           return clib_error_return_unix (0, "read");
2150   
2151       n_read = n < 0 ? 0 : n;
2152       _vec_len (cf->input_vector) = l + n_read;
2153   }
2154
2155   if (! (n < 0))
2156     vlib_process_signal_event (um->vlib_main,
2157                                cf->process_node_index,
2158                                (n_read == 0
2159                                 ? UNIX_CLI_PROCESS_EVENT_QUIT
2160                                 : UNIX_CLI_PROCESS_EVENT_READ_READY),
2161                                /* event data */ uf->private_data);
2162
2163   return /* no error */ 0;
2164 }
2165
2166 /** Store a new CLI session.
2167  * @param name The name of the session.
2168  * @param fd   The file descriptor for the session I/O.
2169  * @return The session ID.
2170  */
2171 static u32 unix_cli_file_add (unix_cli_main_t * cm, char * name, int fd)
2172 {
2173   unix_main_t * um = &unix_main;
2174   unix_cli_file_t * cf;
2175   unix_file_t template = {0};
2176   vlib_main_t * vm = um->vlib_main;
2177   vlib_node_t * n;
2178
2179   name = (char *) format (0, "unix-cli-%s", name);
2180
2181   if (vec_len (cm->unused_cli_process_node_indices) > 0)
2182     {
2183       uword l = vec_len (cm->unused_cli_process_node_indices);
2184
2185       /* Find node and give it new name. */
2186       n = vlib_get_node (vm, cm->unused_cli_process_node_indices[l - 1]);
2187       vec_free (n->name);
2188       n->name = (u8 *) name;
2189
2190       vlib_node_set_state (vm, n->index, VLIB_NODE_STATE_POLLING);
2191
2192       _vec_len (cm->unused_cli_process_node_indices) = l - 1;
2193     }
2194   else
2195     {
2196       static vlib_node_registration_t r = {
2197         .function = unix_cli_process,
2198         .type = VLIB_NODE_TYPE_PROCESS,
2199         .process_log2_n_stack_bytes = 16,
2200       };
2201
2202       r.name = name;
2203       vlib_register_node (vm, &r);
2204       vec_free (name);
2205
2206       n = vlib_get_node (vm, r.index);
2207     }
2208
2209   pool_get (cm->cli_file_pool, cf);
2210   memset (cf, 0, sizeof (*cf));
2211
2212   template.read_function = unix_cli_read_ready;
2213   template.write_function = unix_cli_write_ready;
2214   template.file_descriptor = fd;
2215   template.private_data = cf - cm->cli_file_pool;
2216
2217   cf->process_node_index = n->index;
2218   cf->unix_file_index = unix_file_add (um, &template);
2219   cf->output_vector = 0;
2220   cf->input_vector = 0;
2221
2222   vlib_start_process (vm, n->runtime_index);
2223
2224   vlib_process_t * p = vlib_get_process_from_node(vm, n);
2225   p->output_function = unix_vlib_cli_output;
2226   p->output_function_arg = cf - cm->cli_file_pool;
2227
2228   return cf - cm->cli_file_pool;
2229 }
2230
2231 /** Telnet listening socket has a new connection. */
2232 static clib_error_t * unix_cli_listen_read_ready (unix_file_t * uf)
2233 {
2234   unix_main_t * um = &unix_main;
2235   unix_cli_main_t * cm = &unix_cli_main;
2236   clib_socket_t * s = &um->cli_listen_socket;
2237   clib_socket_t client;
2238   char * client_name;
2239   clib_error_t * error;
2240   unix_cli_file_t * cf;
2241   u32 cf_index;
2242
2243   error = clib_socket_accept (s, &client);
2244   if (error)
2245     return error;
2246
2247   client_name = (char *) format (0, "%U%c", format_sockaddr, &client.peer, 0);
2248
2249   cf_index = unix_cli_file_add (cm, client_name, client.fd);
2250   cf = pool_elt_at_index (cm->cli_file_pool, cf_index);
2251
2252   /* No longer need CLIB version of socket. */
2253   clib_socket_free (&client);
2254
2255   vec_free (client_name);
2256
2257   /* if we're supposed to run telnet session in character mode (default) */
2258   if (um->cli_line_mode == 0)
2259     {
2260       /*
2261        * Set telnet client character mode, echo on, suppress "go-ahead".
2262        * Technically these should be negotiated, but this works.
2263        */
2264       u8 charmode_option[] = {
2265         IAC, WONT, TELOPT_LINEMODE, /* server will do char-by-char */
2266         IAC, DONT, TELOPT_LINEMODE, /* client should do char-by-char */
2267         IAC, WILL, TELOPT_SGA,      /* server willl supress GA */
2268         IAC, DO,   TELOPT_SGA,      /* client should supress Go Ahead */
2269         IAC, WILL, TELOPT_ECHO,     /* server will do echo */
2270         IAC, DONT, TELOPT_ECHO,     /* client should not echo */
2271         IAC, DO,   TELOPT_TTYPE,    /* client should tell us its term type */
2272         IAC, SB,   TELOPT_TTYPE, 1, IAC, SE, /* now tell me ttype */
2273         IAC, DO,   TELOPT_NAWS,     /* client should tell us its window sz */
2274         IAC, SB,   TELOPT_NAWS, 1, IAC, SE,  /* now tell me window size */
2275       };
2276
2277       /* Enable history on this CLI */
2278       cf->history_limit = um->cli_history_limit;
2279       cf->has_history = cf->history_limit != 0;
2280
2281       /* Make sure this session is in line mode */
2282       cf->line_mode = 0;
2283
2284       /* We need CRLF */
2285       cf->crlf_mode = 1;
2286
2287       /* Setup the pager */
2288       cf->no_pager = um->cli_no_pager;
2289
2290       uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
2291
2292       /* Send the telnet options */
2293       unix_vlib_cli_output_raw (cf, uf, charmode_option,
2294                                    ARRAY_LEN(charmode_option));
2295
2296       /* In case the client doesn't negotiate terminal type, use
2297        * a timer to kick off the initial prompt. */
2298       timer_call (unix_cli_file_welcome_timer, cf_index, 1);
2299     }
2300
2301   return error;
2302 }
2303
2304 /** The system terminal has informed us that the window size
2305  * has changed.
2306  */
2307 static void
2308 unix_cli_resize_interrupt (int signum)
2309 {
2310   unix_main_t * um = &unix_main;
2311   unix_cli_main_t * cm = &unix_cli_main;
2312   unix_cli_file_t * cf = pool_elt_at_index (cm->cli_file_pool,
2313                                 cm->stdin_cli_file_index);
2314   unix_file_t * uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
2315   struct winsize ws;
2316   (void)signum;
2317
2318   /* Terminal resized, fetch the new size */
2319   ioctl(UNIX_CLI_STDIN_FD, TIOCGWINSZ, &ws);
2320   cf->width = ws.ws_col;
2321   cf->height = ws.ws_row;
2322
2323   /* Reindex the pager buffer */
2324   unix_cli_pager_reindex (cf);
2325
2326   /* Redraw the page */
2327   unix_cli_pager_redraw (cf, uf);
2328 }
2329
2330 /** Handle configuration directives in the @em unix section. */
2331 static clib_error_t *
2332 unix_cli_config (vlib_main_t * vm, unformat_input_t * input)
2333 {
2334   unix_main_t * um = &unix_main;
2335   unix_cli_main_t * cm = &unix_cli_main;
2336   int flags;
2337   clib_error_t * error = 0;
2338   unix_cli_file_t * cf;
2339   u32 cf_index;
2340   struct termios tio;
2341   struct sigaction sa;
2342   struct winsize ws;
2343   u8 * term;
2344
2345   /* We depend on unix flags being set. */
2346   if ((error = vlib_call_config_function (vm, unix_config)))
2347     return error;
2348
2349   if (um->flags & UNIX_FLAG_INTERACTIVE)
2350     {
2351       /* Set stdin to be non-blocking. */
2352       if ((flags = fcntl (UNIX_CLI_STDIN_FD, F_GETFL, 0)) < 0)
2353         flags = 0;
2354       fcntl (UNIX_CLI_STDIN_FD, F_SETFL, flags | O_NONBLOCK);
2355
2356       cf_index = unix_cli_file_add (cm, "stdin", UNIX_CLI_STDIN_FD);
2357       cf = pool_elt_at_index (cm->cli_file_pool, cf_index);
2358       cm->stdin_cli_file_index = cf_index;
2359
2360       /* If stdin is a tty and we are using chacracter mode, enable
2361        * history on the CLI and set the tty line discipline accordingly. */
2362       if (isatty(UNIX_CLI_STDIN_FD) && um->cli_line_mode == 0)
2363         {
2364           /* Capture terminal resize events */
2365           sa.sa_handler = unix_cli_resize_interrupt;
2366           sa.sa_flags = 0;
2367           if (sigaction (SIGWINCH, &sa, 0) < 0)
2368               clib_panic ("sigaction");
2369
2370           /* Retrieve the current terminal size */
2371           ioctl(UNIX_CLI_STDIN_FD, TIOCGWINSZ, &ws);
2372           cf->width = ws.ws_col;
2373           cf->height = ws.ws_row;
2374
2375           if (cf->width == 0 || cf->height == 0)
2376             /* We have a tty, but no size. Stick to line mode. */
2377             goto notty;
2378
2379           /* Setup the history */
2380           cf->history_limit = um->cli_history_limit;
2381           cf->has_history = cf->history_limit != 0;
2382
2383           /* Setup the pager */
2384           cf->no_pager = um->cli_no_pager;
2385
2386           /* We're going to be in char by char mode */
2387           cf->line_mode = 0;
2388
2389           /* Save the original tty state so we can restore it later */
2390           tcgetattr(UNIX_CLI_STDIN_FD, &um->tio_stdin);
2391           um->tio_isset = 1;
2392
2393           /* Tweak the tty settings */
2394           tio = um->tio_stdin;
2395           /* echo off, canonical mode off, ext'd input processing off */
2396           tio.c_lflag &= ~(ECHO | ICANON | IEXTEN);
2397           tio.c_cc[VMIN] = 1; /* 1 byte at a time */
2398           tio.c_cc[VTIME] = 0; /* no timer */
2399           tcsetattr(UNIX_CLI_STDIN_FD, TCSAFLUSH, &tio);
2400
2401           /* See if we can do ANSI/VT100 output */
2402           term = (u8 *)getenv("TERM");
2403           if (term != NULL)
2404             cf->ansi_capable = unix_cli_terminal_type(term,
2405                         strlen((char *)term));
2406         }
2407       else
2408         {
2409         notty:
2410           /* No tty, so make sure these things are off */
2411           cf->no_pager = 1;
2412           cf->history_limit = 0;
2413           cf->has_history = 0;
2414           cf->line_mode = 1;
2415         }
2416
2417       /* Send banner and initial prompt */
2418       unix_cli_file_welcome(cm, cf);
2419     }
2420
2421   /* If we have socket config, LISTEN, otherwise, don't */
2422   clib_socket_t * s = &um->cli_listen_socket;
2423   if(s->config && s->config[0] != 0) {
2424     /* CLI listen. */
2425     unix_file_t template = {0};
2426
2427     s->flags = SOCKET_IS_SERVER; /* listen, don't connect */
2428     error = clib_socket_init (s);
2429
2430     if (error)
2431       return error;
2432
2433     template.read_function = unix_cli_listen_read_ready;
2434     template.file_descriptor = s->fd;
2435
2436     unix_file_add (um, &template);
2437   }
2438
2439   /* Set CLI prompt. */
2440   if (! cm->cli_prompt)
2441     cm->cli_prompt = format (0, "VLIB: ");
2442
2443   return 0;
2444 }
2445
2446 VLIB_CONFIG_FUNCTION (unix_cli_config, "unix-cli");
2447
2448 /** Called when VPP is shutting down, this resets the system
2449  * terminal state, if previously saved.
2450  */
2451 static clib_error_t *
2452 unix_cli_exit (vlib_main_t * vm)
2453 {
2454   unix_main_t * um = &unix_main;
2455
2456   /* If stdin is a tty and we saved the tty state, reset the tty state */
2457   if (isatty(UNIX_CLI_STDIN_FD) && um->tio_isset)
2458     tcsetattr(UNIX_CLI_STDIN_FD, TCSAFLUSH, &um->tio_stdin);
2459
2460   return 0;
2461 }
2462
2463 VLIB_MAIN_LOOP_EXIT_FUNCTION (unix_cli_exit);
2464
2465 /** Set the CLI prompt.
2466  * @param The C string to set the prompt to.
2467  * @note This setting is global; it impacts all current
2468  *       and future CLI sessions.
2469  */
2470 void vlib_unix_cli_set_prompt (char * prompt)
2471 {
2472   char * fmt = (prompt[strlen(prompt)-1] == ' ') ? "%s" : "%s ";
2473   unix_cli_main_t * cm = &unix_cli_main;
2474   if (cm->cli_prompt)
2475     vec_free (cm->cli_prompt);
2476   cm->cli_prompt = format (0, fmt, prompt);
2477 }
2478
2479 /** CLI command to quit the terminal session.
2480  * @note If this is a stdin session then this will
2481  *       shutdown VPP also.
2482  */
2483 static clib_error_t *
2484 unix_cli_quit (vlib_main_t * vm,
2485                unformat_input_t * input,
2486                vlib_cli_command_t * cmd)
2487 {
2488   unix_cli_main_t * cm = &unix_cli_main;
2489
2490   vlib_process_signal_event (vm,
2491                              vlib_current_process (vm),
2492                              UNIX_CLI_PROCESS_EVENT_QUIT,
2493                              cm->current_input_file_index);
2494   return 0;
2495 }
2496
2497 VLIB_CLI_COMMAND (unix_cli_quit_command, static) = {
2498   .path = "quit",
2499   .short_help = "Exit CLI",
2500   .function = unix_cli_quit,
2501 };
2502
2503 /** CLI command to execute a VPP command script. */
2504 static clib_error_t *
2505 unix_cli_exec (vlib_main_t * vm,
2506                unformat_input_t * input,
2507                vlib_cli_command_t * cmd)
2508 {
2509   char * file_name;
2510   int fd;
2511   unformat_input_t sub_input;
2512   clib_error_t * error;
2513
2514   file_name = 0;
2515   fd = -1;
2516   error = 0;
2517
2518   if (! unformat (input, "%s", &file_name))
2519     {
2520       error = clib_error_return (0, "expecting file name, got `%U'",
2521                                  format_unformat_error, input);
2522       goto done;
2523     }
2524
2525   fd = open (file_name, O_RDONLY);
2526   if (fd < 0)
2527     {
2528       error = clib_error_return_unix (0, "failed to open `%s'", file_name);
2529       goto done;
2530     }
2531
2532   /* Make sure its a regular file. */
2533   {
2534     struct stat s;
2535
2536     if (fstat (fd, &s) < 0)
2537       {
2538         error = clib_error_return_unix (0, "failed to stat `%s'", file_name);
2539         goto done;
2540       }
2541     
2542     if (! (S_ISREG (s.st_mode) || S_ISLNK (s.st_mode)))
2543       {
2544         error = clib_error_return (0, "not a regular file `%s'", file_name);
2545         goto done;
2546       }
2547   }
2548
2549   unformat_init_unix_file (&sub_input, fd);
2550
2551   vlib_cli_input (vm, &sub_input, 0, 0);
2552   unformat_free (&sub_input);
2553
2554  done:
2555   if (fd > 0)
2556     close (fd);
2557   vec_free (file_name);
2558
2559   return error;
2560 }
2561
2562 VLIB_CLI_COMMAND (cli_exec, static) = {
2563   .path = "exec",
2564   .short_help = "Execute commands from file",
2565   .function = unix_cli_exec,
2566   .is_mp_safe = 1,
2567 };
2568
2569 /** CLI command to show various unix error statistics. */
2570 static clib_error_t *
2571 unix_show_errors (vlib_main_t * vm,
2572                   unformat_input_t * input,
2573                   vlib_cli_command_t * cmd)
2574 {
2575   unix_main_t * um = &unix_main;
2576   clib_error_t * error = 0;
2577   int i, n_errors_to_show;
2578   unix_error_history_t * unix_errors = 0;
2579
2580   n_errors_to_show = 1 << 30;
2581
2582   if (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2583     {
2584       if (! unformat (input, "%d", &n_errors_to_show))
2585         {
2586           error = clib_error_return (0, "expecting integer number of errors to show, got `%U'",
2587                                      format_unformat_error, input);
2588           goto done;
2589         }
2590     }
2591
2592   n_errors_to_show = clib_min (ARRAY_LEN (um->error_history), n_errors_to_show);
2593
2594   i = um->error_history_index > 0 ? um->error_history_index - 1 : ARRAY_LEN (um->error_history) - 1;
2595
2596   while (n_errors_to_show > 0)
2597     {
2598       unix_error_history_t * eh = um->error_history + i;
2599
2600       if (! eh->error)
2601         break;
2602
2603       vec_add1 (unix_errors, eh[0]);
2604       n_errors_to_show -= 1;
2605       if (i == 0)
2606         i = ARRAY_LEN (um->error_history) - 1;
2607       else
2608         i--;
2609     }
2610
2611   if (vec_len (unix_errors) == 0)
2612     vlib_cli_output (vm, "no Unix errors so far");
2613   else
2614     {
2615       vlib_cli_output (vm, "%Ld total errors seen", um->n_total_errors);
2616       for (i = vec_len (unix_errors) - 1; i >= 0; i--)
2617         {
2618           unix_error_history_t * eh = vec_elt_at_index (unix_errors, i);
2619           vlib_cli_output (vm, "%U: %U",
2620                            format_time_interval, "h:m:s:u", eh->time,
2621                            format_clib_error, eh->error);
2622         }
2623       vlib_cli_output (vm, "%U: time now",
2624                        format_time_interval, "h:m:s:u", vlib_time_now (vm));
2625     }
2626
2627  done:
2628   vec_free (unix_errors);
2629   return error;
2630 }
2631
2632 VLIB_CLI_COMMAND (cli_unix_show_errors, static) = {
2633   .path = "show unix-errors",
2634   .short_help = "Show Unix system call error history",
2635   .function = unix_show_errors,
2636 };
2637
2638 /** CLI command to show session command history. */
2639 static clib_error_t *
2640 unix_cli_show_history (vlib_main_t * vm,
2641       unformat_input_t * input,
2642       vlib_cli_command_t * cmd)
2643 {
2644   unix_cli_main_t * cm = &unix_cli_main;
2645   unix_cli_file_t * cf;
2646   int i, j;
2647
2648   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2649
2650   if (cf->has_history && cf->history_limit)
2651     {
2652       i = 1 + cf->command_number - vec_len(cf->command_history);
2653       for (j = 0; j < vec_len (cf->command_history); j++)
2654           vlib_cli_output (vm, "%d  %v\n", i + j, cf->command_history[j]);
2655     }
2656   else
2657     {
2658       vlib_cli_output (vm, "History not enabled.\n");
2659     }
2660
2661   return 0;
2662 }
2663
2664 VLIB_CLI_COMMAND (cli_unix_cli_show_history, static) = {
2665   .path = "history",
2666   .short_help = "Show current session command history",
2667   .function = unix_cli_show_history,
2668 };
2669
2670 /** CLI command to show terminal status. */
2671 static clib_error_t *
2672 unix_cli_show_terminal (vlib_main_t * vm,
2673       unformat_input_t * input,
2674       vlib_cli_command_t * cmd)
2675 {
2676   unix_main_t * um = &unix_main;
2677   unix_cli_main_t * cm = &unix_cli_main;
2678   unix_cli_file_t * cf;
2679   vlib_node_t * n;
2680
2681   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2682   n = vlib_get_node (vm, cf->process_node_index);
2683
2684   vlib_cli_output (vm, "Terminal name:   %v\n", n->name);
2685   vlib_cli_output (vm, "Terminal mode:   %s\n", cf->line_mode ? 
2686                                                 "line-by-line" :
2687                                                 "char-by-char");
2688   vlib_cli_output (vm, "Terminal width:  %d\n", cf->width);
2689   vlib_cli_output (vm, "Terminal height: %d\n", cf->height);
2690   vlib_cli_output (vm, "ANSI capable:    %s\n", cf->ansi_capable ? "yes" : "no");
2691   vlib_cli_output (vm, "History enabled: %s%s\n",
2692         cf->has_history ? "yes" : "no",
2693         !cf->has_history || cf->history_limit ? "" : " (disabled by history limit)");
2694   if (cf->has_history)
2695     vlib_cli_output (vm, "History limit:   %d\n", cf->history_limit);
2696   vlib_cli_output (vm, "Pager enabled:   %s%s%s\n",
2697         cf->no_pager ? "no" : "yes",
2698         cf->no_pager || cf->height ? "" : " (disabled by terminal height)",
2699         cf->no_pager || um->cli_pager_buffer_limit ? "" : " (disabled by buffer limit)");
2700   if (!cf->no_pager)
2701     vlib_cli_output (vm, "Pager limit:     %d\n", um->cli_pager_buffer_limit);
2702   vlib_cli_output (vm, "CRLF mode:       %s\n", cf->crlf_mode ? "CR+LF" : "LF");
2703
2704   return 0;
2705 }
2706
2707 VLIB_CLI_COMMAND (cli_unix_cli_show_terminal, static) = {
2708   .path = "show terminal",
2709   .short_help = "Show current session terminal settings",
2710   .function = unix_cli_show_terminal,
2711 };
2712
2713 /** CLI command to set terminal pager settings. */
2714 static clib_error_t *
2715 unix_cli_set_terminal_pager (vlib_main_t * vm,
2716       unformat_input_t * input,
2717       vlib_cli_command_t * cmd)
2718 {
2719   unix_main_t * um = &unix_main;
2720   unix_cli_main_t * cm = &unix_cli_main;
2721   unix_cli_file_t * cf;
2722   unformat_input_t _line_input, * line_input = &_line_input;
2723
2724   if (! unformat_user (input, unformat_line_input, line_input))
2725     return 0;
2726
2727   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2728
2729   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2730     {
2731     if (unformat (line_input, "on"))
2732       cf->no_pager = 0;
2733     else if (unformat (line_input, "off"))
2734       cf->no_pager = 1;
2735     else if (unformat (line_input, "limit %u", &um->cli_pager_buffer_limit))
2736       vlib_cli_output (vm, "Pager limit set to %u lines; note, this is global.\n",
2737         um->cli_pager_buffer_limit);
2738     else
2739       return clib_error_return (0, "unknown parameter: `%U`",
2740                                 format_unformat_error, line_input);
2741   }
2742
2743   unformat_free(line_input);
2744
2745   return 0;
2746 }
2747
2748 VLIB_CLI_COMMAND (cli_unix_cli_set_terminal_pager, static) = {
2749   .path = "set terminal pager",
2750   .short_help = "set terminal pager [on|off] [limit <lines>]",
2751   .function = unix_cli_set_terminal_pager,
2752 };
2753
2754 /** CLI command to set terminal history settings. */
2755 static clib_error_t *
2756 unix_cli_set_terminal_history (vlib_main_t * vm,
2757       unformat_input_t * input,
2758       vlib_cli_command_t * cmd)
2759 {
2760   unix_cli_main_t * cm = &unix_cli_main;
2761   unix_cli_file_t * cf;
2762   unformat_input_t _line_input, * line_input = &_line_input;
2763   u32 limit;
2764
2765   if (! unformat_user (input, unformat_line_input, line_input))
2766     return 0;
2767
2768   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2769
2770   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2771     {
2772     if (unformat (line_input, "on"))
2773       cf->has_history = 1;
2774     else if (unformat (line_input, "off"))
2775       cf->has_history = 0;
2776     else if (unformat (line_input, "limit %u", &cf->history_limit))
2777       ;
2778     else
2779       return clib_error_return (0, "unknown parameter: `%U`",
2780                                 format_unformat_error, line_input);
2781
2782     /* If we reduced history size, or turned it off, purge the history */
2783     limit = cf->has_history ? cf->history_limit : 0;
2784
2785     while (cf->command_history && vec_len(cf->command_history) >= limit)
2786       {
2787         vec_free (cf->command_history[0]);
2788         vec_delete (cf->command_history, 1, 0);
2789       }
2790   }
2791
2792   unformat_free(line_input);
2793
2794   return 0;
2795 }
2796
2797 VLIB_CLI_COMMAND (cli_unix_cli_set_terminal_history, static) = {
2798   .path = "set terminal history",
2799   .short_help = "set terminal history [on|off] [limit <lines>]",
2800   .function = unix_cli_set_terminal_history,
2801 };
2802
2803 /** CLI command to set terminal ANSI settings. */
2804 static clib_error_t *
2805 unix_cli_set_terminal_ansi (vlib_main_t * vm,
2806       unformat_input_t * input,
2807       vlib_cli_command_t * cmd)
2808 {
2809   unix_cli_main_t * cm = &unix_cli_main;
2810   unix_cli_file_t * cf;
2811
2812   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2813
2814   if (unformat (input, "on"))
2815     cf->ansi_capable = 1;
2816   else if (unformat (input, "off"))
2817     cf->ansi_capable = 0;
2818   else
2819     return clib_error_return (0, "unknown parameter: `%U`",
2820                               format_unformat_error, input);
2821
2822   return 0;
2823 }
2824
2825 VLIB_CLI_COMMAND (cli_unix_cli_set_terminal_ansi, static) = {
2826   .path = "set terminal ansi",
2827   .short_help = "set terminal ansi [on|off]",
2828   .function = unix_cli_set_terminal_ansi,
2829 };
2830
2831 static clib_error_t *
2832 unix_cli_init (vlib_main_t * vm)
2833 {
2834   return 0;
2835 }
2836
2837 VLIB_INIT_FUNCTION (unix_cli_init);