1 /* SPDX-License-Identifier: BSD-3-Clause 2 * Copyright(c) 2010-2014 Intel Corporation. 3 * Copyright (c) 2009, Olivier MATZ <zer0@droids-corp.org> 4 * All rights reserved. 5 */ 6 7 #include <stdlib.h> 8 #include <stdint.h> 9 #include <stdio.h> 10 #include <string.h> 11 #include <stdarg.h> 12 #include <ctype.h> 13 14 #include "cmdline_vt100.h" 15 16 const char *cmdline_vt100_commands[] = { 17 vt100_up_arr, 18 vt100_down_arr, 19 vt100_right_arr, 20 vt100_left_arr, 21 "\177", 22 "\n", 23 "\001", 24 "\005", 25 "\013", 26 "\031", 27 "\003", 28 "\006", 29 "\002", 30 vt100_suppr, 31 vt100_tab, 32 "\004", 33 "\014", 34 "\r", 35 "\033\177", 36 vt100_word_left, 37 vt100_word_right, 38 "?", 39 "\027", 40 "\020", 41 "\016", 42 "\033\144", 43 vt100_bs, 44 }; 45 46 void 47 vt100_init(struct cmdline_vt100 *vt) 48 { 49 if (!vt) 50 return; 51 vt->state = CMDLINE_VT100_INIT; 52 } 53 54 55 static int 56 match_command(char *buf, unsigned int size) 57 { 58 const char *cmd; 59 size_t cmdlen; 60 unsigned int i = 0; 61 62 for (i=0 ; i<sizeof(cmdline_vt100_commands)/sizeof(const char *) ; i++) { 63 cmd = *(cmdline_vt100_commands + i); 64 65 cmdlen = strnlen(cmd, CMDLINE_VT100_BUF_SIZE); 66 if (size == cmdlen && 67 !strncmp(buf, cmd, cmdlen)) { 68 return i; 69 } 70 } 71 72 return -1; 73 } 74 75 int 76 vt100_parser(struct cmdline_vt100 *vt, char ch) 77 { 78 unsigned int size; 79 uint8_t c = (uint8_t) ch; 80 81 if (!vt) 82 return -1; 83 84 if (vt->bufpos >= CMDLINE_VT100_BUF_SIZE) { 85 vt->state = CMDLINE_VT100_INIT; 86 vt->bufpos = 0; 87 } 88 89 vt->buf[vt->bufpos++] = c; 90 size = vt->bufpos; 91 92 switch (vt->state) { 93 case CMDLINE_VT100_INIT: 94 if (c == 033) { 95 vt->state = CMDLINE_VT100_ESCAPE; 96 } 97 else { 98 vt->bufpos = 0; 99 goto match_command; 100 } 101 break; 102 103 case CMDLINE_VT100_ESCAPE: 104 if (c == 0133) { 105 vt->state = CMDLINE_VT100_ESCAPE_CSI; 106 } 107 else if (c >= 060 && c <= 0177) { /* XXX 0177 ? */ 108 vt->bufpos = 0; 109 vt->state = CMDLINE_VT100_INIT; 110 goto match_command; 111 } 112 break; 113 114 case CMDLINE_VT100_ESCAPE_CSI: 115 if (c >= 0100 && c <= 0176) { 116 vt->bufpos = 0; 117 vt->state = CMDLINE_VT100_INIT; 118 goto match_command; 119 } 120 break; 121 122 default: 123 vt->bufpos = 0; 124 break; 125 } 126 127 return -2; 128 129 match_command: 130 return match_command(vt->buf, size); 131 } 132