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