summaryrefslogtreecommitdiff
path: root/avr/cli.c
blob: 9f48d3dca87f92ef942fefc26a8c68da5c9bb0b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
 * (C) Copyright 2014-2016 Leo C. <erbl259-lmu@yahoo.de>
 *
 * (C) Copyright 2000
 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
 *
 * Add to readline cmdline-editing by
 * (C) Copyright 2005
 * JinHua Luo, GuangDong Linux Center, <luo.jinhua@gd-linux.com>
 *
 * SPDX-License-Identifier:	GPL-2.0
 */

#include "cli.h"
#include "common.h"

#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>

#include "config.h"
#include "command.h"
#include "xmalloc.h"
#include "debug.h"
#include "env.h"
#include "cli_readline.h"
#include "con-utils.h"


/* FIXME: Quoting problems */

#define DEBUG_PARSER	0	/* set to 1 to debug */

#define debug_parser(fmt, args...)		\
	debug_cond(DEBUG_PARSER, fmt, ##args)


static bool opt_xtrace;
static bool opt_verbose;
static int_least8_t command_level;

static void cli_trace_cmd(int_fast8_t level, int argc, char *argv[])
{
	while (level-- > 0)
		putchar('+');
	for (int_fast8_t i = 0; i < argc; i++)
		printf_P(PSTR(" %s"), argv[i]);
	putchar('\n');
}




static int cli_parse_line(char *line, char *argv[])
{
	uint_fast8_t state = 0;
	uint_fast8_t nargs = 0;
	char *inp, *outp;
	char c, quote;

	debug_parser("%s: \"%s\"\n", __func__, line);

	for (outp = inp = line, quote = '\0'; (c = *inp) != '\0'; inp++) {

		switch (state) {
		case 0:						/* before arg string, waiting for arg start */
			if (isblank(c))
				continue;

			argv[nargs++] = inp;	/* begin of argument string	*/
			outp = inp;
			state = 1;
			/* fall thru */

		case 1:						/* in arg string, waiting for end of arg string */
			if (c == '\\') {
				++state;
				continue;
			}
			if (c == '\"' || c == '\'') {
				quote = c;
				state = 3;
				continue;
			}
			if (isblank(c)) {
				c = '\0';
				state = 0;
			}
			break;

		case 3:						/* in quote */
			if (c == '\\' && quote == '\"') {
				++state;
				continue;
			}
			if (c == quote) {
				state = 1;
				continue;
			}
			break;

		case 2:						/* waiting for next char */
		case 4:
			--state;
			break;

		}

		if (nargs > CONFIG_SYS_MAXARGS) {
			--nargs;
			break;
		}
		*outp++ = c;
	}

	if (*inp != '\0')
		printf_P(PSTR("** Too many args (max. %d) **\n"), CONFIG_SYS_MAXARGS);

	*outp = '\0';
	argv[nargs] = NULL;
	debug_parser("%s: nargs=%d\n", __func__, nargs);
#if 0
	for (int i = 0; i < nargs; i++)
		debug_parser("%s: arg %d: >%s<\n", __func__, i, argv[i]);
#endif
	return nargs;

}

static
void append_char(uint_fast8_t pass, char **p, char c)
{

	if (pass) {
		**p = c;
	}
	++(*p);
}

static
char *process_macros(char *input, char *output)
{
	char c, prev, *inp, *outp;
	const char *varname = NULL;

	for(uint_fast8_t pass = 0; pass < 2; pass++)
	{
		uint_fast8_t state = 0;
		/* 0 = waiting for '$'  */
		/* 1 = waiting for '{' */
		/* 2 = waiting for '}' */
		/* 3 = waiting for ''' */

		if (pass == 0) {
			outp = output;
		} else {
			int outputlen = outp - output;
			outp = xrealloc(output, outputlen);
			output = outp;
		}

		inp = input;

		debug_parser("[PROCESS_MACROS] INPUT len %d: \"%s\"\n",
						strlen(inp), inp);

		for (prev = '\0'; (c = *inp++) != '\0'; prev = c) {



			switch (state) {
			case 0:	/* Waiting for (unescaped) $    */
				if ((c == '\'') && (prev != '\\')) {
					state = 3;
					break;
				}
				if ((c == '$') && (prev != '\\')) {
					state++;
					continue;
				}
				break;
			case 1:	/* Waiting for {        */
				if (c == '{') {
					state++;
					varname = inp;
					continue;
				} else {
					state = 0;
					append_char(pass, &outp, '$');
				}
				break;
			case 2:	/* Waiting for }        */
				if (c == '}') {
					/* Terminate variable name */
					*(inp-1) = '\0';
					const char *envval = getenv_str(varname);
					*(inp-1) = '}';
					/* Copy into the line if it exists */
					if (envval != NULL)
						while (*envval)
							append_char(pass, &outp, *(envval++));
					/* Look for another '$' */
					state = 0;
				}
				continue;
			case 3:	/* Waiting for '        */
				if (c == '\'')
					state = 0;
				break;
			}
			append_char(pass, &outp, c);
		}

		append_char(pass, &outp, 0);
	}

	debug_parser("[PROCESS_MACROS] OUTPUT len %d: \"%s\"\n",
		     strlen(output), output);

	return output;
}

/**
 *
 *
 * WARNING:
 *
 * We must create a temporary copy of the command since the command we get
 * may be the result from getenv_str(), which returns a pointer directly to
 * the environment data, which may change magicly when the command we run
 * creates or modifies environment variables (like "bootp" does).
 *
 *
 * @param cmd
 * @param flag
 * @returns
 *
 */
static int cli_run_command(const char *cmd, int flag)
{
	char *cmdbuf;			/* working copy of cmd		*/
	char *token;			/* start of token in cmdbuf	*/
	char *sep;			/* end of token (separator) in cmdbuf */
	char *finaltoken = NULL;	/* token after macro expansion	*/
	char *str;
	char *argv[CONFIG_SYS_MAXARGS + 1];	/* NULL terminated	*/
	int argc;
	uint_fast8_t inquotes, repeatable = 1;
	int rc = 0;

	opt_verbose = 0;
	opt_xtrace = 0;
	char *optenv = getenv_str(PSTR("cli"));
	if (optenv) {
		opt_verbose = (strstr_P(optenv, PSTR("verbose")) != NULL);
		opt_xtrace = (strstr_P(optenv, PSTR("xtrace")) != NULL);
	}

	debug_parser("[RUN_COMMAND] cmd[%p]=\"%s\"\n",
			cmd, cmd ? cmd : "NULL");

	if (opt_verbose)
		printf_P(PSTR("%s\n"), cmd, cmd ? cmd : "");

	clear_ctrlc();		/* forget any previous Control C */

	if (!cmd || !*cmd)
		return -1;	/* empty command */

	cmdbuf = strdup(cmd);
	if (!cmdbuf)
		return -1;	/* not enough memory */

	++command_level;
	str = cmdbuf;

	/* Process separators and check for invalid
	 * repeatable commands
	 */

	debug_parser("[PROCESS_SEPARATORS] %s\n", cmd);
	while (*str) {
		/*
		 * Find separator, or string end
		 * Allow simple escape of ';' by writing "\;"
		 */
		for (inquotes = 0, sep = str; *sep; sep++) {
			if ((*sep == '\'') &&
			    (sep != str) &&					/* past string start */
			    (*(sep - 1) != '\\'))			/* and NOT escaped */
				inquotes = !inquotes;

			if (!inquotes &&
			    (*sep == ';' || *sep == '\n'	/* separator */
					|| *sep == '#') &&			/*   or start of comment */
			    ((sep == str) ||				/* string start */
			    (*(sep - 1) != '\\')))			/*   or NOT escaped */
				break;
		}

		/* no more commands after unescaped '#' token */
		if (*sep == '#')
			*sep = '\0';

		/* Limit the token to data between separators */
		token = str;
		if (*sep) {
			str = sep + 1;		/* start of command for next pass */
			*sep = '\0';
		} else {
			str = sep;			/* no more commands for next pass */
		}
		debug_parser("token: \"%s\"\n", token);

		/* find macros in this token and replace them */
		finaltoken = process_macros(token, finaltoken);

		/* Extract arguments */
		argc = cli_parse_line(finaltoken, argv);
		if (argc == 0) {
			//rc = -1;
			continue; /* no command at all */
		}

		if (opt_xtrace)
			cli_trace_cmd(command_level, argc, argv);

		rc = cmd_process(flag, argc, argv, &repeatable);
		if (rc != CMD_RET_SUCCESS) {
			if (opt_verbose)
				printf_P(PSTR("Command failed, result=%d\n"), rc);
			rc = -1;
		}

		/* Did the user stop this? */
		if (had_ctrlc()) {
			rc = -1;	/* if stopped then not repeatable */
			break;
		}
	}

	free(cmdbuf);
	free(finaltoken);
	--command_level;

	return rc ? rc : repeatable;
}

static int cli_run_command_list(const char *cmd)
{
	return (cli_run_command(cmd, 0) < 0);
}

/******************************************************************************/


/*
 * Run a command.
 *
 * @param cmd	Command to run
 * @param flag	Execution flags (CMD_FLAG_...)
 * @return 0 on success, or != 0 on error.
 */
int run_command(const char *cmd, int flag)
{
	/*
	 * cli_run_command can return 0 or 1 for success, so clean up
	 * its result.
	 */
	if (cli_run_command(cmd, flag) == -1)
		return 1;

	return 0;
}

/*
 * Run a command using the selected parser, and check if it is repeatable.
 *
 * @param cmd	Command to run
 * @param flag	Execution flags (CMD_FLAG_...)
 * @return 0 (not repeatable) or 1 (repeatable) on success, -1 on error.
 */
static int run_command_repeatable(const char *cmd, int flag)
{
	return cli_run_command(cmd, flag);
}

int run_command_list(const char *cmd, int len)
{
	(void) len;

	return cli_run_command_list(cmd);
}

/****************************************************************************/


void cli_loop(void)
{
	char *lastcommand = NULL;
	int len;
	int flag;
	int rc = 1;

	for (;;) {
		len = cli_readline(lastcommand ? PSTR(CONFIG_SYS_PROMPT_REPEAT) : PSTR(CONFIG_SYS_PROMPT), 1);

		flag = 0;	/* assume no special flags for now */
		if (len > 0) {
			free (lastcommand);
			lastcommand = strdup(console_buffer);
		} else if (len == 0)
			flag |= CMD_FLAG_REPEAT;

		if (len == -1) {
			if (opt_verbose)
				my_puts_P(PSTR("<INTERRUPT>\n"));
		} else
			rc = run_command_repeatable(lastcommand, flag);

		if (rc <= 0) {
			/* invalid command or not repeatable, forget it */
			free(lastcommand);
			lastcommand = NULL;
		}
	}
}