c34ae21929794e4148b5d03bb9ab1403c8b993a0
[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
633   prompt = format(0, "\r%s-- more -- (%d-%d/%d)%s",
634     cf->ansi_capable ? ANSI_BOLD : "",
635     cf->pager_start + 1,
636     cf->pager_start + cf->height,
637     vec_len (cf->pager_index),
638     cf->ansi_capable ? ANSI_RESET: "");
639
640   unix_vlib_cli_output_cooked(cf, uf, prompt, vec_len(prompt));
641
642   vec_free(prompt);
643 }
644
645 /** \brief Output a pager "skipping" message */
646 static void unix_cli_pager_message(unix_cli_file_t * cf, unix_file_t * uf,
647     char *message, char *postfix)
648 {
649   u8 * prompt;
650
651   prompt = format(0, "\r%s-- %s --%s%s",
652     cf->ansi_capable ? ANSI_BOLD : "",
653     message,
654     cf->ansi_capable ? ANSI_RESET: "",
655     postfix);
656
657   unix_vlib_cli_output_cooked(cf, uf, prompt, vec_len(prompt));
658
659   vec_free(prompt);
660 }
661
662 /** \brief Erase the printed pager prompt */
663 static void unix_cli_pager_prompt_erase(unix_cli_file_t * cf, unix_file_t * uf)
664 {
665   if (cf->ansi_capable)
666     {
667       unix_vlib_cli_output_cooked(cf, uf, (u8 *)"\r", 1);
668       unix_vlib_cli_output_cooked(cf, uf,
669           (u8 *)ANSI_CLEARLINE, sizeof(ANSI_CLEARLINE) - 1);
670     }
671   else
672     {
673       int i;
674
675       unix_vlib_cli_output_cooked(cf, uf, (u8 *)"\r", 1);
676       for (i = 0; i < cf->width - 1; i ++)
677         unix_vlib_cli_output_cooked(cf, uf, (u8 *)" ", 1);
678       unix_vlib_cli_output_cooked(cf, uf, (u8 *)"\r", 1);
679     }
680 }
681
682 /** \brief Uses an ANSI escape sequence to move the cursor */
683 static void unix_cli_ansi_cursor(unix_cli_file_t * cf, unix_file_t * uf,
684       u16 x, u16 y)
685 {
686   u8 * str;
687
688   str = format(0, "%s%d;%dH", CSI, y, x);
689
690   unix_vlib_cli_output_cooked(cf, uf, str, vec_len(str));
691
692   vec_free(str);
693 }
694
695 /** Redraw the currently displayed page of text.
696  * @param cf CLI session to redraw the pager buffer of.
697  * @param uf Unix file of the CLI session.
698  */
699 static void unix_cli_pager_redraw(unix_cli_file_t * cf, unix_file_t * uf)
700 {
701   unix_cli_pager_index_t * pi = NULL;
702   u8 * line = NULL;
703   word i;
704
705   /* No active pager? Do nothing. */
706   if (!vec_len (cf->pager_index))
707     return;
708
709   if (cf->ansi_capable)
710     {
711       /* If we have ANSI, send the clear screen sequence */
712       unix_vlib_cli_output_cooked (cf, uf,
713           (u8 *)ANSI_CLEAR, sizeof(ANSI_CLEAR) - 1);
714     }
715   else
716     {
717       /* Otherwise make sure we're on a blank line */
718       unix_cli_pager_prompt_erase (cf, uf);
719     }
720
721   /* (Re-)send the current page of content */
722   for (i = 0; i < cf->height - 1 &&
723           i + cf->pager_start < vec_len (cf->pager_index);
724           i ++)
725     {
726       pi = &cf->pager_index[cf->pager_start + i];
727       line = cf->pager_vector[pi->line] + pi->offset;
728
729       unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
730     }
731   /* if the last line didn't end in newline, add a newline */
732   if (pi && line[pi->length - 1] != '\n')
733     unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
734
735   unix_cli_pager_prompt (cf, uf);
736 }
737
738 /** @brief Process and add a line to the pager index.
739  * In normal operation this function will take the given character string
740  * found in @c line and with length @c len_or_index and iterates the over the
741  * contents, adding each line of text discovered within it to the
742  * pager index. Lines are identified by newlines ("<code>\\n</code>") and by
743  * strings longer than the width of the terminal.
744  *
745  * If instead @c line is @c NULL then @c len_or_index is taken to mean the
746  * index of an existing line in the pager buffer; this simply means that the
747  * input line does not need to be cloned since we alreayd have it. This is
748  * typical if we are reindexing the pager buffer.
749  *
750  * @param cf           The CLI session whose pager we are adding to.
751  * @param line         The string of text to be indexed into the pager buffer.
752  *                     If @c line is @c NULL then the mode of operation
753  *                     changes slightly; see the description above.
754  * @param len_or_index If @c line is a pointer to a string then this parameter
755  *                     indicates the length of that string; Otherwise this
756  *                     value provides the index in the pager buffer of an
757  *                     existing string to be indexed.
758  */
759 static void unix_cli_pager_add_line (unix_cli_file_t * cf,
760                                      u8 * line,
761                                      word len_or_index)
762 {
763   u8 * p;
764   word i, j, k;
765   word line_index, len;
766   u32 width = cf->width;
767   unix_cli_pager_index_t * pi;
768
769   if (line == NULL)
770     {
771       /* Use a line already in the pager buffer */
772       line_index = len_or_index;
773       p = cf->pager_vector[line_index];
774       len = vec_len (p);
775     }
776   else
777     {
778       len = len_or_index;
779       /* Add a copy of the raw string to the pager buffer */
780       p = vec_new (u8, len);
781       clib_memcpy (p, line, len);
782
783       /* store in pager buffer */
784       line_index = vec_len (cf->pager_vector);
785       vec_add1 (cf->pager_vector, p);
786     }
787
788   i = 0;
789   while (i < len)
790     {
791       /* Find the next line, or run to terminal width, or run to EOL */
792       int l = len - i;
793       j = unix_vlib_findchr((u8)'\n', p, l < width ? l : width);
794
795       if (j < l && p[j] == '\n') /* incl \n */
796         j ++;
797
798       /* Add the line to the index */
799       k = vec_len (cf->pager_index);
800       vec_validate (cf->pager_index, k);
801       pi = &cf->pager_index[k];
802
803       pi->line = line_index;
804       pi->offset = i;
805       pi->length = j;
806
807       i += j;
808       p += j;
809     }
810 }
811
812 /** @brief Reindex entire pager buffer.
813  * Resets the current pager index and then re-adds the lines in the pager
814  * buffer to the index.
815  *
816  * Additionally this function attempts to retain the current page start
817  * line offset by searching for the same top-of-screen line in the new index.
818  *
819  * @param cf The CLI session whose pager buffer should be reindexed.
820  */
821 static void unix_cli_pager_reindex (unix_cli_file_t * cf)
822 {
823   word i, old_line, old_offset;
824   unix_cli_pager_index_t * pi;
825
826   /* If there is nothing in the pager buffer then make sure the index
827    * is empty and move on.
828    */
829   if (cf->pager_vector == 0)
830     {
831       vec_reset_length (cf->pager_index);
832       return;
833     }
834
835   /* Retain a pointer to the current page start line so we can
836    * find it later
837    */
838   pi = &cf->pager_index[cf->pager_start];
839   old_line = pi->line;
840   old_offset = pi->offset;
841
842   /* Re-add the buffered lines to the index */
843   vec_reset_length (cf->pager_index);
844   vec_foreach_index(i, cf->pager_vector)
845     {
846       unix_cli_pager_add_line(cf, NULL, i);
847     }
848
849   /* Attempt to re-locate the previously stored page start line */
850   vec_foreach_index(i, cf->pager_index)
851     {
852       pi = &cf->pager_index[i];
853
854       if (pi->line == old_line &&
855             (pi->offset <= old_offset ||
856              pi->offset + pi->length > old_offset))
857         {
858           /* Found it! */
859           cf->pager_start = i;
860           break;
861         }
862     }
863
864   /* In case the start line was not found (rare), ensure the pager start
865    * index is within bounds
866    */
867   if (cf->pager_start >= vec_len (cf->pager_index))
868     {
869       cf->pager_start = vec_len (cf->pager_index) - cf->height + 1;
870
871       if (cf->pager_start < 0)
872         cf->pager_start = 0;
873     }
874 }
875
876 /** VLIB CLI output function.
877  *
878  * If the terminal has a pager configured then this function takes care
879  * of collating output into the pager buffer; ensuring only the first page
880  * is displayed and any lines in excess of the first page are buffered.
881  *
882  * If the maximum number of index lines in the buffer is exceeded then the
883  * pager is cancelled and the contents of the current buffer are sent to the
884  * terminal.
885  *
886  * If there is no pager configured then the output is sent directly to the
887  * terminal.
888  *
889  * @param cli_file_index Index of the CLI session where this output is
890  *                       directed.
891  * @param buffer         String of printabe bytes to be output.
892  * @param buffer_bytes   The number of bytes in @c buffer to be output.
893  */
894 static void unix_vlib_cli_output (uword cli_file_index,
895                                   u8 * buffer,
896                                   uword buffer_bytes)
897 {
898   unix_main_t * um = &unix_main;
899   unix_cli_main_t * cm = &unix_cli_main;
900   unix_cli_file_t * cf;
901   unix_file_t * uf;
902
903   cf = pool_elt_at_index (cm->cli_file_pool, cli_file_index);
904   uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
905
906   if (cf->no_pager || um->cli_pager_buffer_limit == 0 || cf->height == 0)
907     {
908       unix_vlib_cli_output_cooked (cf, uf, buffer, buffer_bytes);
909     }
910   else
911     {
912       word row = vec_len (cf->pager_index);
913       u8 * line;
914       unix_cli_pager_index_t * pi;
915
916       /* Index and add the output lines to the pager buffer. */
917       unix_cli_pager_add_line (cf, buffer, buffer_bytes);
918
919       /* Now iterate what was added to display the lines.
920        * If we reach the bottom of the page, display a prompt.
921        */
922       while (row < vec_len (cf->pager_index))
923         {
924           if (row < cf->height - 1)
925             {
926               /* output this line */
927               pi = &cf->pager_index[row];
928               line = cf->pager_vector[pi->line] + pi->offset;
929               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
930
931               /* if the last line didn't end in newline, and we're at the
932                * bottom of the page, add a newline */
933               if (line[pi->length - 1] != '\n' && row == cf->height - 2)
934                 unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
935             }
936           else
937             {
938               /* Display the pager prompt every 10 lines */
939               if (!(row % 10))
940                 unix_cli_pager_prompt(cf, uf);
941             }
942           row ++;
943         }
944
945       /* Check if we went over the pager buffer limit */
946       if (vec_len (cf->pager_index) > um->cli_pager_buffer_limit)
947         {
948           /* Stop using the pager for the remainder of this CLI command */
949           cf->no_pager = 2;
950
951           /* If we likely printed the prompt, erase it */
952           if (vec_len (cf->pager_index) > cf->height - 1)
953             unix_cli_pager_prompt_erase (cf, uf);
954
955           /* Dump out the contents of the buffer */
956           for (row = cf->pager_start + (cf->height - 1);
957                         row < vec_len (cf->pager_index); row ++)
958             {
959               pi = &cf->pager_index[row];
960               line = cf->pager_vector[pi->line] + pi->offset;
961               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
962             }
963
964           unix_cli_pager_reset (cf);
965         }
966     }
967 }
968
969 /** Identify whether a terminal type is ANSI capable.
970  *
971  * Compares the string given in @term with a list of terminal types known
972  * to support ANSI escape sequences.
973  *
974  * This list contains, for example, @c xterm, @c screen and @c ansi.
975  *
976  * @param term A string with a terminal type in it.
977  * @param len The length of the string in @term.
978  *
979  * @return @c 1 if the terminal type is recognized as supporting ANSI
980  *         terminal sequences; @c 0 otherwise.
981  */
982 static u8 unix_cli_terminal_type(u8 * term, uword len)
983 {
984   /* This may later be better done as a hash of some sort. */
985 #define _(a) do { \
986     if (strncasecmp(a, (char *)term, (size_t)len) == 0) return 1; \
987   } while(0)
988
989   _("xterm");
990   _("xterm-color");
991   _("xterm-256color"); /* iTerm on Mac */
992   _("screen");
993   _("ansi"); /* Microsoft Telnet */
994 #undef _
995
996   return 0;
997 }
998
999 /** \brief Emit initial welcome banner and prompt on a connection. */
1000 static void unix_cli_file_welcome(unix_cli_main_t * cm, unix_cli_file_t * cf)
1001 {
1002   unix_main_t * um = &unix_main;
1003   unix_file_t * uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
1004   unix_cli_banner_t *banner;
1005   int i, len;
1006
1007   /*
1008    * Put the first bytes directly into the buffer so that further output is
1009    * queued until everything is ready. (oterwise initial prompt can appear
1010    * mid way through VPP initialization)
1011    */
1012   unix_cli_add_pending_output (uf, cf, (u8 *)"\r", 1);
1013
1014   if (!um->cli_no_banner)
1015     {
1016       if (cf->ansi_capable)
1017         {
1018           banner = unix_cli_banner_color;
1019           len = ARRAY_LEN(unix_cli_banner_color);
1020         }
1021       else
1022         {
1023           banner = unix_cli_banner;
1024           len = ARRAY_LEN(unix_cli_banner);
1025         }
1026
1027       for (i = 0; i < len; i++)
1028         {
1029           unix_vlib_cli_output_cooked(cf, uf,
1030             banner[i].line,
1031             banner[i].length);
1032         }
1033       }
1034
1035   /* Prompt. */
1036   unix_cli_cli_prompt (cf, uf);
1037
1038   cf->started = 1;
1039 }
1040
1041 /** \brief A failsafe triggered on a timer to ensure we send the prompt
1042  * to telnet sessions that fail to negotiate the terminal type. */
1043 static void unix_cli_file_welcome_timer(any arg, f64 delay)
1044 {
1045   unix_cli_main_t * cm = &unix_cli_main;
1046   unix_cli_file_t * cf;
1047   (void)delay;
1048
1049   /* Check the connection didn't close already */
1050   if (pool_is_free_index (cm->cli_file_pool, (uword)arg))
1051     return;
1052
1053   cf = pool_elt_at_index (cm->cli_file_pool, (uword)arg);
1054
1055   if (!cf->started)
1056     unix_cli_file_welcome(cm, cf);
1057 }
1058
1059 /** \brief A mostly no-op Telnet state machine.
1060  * Process Telnet command bytes in a way that ensures we're mostly
1061  * transparent to the Telnet protocol. That is, it's mostly a no-op.
1062  *
1063  * @return -1 if we need more bytes, otherwise a positive integer number of
1064  *          bytes to consume from the input_vector, not including the initial
1065  *          IAC byte.
1066  */
1067 static i32 unix_cli_process_telnet(unix_main_t * um,
1068         unix_cli_file_t * cf,
1069         unix_file_t * uf,
1070         u8 * input_vector,
1071         uword len)
1072 {
1073   /* Input_vector starts at IAC byte.
1074    * See if we have a complete message; if not, return -1 so we wait for more.
1075    * if we have a complete message, consume those bytes from the vector.
1076    */
1077   i32 consume = 0;
1078
1079   if (len == 1)
1080     return -1; /* want more bytes */
1081
1082   switch (input_vector[1])
1083     {
1084       case IAC:
1085         /* two IAC's in a row means to pass through 0xff.
1086          * since that makes no sense here, just consume it.
1087          */
1088         consume = 1;
1089         break;
1090
1091       case WILL:
1092       case WONT:
1093       case DO:
1094       case DONT:
1095         /* Expect 3 bytes */
1096         if (vec_len(input_vector) < 3)
1097           return -1; /* want more bytes */
1098
1099         consume = 2;
1100         break;
1101
1102       case SB:
1103         {
1104           /* Sub option - search ahead for IAC SE to end it */
1105           i32 i;
1106           for (i = 3; i < len && i < UNIX_CLI_MAX_DEPTH_TELNET; i++)
1107             {
1108               if (input_vector[i - 1] == IAC && input_vector[i] == SE)
1109                 {
1110                   /* We have a complete message; see if we care about it */
1111                   switch (input_vector[2])
1112                     {
1113                       case TELOPT_TTYPE:
1114                         if (input_vector[3] != 0)
1115                           break;
1116                         /* See if the terminal type is ANSI capable */
1117                         cf->ansi_capable =
1118                             unix_cli_terminal_type(input_vector + 4, i - 5);
1119                         /* If session not started, we can release the pause */
1120                         if (!cf->started)
1121                           /* Send the welcome banner and initial prompt */
1122                           unix_cli_file_welcome(&unix_cli_main, cf);
1123                         break;
1124
1125                       case TELOPT_NAWS:
1126                         /* Window size */
1127                         if (i != 8) /* check message is correct size */
1128                           break;
1129                         cf->width = clib_net_to_host_u16(*((u16 *)(input_vector + 3)));
1130                         cf->height = clib_net_to_host_u16(*((u16 *)(input_vector + 5)));
1131                         /* reindex pager buffer */
1132                         unix_cli_pager_reindex (cf);
1133                         /* redraw page */
1134                         unix_cli_pager_redraw (cf, uf);
1135                         break;
1136
1137                       default:
1138                         break;
1139                     }
1140                   /* Consume it all */
1141                   consume = i;
1142                   break;
1143                 }
1144             }
1145
1146           if (i == UNIX_CLI_MAX_DEPTH_TELNET)
1147             consume = 1; /* hit max search depth, advance one byte */
1148
1149           if (consume == 0)
1150             return -1; /* want more bytes */
1151
1152           break;
1153         }
1154
1155       case GA:
1156       case EL:
1157       case EC:
1158       case AO:
1159       case IP:
1160       case BREAK:
1161       case DM:
1162       case NOP:
1163       case SE:
1164       case EOR:
1165       case ABORT:
1166       case SUSP:
1167       case xEOF:
1168         /* Simple one-byte messages */
1169         consume = 1;
1170         break;
1171
1172       case AYT:
1173         /* Are You There - trigger a visible response */
1174         consume = 1;
1175         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "fd.io VPP\n", 10);
1176         break;
1177
1178       default:
1179         /* Unknown command! Eat the IAC byte */
1180         break;
1181     }
1182
1183     return consume;
1184 }
1185
1186 /** \brief Process actionable input.
1187  * Based on the \c action process the input; this typically involves
1188  * searching the command history or editing the current command line.
1189  */
1190 static int unix_cli_line_process_one(unix_cli_main_t * cm,
1191         unix_main_t * um,
1192         unix_cli_file_t * cf,
1193         unix_file_t * uf,
1194         u8 input,
1195         unix_cli_parse_action_t action)
1196 {
1197   u8 * prev;
1198   int j, delta;
1199
1200   switch (action)
1201     {
1202     case UNIX_CLI_PARSE_ACTION_NOACTION:
1203       break;
1204
1205     case UNIX_CLI_PARSE_ACTION_REVSEARCH:
1206     case UNIX_CLI_PARSE_ACTION_FWDSEARCH:
1207       if (!cf->has_history || !cf->history_limit)
1208         break;
1209       if (cf->search_mode == 0)
1210         {
1211           /* Erase the current command (if any) */
1212           for (j = 0; j < (vec_len (cf->current_command)); j++)
1213               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b \b", 3);
1214
1215           vec_reset_length (cf->search_key);
1216           vec_reset_length (cf->current_command);
1217           if (action == UNIX_CLI_PARSE_ACTION_REVSEARCH)
1218               cf->search_mode = -1;
1219           else
1220               cf->search_mode = 1;
1221           cf->cursor = 0;
1222         }
1223       else
1224         {
1225           if (action == UNIX_CLI_PARSE_ACTION_REVSEARCH)
1226             cf->search_mode = -1;
1227           else
1228             cf->search_mode = 1;
1229
1230           cf->excursion += cf->search_mode;
1231           goto search_again;
1232         }
1233       break;
1234
1235     case UNIX_CLI_PARSE_ACTION_ERASELINELEFT:
1236       /* Erase the command from the cursor to the start */
1237
1238       /* Shimmy forwards to the new end of line position */
1239       delta = vec_len (cf->current_command) - cf->cursor;
1240       for (j = cf->cursor; j > delta; j--)
1241         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1242       /* Zap from here to the end of what is currently displayed */
1243       for (; j < (vec_len (cf->current_command)); j++)
1244         unix_vlib_cli_output_cooked (cf, uf, (u8 *) " ", 1);
1245       /* Get back to the start of the line */
1246       for (j = 0; j < (vec_len (cf->current_command)); j++)
1247         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1248
1249       j = vec_len(cf->current_command) - cf->cursor;
1250       memmove(cf->current_command,
1251               cf->current_command + cf->cursor,
1252               j);
1253       _vec_len(cf->current_command) = j;
1254
1255       /* Print the new contents */
1256       unix_vlib_cli_output_cooked (cf, uf, cf->current_command, j);
1257       /* Shimmy back to the start */
1258       for (j = 0; j < (vec_len (cf->current_command)); j++)
1259         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1260       cf->cursor = 0;
1261
1262       cf->search_mode = 0;
1263       break;
1264
1265     case UNIX_CLI_PARSE_ACTION_ERASELINERIGHT:
1266       /* Erase the command from the cursor to the end */
1267
1268       /* Zap from cursor to end of what is currently displayed */
1269       for (j = cf->cursor; j < (vec_len (cf->current_command)); j++)
1270         unix_vlib_cli_output_cooked (cf, uf, (u8 *) " ", 1);
1271       /* Get back to where we were */
1272       for (j = cf->cursor; j < (vec_len (cf->current_command)); j++)
1273         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1274
1275       /* Truncate the line at the cursor */
1276       _vec_len(cf->current_command) = cf->cursor;
1277
1278       cf->search_mode = 0;
1279       break;
1280
1281     case UNIX_CLI_PARSE_ACTION_LEFT:
1282       if (cf->cursor > 0)
1283         {
1284           unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1285           cf->cursor --;
1286         }
1287
1288       cf->search_mode = 0;
1289       break;
1290
1291     case UNIX_CLI_PARSE_ACTION_RIGHT:
1292       if (cf->cursor < vec_len(cf->current_command))
1293         {
1294           /* have to emit the character under the cursor */
1295           unix_vlib_cli_output_cooked (cf, uf, cf->current_command + cf->cursor, 1);
1296           cf->cursor ++;
1297         }
1298
1299       cf->search_mode = 0;
1300       break;
1301
1302     case UNIX_CLI_PARSE_ACTION_UP:
1303     case UNIX_CLI_PARSE_ACTION_DOWN:
1304       if (!cf->has_history || !cf->history_limit)
1305         break;
1306       cf->search_mode = 0;
1307       /* Erase the command */
1308       for (j = cf->cursor; j < (vec_len (cf->current_command)); j++)
1309         unix_vlib_cli_output_cooked (cf, uf, (u8 *) " ", 1);
1310       for (j = 0; j < (vec_len (cf->current_command)); j++)
1311         unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b \b", 3);
1312       vec_reset_length (cf->current_command);
1313       if (vec_len (cf->command_history))
1314         {
1315           if (action == UNIX_CLI_PARSE_ACTION_UP)
1316             delta = -1;
1317           else
1318             delta = 1;
1319
1320           cf->excursion += delta;
1321
1322           if (cf->excursion == vec_len (cf->command_history))
1323             {
1324               /* down-arrowed to last entry - want a blank line */
1325               _vec_len (cf->current_command) = 0;
1326             }
1327           else if (cf->excursion < 0)
1328             {
1329               /* up-arrowed over the start to the end, want a blank line */
1330               cf->excursion = vec_len (cf->command_history);
1331               _vec_len (cf->current_command) = 0;
1332             }
1333           else
1334             {
1335               if (cf->excursion > (i32) vec_len (cf->command_history) -1)
1336                 /* down-arrowed past end - wrap to start */
1337                 cf->excursion = 0;
1338
1339               /* Print the command at the current position */
1340               prev = cf->command_history [cf->excursion];
1341               vec_validate (cf->current_command, vec_len(prev)-1);
1342
1343               clib_memcpy (cf->current_command, prev, vec_len(prev));
1344               _vec_len (cf->current_command) = vec_len(prev);
1345               unix_vlib_cli_output_cooked (cf, uf, cf->current_command,
1346                                            vec_len (cf->current_command));
1347             }
1348           cf->cursor = vec_len(cf->current_command);
1349
1350           break;
1351         }
1352       break;
1353
1354     case UNIX_CLI_PARSE_ACTION_HOME:
1355       if (vec_len (cf->current_command) && cf->cursor > 0)
1356         {
1357           while (cf->cursor)
1358             {
1359               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1360               cf->cursor --;
1361             }
1362         }
1363
1364       cf->search_mode = 0;
1365       break;
1366
1367     case UNIX_CLI_PARSE_ACTION_END:
1368       if (vec_len (cf->current_command) &&
1369               cf->cursor < vec_len(cf->current_command))
1370         {
1371           unix_vlib_cli_output_cooked (cf, uf,
1372                 cf->current_command + cf->cursor,
1373                 vec_len(cf->current_command) - cf->cursor);
1374           cf->cursor = vec_len(cf->current_command);
1375         }
1376
1377       cf->search_mode = 0;
1378       break;
1379
1380     case UNIX_CLI_PARSE_ACTION_WORDLEFT:
1381       if (vec_len (cf->current_command) && cf->cursor > 0)
1382         {
1383           j = cf->cursor;
1384
1385           unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1386           j --;
1387
1388           while (j && isspace(cf->current_command[j]))
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               if (isspace(cf->current_command[j - 1]))
1396                 break;
1397               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1398               j --;
1399             }
1400
1401           cf->cursor = j;
1402         }
1403
1404       cf->search_mode = 0;
1405       break;
1406
1407     case UNIX_CLI_PARSE_ACTION_WORDRIGHT:
1408       if (vec_len (cf->current_command) &&
1409               cf->cursor < vec_len(cf->current_command))
1410         {
1411           int e = vec_len(cf->current_command);
1412           j = cf->cursor;
1413           while (j < e && !isspace(cf->current_command[j]))
1414             j ++;
1415           while (j < e && isspace(cf->current_command[j]))
1416             j ++;
1417           unix_vlib_cli_output_cooked (cf, uf,
1418                 cf->current_command + cf->cursor,
1419                 j - cf->cursor);
1420           cf->cursor = j;
1421         }
1422
1423       cf->search_mode = 0;
1424       break;
1425
1426
1427     case UNIX_CLI_PARSE_ACTION_ERASE:
1428       if (vec_len (cf->current_command))
1429         {
1430           if (cf->cursor == vec_len(cf->current_command))
1431             {
1432               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b \b", 3);
1433               _vec_len (cf->current_command)--;
1434               cf->cursor --;
1435             }
1436           else if (cf->cursor > 0)
1437             {
1438               /* shift everything at & to the right of the cursor left by 1 */
1439               j = vec_len (cf->current_command) - cf->cursor;
1440               memmove (cf->current_command + cf->cursor - 1,
1441                 cf->current_command + cf->cursor,
1442                 j);
1443               _vec_len (cf->current_command)--;
1444               cf->cursor --;
1445               /* redraw the rest of the line */
1446               unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1447               unix_vlib_cli_output_cooked (cf, uf,
1448                     cf->current_command + cf->cursor, j);
1449               unix_vlib_cli_output_cooked (cf, uf, (u8 *) " \b\b", 3);
1450               /* and shift the terminal cursor back where it should be */
1451               while (-- j)
1452                 unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1453             }
1454         }
1455       cf->search_mode = 0;
1456       cf->excursion = 0;
1457       vec_reset_length (cf->search_key);
1458       break;
1459
1460     case UNIX_CLI_PARSE_ACTION_ERASERIGHT:
1461       if (vec_len (cf->current_command))
1462         {
1463           if (cf->cursor < vec_len(cf->current_command))
1464             {
1465               /* shift everything to the right of the cursor left by 1 */
1466               j = vec_len (cf->current_command) - cf->cursor - 1;
1467               memmove (cf->current_command + cf->cursor,
1468                 cf->current_command + cf->cursor + 1,
1469                 j);
1470               _vec_len (cf->current_command)--;
1471               /* redraw the rest of the line */
1472               unix_vlib_cli_output_cooked (cf, uf,
1473                     cf->current_command + cf->cursor, j);
1474               unix_vlib_cli_output_cooked (cf, uf, (u8 *) " \b", 2);
1475               /* and shift the terminal cursor back where it should be */
1476               if (j)
1477                 {
1478                   unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1479                   while (-- j)
1480                     unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1481                 }
1482             }
1483         }
1484       else if (input == 'D' - '@')
1485         {
1486           /* ^D with no command entered = quit */
1487           unix_vlib_cli_output_cooked (cf, uf, (u8 *) "quit\n", 5);
1488           vlib_process_signal_event (um->vlib_main,
1489                 vlib_current_process (um->vlib_main),
1490                 UNIX_CLI_PROCESS_EVENT_QUIT,
1491                 cf - cm->cli_file_pool);
1492         }
1493       cf->search_mode = 0;
1494       cf->excursion = 0;
1495       vec_reset_length (cf->search_key);
1496       break;
1497
1498     case UNIX_CLI_PARSE_ACTION_CLEAR:
1499       /* If we're in ANSI mode, clear the screen.
1500        * Then redraw the prompt and any existing command input, then put
1501        * the cursor back where it was in that line.
1502        */
1503       if (cf->ansi_capable)
1504           unix_vlib_cli_output_cooked (cf, uf,
1505                     (u8 *) ANSI_CLEAR,
1506                     sizeof(ANSI_CLEAR)-1);
1507       else
1508           unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\n", 1);
1509
1510       unix_vlib_cli_output_raw (cf, uf,
1511                 cm->cli_prompt,
1512                 vec_len (cm->cli_prompt));
1513       unix_vlib_cli_output_raw (cf, uf,
1514                 cf->current_command,
1515                 vec_len (cf->current_command));
1516       for (j = cf->cursor; j < vec_len(cf->current_command); j++)
1517          unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b", 1);
1518
1519       break;
1520
1521     case UNIX_CLI_PARSE_ACTION_TAB:
1522     case UNIX_CLI_PARSE_ACTION_YANK:
1523       /* TODO */
1524       break;
1525
1526
1527     case UNIX_CLI_PARSE_ACTION_PAGER_QUIT:
1528     pager_quit:
1529       unix_cli_pager_prompt_erase (cf, uf);
1530       unix_cli_pager_reset (cf);
1531       unix_cli_cli_prompt (cf, uf);
1532       break;
1533
1534     case UNIX_CLI_PARSE_ACTION_PAGER_NEXT:
1535     case UNIX_CLI_PARSE_ACTION_PAGER_PGDN:
1536       /* show next page of the buffer */
1537       if (cf->height + cf->pager_start < vec_len (cf->pager_index))
1538         {
1539           u8 * line = NULL;
1540           unix_cli_pager_index_t * pi = NULL;
1541
1542           int m = cf->pager_start + (cf->height - 1);
1543           unix_cli_pager_prompt_erase (cf, uf);
1544           for (j = m;
1545                 j < vec_len (cf->pager_index) && cf->pager_start < m;
1546                 j ++, cf->pager_start ++)
1547             {
1548               pi = &cf->pager_index[j];
1549               line = cf->pager_vector[pi->line] + pi->offset;
1550               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1551             }
1552             /* if the last line didn't end in newline, add a newline */
1553             if (pi && line[pi->length - 1] != '\n')
1554               unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1555           unix_cli_pager_prompt (cf, uf);
1556         }
1557       else
1558         {
1559           if (action == UNIX_CLI_PARSE_ACTION_PAGER_NEXT)
1560             /* no more in buffer, exit, but only if it was <space> */
1561             goto pager_quit;
1562         }
1563       break;
1564
1565     case UNIX_CLI_PARSE_ACTION_PAGER_DN:
1566     case UNIX_CLI_PARSE_ACTION_PAGER_CRLF:
1567       /* display the next line of the buffer */
1568       if (cf->pager_start < vec_len (cf->pager_index) - (cf->height - 1))
1569         {
1570           u8 * line;
1571           unix_cli_pager_index_t * pi;
1572
1573           unix_cli_pager_prompt_erase (cf, uf);
1574           pi = &cf->pager_index[cf->pager_start + (cf->height - 1)];
1575           line = cf->pager_vector[pi->line] + pi->offset;
1576           unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1577           cf->pager_start ++;
1578           /* if the last line didn't end in newline, add a newline */
1579           if (line[pi->length - 1] != '\n')
1580             unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1581           unix_cli_pager_prompt (cf, uf);
1582         }
1583       else
1584         {
1585           if (action == UNIX_CLI_PARSE_ACTION_PAGER_CRLF)
1586             /* no more in buffer, exit, but only if it was <enter> */
1587             goto pager_quit;
1588         }
1589
1590       break;
1591
1592     case UNIX_CLI_PARSE_ACTION_PAGER_UP:
1593       /* scroll the page back one line */
1594       if (cf->pager_start > 0)
1595         {
1596           u8 * line = NULL;
1597           unix_cli_pager_index_t * pi = NULL;
1598
1599           cf->pager_start --;
1600           if (cf->ansi_capable)
1601             {
1602               pi = &cf->pager_index[cf->pager_start];
1603               line = cf->pager_vector[pi->line] + pi->offset;
1604               unix_cli_pager_prompt_erase (cf, uf);
1605               unix_vlib_cli_output_cooked (cf, uf, (u8 *)ANSI_SCROLLDN, sizeof(ANSI_SCROLLDN) - 1);
1606               unix_vlib_cli_output_cooked (cf, uf, (u8 *)ANSI_SAVECURSOR, sizeof(ANSI_SAVECURSOR) - 1);
1607               unix_cli_ansi_cursor(cf, uf, 1, 1);
1608               unix_vlib_cli_output_cooked (cf, uf, (u8 *)ANSI_CLEARLINE, sizeof(ANSI_CLEARLINE) - 1);
1609               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1610               unix_vlib_cli_output_cooked (cf, uf, (u8 *)ANSI_RESTCURSOR, sizeof(ANSI_RESTCURSOR) - 1);
1611               unix_cli_pager_prompt_erase (cf, uf);
1612               unix_cli_pager_prompt (cf, uf);
1613             }
1614           else
1615             {
1616               int m = cf->pager_start + (cf->height - 1);
1617               unix_cli_pager_prompt_erase (cf, uf);
1618               for (j = cf->pager_start; j < vec_len (cf->pager_index) && j < m; j ++)
1619                 {
1620                   pi = &cf->pager_index[j];
1621                   line = cf->pager_vector[pi->line] + pi->offset;
1622                   unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1623                 }
1624               /* if the last line didn't end in newline, add a newline */
1625               if (pi && line[pi->length - 1] != '\n')
1626                 unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1627               unix_cli_pager_prompt (cf, uf);
1628             }
1629         }
1630       break;
1631
1632     case UNIX_CLI_PARSE_ACTION_PAGER_TOP:
1633       /* back to the first page of the buffer */
1634       if (cf->pager_start > 0)
1635         {
1636           u8 * line = NULL;
1637           unix_cli_pager_index_t * pi = NULL;
1638
1639           cf->pager_start = 0;
1640           int m = cf->pager_start + (cf->height - 1);
1641           unix_cli_pager_prompt_erase (cf, uf);
1642           for (j = cf->pager_start; j < vec_len (cf->pager_index) && j < m; j ++)
1643             {
1644               pi = &cf->pager_index[j];
1645               line = cf->pager_vector[pi->line] + pi->offset;
1646               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1647             }
1648           /* if the last line didn't end in newline, add a newline */
1649           if (pi && line[pi->length - 1] != '\n')
1650             unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1651           unix_cli_pager_prompt (cf, uf);
1652         }
1653       break;
1654
1655     case UNIX_CLI_PARSE_ACTION_PAGER_BOTTOM:
1656       /* skip to the last page of the buffer */
1657       if (cf->pager_start < vec_len (cf->pager_index) - (cf->height - 1))
1658         {
1659           u8 * line = NULL;
1660           unix_cli_pager_index_t * pi = NULL;
1661
1662           cf->pager_start = vec_len (cf->pager_index) - (cf->height - 1);
1663           unix_cli_pager_prompt_erase (cf, uf);
1664           unix_cli_pager_message (cf, uf, "skipping", "\n");
1665           for (j = cf->pager_start; j < vec_len (cf->pager_index); j ++)
1666             {
1667               pi = &cf->pager_index[j];
1668               line = cf->pager_vector[pi->line] + pi->offset;
1669               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1670             }
1671           /* if the last line didn't end in newline, add a newline */
1672           if (pi && line[pi->length - 1] != '\n')
1673             unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1674           unix_cli_pager_prompt (cf, uf);
1675         }
1676       break;
1677
1678     case UNIX_CLI_PARSE_ACTION_PAGER_PGUP:
1679       /* wander back one page in the buffer */
1680       if (cf->pager_start > 0)
1681         {
1682           u8 * line = NULL;
1683           unix_cli_pager_index_t * pi = NULL;
1684           int m;
1685
1686           if (cf->pager_start >= cf->height)
1687             cf->pager_start -= cf->height - 1;
1688           else
1689             cf->pager_start = 0;
1690           m = cf->pager_start + cf->height - 1;
1691           unix_cli_pager_prompt_erase (cf, uf);
1692           for (j = cf->pager_start; j < vec_len (cf->pager_index) && j < m; j ++)
1693             {
1694               pi = &cf->pager_index[j];
1695               line = cf->pager_vector[pi->line] + pi->offset;
1696               unix_vlib_cli_output_cooked (cf, uf, line, pi->length);
1697             }
1698           /* if the last line didn't end in newline, add a newline */
1699           if (pi && line[pi->length - 1] != '\n')
1700             unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\n", 1);
1701           unix_cli_pager_prompt (cf, uf);
1702         }
1703       break;
1704
1705     case UNIX_CLI_PARSE_ACTION_PAGER_REDRAW:
1706       /* Redraw the current pager screen */
1707       unix_cli_pager_redraw (cf, uf);
1708       break;
1709
1710     case UNIX_CLI_PARSE_ACTION_PAGER_SEARCH:
1711       /* search forwards in the buffer */
1712       break;
1713
1714
1715     case UNIX_CLI_PARSE_ACTION_CRLF:
1716     crlf:
1717       unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\n", 1);
1718
1719       if (cf->has_history && cf->history_limit)
1720         {
1721           if (cf->command_history && vec_len(cf->command_history) >= cf->history_limit)
1722             {
1723               vec_free (cf->command_history[0]);
1724               vec_delete (cf->command_history, 1, 0);
1725             }
1726           /* Don't add blank lines to the cmd history */
1727           if (vec_len (cf->current_command))
1728             {
1729               /* Don't duplicate the previous command */
1730               j = vec_len(cf->command_history);
1731               if (j == 0 ||
1732                 (vec_len (cf->current_command) != vec_len (cf->command_history[j - 1]) ||
1733                     memcmp(cf->current_command, cf->command_history[j - 1],
1734                            vec_len (cf->current_command)) != 0))
1735                 {
1736                   /* copy the command to the history */
1737                   u8 * c = 0;
1738                   vec_append(c, cf->current_command);
1739                   vec_add1 (cf->command_history, c);
1740                   cf->command_number ++;
1741                 }
1742             }
1743           cf->excursion = vec_len (cf->command_history);
1744         }
1745
1746       cf->search_mode = 0;
1747       vec_reset_length (cf->search_key);
1748       cf->cursor = 0;
1749
1750       return 0;
1751
1752     case UNIX_CLI_PARSE_ACTION_PARTIALMATCH:
1753     case UNIX_CLI_PARSE_ACTION_NOMATCH:
1754       if (vec_len (cf->pager_index))
1755         {
1756           /* no-op for now */
1757         }
1758       else if (cf->has_history && cf->search_mode && isprint(input))
1759         {
1760           int k, limit, offset;
1761           u8 * item;
1762
1763           vec_add1 (cf->search_key, input);
1764
1765         search_again:
1766           for (j = 0; j < vec_len(cf->command_history); j++)
1767             {
1768               if (cf->excursion > (i32) vec_len (cf->command_history) -1)
1769                 cf->excursion = 0;
1770               else if (cf->excursion < 0)
1771                 cf->excursion = vec_len (cf->command_history) -1;
1772
1773               item = cf->command_history[cf->excursion];
1774
1775               limit = (vec_len(cf->search_key) > vec_len (item)) ?
1776                 vec_len(item) : vec_len (cf->search_key);
1777
1778               for (offset = 0; offset <= vec_len(item) - limit; offset++)
1779                 {
1780                   for (k = 0; k < limit; k++)
1781                     {
1782                       if (item[k+offset] != cf->search_key[k])
1783                         goto next_offset;
1784                     }
1785                   goto found_at_offset;
1786
1787                 next_offset:
1788                   ;
1789                 }
1790               goto next;
1791
1792             found_at_offset:
1793               for (j = 0; j < vec_len (cf->current_command); j++)
1794                 unix_vlib_cli_output_cooked (cf, uf, (u8 *) "\b \b", 3);
1795
1796               vec_validate (cf->current_command, vec_len(item)-1);
1797               clib_memcpy (cf->current_command, item, vec_len(item));
1798               _vec_len (cf->current_command) = vec_len(item);
1799
1800               unix_vlib_cli_output_cooked (cf, uf, cf->current_command,
1801                                            vec_len (cf->current_command));
1802               cf->cursor = vec_len (cf->current_command);
1803               goto found;
1804
1805             next:
1806               cf->excursion += cf->search_mode;
1807             }
1808
1809           unix_vlib_cli_output_cooked (cf, uf, (u8 *)"\nNo match...", 12);
1810           vec_reset_length (cf->search_key);
1811           vec_reset_length (cf->current_command);
1812           cf->search_mode = 0;
1813           cf->cursor = 0;
1814           goto crlf;
1815         }
1816       else if (isprint(input)) /* skip any errant control codes */
1817         {
1818           if (cf->cursor == vec_len(cf->current_command))
1819             {
1820               /* Append to end */
1821               vec_add1 (cf->current_command, input);
1822               cf->cursor ++;
1823
1824               /* Echo the character back to the client */
1825               unix_vlib_cli_output_raw (cf, uf, &input, 1);
1826             }
1827           else
1828             {
1829               /* Insert at cursor: resize +1 byte, move everything over */
1830               j = vec_len (cf->current_command) - cf->cursor;
1831               vec_add1 (cf->current_command, (u8)'A');
1832               memmove (cf->current_command + cf->cursor + 1,
1833                 cf->current_command + cf->cursor,
1834                 j);
1835               cf->current_command[cf->cursor] = input;
1836               /* Redraw the line */
1837               j ++;
1838               unix_vlib_cli_output_raw (cf, uf,
1839                     cf->current_command + cf->cursor, j);
1840               /* Put terminal cursor back */
1841               while (-- j)
1842                 unix_vlib_cli_output_raw (cf, uf, (u8 *)"\b", 1);
1843               cf->cursor ++;
1844             }
1845         }
1846       else
1847         {
1848           /* no-op - not printable or otherwise not actionable */
1849         }
1850
1851     found:
1852
1853       break;
1854
1855     case UNIX_CLI_PARSE_ACTION_TELNETIAC:
1856       break;
1857     }
1858     return 1;
1859 }
1860
1861 /** \brief Process input bytes on a stream to provide line editing and
1862  * command history in the CLI. */
1863 static int unix_cli_line_edit (unix_cli_main_t * cm,
1864                       unix_main_t * um,
1865                       unix_cli_file_t * cf)
1866 {
1867   unix_file_t * uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
1868   int i;
1869
1870   for (i = 0; i < vec_len (cf->input_vector); i++)
1871     {
1872       unix_cli_parse_action_t action;
1873       i32 matched = 0;
1874       unix_cli_parse_actions_t *a;
1875
1876       /* If we're in the pager mode, search the pager actions */
1877       a = vec_len (cf->pager_index) ? unix_cli_parse_pager : unix_cli_parse_strings;
1878
1879       /* See if the input buffer is some sort of control code */
1880       action = unix_cli_match_action(a, &cf->input_vector[i],
1881         vec_len (cf->input_vector) - i, &matched);
1882
1883       switch (action)
1884         {
1885         case UNIX_CLI_PARSE_ACTION_PARTIALMATCH:
1886           if (i)
1887             {
1888               /* There was a partial match which means we need more bytes
1889                * than the input buffer currently has.
1890                * Since the bytes before here have been processed, shift
1891                * the remaining contents to the start of the input buffer.
1892                */
1893               vec_delete (cf->input_vector, i, 0);
1894             }
1895           return 1; /* wait for more */
1896
1897         case UNIX_CLI_PARSE_ACTION_TELNETIAC:
1898           /* process telnet options */
1899           matched = unix_cli_process_telnet(um, cf, uf,
1900                 cf->input_vector + i, vec_len(cf->input_vector) - i);
1901           if (matched < 0)
1902             {
1903               if (i)
1904                 {
1905                   /* There was a partial match which means we need more bytes
1906                    * than the input buffer currently has.
1907                    * Since the bytes before here have been processed, shift
1908                    * the remaining contents to the start of the input buffer.
1909                    */
1910                   vec_delete (cf->input_vector, i, 0);
1911                 }
1912               return 1; /* wait for more */
1913             }
1914           break;
1915
1916         default:
1917           /* process the action */
1918           if (!unix_cli_line_process_one(cm, um, cf, uf,
1919                 cf->input_vector[i], action))
1920             {
1921               /* CRLF found. Consume the bytes from the input_vector */
1922               vec_delete (cf->input_vector, i + matched, 0);
1923               /* And tell our caller to execute cf->input_command */
1924               return 0;
1925             }
1926         }
1927
1928       i += matched;
1929     }
1930
1931   vec_reset_length(cf->input_vector);
1932   return 1;
1933 }
1934
1935 /** \brief Process input to a CLI session. */
1936 static void unix_cli_process_input (unix_cli_main_t * cm,
1937                         uword cli_file_index)
1938 {
1939   unix_main_t * um = &unix_main;
1940   unix_file_t * uf;
1941   unix_cli_file_t * cf = pool_elt_at_index (cm->cli_file_pool, cli_file_index);
1942   unformat_input_t input;
1943   int vlib_parse_eval (u8 *);
1944
1945 more:
1946   /* Try vlibplex first.  Someday... */
1947   if (0 && vlib_parse_eval (cf->input_vector) == 0)
1948       goto done;
1949
1950   if (cf->line_mode)
1951     {
1952       /* just treat whatever we got as a complete line of input */
1953       cf->current_command = cf->input_vector;
1954     }
1955   else
1956     {
1957       /* Line edit, echo, etc. */
1958       if (unix_cli_line_edit (cm, um, cf))
1959         /* want more input */
1960         return;
1961     }
1962
1963   if (um->log_fd)
1964     {
1965       static u8 * lv;
1966       vec_reset_length (lv);
1967       lv = format (lv, "%U[%d]: %v", 
1968                    format_timeval,
1969                    0 /* current bat-time */,
1970                    0 /* current bat-format */,
1971                    cli_file_index,
1972                    cf->input_vector);
1973       {
1974         int rv __attribute__((unused)) = 
1975           write (um->log_fd, lv, vec_len(lv));
1976       }
1977     }
1978
1979   /* Copy our input command to a new string */
1980   unformat_init_vector (&input, cf->current_command);
1981
1982   /* Remove leading white space from input. */
1983   (void) unformat (&input, "");
1984
1985   cm->current_input_file_index = cli_file_index;
1986   cf->pager_start = 0; /* start a new pager session */
1987
1988   if (unformat_check_input (&input) != UNFORMAT_END_OF_INPUT)
1989     vlib_cli_input (um->vlib_main, &input, unix_vlib_cli_output, cli_file_index);
1990
1991   /* Zero buffer since otherwise unformat_free will call vec_free on it. */
1992   input.buffer = 0;
1993
1994   unformat_free (&input);
1995
1996   /* Re-fetch pointer since pool may have moved. */
1997   cf = pool_elt_at_index (cm->cli_file_pool, cli_file_index);
1998   uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
1999
2000 done:
2001   /* reset vector; we'll re-use it later  */
2002   if (cf->line_mode)
2003     vec_reset_length (cf->input_vector);
2004   else
2005     vec_reset_length (cf->current_command);
2006
2007   if (cf->no_pager == 2)
2008     {
2009       /* Pager was programmatically disabled */
2010       unix_cli_pager_message (cf, uf, "pager buffer overflowed", "\n");
2011       cf->no_pager = um->cli_no_pager;
2012     }
2013
2014   if (vec_len (cf->pager_index) == 0 || vec_len (cf->pager_index) < cf->height)
2015     {
2016       /* There was no need for the pager */
2017       unix_cli_pager_reset (cf);
2018
2019       /* Prompt. */
2020       unix_cli_cli_prompt (cf, uf);
2021     }
2022   else
2023     {
2024       /* Display the pager prompt */
2025       unix_cli_pager_prompt(cf, uf);
2026     }
2027
2028     /* Any residual data in the input vector? */
2029     if (vec_len (cf->input_vector))
2030       goto more;
2031 }
2032
2033 static void unix_cli_kill (unix_cli_main_t * cm, uword cli_file_index)
2034 {
2035   unix_main_t * um = &unix_main;
2036   unix_cli_file_t * cf;
2037   unix_file_t * uf;
2038   int i;
2039
2040   cf = pool_elt_at_index (cm->cli_file_pool, cli_file_index);
2041   uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
2042
2043   /* Quit/EOF on stdin means quit program. */
2044   if (uf->file_descriptor == UNIX_CLI_STDIN_FD)
2045     clib_longjmp (&um->vlib_main->main_loop_exit, VLIB_MAIN_LOOP_EXIT_CLI);
2046
2047   vec_free (cf->current_command);
2048   vec_free (cf->search_key);
2049
2050   for (i = 0; i < vec_len (cf->command_history); i++)
2051       vec_free (cf->command_history[i]);
2052
2053   vec_free (cf->command_history);
2054
2055   unix_file_del (um, uf);
2056
2057   unix_cli_file_free (cf);
2058   pool_put (cm->cli_file_pool, cf);
2059 }
2060
2061 static uword
2062 unix_cli_process (vlib_main_t * vm,
2063                   vlib_node_runtime_t * rt,
2064                   vlib_frame_t * f)
2065 {
2066   unix_cli_main_t * cm = &unix_cli_main;
2067   uword i, * data = 0;
2068
2069   while (1)
2070     {
2071       unix_cli_process_event_type_t event_type;
2072       vlib_process_wait_for_event (vm);
2073       event_type = vlib_process_get_events (vm, &data);
2074
2075       switch (event_type)
2076         {
2077         case UNIX_CLI_PROCESS_EVENT_READ_READY:
2078           for (i = 0; i < vec_len (data); i++)
2079             unix_cli_process_input (cm, data[i]);
2080           break;
2081
2082         case UNIX_CLI_PROCESS_EVENT_QUIT:
2083           /* Kill this process. */
2084           for (i = 0; i < vec_len (data); i++)
2085             unix_cli_kill (cm, data[i]);
2086           goto done;
2087         }
2088
2089       if (data)
2090         _vec_len (data) = 0;
2091     }
2092
2093  done:
2094   vec_free (data);
2095
2096   vlib_node_set_state (vm, rt->node_index, VLIB_NODE_STATE_DISABLED);
2097
2098   /* Add node index so we can re-use this process later. */
2099   vec_add1 (cm->unused_cli_process_node_indices, rt->node_index);
2100
2101   return 0;
2102 }
2103
2104 static clib_error_t * unix_cli_write_ready (unix_file_t * uf)
2105 {
2106   unix_cli_main_t * cm = &unix_cli_main;
2107   unix_cli_file_t * cf;
2108   int n;
2109
2110   cf = pool_elt_at_index (cm->cli_file_pool, uf->private_data);
2111
2112   /* Flush output vector. */
2113   n = write (uf->file_descriptor,
2114              cf->output_vector, vec_len (cf->output_vector));
2115
2116   if (n < 0 && errno != EAGAIN)
2117     return clib_error_return_unix (0, "write");
2118
2119   else if (n > 0)
2120     unix_cli_del_pending_output (uf, cf, n);
2121
2122   return /* no error */ 0;
2123 }
2124
2125 static clib_error_t * unix_cli_read_ready (unix_file_t * uf)
2126 {
2127   unix_main_t * um = &unix_main;
2128   unix_cli_main_t * cm = &unix_cli_main;
2129   unix_cli_file_t * cf;
2130   uword l;
2131   int n, n_read, n_try;
2132
2133   cf = pool_elt_at_index (cm->cli_file_pool, uf->private_data);
2134
2135   n = n_try = 4096;
2136   while (n == n_try) {
2137       l = vec_len (cf->input_vector);
2138       vec_resize (cf->input_vector, l + n_try);
2139
2140       n = read (uf->file_descriptor, cf->input_vector + l, n_try);
2141
2142       /* Error? */
2143       if (n < 0 && errno != EAGAIN)
2144           return clib_error_return_unix (0, "read");
2145   
2146       n_read = n < 0 ? 0 : n;
2147       _vec_len (cf->input_vector) = l + n_read;
2148   }
2149
2150   if (! (n < 0))
2151     vlib_process_signal_event (um->vlib_main,
2152                                cf->process_node_index,
2153                                (n_read == 0
2154                                 ? UNIX_CLI_PROCESS_EVENT_QUIT
2155                                 : UNIX_CLI_PROCESS_EVENT_READ_READY),
2156                                /* event data */ uf->private_data);
2157
2158   return /* no error */ 0;
2159 }
2160
2161 /** Store a new CLI session.
2162  * @param name The name of the session.
2163  * @param fd   The file descriptor for the session I/O.
2164  * @return The session ID.
2165  */
2166 static u32 unix_cli_file_add (unix_cli_main_t * cm, char * name, int fd)
2167 {
2168   unix_main_t * um = &unix_main;
2169   unix_cli_file_t * cf;
2170   unix_file_t template = {0};
2171   vlib_main_t * vm = um->vlib_main;
2172   vlib_node_t * n;
2173
2174   name = (char *) format (0, "unix-cli-%s", name);
2175
2176   if (vec_len (cm->unused_cli_process_node_indices) > 0)
2177     {
2178       uword l = vec_len (cm->unused_cli_process_node_indices);
2179
2180       /* Find node and give it new name. */
2181       n = vlib_get_node (vm, cm->unused_cli_process_node_indices[l - 1]);
2182       vec_free (n->name);
2183       n->name = (u8 *) name;
2184
2185       vlib_node_set_state (vm, n->index, VLIB_NODE_STATE_POLLING);
2186
2187       _vec_len (cm->unused_cli_process_node_indices) = l - 1;
2188     }
2189   else
2190     {
2191       static vlib_node_registration_t r = {
2192         .function = unix_cli_process,
2193         .type = VLIB_NODE_TYPE_PROCESS,
2194         .process_log2_n_stack_bytes = 14,
2195       };
2196
2197       r.name = name;
2198       vlib_register_node (vm, &r);
2199       vec_free (name);
2200
2201       n = vlib_get_node (vm, r.index);
2202     }
2203
2204   pool_get (cm->cli_file_pool, cf);
2205   memset (cf, 0, sizeof (*cf));
2206
2207   template.read_function = unix_cli_read_ready;
2208   template.write_function = unix_cli_write_ready;
2209   template.file_descriptor = fd;
2210   template.private_data = cf - cm->cli_file_pool;
2211
2212   cf->process_node_index = n->index;
2213   cf->unix_file_index = unix_file_add (um, &template);
2214   cf->output_vector = 0;
2215   cf->input_vector = 0;
2216
2217   vlib_start_process (vm, n->runtime_index);
2218
2219   vlib_process_t * p = vlib_get_process_from_node(vm, n);
2220   p->output_function = unix_vlib_cli_output;
2221   p->output_function_arg = cf - cm->cli_file_pool;
2222
2223   return cf - cm->cli_file_pool;
2224 }
2225
2226 /** Telnet listening socket has a new connection. */
2227 static clib_error_t * unix_cli_listen_read_ready (unix_file_t * uf)
2228 {
2229   unix_main_t * um = &unix_main;
2230   unix_cli_main_t * cm = &unix_cli_main;
2231   clib_socket_t * s = &um->cli_listen_socket;
2232   clib_socket_t client;
2233   char * client_name;
2234   clib_error_t * error;
2235   unix_cli_file_t * cf;
2236   u32 cf_index;
2237
2238   error = clib_socket_accept (s, &client);
2239   if (error)
2240     return error;
2241
2242   client_name = (char *) format (0, "%U%c", format_sockaddr, &client.peer, 0);
2243
2244   cf_index = unix_cli_file_add (cm, client_name, client.fd);
2245   cf = pool_elt_at_index (cm->cli_file_pool, cf_index);
2246
2247   /* No longer need CLIB version of socket. */
2248   clib_socket_free (&client);
2249
2250   vec_free (client_name);
2251
2252   /* if we're supposed to run telnet session in character mode (default) */
2253   if (um->cli_line_mode == 0)
2254     {
2255       /*
2256        * Set telnet client character mode, echo on, suppress "go-ahead".
2257        * Technically these should be negotiated, but this works.
2258        */
2259       u8 charmode_option[] = {
2260         IAC, WONT, TELOPT_LINEMODE, /* server will do char-by-char */
2261         IAC, DONT, TELOPT_LINEMODE, /* client should do char-by-char */
2262         IAC, WILL, TELOPT_SGA,      /* server willl supress GA */
2263         IAC, DO,   TELOPT_SGA,      /* client should supress Go Ahead */
2264         IAC, WILL, TELOPT_ECHO,     /* server will do echo */
2265         IAC, DONT, TELOPT_ECHO,     /* client should not echo */
2266         IAC, DO,   TELOPT_TTYPE,    /* client should tell us its term type */
2267         IAC, SB,   TELOPT_TTYPE, 1, IAC, SE, /* now tell me ttype */
2268         IAC, DO,   TELOPT_NAWS,     /* client should tell us its window sz */
2269         IAC, SB,   TELOPT_NAWS, 1, IAC, SE,  /* now tell me window size */
2270       };
2271
2272       /* Enable history on this CLI */
2273       cf->history_limit = um->cli_history_limit;
2274       cf->has_history = cf->history_limit != 0;
2275
2276       /* Make sure this session is in line mode */
2277       cf->line_mode = 0;
2278
2279       /* We need CRLF */
2280       cf->crlf_mode = 1;
2281
2282       /* Setup the pager */
2283       cf->no_pager = um->cli_no_pager;
2284
2285       uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
2286
2287       /* Send the telnet options */
2288       unix_vlib_cli_output_raw (cf, uf, charmode_option,
2289                                    ARRAY_LEN(charmode_option));
2290
2291       /* In case the client doesn't negotiate terminal type, use
2292        * a timer to kick off the initial prompt. */
2293       timer_call (unix_cli_file_welcome_timer, cf_index, 1);
2294     }
2295
2296   return error;
2297 }
2298
2299 /** The system terminal has informed us that the window size
2300  * has changed.
2301  */
2302 static void
2303 unix_cli_resize_interrupt (int signum)
2304 {
2305   unix_main_t * um = &unix_main;
2306   unix_cli_main_t * cm = &unix_cli_main;
2307   unix_cli_file_t * cf = pool_elt_at_index (cm->cli_file_pool,
2308                                 cm->stdin_cli_file_index);
2309   unix_file_t * uf = pool_elt_at_index (um->file_pool, cf->unix_file_index);
2310   struct winsize ws;
2311   (void)signum;
2312
2313   /* Terminal resized, fetch the new size */
2314   ioctl(UNIX_CLI_STDIN_FD, TIOCGWINSZ, &ws);
2315   cf->width = ws.ws_col;
2316   cf->height = ws.ws_row;
2317
2318   /* Reindex the pager buffer */
2319   unix_cli_pager_reindex (cf);
2320
2321   /* Redraw the page */
2322   unix_cli_pager_redraw (cf, uf);
2323 }
2324
2325 /** Handle configuration directives in the @em unix section. */
2326 static clib_error_t *
2327 unix_cli_config (vlib_main_t * vm, unformat_input_t * input)
2328 {
2329   unix_main_t * um = &unix_main;
2330   unix_cli_main_t * cm = &unix_cli_main;
2331   int flags;
2332   clib_error_t * error = 0;
2333   unix_cli_file_t * cf;
2334   u32 cf_index;
2335   struct termios tio;
2336   struct sigaction sa;
2337   struct winsize ws;
2338   u8 * term;
2339
2340   /* We depend on unix flags being set. */
2341   if ((error = vlib_call_config_function (vm, unix_config)))
2342     return error;
2343
2344   if (um->flags & UNIX_FLAG_INTERACTIVE)
2345     {
2346       /* Set stdin to be non-blocking. */
2347       if ((flags = fcntl (UNIX_CLI_STDIN_FD, F_GETFL, 0)) < 0)
2348         flags = 0;
2349       fcntl (UNIX_CLI_STDIN_FD, F_SETFL, flags | O_NONBLOCK);
2350
2351       cf_index = unix_cli_file_add (cm, "stdin", UNIX_CLI_STDIN_FD);
2352       cf = pool_elt_at_index (cm->cli_file_pool, cf_index);
2353       cm->stdin_cli_file_index = cf_index;
2354
2355       /* If stdin is a tty and we are using chacracter mode, enable
2356        * history on the CLI and set the tty line discipline accordingly. */
2357       if (isatty(UNIX_CLI_STDIN_FD) && um->cli_line_mode == 0)
2358         {
2359           /* Capture terminal resize events */
2360           sa.sa_handler = unix_cli_resize_interrupt;
2361           sa.sa_flags = 0;
2362           if (sigaction (SIGWINCH, &sa, 0) < 0)
2363               clib_panic ("sigaction");
2364
2365           /* Retrieve the current terminal size */
2366           ioctl(UNIX_CLI_STDIN_FD, TIOCGWINSZ, &ws);
2367           cf->width = ws.ws_col;
2368           cf->height = ws.ws_row;
2369
2370           if (cf->width == 0 || cf->height == 0)
2371             /* We have a tty, but no size. Stick to line mode. */
2372             goto notty;
2373
2374           /* Setup the history */
2375           cf->history_limit = um->cli_history_limit;
2376           cf->has_history = cf->history_limit != 0;
2377
2378           /* Setup the pager */
2379           cf->no_pager = um->cli_no_pager;
2380
2381           /* We're going to be in char by char mode */
2382           cf->line_mode = 0;
2383
2384           /* Save the original tty state so we can restore it later */
2385           tcgetattr(UNIX_CLI_STDIN_FD, &um->tio_stdin);
2386           um->tio_isset = 1;
2387
2388           /* Tweak the tty settings */
2389           tio = um->tio_stdin;
2390           /* echo off, canonical mode off, ext'd input processing off */
2391           tio.c_lflag &= ~(ECHO | ICANON | IEXTEN);
2392           tio.c_cc[VMIN] = 1; /* 1 byte at a time */
2393           tio.c_cc[VTIME] = 0; /* no timer */
2394           tcsetattr(UNIX_CLI_STDIN_FD, TCSAFLUSH, &tio);
2395
2396           /* See if we can do ANSI/VT100 output */
2397           term = (u8 *)getenv("TERM");
2398           if (term != NULL)
2399             cf->ansi_capable = unix_cli_terminal_type(term,
2400                         strlen((char *)term));
2401         }
2402       else
2403         {
2404         notty:
2405           /* No tty, so make sure these things are off */
2406           cf->no_pager = 1;
2407           cf->history_limit = 0;
2408           cf->has_history = 0;
2409           cf->line_mode = 1;
2410         }
2411
2412       /* Send banner and initial prompt */
2413       unix_cli_file_welcome(cm, cf);
2414     }
2415
2416   /* If we have socket config, LISTEN, otherwise, don't */
2417   clib_socket_t * s = &um->cli_listen_socket;
2418   if(s->config && s->config[0] != 0) {
2419     /* CLI listen. */
2420     unix_file_t template = {0};
2421
2422     s->flags = SOCKET_IS_SERVER; /* listen, don't connect */
2423     error = clib_socket_init (s);
2424
2425     if (error)
2426       return error;
2427
2428     template.read_function = unix_cli_listen_read_ready;
2429     template.file_descriptor = s->fd;
2430
2431     unix_file_add (um, &template);
2432   }
2433
2434   /* Set CLI prompt. */
2435   if (! cm->cli_prompt)
2436     cm->cli_prompt = format (0, "VLIB: ");
2437
2438   return 0;
2439 }
2440
2441 VLIB_CONFIG_FUNCTION (unix_cli_config, "unix-cli");
2442
2443 /** Called when VPP is shutting down, this resets the system
2444  * terminal state, if previously saved.
2445  */
2446 static clib_error_t *
2447 unix_cli_exit (vlib_main_t * vm)
2448 {
2449   unix_main_t * um = &unix_main;
2450
2451   /* If stdin is a tty and we saved the tty state, reset the tty state */
2452   if (isatty(UNIX_CLI_STDIN_FD) && um->tio_isset)
2453     tcsetattr(UNIX_CLI_STDIN_FD, TCSAFLUSH, &um->tio_stdin);
2454
2455   return 0;
2456 }
2457
2458 VLIB_MAIN_LOOP_EXIT_FUNCTION (unix_cli_exit);
2459
2460 /** Set the CLI prompt.
2461  * @param The C string to set the prompt to.
2462  * @note This setting is global; it impacts all current
2463  *       and future CLI sessions.
2464  */
2465 void vlib_unix_cli_set_prompt (char * prompt)
2466 {
2467   char * fmt = (prompt[strlen(prompt)-1] == ' ') ? "%s" : "%s ";
2468   unix_cli_main_t * cm = &unix_cli_main;
2469   if (cm->cli_prompt)
2470     vec_free (cm->cli_prompt);
2471   cm->cli_prompt = format (0, fmt, prompt);
2472 }
2473
2474 /** CLI command to quit the terminal session.
2475  * @note If this is a stdin session then this will
2476  *       shutdown VPP also.
2477  */
2478 static clib_error_t *
2479 unix_cli_quit (vlib_main_t * vm,
2480                unformat_input_t * input,
2481                vlib_cli_command_t * cmd)
2482 {
2483   unix_cli_main_t * cm = &unix_cli_main;
2484
2485   vlib_process_signal_event (vm,
2486                              vlib_current_process (vm),
2487                              UNIX_CLI_PROCESS_EVENT_QUIT,
2488                              cm->current_input_file_index);
2489   return 0;
2490 }
2491
2492 VLIB_CLI_COMMAND (unix_cli_quit_command, static) = {
2493   .path = "quit",
2494   .short_help = "Exit CLI",
2495   .function = unix_cli_quit,
2496 };
2497
2498 /** CLI command to execute a VPP command script. */
2499 static clib_error_t *
2500 unix_cli_exec (vlib_main_t * vm,
2501                unformat_input_t * input,
2502                vlib_cli_command_t * cmd)
2503 {
2504   char * file_name;
2505   int fd;
2506   unformat_input_t sub_input;
2507   clib_error_t * error;
2508
2509   file_name = 0;
2510   fd = -1;
2511   error = 0;
2512
2513   if (! unformat (input, "%s", &file_name))
2514     {
2515       error = clib_error_return (0, "expecting file name, got `%U'",
2516                                  format_unformat_error, input);
2517       goto done;
2518     }
2519
2520   fd = open (file_name, O_RDONLY);
2521   if (fd < 0)
2522     {
2523       error = clib_error_return_unix (0, "failed to open `%s'", file_name);
2524       goto done;
2525     }
2526
2527   /* Make sure its a regular file. */
2528   {
2529     struct stat s;
2530
2531     if (fstat (fd, &s) < 0)
2532       {
2533         error = clib_error_return_unix (0, "failed to stat `%s'", file_name);
2534         goto done;
2535       }
2536     
2537     if (! (S_ISREG (s.st_mode) || S_ISLNK (s.st_mode)))
2538       {
2539         error = clib_error_return (0, "not a regular file `%s'", file_name);
2540         goto done;
2541       }
2542   }
2543
2544   unformat_init_unix_file (&sub_input, fd);
2545
2546   vlib_cli_input (vm, &sub_input, 0, 0);
2547   unformat_free (&sub_input);
2548
2549  done:
2550   if (fd > 0)
2551     close (fd);
2552   vec_free (file_name);
2553
2554   return error;
2555 }
2556
2557 VLIB_CLI_COMMAND (cli_exec, static) = {
2558   .path = "exec",
2559   .short_help = "Execute commands from file",
2560   .function = unix_cli_exec,
2561   .is_mp_safe = 1,
2562 };
2563
2564 /** CLI command to show various unix error statistics. */
2565 static clib_error_t *
2566 unix_show_errors (vlib_main_t * vm,
2567                   unformat_input_t * input,
2568                   vlib_cli_command_t * cmd)
2569 {
2570   unix_main_t * um = &unix_main;
2571   clib_error_t * error = 0;
2572   int i, n_errors_to_show;
2573   unix_error_history_t * unix_errors = 0;
2574
2575   n_errors_to_show = 1 << 30;
2576
2577   if (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2578     {
2579       if (! unformat (input, "%d", &n_errors_to_show))
2580         {
2581           error = clib_error_return (0, "expecting integer number of errors to show, got `%U'",
2582                                      format_unformat_error, input);
2583           goto done;
2584         }
2585     }
2586
2587   n_errors_to_show = clib_min (ARRAY_LEN (um->error_history), n_errors_to_show);
2588
2589   i = um->error_history_index > 0 ? um->error_history_index - 1 : ARRAY_LEN (um->error_history) - 1;
2590
2591   while (n_errors_to_show > 0)
2592     {
2593       unix_error_history_t * eh = um->error_history + i;
2594
2595       if (! eh->error)
2596         break;
2597
2598       vec_add1 (unix_errors, eh[0]);
2599       n_errors_to_show -= 1;
2600       if (i == 0)
2601         i = ARRAY_LEN (um->error_history) - 1;
2602       else
2603         i--;
2604     }
2605
2606   if (vec_len (unix_errors) == 0)
2607     vlib_cli_output (vm, "no Unix errors so far");
2608   else
2609     {
2610       vlib_cli_output (vm, "%Ld total errors seen", um->n_total_errors);
2611       for (i = vec_len (unix_errors) - 1; i >= 0; i--)
2612         {
2613           unix_error_history_t * eh = vec_elt_at_index (unix_errors, i);
2614           vlib_cli_output (vm, "%U: %U",
2615                            format_time_interval, "h:m:s:u", eh->time,
2616                            format_clib_error, eh->error);
2617         }
2618       vlib_cli_output (vm, "%U: time now",
2619                        format_time_interval, "h:m:s:u", vlib_time_now (vm));
2620     }
2621
2622  done:
2623   vec_free (unix_errors);
2624   return error;
2625 }
2626
2627 VLIB_CLI_COMMAND (cli_unix_show_errors, static) = {
2628   .path = "show unix-errors",
2629   .short_help = "Show Unix system call error history",
2630   .function = unix_show_errors,
2631 };
2632
2633 /** CLI command to show session command history. */
2634 static clib_error_t *
2635 unix_cli_show_history (vlib_main_t * vm,
2636       unformat_input_t * input,
2637       vlib_cli_command_t * cmd)
2638 {
2639   unix_cli_main_t * cm = &unix_cli_main;
2640   unix_cli_file_t * cf;
2641   int i, j;
2642
2643   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2644
2645   if (cf->has_history && cf->history_limit)
2646     {
2647       i = 1 + cf->command_number - vec_len(cf->command_history);
2648       for (j = 0; j < vec_len (cf->command_history); j++)
2649           vlib_cli_output (vm, "%d  %v\n", i + j, cf->command_history[j]);
2650     }
2651   else
2652     {
2653       vlib_cli_output (vm, "History not enabled.\n");
2654     }
2655
2656   return 0;
2657 }
2658
2659 VLIB_CLI_COMMAND (cli_unix_cli_show_history, static) = {
2660   .path = "history",
2661   .short_help = "Show current session command history",
2662   .function = unix_cli_show_history,
2663 };
2664
2665 /** CLI command to show terminal status. */
2666 static clib_error_t *
2667 unix_cli_show_terminal (vlib_main_t * vm,
2668       unformat_input_t * input,
2669       vlib_cli_command_t * cmd)
2670 {
2671   unix_main_t * um = &unix_main;
2672   unix_cli_main_t * cm = &unix_cli_main;
2673   unix_cli_file_t * cf;
2674   vlib_node_t * n;
2675
2676   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2677   n = vlib_get_node (vm, cf->process_node_index);
2678
2679   vlib_cli_output (vm, "Terminal name:   %v\n", n->name);
2680   vlib_cli_output (vm, "Terminal mode:   %s\n", cf->line_mode ? 
2681                                                 "line-by-line" :
2682                                                 "char-by-char");
2683   vlib_cli_output (vm, "Terminal width:  %d\n", cf->width);
2684   vlib_cli_output (vm, "Terminal height: %d\n", cf->height);
2685   vlib_cli_output (vm, "ANSI capable:    %s\n", cf->ansi_capable ? "yes" : "no");
2686   vlib_cli_output (vm, "History enabled: %s%s\n",
2687         cf->has_history ? "yes" : "no",
2688         !cf->has_history || cf->history_limit ? "" : " (disabled by history limit)");
2689   if (cf->has_history)
2690     vlib_cli_output (vm, "History limit:   %d\n", cf->history_limit);
2691   vlib_cli_output (vm, "Pager enabled:   %s%s%s\n",
2692         cf->no_pager ? "no" : "yes",
2693         cf->no_pager || cf->height ? "" : " (disabled by terminal height)",
2694         cf->no_pager || um->cli_pager_buffer_limit ? "" : " (disabled by buffer limit)");
2695   if (!cf->no_pager)
2696     vlib_cli_output (vm, "Pager limit:     %d\n", um->cli_pager_buffer_limit);
2697   vlib_cli_output (vm, "CRLF mode:       %s\n", cf->crlf_mode ? "CR+LF" : "LF");
2698
2699   return 0;
2700 }
2701
2702 VLIB_CLI_COMMAND (cli_unix_cli_show_terminal, static) = {
2703   .path = "show terminal",
2704   .short_help = "Show current session terminal settings",
2705   .function = unix_cli_show_terminal,
2706 };
2707
2708 /** CLI command to set terminal pager settings. */
2709 static clib_error_t *
2710 unix_cli_set_terminal_pager (vlib_main_t * vm,
2711       unformat_input_t * input,
2712       vlib_cli_command_t * cmd)
2713 {
2714   unix_main_t * um = &unix_main;
2715   unix_cli_main_t * cm = &unix_cli_main;
2716   unix_cli_file_t * cf;
2717   unformat_input_t _line_input, * line_input = &_line_input;
2718
2719   if (! unformat_user (input, unformat_line_input, line_input))
2720     return 0;
2721
2722   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2723
2724   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2725     {
2726     if (unformat (line_input, "on"))
2727       cf->no_pager = 0;
2728     else if (unformat (line_input, "off"))
2729       cf->no_pager = 1;
2730     else if (unformat (line_input, "limit %u", &um->cli_pager_buffer_limit))
2731       vlib_cli_output (vm, "Pager limit set to %u lines; note, this is global.\n",
2732         um->cli_pager_buffer_limit);
2733     else
2734       return clib_error_return (0, "unknown parameter: `%U`",
2735                                 format_unformat_error, line_input);
2736   }
2737
2738   unformat_free(line_input);
2739
2740   return 0;
2741 }
2742
2743 VLIB_CLI_COMMAND (cli_unix_cli_set_terminal_pager, static) = {
2744   .path = "set terminal pager",
2745   .short_help = "set terminal pager [on|off] [limit <lines>]",
2746   .function = unix_cli_set_terminal_pager,
2747 };
2748
2749 /** CLI command to set terminal history settings. */
2750 static clib_error_t *
2751 unix_cli_set_terminal_history (vlib_main_t * vm,
2752       unformat_input_t * input,
2753       vlib_cli_command_t * cmd)
2754 {
2755   unix_cli_main_t * cm = &unix_cli_main;
2756   unix_cli_file_t * cf;
2757   unformat_input_t _line_input, * line_input = &_line_input;
2758   u32 limit;
2759
2760   if (! unformat_user (input, unformat_line_input, line_input))
2761     return 0;
2762
2763   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2764
2765   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2766     {
2767     if (unformat (line_input, "on"))
2768       cf->has_history = 1;
2769     else if (unformat (line_input, "off"))
2770       cf->has_history = 0;
2771     else if (unformat (line_input, "limit %u", &cf->history_limit))
2772       ;
2773     else
2774       return clib_error_return (0, "unknown parameter: `%U`",
2775                                 format_unformat_error, line_input);
2776
2777     /* If we reduced history size, or turned it off, purge the history */
2778     limit = cf->has_history ? cf->history_limit : 0;
2779
2780     while (cf->command_history && vec_len(cf->command_history) >= limit)
2781       {
2782         vec_free (cf->command_history[0]);
2783         vec_delete (cf->command_history, 1, 0);
2784       }
2785   }
2786
2787   unformat_free(line_input);
2788
2789   return 0;
2790 }
2791
2792 VLIB_CLI_COMMAND (cli_unix_cli_set_terminal_history, static) = {
2793   .path = "set terminal history",
2794   .short_help = "set terminal history [on|off] [limit <lines>]",
2795   .function = unix_cli_set_terminal_history,
2796 };
2797
2798 /** CLI command to set terminal ANSI settings. */
2799 static clib_error_t *
2800 unix_cli_set_terminal_ansi (vlib_main_t * vm,
2801       unformat_input_t * input,
2802       vlib_cli_command_t * cmd)
2803 {
2804   unix_cli_main_t * cm = &unix_cli_main;
2805   unix_cli_file_t * cf;
2806
2807   cf = pool_elt_at_index (cm->cli_file_pool, cm->current_input_file_index);
2808
2809   if (unformat (input, "on"))
2810     cf->ansi_capable = 1;
2811   else if (unformat (input, "off"))
2812     cf->ansi_capable = 0;
2813   else
2814     return clib_error_return (0, "unknown parameter: `%U`",
2815                               format_unformat_error, input);
2816
2817   return 0;
2818 }
2819
2820 VLIB_CLI_COMMAND (cli_unix_cli_set_terminal_ansi, static) = {
2821   .path = "set terminal ansi",
2822   .short_help = "set terminal ansi [on|off]",
2823   .function = unix_cli_set_terminal_ansi,
2824 };
2825
2826 static clib_error_t *
2827 unix_cli_init (vlib_main_t * vm)
2828 {
2829   return 0;
2830 }
2831
2832 VLIB_INIT_FUNCTION (unix_cli_init);