xref: /dpdk/app/graph/cli.c (revision 2d7b3ccc9794bbedc5e388c0ced7389eeade96e7)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2023 Marvell.
3  */
4 
5 #include <errno.h>
6 #include <stdio.h>
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <string.h>
10 
11 #include <cmdline_parse.h>
12 #include <cmdline_parse_num.h>
13 #include <cmdline_parse_string.h>
14 #include <cmdline_socket.h>
15 #include <rte_common.h>
16 
17 #include "module_api.h"
18 
19 #define CMD_MAX_TOKENS 256
20 #define MAX_LINE_SIZE 2048
21 
22 cmdline_parse_ctx_t modules_ctx[] = {
23 	(cmdline_parse_inst_t *)&mempool_config_cmd_ctx,
24 	(cmdline_parse_inst_t *)&mempool_help_cmd_ctx,
25 	NULL,
26 };
27 
28 static struct cmdline *cl;
29 
30 static int
31 is_comment(char *in)
32 {
33 	if ((strlen(in) && index("!#%;", in[0])) ||
34 		(strncmp(in, "//", 2) == 0) ||
35 		(strncmp(in, "--", 2) == 0))
36 		return 1;
37 
38 	return 0;
39 }
40 
41 void
42 cli_init(void)
43 {
44 	cl = cmdline_stdin_new(modules_ctx, "");
45 }
46 
47 void
48 cli_exit(void)
49 {
50 	cmdline_stdin_exit(cl);
51 }
52 
53 void
54 cli_process(char *in, char *out, size_t out_size, __rte_unused void *obj)
55 {
56 	int rc;
57 
58 	if (is_comment(in))
59 		return;
60 
61 	rc = cmdline_parse(cl, in);
62 	if (rc == CMDLINE_PARSE_AMBIGUOUS)
63 		snprintf(out, out_size, MSG_CMD_FAIL, "Ambiguous command");
64 	else if (rc == CMDLINE_PARSE_NOMATCH)
65 		snprintf(out, out_size, MSG_CMD_FAIL, "Command mismatch");
66 	else if (rc == CMDLINE_PARSE_BAD_ARGS)
67 		snprintf(out, out_size, MSG_CMD_FAIL, "Bad arguments");
68 
69 	return;
70 
71 }
72 
73 int
74 cli_script_process(const char *file_name, size_t msg_in_len_max, size_t msg_out_len_max, void *obj)
75 {
76 	char *msg_in = NULL, *msg_out = NULL;
77 	int rc = -EINVAL;
78 	FILE *f = NULL;
79 
80 	/* Check input arguments */
81 	if ((file_name == NULL) || (strlen(file_name) == 0) || (msg_in_len_max == 0) ||
82 	    (msg_out_len_max == 0))
83 		return rc;
84 
85 	msg_in = malloc(msg_in_len_max + 1);
86 	msg_out = malloc(msg_out_len_max + 1);
87 	if ((msg_in == NULL) || (msg_out == NULL)) {
88 		rc = -ENOMEM;
89 		goto exit;
90 	}
91 
92 	/* Open input file */
93 	f = fopen(file_name, "r");
94 	if (f == NULL) {
95 		rc = -EIO;
96 		goto exit;
97 	}
98 
99 	/* Read file */
100 	while (fgets(msg_in, msg_in_len_max, f) != NULL) {
101 		msg_out[0] = 0;
102 
103 		cli_process(msg_in, msg_out, msg_out_len_max, obj);
104 
105 		if (strlen(msg_out))
106 			printf("%s", msg_out);
107 	}
108 
109 	/* Close file */
110 	fclose(f);
111 	rc = 0;
112 
113 exit:
114 	free(msg_out);
115 	free(msg_in);
116 	return rc;
117 }
118