1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright(c) 2010-2014 Intel Corporation.
3 * Copyright (c) 2009, Olivier MATZ <zer0@droids-corp.org>
17 #include <netinet/in.h>
19 #include <rte_string_fns.h>
21 #include "cmdline_parse.h"
22 #include "cmdline_rdline.h"
26 cmdline_valid_buffer(struct rdline *rdl, const char *buf,
27 __attribute__((unused)) unsigned int size)
29 struct cmdline *cl = rdl->opaque;
31 ret = cmdline_parse(cl, buf);
32 if (ret == CMDLINE_PARSE_AMBIGUOUS)
33 cmdline_printf(cl, "Ambiguous command\n");
34 else if (ret == CMDLINE_PARSE_NOMATCH)
35 cmdline_printf(cl, "Command not found\n");
36 else if (ret == CMDLINE_PARSE_BAD_ARGS)
37 cmdline_printf(cl, "Bad arguments\n");
41 cmdline_complete_buffer(struct rdline *rdl, const char *buf,
42 char *dstbuf, unsigned int dstsize,
45 struct cmdline *cl = rdl->opaque;
46 return cmdline_complete(cl, buf, state, dstbuf, dstsize);
50 cmdline_write_char(struct rdline *rdl, char c)
61 ret = write(cl->s_out, &c, 1);
68 cmdline_set_prompt(struct cmdline *cl, const char *prompt)
72 snprintf(cl->prompt, sizeof(cl->prompt), "%s", prompt);
76 cmdline_new(cmdline_parse_ctx_t *ctx, const char *prompt, int s_in, int s_out)
84 cl = malloc(sizeof(struct cmdline));
87 memset(cl, 0, sizeof(struct cmdline));
92 ret = rdline_init(&cl->rdl, cmdline_write_char, cmdline_valid_buffer,
93 cmdline_complete_buffer);
100 cmdline_set_prompt(cl, prompt);
101 rdline_newline(&cl->rdl, cl->prompt);
107 cmdline_free(struct cmdline *cl)
116 if (cl->s_out != cl->s_in && cl->s_out > 2)
122 cmdline_printf(const struct cmdline *cl, const char *fmt, ...)
133 vdprintf(cl->s_out, fmt, ap);
142 buf = malloc(BUFSIZ);
146 ret = vsnprintf(buf, BUFSIZ, fmt, ap);
154 ret = write(cl->s_out, buf, ret);
161 cmdline_in(struct cmdline *cl, const char *buf, int size)
163 const char *history, *buffer;
164 size_t histlen, buflen;
171 for (i=0; i<size; i++) {
172 ret = rdline_char_in(&cl->rdl, buf[i]);
174 if (ret == RDLINE_RES_VALIDATED) {
175 buffer = rdline_get_buffer(&cl->rdl);
176 history = rdline_get_history_item(&cl->rdl, 0);
178 histlen = strnlen(history, RDLINE_BUF_SIZE);
179 same = !memcmp(buffer, history, histlen) &&
180 buffer[histlen] == '\n';
184 buflen = strnlen(buffer, RDLINE_BUF_SIZE);
185 if (buflen > 1 && !same)
186 rdline_add_history(&cl->rdl, buffer);
187 rdline_newline(&cl->rdl, cl->prompt);
189 else if (ret == RDLINE_RES_EOF)
191 else if (ret == RDLINE_RES_EXITED)
198 cmdline_quit(struct cmdline *cl)
202 rdline_quit(&cl->rdl);
206 cmdline_poll(struct cmdline *cl)
215 else if (cl->rdl.status == RDLINE_EXITED)
216 return RDLINE_EXITED;
222 status = poll(&pfd, 1, 0);
225 else if (status > 0) {
227 read_status = read(cl->s_in, &c, 1);
231 status = cmdline_in(cl, &c, 1);
232 if (status < 0 && cl->rdl.status != RDLINE_EXITED)
236 return cl->rdl.status;
240 cmdline_interact(struct cmdline *cl)
249 if (read(cl->s_in, &c, 1) <= 0)
251 if (cmdline_in(cl, &c, 1) < 0)