1 /*
2  * Copyright (c) 2016 Intel Corporation
3  * Copyright (c) 2023 Nordic Semiconductor ASA
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 /* Dynamic shell command completion for network interface.
9  * This is be used by multiple commands.
10  */
11 
12 #define MAX_IFACE_HELP_STR_LEN sizeof("longbearername (0xabcd0123)")
13 #define MAX_IFACE_STR_LEN sizeof("xxx")
14 
15 static char iface_help_buffer[MAX_IFACE_COUNT][MAX_IFACE_HELP_STR_LEN];
16 static char iface_index_buffer[MAX_IFACE_COUNT][MAX_IFACE_STR_LEN];
17 
18 static void iface_index_get(size_t idx, struct shell_static_entry *entry);
19 
20 SHELL_DYNAMIC_CMD_CREATE(iface_index, iface_index_get);
21 
set_iface_index_buffer(size_t idx)22 static char *set_iface_index_buffer(size_t idx)
23 {
24 	struct net_if *iface = net_if_get_by_index(idx);
25 	size_t array_idx;
26 
27 	/* Network interfaces start at 1 */
28 	if (idx == 0) {
29 		return "";
30 	}
31 
32 	if (!iface) {
33 		return NULL;
34 	}
35 
36 	array_idx = idx - 1;
37 	if (array_idx >= ARRAY_SIZE(iface_index_buffer)) {
38 		return NULL;
39 	}
40 
41 	snprintk(iface_index_buffer[array_idx], MAX_IFACE_STR_LEN, "%d", (uint8_t)idx);
42 
43 	return iface_index_buffer[array_idx];
44 }
45 
set_iface_index_help(size_t idx)46 static char *set_iface_index_help(size_t idx)
47 {
48 	struct net_if *iface = net_if_get_by_index(idx);
49 	size_t array_idx;
50 
51 	/* Network interfaces start at 1 */
52 	if (idx == 0) {
53 		return "";
54 	}
55 
56 	if (!iface) {
57 		return NULL;
58 	}
59 
60 	array_idx = idx - 1;
61 	if (array_idx >= ARRAY_SIZE(iface_help_buffer)) {
62 		return NULL;
63 	}
64 
65 #if defined(CONFIG_NET_INTERFACE_NAME)
66 	char name[CONFIG_NET_INTERFACE_NAME_LEN + 1];
67 
68 	net_if_get_name(iface, name, CONFIG_NET_INTERFACE_NAME_LEN);
69 	name[CONFIG_NET_INTERFACE_NAME_LEN] = '\0';
70 
71 	snprintk(iface_help_buffer[array_idx], MAX_IFACE_HELP_STR_LEN,
72 		 "%s [%s] (%p)", name, iface2str(iface, NULL), iface);
73 #else
74 	snprintk(iface_help_buffer[array_idx], MAX_IFACE_HELP_STR_LEN,
75 		 "[%s] (%p)", iface2str(iface, NULL), iface);
76 #endif
77 
78 	return iface_help_buffer[array_idx];
79 }
80 
iface_index_get(size_t idx,struct shell_static_entry * entry)81 static void iface_index_get(size_t idx, struct shell_static_entry *entry)
82 {
83 	entry->handler = NULL;
84 	entry->help  = set_iface_index_help(idx);
85 	entry->subcmd = &iface_index;
86 	entry->syntax = set_iface_index_buffer(idx);
87 }
88