xref: /dpdk/app/graph/cli.c (revision 5b21ffb2330813c68b77056ea13f0458fb5085f0)
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 	NULL,
24 };
25 
26 static struct cmdline *cl;
27 
28 static int
29 is_comment(char *in)
30 {
31 	if ((strlen(in) && index("!#%;", in[0])) ||
32 		(strncmp(in, "//", 2) == 0) ||
33 		(strncmp(in, "--", 2) == 0))
34 		return 1;
35 
36 	return 0;
37 }
38 
39 void
40 cli_init(void)
41 {
42 	cl = cmdline_stdin_new(modules_ctx, "");
43 }
44 
45 void
46 cli_exit(void)
47 {
48 	cmdline_stdin_exit(cl);
49 }
50 
51 void
52 cli_process(char *in, char *out, size_t out_size, __rte_unused void *obj)
53 {
54 	int rc;
55 
56 	if (is_comment(in))
57 		return;
58 
59 	rc = cmdline_parse(cl, in);
60 	if (rc == CMDLINE_PARSE_AMBIGUOUS)
61 		snprintf(out, out_size, MSG_CMD_FAIL, "Ambiguous command");
62 	else if (rc == CMDLINE_PARSE_NOMATCH)
63 		snprintf(out, out_size, MSG_CMD_FAIL, "Command mismatch");
64 	else if (rc == CMDLINE_PARSE_BAD_ARGS)
65 		snprintf(out, out_size, MSG_CMD_FAIL, "Bad arguments");
66 
67 	return;
68 
69 }
70 
71 int
72 cli_script_process(const char *file_name, size_t msg_in_len_max, size_t msg_out_len_max, void *obj)
73 {
74 	char *msg_in = NULL, *msg_out = NULL;
75 	int rc = -EINVAL;
76 	FILE *f = NULL;
77 
78 	/* Check input arguments */
79 	if ((file_name == NULL) || (strlen(file_name) == 0) || (msg_in_len_max == 0) ||
80 	    (msg_out_len_max == 0))
81 		return rc;
82 
83 	msg_in = malloc(msg_in_len_max + 1);
84 	msg_out = malloc(msg_out_len_max + 1);
85 	if ((msg_in == NULL) || (msg_out == NULL)) {
86 		rc = -ENOMEM;
87 		goto exit;
88 	}
89 
90 	/* Open input file */
91 	f = fopen(file_name, "r");
92 	if (f == NULL) {
93 		rc = -EIO;
94 		goto exit;
95 	}
96 
97 	/* Read file */
98 	while (fgets(msg_in, msg_in_len_max, f) != NULL) {
99 		msg_out[0] = 0;
100 
101 		cli_process(msg_in, msg_out, msg_out_len_max, obj);
102 
103 		if (strlen(msg_out))
104 			printf("%s", msg_out);
105 	}
106 
107 	/* Close file */
108 	fclose(f);
109 	rc = 0;
110 
111 exit:
112 	free(msg_out);
113 	free(msg_in);
114 	return rc;
115 }
116