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 
26 	/* Network interfaces start at 1 */
27 	if (idx == 0) {
28 		return "";
29 	}
30 
31 	if (!iface) {
32 		return NULL;
33 	}
34 
35 	snprintk(iface_index_buffer[idx - 1], MAX_IFACE_STR_LEN, "%d", (uint8_t)idx);
36 
37 	return iface_index_buffer[idx - 1];
38 }
39 
set_iface_index_help(size_t idx)40 static char *set_iface_index_help(size_t idx)
41 {
42 	struct net_if *iface = net_if_get_by_index(idx);
43 
44 	/* Network interfaces start at 1 */
45 	if (idx == 0) {
46 		return "";
47 	}
48 
49 	if (!iface) {
50 		return NULL;
51 	}
52 
53 #if defined(CONFIG_NET_INTERFACE_NAME)
54 	char name[CONFIG_NET_INTERFACE_NAME_LEN + 1];
55 
56 	net_if_get_name(iface, name, CONFIG_NET_INTERFACE_NAME_LEN);
57 	name[CONFIG_NET_INTERFACE_NAME_LEN] = '\0';
58 
59 	snprintk(iface_help_buffer[idx - 1], MAX_IFACE_HELP_STR_LEN,
60 		 "%s [%s] (%p)", name, iface2str(iface, NULL), iface);
61 #else
62 	snprintk(iface_help_buffer[idx - 1], MAX_IFACE_HELP_STR_LEN,
63 		 "[%s] (%p)", iface2str(iface, NULL), iface);
64 #endif
65 
66 	return iface_help_buffer[idx - 1];
67 }
68 
iface_index_get(size_t idx,struct shell_static_entry * entry)69 static void iface_index_get(size_t idx, struct shell_static_entry *entry)
70 {
71 	entry->handler = NULL;
72 	entry->help  = set_iface_index_help(idx);
73 	entry->subcmd = &iface_index;
74 	entry->syntax = set_iface_index_buffer(idx);
75 }
76