diff options
| author | Michael Biebl <biebl@debian.org> | 2021-10-01 23:05:04 +0200 |
|---|---|---|
| committer | Michael Biebl <biebl@debian.org> | 2021-10-01 23:05:04 +0200 |
| commit | e74c568b07b50b97873fb4ee1d776dedefbd54d6 (patch) | |
| tree | 3469f17ea9af91f7ff169b890633bda68b0cf76e /src/nmcli | |
| parent | bfe522304da217296e2a61040f58e35ec5d6f3f2 (diff) | |
New upstream version 1.32.12 upstream/1.32.12
Diffstat (limited to 'src/nmcli')
| -rw-r--r-- | src/nmcli/agent.c | 230 | ||||
| -rw-r--r-- | src/nmcli/common.c | 1470 | ||||
| -rw-r--r-- | src/nmcli/common.h | 77 | ||||
| -rw-r--r-- | src/nmcli/connections.c | 9654 | ||||
| -rw-r--r-- | src/nmcli/connections.h | 29 | ||||
| -rw-r--r-- | src/nmcli/devices.c | 5050 | ||||
| -rw-r--r-- | src/nmcli/devices.h | 37 | ||||
| -rw-r--r-- | src/nmcli/general.c | 1618 | ||||
| -rw-r--r-- | src/nmcli/generate-docs-nm-settings-nmcli.c | 71 | ||||
| -rw-r--r-- | src/nmcli/generate-docs-nm-settings-nmcli.xml | 1143 | ||||
| -rw-r--r-- | src/nmcli/generate-docs-nm-settings-nmcli.xml.in | 1143 | ||||
| -rw-r--r-- | src/nmcli/meson.build | 97 | ||||
| -rw-r--r-- | src/nmcli/nmcli-completion | 116 | ||||
| -rw-r--r-- | src/nmcli/nmcli.c | 1051 | ||||
| -rw-r--r-- | src/nmcli/nmcli.h | 197 | ||||
| -rw-r--r-- | src/nmcli/polkit-agent.c | 96 | ||||
| -rw-r--r-- | src/nmcli/polkit-agent.h | 16 | ||||
| -rw-r--r-- | src/nmcli/settings.c | 762 | ||||
| -rw-r--r-- | src/nmcli/settings.h | 37 | ||||
| -rw-r--r-- | src/nmcli/utils.c | 1821 | ||||
| -rw-r--r-- | src/nmcli/utils.h | 372 |
21 files changed, 25087 insertions, 0 deletions
diff --git a/src/nmcli/agent.c b/src/nmcli/agent.c new file mode 100644 index 00000000..a0b23dd1 --- /dev/null +++ b/src/nmcli/agent.c @@ -0,0 +1,230 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2014 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include <stdio.h> +#include <stdlib.h> +#include <readline/readline.h> +#include <readline/history.h> + +#include "common.h" +#include "utils.h" +#include "libnmc-base/nm-secret-agent-simple.h" +#include "polkit-agent.h" +#include "libnmc-base/nm-polkit-listener.h" + +static void +usage(void) +{ + g_printerr(_("Usage: nmcli agent { COMMAND | help }\n\n" + "COMMAND := { secret | polkit | all }\n\n")); +} + +static void +usage_agent_secret(void) +{ + g_printerr(_("Usage: nmcli agent secret { help }\n" + "\n" + "Runs nmcli as NetworkManager secret agent. When NetworkManager requires\n" + "a password it asks registered agents for it. This command keeps nmcli running\n" + "and if a password is required asks the user for it.\n\n")); +} + +static void +usage_agent_polkit(void) +{ + g_printerr(_("Usage: nmcli agent polkit { help }\n" + "\n" + "Registers nmcli as a polkit action for the user session.\n" + "When a polkit daemon requires an authorization, nmcli asks the user and gives\n" + "the response back to polkit.\n\n")); +} + +static void +usage_agent_all(void) +{ + g_printerr(_("Usage: nmcli agent all { help }\n" + "\n" + "Runs nmcli as both NetworkManager secret and a polkit agent.\n\n")); +} + +/* for pre-filling a string to readline prompt */ +static char *pre_input_deftext; +static int +set_deftext(void) +{ + if (pre_input_deftext && rl_startup_hook) { + rl_insert_text(pre_input_deftext); + g_free(pre_input_deftext); + pre_input_deftext = NULL; + rl_startup_hook = NULL; + } + return 0; +} + +static gboolean +get_secrets_from_user(const NmcConfig *nmc_config, + const char * request_id, + const char * title, + const char * msg, + GPtrArray * secrets) +{ + int i; + + for (i = 0; i < secrets->len; i++) { + NMSecretAgentSimpleSecret *secret = secrets->pdata[i]; + char * pwd = NULL; + + /* Ask user for the password */ + if (msg) + g_print("%s\n", msg); + if (secret->value) { + /* Prefill the password if we have it. */ + rl_startup_hook = set_deftext; + pre_input_deftext = g_strdup(secret->value); + } + if (secret->no_prompt_entry_id) + pwd = nmc_readline(nmc_config, "%s: ", secret->pretty_name); + else + pwd = nmc_readline(nmc_config, "%s (%s): ", secret->pretty_name, secret->entry_id); + + /* No password provided, cancel the secrets. */ + if (!pwd) + return FALSE; + g_free(secret->value); + secret->value = pwd; + } + return TRUE; +} + +static void +secrets_requested(NMSecretAgentSimple *agent, + const char * request_id, + const char * title, + const char * msg, + GPtrArray * secrets, + gpointer user_data) +{ + NmCli * nmc = user_data; + gboolean success; + + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + nmc_terminal_erase_line(); + + success = get_secrets_from_user(&nmc->nmc_config, request_id, title, msg, secrets); + nm_secret_agent_simple_response(agent, request_id, success ? secrets : NULL); +} + +static void +do_agent_secret(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) + return; + + /* Create secret agent */ + nmc->secret_agent = nm_secret_agent_simple_new("nmcli-agent"); + if (nmc->secret_agent) { + /* We keep running */ + nmc->should_wait++; + + nm_secret_agent_simple_enable(nmc->secret_agent, NULL); + g_signal_connect(nmc->secret_agent, + NM_SECRET_AGENT_SIMPLE_REQUEST_SECRETS, + G_CALLBACK(secrets_requested), + nmc); + g_print(_("nmcli successfully registered as a NetworkManager's secret agent.\n")); + } else { + g_string_printf(nmc->return_text, _("Error: secret agent initialization failed")); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } +} + +static void +polkit_registered(gpointer instance, gpointer user_data) +{ + g_print(_("nmcli successfully registered as a polkit agent.\n")); +} + +static void +polkit_error(gpointer instance, const char *error, gpointer user_data) +{ + g_main_loop_quit(loop); +} + +static void +do_agent_polkit(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gs_free_error GError *error = NULL; + + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) + return; + + if (!nmc_polkit_agent_init(nmc, TRUE, &error)) { + g_dbus_error_strip_remote_error(error); + g_string_printf(nmc->return_text, + _("Error: polkit agent initialization failed: %s"), + error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } else { + /* We keep running */ + nmc->should_wait++; + g_signal_connect(nmc->pk_listener, + NM_POLKIT_LISTENER_SIGNAL_ERROR, + G_CALLBACK(polkit_error), + NULL); + g_signal_connect(nmc->pk_listener, + NM_POLKIT_LISTENER_SIGNAL_REGISTERED, + G_CALLBACK(polkit_registered), + NULL); + + /* keep running */ + nmc->should_wait++; + } +} + +static void +do_agent_all(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMCResultCode r; + + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) + return; + + /* Run both secret and polkit agent */ + do_agent_secret(cmd, nmc, argc, argv); + r = nmc->return_value; + if (r != NMC_RESULT_SUCCESS) { + g_printerr("%s\n", nmc->return_text->str); + g_string_truncate(nmc->return_text, 0); + nmc->return_value = NMC_RESULT_SUCCESS; + } + + do_agent_polkit(cmd, nmc, argc, argv); + if (nmc->return_value != NMC_RESULT_SUCCESS) { + g_printerr("%s\n", nmc->return_text->str); + g_string_truncate(nmc->return_text, 0); + } + + if (r != NMC_RESULT_SUCCESS) + nmc->return_value = r; +} + +void +nmc_command_func_agent(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + static const NMCCommand cmds[] = { + {"secret", do_agent_secret, usage_agent_secret, TRUE, TRUE}, + {"polkit", do_agent_polkit, usage_agent_polkit, TRUE, TRUE}, + {"all", do_agent_all, usage_agent_all, TRUE, TRUE}, + {NULL, do_agent_all, usage, TRUE, TRUE}, + }; + + next_arg(nmc, &argc, &argv, NULL); + nmc_do_cmd(nmc, cmds, *argv, argc, argv); +} diff --git a/src/nmcli/common.c b/src/nmcli/common.c new file mode 100644 index 00000000..a01a2f72 --- /dev/null +++ b/src/nmcli/common.c @@ -0,0 +1,1470 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2012 - 2018 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include "common.h" + +#include <stdio.h> +#include <stdlib.h> +#include <sys/ioctl.h> +#include <readline/readline.h> +#include <readline/history.h> + +#include "libnm-client-aux-extern/nm-libnm-aux.h" + +#include "libnmc-base/nm-vpn-helpers.h" +#include "libnmc-base/nm-client-utils.h" +#include "libnm-glib-aux/nm-secret-utils.h" + +#include "utils.h" + +/*****************************************************************************/ + +static char ** +_ip_config_get_routes(NMIPConfig *cfg) +{ + gs_unref_hashtable GHashTable *hash = NULL; + GPtrArray * ptr_array; + char ** arr; + guint i; + + ptr_array = nm_ip_config_get_routes(cfg); + if (!ptr_array) + return NULL; + + if (ptr_array->len == 0) + return NULL; + + arr = g_new(char *, ptr_array->len + 1); + for (i = 0; i < ptr_array->len; i++) { + NMIPRoute * route = g_ptr_array_index(ptr_array, i); + gs_strfreev char **names = NULL; + gsize j; + GString * str; + guint64 metric; + gs_free char * attributes = NULL; + + str = g_string_new(NULL); + g_string_append_printf( + str, + "dst = %s/%u, nh = %s", + nm_ip_route_get_dest(route), + nm_ip_route_get_prefix(route), + nm_ip_route_get_next_hop(route) + ?: (nm_ip_route_get_family(route) == AF_INET ? "0.0.0.0" : "::")); + + metric = nm_ip_route_get_metric(route); + if (metric != -1) { + g_string_append_printf(str, ", mt = %u", (guint) metric); + } + + names = nm_ip_route_get_attribute_names(route); + if (names[0]) { + if (!hash) + hash = g_hash_table_new(nm_str_hash, g_str_equal); + else + g_hash_table_remove_all(hash); + + for (j = 0; names[j]; j++) + g_hash_table_insert(hash, names[j], nm_ip_route_get_attribute(route, names[j])); + + attributes = nm_utils_format_variant_attributes(hash, ',', '='); + if (attributes) { + g_string_append(str, ", "); + g_string_append(str, attributes); + } + } + + arr[i] = g_string_free(str, FALSE); + } + + nm_assert(i == ptr_array->len); + arr[i] = NULL; + + return arr; +} + +/*****************************************************************************/ + +static gconstpointer _metagen_ip4_config_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMIPConfig * cfg4 = target; + GPtrArray * ptr_array; + char ** arr; + const char *const *arrc; + guint i = 0; + const char * str; + + nm_assert(info->info_type < _NMC_GENERIC_INFO_TYPE_IP4_CONFIG_NUM); + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + NM_SET_OUT(out_is_default, TRUE); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_IP4_CONFIG_ADDRESS: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + ptr_array = nm_ip_config_get_addresses(cfg4); + if (ptr_array) { + arr = g_new(char *, ptr_array->len + 1); + for (i = 0; i < ptr_array->len; i++) { + NMIPAddress *addr = g_ptr_array_index(ptr_array, i); + + arr[i] = g_strdup_printf("%s/%u", + nm_ip_address_get_address(addr), + nm_ip_address_get_prefix(addr)); + } + arr[i] = NULL; + } else + arr = NULL; + goto arr_out; + case NMC_GENERIC_INFO_TYPE_IP4_CONFIG_GATEWAY: + str = nm_ip_config_get_gateway(cfg4); + NM_SET_OUT(out_is_default, !str); + return str; + case NMC_GENERIC_INFO_TYPE_IP4_CONFIG_ROUTE: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arr = _ip_config_get_routes(cfg4); + goto arr_out; + case NMC_GENERIC_INFO_TYPE_IP4_CONFIG_DNS: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arrc = nm_ip_config_get_nameservers(cfg4); + goto arrc_out; + case NMC_GENERIC_INFO_TYPE_IP4_CONFIG_DOMAIN: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arrc = nm_ip_config_get_domains(cfg4); + goto arrc_out; + case NMC_GENERIC_INFO_TYPE_IP4_CONFIG_SEARCHES: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arrc = nm_ip_config_get_searches(cfg4); + goto arrc_out; + case NMC_GENERIC_INFO_TYPE_IP4_CONFIG_WINS: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arrc = nm_ip_config_get_wins_servers(cfg4); + goto arrc_out; + default: + break; + } + + g_return_val_if_reached(NULL); + +arrc_out: + NM_SET_OUT(out_is_default, !arrc || !arrc[0]); + *out_flags |= NM_META_ACCESSOR_GET_OUT_FLAGS_STRV; + return arrc; + +arr_out: + NM_SET_OUT(out_is_default, !arr || !arr[0]); + *out_flags |= NM_META_ACCESSOR_GET_OUT_FLAGS_STRV; + *out_to_free = arr; + return arr; +} + +const NmcMetaGenericInfo *const metagen_ip4_config[_NMC_GENERIC_INFO_TYPE_IP4_CONFIG_NUM + 1] = { +#define _METAGEN_IP4_CONFIG(type, name) \ + [type] = NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_ip4_config_get_fcn) + _METAGEN_IP4_CONFIG(NMC_GENERIC_INFO_TYPE_IP4_CONFIG_ADDRESS, "ADDRESS"), + _METAGEN_IP4_CONFIG(NMC_GENERIC_INFO_TYPE_IP4_CONFIG_GATEWAY, "GATEWAY"), + _METAGEN_IP4_CONFIG(NMC_GENERIC_INFO_TYPE_IP4_CONFIG_ROUTE, "ROUTE"), + _METAGEN_IP4_CONFIG(NMC_GENERIC_INFO_TYPE_IP4_CONFIG_DNS, "DNS"), + _METAGEN_IP4_CONFIG(NMC_GENERIC_INFO_TYPE_IP4_CONFIG_DOMAIN, "DOMAIN"), + _METAGEN_IP4_CONFIG(NMC_GENERIC_INFO_TYPE_IP4_CONFIG_SEARCHES, "SEARCHES"), + _METAGEN_IP4_CONFIG(NMC_GENERIC_INFO_TYPE_IP4_CONFIG_WINS, "WINS"), +}; + +/*****************************************************************************/ + +static gconstpointer _metagen_ip6_config_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMIPConfig * cfg6 = target; + GPtrArray * ptr_array; + char ** arr; + const char *const *arrc; + guint i = 0; + const char * str; + + nm_assert(info->info_type < _NMC_GENERIC_INFO_TYPE_IP6_CONFIG_NUM); + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + NM_SET_OUT(out_is_default, TRUE); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_IP6_CONFIG_ADDRESS: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + ptr_array = nm_ip_config_get_addresses(cfg6); + if (ptr_array) { + arr = g_new(char *, ptr_array->len + 1); + for (i = 0; i < ptr_array->len; i++) { + NMIPAddress *addr = g_ptr_array_index(ptr_array, i); + + arr[i] = g_strdup_printf("%s/%u", + nm_ip_address_get_address(addr), + nm_ip_address_get_prefix(addr)); + } + arr[i] = NULL; + } else + arr = NULL; + goto arr_out; + case NMC_GENERIC_INFO_TYPE_IP6_CONFIG_GATEWAY: + str = nm_ip_config_get_gateway(cfg6); + NM_SET_OUT(out_is_default, !str); + return str; + case NMC_GENERIC_INFO_TYPE_IP6_CONFIG_ROUTE: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arr = _ip_config_get_routes(cfg6); + goto arr_out; + case NMC_GENERIC_INFO_TYPE_IP6_CONFIG_DNS: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arrc = nm_ip_config_get_nameservers(cfg6); + goto arrc_out; + case NMC_GENERIC_INFO_TYPE_IP6_CONFIG_DOMAIN: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arrc = nm_ip_config_get_domains(cfg6); + goto arrc_out; + case NMC_GENERIC_INFO_TYPE_IP6_CONFIG_SEARCHES: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + arrc = nm_ip_config_get_searches(cfg6); + goto arrc_out; + default: + break; + } + + g_return_val_if_reached(NULL); + +arrc_out: + NM_SET_OUT(out_is_default, !arrc || !arrc[0]); + *out_flags |= NM_META_ACCESSOR_GET_OUT_FLAGS_STRV; + return arrc; + +arr_out: + NM_SET_OUT(out_is_default, !arr || !arr[0]); + *out_flags |= NM_META_ACCESSOR_GET_OUT_FLAGS_STRV; + *out_to_free = arr; + return arr; +} + +const NmcMetaGenericInfo *const metagen_ip6_config[_NMC_GENERIC_INFO_TYPE_IP6_CONFIG_NUM + 1] = { +#define _METAGEN_IP6_CONFIG(type, name) \ + [type] = NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_ip6_config_get_fcn) + _METAGEN_IP6_CONFIG(NMC_GENERIC_INFO_TYPE_IP6_CONFIG_ADDRESS, "ADDRESS"), + _METAGEN_IP6_CONFIG(NMC_GENERIC_INFO_TYPE_IP6_CONFIG_GATEWAY, "GATEWAY"), + _METAGEN_IP6_CONFIG(NMC_GENERIC_INFO_TYPE_IP6_CONFIG_ROUTE, "ROUTE"), + _METAGEN_IP6_CONFIG(NMC_GENERIC_INFO_TYPE_IP6_CONFIG_DNS, "DNS"), + _METAGEN_IP6_CONFIG(NMC_GENERIC_INFO_TYPE_IP6_CONFIG_DOMAIN, "DOMAIN"), + _METAGEN_IP6_CONFIG(NMC_GENERIC_INFO_TYPE_IP6_CONFIG_SEARCHES, "SEARCHES"), +}; + +/*****************************************************************************/ + +static gconstpointer _metagen_dhcp_config_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMDhcpConfig *dhcp = target; + guint i; + char ** arr = NULL; + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_DHCP_CONFIG_OPTION: + { + GHashTable * table; + gs_free char **arr2 = NULL; + guint n; + + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + + table = nm_dhcp_config_get_options(dhcp); + if (!table) + goto arr_out; + + arr2 = (char **) nm_utils_strdict_get_keys(table, TRUE, &n); + if (!n) + goto arr_out; + + nm_assert(arr2 && !arr2[n] && n == NM_PTRARRAY_LEN(arr2)); + for (i = 0; i < n; i++) { + const char *k = arr2[i]; + const char *v; + + nm_assert(k); + v = g_hash_table_lookup(table, k); + arr2[i] = g_strdup_printf("%s = %s", k, v); + } + + arr = g_steal_pointer(&arr2); + goto arr_out; + } + default: + break; + } + + g_return_val_if_reached(NULL); + +arr_out: + NM_SET_OUT(out_is_default, !arr || !arr[0]); + *out_flags |= NM_META_ACCESSOR_GET_OUT_FLAGS_STRV; + *out_to_free = arr; + return arr; +} + +const NmcMetaGenericInfo *const metagen_dhcp_config[_NMC_GENERIC_INFO_TYPE_DHCP_CONFIG_NUM + 1] = { +#define _METAGEN_DHCP_CONFIG(type, name) \ + [type] = NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_dhcp_config_get_fcn) + _METAGEN_DHCP_CONFIG(NMC_GENERIC_INFO_TYPE_DHCP_CONFIG_OPTION, "OPTION"), +}; + +/*****************************************************************************/ + +gboolean +print_ip_config(NMIPConfig * cfg, + int addr_family, + const NmcConfig *nmc_config, + const char * one_field) +{ + gs_free_error GError *error = NULL; + gs_free char * field_str = NULL; + + if (!cfg) + return FALSE; + + if (one_field) { + field_str = + g_strdup_printf("IP%c.%s", nm_utils_addr_family_to_char(addr_family), one_field); + } + + if (!nmc_print(nmc_config, + (gpointer[]){cfg, NULL}, + NULL, + NULL, + addr_family == AF_INET + ? NMC_META_GENERIC_GROUP("IP4", metagen_ip4_config, N_("GROUP")) + : NMC_META_GENERIC_GROUP("IP6", metagen_ip6_config, N_("GROUP")), + field_str, + &error)) { + return FALSE; + } + return TRUE; +} + +gboolean +print_dhcp_config(NMDhcpConfig * dhcp, + int addr_family, + const NmcConfig *nmc_config, + const char * one_field) +{ + gs_free_error GError *error = NULL; + gs_free char * field_str = NULL; + + if (!dhcp) + return FALSE; + + if (one_field) { + field_str = + g_strdup_printf("DHCP%c.%s", nm_utils_addr_family_to_char(addr_family), one_field); + } + + if (!nmc_print(nmc_config, + (gpointer[]){dhcp, NULL}, + NULL, + NULL, + addr_family == AF_INET + ? NMC_META_GENERIC_GROUP("DHCP4", metagen_dhcp_config, N_("GROUP")) + : NMC_META_GENERIC_GROUP("DHCP6", metagen_dhcp_config, N_("GROUP")), + field_str, + &error)) { + return FALSE; + } + return TRUE; +} + +/* + * nmc_find_connection: + * @connections: array of NMConnections to search in + * @filter_type: "id", "uuid", "path", "filename", or %NULL + * @filter_val: connection to find (connection name, UUID or path) + * @out_result: if not NULL, attach all matching connection to this + * list. If necessary, a new array will be allocated. If the array + * already contains a connection, it will not be added a second time. + * All object are referenced by the array. If the function allocates + * a new array, it will set the free function to g_object_unref. + * @complete: print possible completions + * + * Find a connection in @list according to @filter_val. @filter_type determines + * what property is used for comparison. When @filter_type is NULL, compare + * @filter_val against all types. Otherwise, only compare against the specified + * type. If 'path' filter type is specified, comparison against numeric index + * (in addition to the whole path) is allowed. + * + * Returns: found connection, or %NULL + */ +NMConnection * +nmc_find_connection(const GPtrArray *connections, + const char * filter_type, + const char * filter_val, + GPtrArray ** out_result, + gboolean complete) +{ + NMConnection * best_candidate_uuid = NULL; + NMConnection * best_candidate = NULL; + gs_unref_ptrarray GPtrArray *result_allocated = NULL; + GPtrArray * result = out_result ? *out_result : NULL; + const guint result_inital_len = result ? result->len : 0u; + guint i, j; + + nm_assert(connections); + nm_assert(filter_val); + + for (i = 0; i < connections->len; i++) { + gboolean match_by_uuid = FALSE; + NMConnection *connection; + const char * v; + const char * v_num; + + connection = NM_CONNECTION(connections->pdata[i]); + + if (NM_IN_STRSET(filter_type, NULL, "uuid")) { + v = nm_connection_get_uuid(connection); + if (complete && (filter_type || *filter_val)) + nmc_complete_strings(filter_val, v); + if (nm_streq0(filter_val, v)) { + match_by_uuid = TRUE; + goto found; + } + } + + if (NM_IN_STRSET(filter_type, NULL, "id")) { + v = nm_connection_get_id(connection); + if (complete) + nmc_complete_strings(filter_val, v); + if (nm_streq0(filter_val, v)) + goto found; + } + + if (NM_IN_STRSET(filter_type, NULL, "path")) { + v = nm_connection_get_path(connection); + v_num = nm_utils_dbus_path_get_last_component(v); + if (complete && (filter_type || *filter_val)) + nmc_complete_strings(filter_val, v, (*filter_val ? v_num : NULL)); + if (nm_streq0(filter_val, v) || (filter_type && nm_streq0(filter_val, v_num))) + goto found; + } + + if (NM_IN_STRSET(filter_type, NULL, "filename")) { + v = nm_remote_connection_get_filename(NM_REMOTE_CONNECTION(connections->pdata[i])); + if (complete && (filter_type || *filter_val)) + nmc_complete_strings(filter_val, v); + if (nm_streq0(filter_val, v)) + goto found; + } + + continue; + +found: + if (match_by_uuid) { + if (!complete && !out_result) + return connection; + best_candidate_uuid = connection; + } else { + if (!best_candidate) + best_candidate = connection; + } + if (out_result) { + gboolean already_tracked = FALSE; + + if (!result) { + result_allocated = g_ptr_array_new_with_free_func(g_object_unref); + result = result_allocated; + } else { + for (j = 0; j < result->len; j++) { + if (connection == result->pdata[j]) { + already_tracked = TRUE; + break; + } + } + } + if (!already_tracked) { + if (match_by_uuid) { + /* the profile is matched exactly (by UUID). We prepend it + * to the list of all found profiles. */ + g_ptr_array_insert(result, result_inital_len, g_object_ref(connection)); + } else + g_ptr_array_add(result, g_object_ref(connection)); + } + } + } + + if (result_allocated) + *out_result = g_steal_pointer(&result_allocated); + return best_candidate_uuid ?: best_candidate; +} + +NMActiveConnection * +nmc_find_active_connection(const GPtrArray *active_cons, + const char * filter_type, + const char * filter_val, + GPtrArray ** out_result, + gboolean complete) +{ + guint i, j; + NMActiveConnection *best_candidate = NULL; + GPtrArray * result = out_result ? *out_result : NULL; + + nm_assert(filter_val); + + for (i = 0; i < active_cons->len; i++) { + NMRemoteConnection *con; + NMActiveConnection *candidate = g_ptr_array_index(active_cons, i); + const char * v, *v_num; + + con = nm_active_connection_get_connection(candidate); + + /* When filter_type is NULL, compare connection ID (filter_val) + * against all types. Otherwise, only compare against the specific + * type. If 'path' or 'apath' filter types are specified, comparison + * against numeric index (in addition to the whole path) is allowed. + */ + if (NM_IN_STRSET(filter_type, NULL, "id")) { + v = nm_active_connection_get_id(candidate); + if (complete) + nmc_complete_strings(filter_val, v); + if (nm_streq0(filter_val, v)) + goto found; + } + + if (NM_IN_STRSET(filter_type, NULL, "uuid")) { + v = nm_active_connection_get_uuid(candidate); + if (complete && (filter_type || *filter_val)) + nmc_complete_strings(filter_val, v); + if (nm_streq0(filter_val, v)) + goto found; + } + + if (NM_IN_STRSET(filter_type, NULL, "path")) { + v = con ? nm_connection_get_path(NM_CONNECTION(con)) : NULL; + v_num = nm_utils_dbus_path_get_last_component(v); + if (complete && (filter_type || *filter_val)) + nmc_complete_strings(filter_val, v, filter_type ? v_num : NULL); + if (nm_streq0(filter_val, v) || (filter_type && nm_streq0(filter_val, v_num))) + goto found; + } + + if (NM_IN_STRSET(filter_type, NULL, "filename")) { + v = nm_remote_connection_get_filename(con); + if (complete && (filter_type || *filter_val)) + nmc_complete_strings(filter_val, v); + if (nm_streq0(filter_val, v)) + goto found; + } + + if (NM_IN_STRSET(filter_type, NULL, "apath")) { + v = nm_object_get_path(NM_OBJECT(candidate)); + v_num = nm_utils_dbus_path_get_last_component(v); + if (complete && (filter_type || *filter_val)) + nmc_complete_strings(filter_val, v, filter_type ? v_num : NULL); + if (nm_streq0(filter_val, v) || (filter_type && nm_streq0(filter_val, v_num))) + goto found; + } + + continue; + +found: + if (!out_result) + return candidate; + if (!best_candidate) + best_candidate = candidate; + if (!result) + result = g_ptr_array_new_with_free_func(g_object_unref); + for (j = 0; j < result->len; j++) { + if (candidate == result->pdata[j]) + break; + } + if (j == result->len) + g_ptr_array_add(result, g_object_ref(candidate)); + } + + NM_SET_OUT(out_result, result); + return best_candidate; +} + +static gboolean +vpn_openconnect_get_secrets(NMConnection *connection, GPtrArray *secrets) +{ + GError * error = NULL; + NMSettingVpn *s_vpn; + const char * gw, *port; + gs_free char *cookie = NULL; + gs_free char *gateway = NULL; + gs_free char *gwcert = NULL; + int status = 0; + int i; + gboolean ret; + + if (!connection) + return FALSE; + + if (!nm_connection_is_type(connection, NM_SETTING_VPN_SETTING_NAME)) + return FALSE; + + s_vpn = nm_connection_get_setting_vpn(connection); + if (!nm_streq0(nm_setting_vpn_get_service_type(s_vpn), NM_SECRET_AGENT_VPN_TYPE_OPENCONNECT)) + return FALSE; + + /* Get gateway and port */ + gw = nm_setting_vpn_get_data_item(s_vpn, "gateway"); + port = gw ? strrchr(gw, ':') : NULL; + + /* Interactively authenticate to OpenConnect server and get secrets */ + ret = nm_vpn_openconnect_authenticate_helper(gw, &cookie, &gateway, &gwcert, &status, &error); + if (!ret) { + g_printerr(_("Error: openconnect failed: %s\n"), error->message); + g_clear_error(&error); + return FALSE; + } + + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) != 0) + g_printerr(_("Error: openconnect failed with status %d\n"), WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) + g_printerr(_("Error: openconnect failed with signal %d\n"), WTERMSIG(status)); + + /* Append port to the host value */ + if (gateway && port) { + gs_free char *tmp = gateway; + + gateway = g_strdup_printf("%s%s", tmp, port); + } + + /* Fill secrets to the array */ + for (i = 0; i < secrets->len; i++) { + NMSecretAgentSimpleSecret *secret = secrets->pdata[i]; + + if (secret->secret_type != NM_SECRET_AGENT_SECRET_TYPE_VPN_SECRET) + continue; + if (!nm_streq0(secret->vpn_type, NM_SECRET_AGENT_VPN_TYPE_OPENCONNECT)) + continue; + + if (nm_streq0(secret->entry_id, NM_SECRET_AGENT_ENTRY_ID_PREFX_VPN_SECRETS "cookie")) { + g_free(secret->value); + secret->value = g_steal_pointer(&cookie); + } else if (nm_streq0(secret->entry_id, + NM_SECRET_AGENT_ENTRY_ID_PREFX_VPN_SECRETS "gateway")) { + g_free(secret->value); + secret->value = g_steal_pointer(&gateway); + } else if (nm_streq0(secret->entry_id, + NM_SECRET_AGENT_ENTRY_ID_PREFX_VPN_SECRETS "gwcert")) { + g_free(secret->value); + secret->value = g_steal_pointer(&gwcert); + } + } + + return TRUE; +} + +static gboolean +get_secrets_from_user(const NmcConfig *nmc_config, + const char * request_id, + const char * title, + const char * msg, + NMConnection * connection, + gboolean ask, + GHashTable * pwds_hash, + GPtrArray * secrets) +{ + int i; + + /* Check if there is a VPN OpenConnect secret to ask for */ + if (ask) + vpn_openconnect_get_secrets(connection, secrets); + + for (i = 0; i < secrets->len; i++) { + NMSecretAgentSimpleSecret *secret = secrets->pdata[i]; + char * pwd = NULL; + + /* First try to find the password in provided passwords file, + * then ask user. */ + if (pwds_hash && (pwd = g_hash_table_lookup(pwds_hash, secret->entry_id))) { + pwd = g_strdup(pwd); + } else { + if (ask) { + gboolean echo_on; + + if (secret->value) { + if (!g_strcmp0(secret->vpn_type, NM_DBUS_INTERFACE ".openconnect")) { + /* Do not present and ask user for openconnect secrets, we already have them */ + continue; + } else { + /* Prefill the password if we have it. */ + rl_startup_hook = nmc_rl_set_deftext; + nmc_rl_pre_input_deftext = g_strdup(secret->value); + } + } + if (msg) + g_print("%s\n", msg); + + echo_on = secret->is_secret ? nmc_config->show_secrets : TRUE; + + if (secret->no_prompt_entry_id) + pwd = nmc_readline_echo(nmc_config, echo_on, "%s: ", secret->pretty_name); + else + pwd = nmc_readline_echo(nmc_config, + echo_on, + "%s (%s): ", + secret->pretty_name, + secret->entry_id); + + if (!pwd) + pwd = g_strdup(""); + } else { + if (msg) + g_print("%s\n", msg); + g_printerr(_("Warning: password for '%s' not given in 'passwd-file' " + "and nmcli cannot ask without '--ask' option.\n"), + secret->entry_id); + } + } + /* No password provided, cancel the secrets. */ + if (!pwd) + return FALSE; + nm_free_secret(secret->value); + secret->value = pwd; + } + return TRUE; +} + +/** + * nmc_secrets_requested: + * @agent: the #NMSecretAgentSimple + * @request_id: request ID, to eventually pass to + * nm_secret_agent_simple_response() + * @title: a title for the password request + * @msg: a prompt message for the password request + * @secrets: (element-type #NMSecretAgentSimpleSecret): array of secrets + * being requested. + * @user_data: user data passed to the function + * + * This function is used as a callback for "request-secrets" signal of + * NMSecretAgentSimpleSecret. +*/ +void +nmc_secrets_requested(NMSecretAgentSimple *agent, + const char * request_id, + const char * title, + const char * msg, + GPtrArray * secrets, + gpointer user_data) +{ + NmCli * nmc = (NmCli *) user_data; + NMConnection * connection = NULL; + char * path, *p; + gboolean success = FALSE; + const GPtrArray *connections; + + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + nmc_terminal_erase_line(); + + /* Find the connection for the request */ + path = g_strdup(request_id); + if (path) { + p = strrchr(path, '/'); + if (p) + *p = '\0'; + connections = nm_client_get_connections(nmc->client); + connection = nmc_find_connection(connections, "path", path, NULL, FALSE); + g_free(path); + } + + success = get_secrets_from_user(&nmc->nmc_config, + request_id, + title, + msg, + connection, + nmc->nmc_config.in_editor || nmc->ask, + nmc->pwds_hash, + secrets); + if (success) + nm_secret_agent_simple_response(agent, request_id, secrets); + else { + /* Unregister our secret agent on failure, so that another agent + * may be tried */ + if (nmc->secret_agent) { + nm_secret_agent_old_unregister(NM_SECRET_AGENT_OLD(nmc->secret_agent), NULL, NULL); + g_clear_object(&nmc->secret_agent); + } + } +} + +char * +nmc_unique_connection_name(const GPtrArray *connections, const char *try_name) +{ + NMConnection *connection; + const char * name; + char * new_name; + unsigned num = 1; + int i = 0; + + new_name = g_strdup(try_name); + while (i < connections->len) { + connection = NM_CONNECTION(connections->pdata[i]); + + name = nm_connection_get_id(connection); + if (g_strcmp0(new_name, name) == 0) { + g_free(new_name); + new_name = g_strdup_printf("%s-%d", try_name, num++); + i = 0; + } else + i++; + } + return new_name; +} + +/* readline state variables */ +static gboolean nmcli_in_readline = FALSE; +static gboolean rl_got_line; +static char * rl_string; + +/** + * nmc_cleanup_readline: + * + * Cleanup readline when nmcli is terminated with a signal. + * It makes sure the terminal is not garbled. + */ +void +nmc_cleanup_readline(void) +{ + rl_free_line_state(); + rl_cleanup_after_signal(); +} + +gboolean +nmc_get_in_readline(void) +{ + return nmcli_in_readline; +} + +void +nmc_set_in_readline(gboolean in_readline) +{ + nmcli_in_readline = in_readline; +} + +static void +readline_cb(char *line) +{ + rl_got_line = TRUE; + rl_string = line; + rl_callback_handler_remove(); +} + +static gboolean +stdin_ready_cb(int fd, GIOCondition condition, gpointer data) +{ + rl_callback_read_char(); + return TRUE; +} + +static char * +nmc_readline_helper(const NmcConfig *nmc_config, const char *prompt) +{ + GSource *io_source; + + nmc_set_in_readline(TRUE); + + io_source = nm_g_unix_fd_source_new(STDIN_FILENO, + G_IO_IN, + G_PRIORITY_DEFAULT, + stdin_ready_cb, + NULL, + NULL); + g_source_attach(io_source, NULL); + +read_again: + rl_string = NULL; + rl_got_line = FALSE; + rl_callback_handler_install(prompt, readline_cb); + + while (!rl_got_line && g_main_loop_is_running(loop) && !nmc_seen_sigint()) + g_main_context_iteration(NULL, TRUE); + + /* If Ctrl-C was detected, complete the line */ + if (nmc_seen_sigint()) { + rl_echo_signal_char(SIGINT); + if (!rl_got_line) { + rl_stuff_char('\n'); + rl_callback_read_char(); + } + } + + /* Add string to the history */ + if (rl_string && *rl_string) + add_history(rl_string); + + if (nmc_seen_sigint()) { + /* Ctrl-C */ + nmc_clear_sigint(); + if (nmc_config->in_editor || (rl_string && *rl_string)) { + /* In editor, or the line is not empty */ + /* Call readline again to get new prompt (repeat) */ + g_free(rl_string); + goto read_again; + } else { + /* Not in editor and line is empty, exit */ + nmc_exit(); + } + } else if (!rl_string) { + /* Ctrl-D, exit */ + nmc_exit(); + } + + /* Return NULL, not empty string */ + if (rl_string && *rl_string == '\0') { + g_free(rl_string); + rl_string = NULL; + } + + nm_clear_g_source_inst(&io_source); + + nmc_set_in_readline(FALSE); + + return rl_string; +} + +/** + * nmc_readline: + * @prompt_fmt: prompt to print (telling user what to enter). It is standard + * printf() format string + * @...: a list of arguments according to the @prompt_fmt format string + * + * Wrapper around libreadline's readline() function. + * If user pressed Ctrl-C, readline() is called again (if not in editor and + * line is empty, nmcli will quit). + * If user pressed Ctrl-D on empty line, nmcli will quit. + * + * Returns: the user provided string. In case the user entered empty string, + * this function returns NULL. + */ +char * +nmc_readline(const NmcConfig *nmc_config, const char *prompt_fmt, ...) +{ + va_list args; + gs_free char *prompt = NULL; + + rl_initialize(); + + va_start(args, prompt_fmt); + prompt = g_strdup_vprintf(prompt_fmt, args); + va_end(args); + return nmc_readline_helper(nmc_config, prompt); +} + +static void +nmc_secret_redisplay(void) +{ + int save_point = rl_point; + int save_end = rl_end; + char * save_line_buffer = rl_line_buffer; + const char *subst = nmc_password_subst_char(); + int subst_len = strlen(subst); + int i; + + rl_point = g_utf8_strlen(save_line_buffer, save_point) * subst_len; + rl_end = g_utf8_strlen(rl_line_buffer, -1) * subst_len; + rl_line_buffer = g_slice_alloc(rl_end + 1); + + for (i = 0; i + subst_len <= rl_end; i += subst_len) + memcpy(&rl_line_buffer[i], subst, subst_len); + rl_line_buffer[i] = '\0'; + + rl_redisplay(); + g_slice_free1(rl_end + 1, rl_line_buffer); + rl_line_buffer = save_line_buffer; + rl_end = save_end; + rl_point = save_point; +} + +/** + * nmc_readline_echo: + * + * The same as nmc_readline() except it can disable echoing of input characters if @echo_on is %FALSE. + * nmc_readline(TRUE, ...) == nmc_readline(...) + */ +char * +nmc_readline_echo(const NmcConfig *nmc_config, gboolean echo_on, const char *prompt_fmt, ...) +{ + va_list args; + gs_free char *prompt = NULL; + char * str; + nm_auto_free HISTORY_STATE *saved_history = NULL; + HISTORY_STATE passwd_history = { + 0, + }; + + va_start(args, prompt_fmt); + prompt = g_strdup_vprintf(prompt_fmt, args); + va_end(args); + + rl_initialize(); + + /* Hide the actual password */ + if (!echo_on) { + saved_history = history_get_history_state(); + history_set_history_state(&passwd_history); + /* stifling history is important as it tells readline to + * not store anything, otherwise sensitive data could be + * leaked */ + stifle_history(0); + rl_redisplay_function = nmc_secret_redisplay; + } + + str = nmc_readline_helper(nmc_config, prompt); + + /* Restore the non-hiding behavior */ + if (!echo_on) { + rl_redisplay_function = rl_redisplay; + history_set_history_state(saved_history); + } + + return str; +} + +/** + * nmc_rl_gen_func_basic: + * @text: text to complete + * @state: readline state; says whether start from scratch (state == 0) + * @words: strings for completion + * + * Basic function generating list of completion strings for readline. + * See e.g. http://cnswww.cns.cwru.edu/php/chet/readline/readline.html#SEC49 + */ +char * +nmc_rl_gen_func_basic(const char *text, int state, const char *const *words) +{ + static int list_idx, len; + const char *name; + + if (!state) { + list_idx = 0; + len = strlen(text); + } + + /* Return the next name which partially matches one from the 'words' list. */ + while ((name = words[list_idx])) { + list_idx++; + + if (strncmp(name, text, len) == 0) + return g_strdup(name); + } + return NULL; +} + +static struct { + bool initialized; + guint idx; + char **values; +} _rl_compentry_func_wrap = {0}; + +static char * +_rl_compentry_func_wrap_fcn(const char *text, int state) +{ + g_return_val_if_fail(_rl_compentry_func_wrap.initialized, NULL); + + while (_rl_compentry_func_wrap.values + && _rl_compentry_func_wrap.values[_rl_compentry_func_wrap.idx] + && !g_str_has_prefix(_rl_compentry_func_wrap.values[_rl_compentry_func_wrap.idx], text)) + _rl_compentry_func_wrap.idx++; + + if (!_rl_compentry_func_wrap.values + || !_rl_compentry_func_wrap.values[_rl_compentry_func_wrap.idx]) { + g_strfreev(_rl_compentry_func_wrap.values); + _rl_compentry_func_wrap.values = NULL; + _rl_compentry_func_wrap.initialized = FALSE; + return NULL; + } + + return g_strdup(_rl_compentry_func_wrap.values[_rl_compentry_func_wrap.idx++]); +} + +NmcCompEntryFunc +nmc_rl_compentry_func_wrap(const char *const *values) +{ + g_strfreev(_rl_compentry_func_wrap.values); + _rl_compentry_func_wrap.values = g_strdupv((char **) values); + _rl_compentry_func_wrap.idx = 0; + _rl_compentry_func_wrap.initialized = TRUE; + return _rl_compentry_func_wrap_fcn; +} + +char * +nmc_rl_gen_func_ifnames(const char *text, int state) +{ + int i; + const GPtrArray *devices; + const char ** ifnames; + char * ret; + + devices = nm_client_get_devices(nm_cli_global_readline->client); + if (devices->len == 0) + return NULL; + + ifnames = g_new(const char *, devices->len + 1); + for (i = 0; i < devices->len; i++) { + NMDevice * dev = g_ptr_array_index(devices, i); + const char *ifname = nm_device_get_iface(dev); + ifnames[i] = ifname; + } + ifnames[i] = NULL; + + ret = nmc_rl_gen_func_basic(text, state, ifnames); + + g_free(ifnames); + return ret; +} + +/* for pre-filling a string to readline prompt */ +char *nmc_rl_pre_input_deftext; + +int +nmc_rl_set_deftext(void) +{ + if (nmc_rl_pre_input_deftext && rl_startup_hook) { + rl_insert_text(nmc_rl_pre_input_deftext); + g_free(nmc_rl_pre_input_deftext); + nmc_rl_pre_input_deftext = NULL; + rl_startup_hook = NULL; + } + return 0; +} + +/** + * nmc_parse_lldp_capabilities: + * @value: the capabilities value + * + * Parses LLDP capabilities flags + * + * Returns: a newly allocated string containing capabilities names separated by commas. + */ +char * +nmc_parse_lldp_capabilities(guint value) +{ + /* IEEE Std 802.1AB-2009 - Table 8.4 */ + const char *names[] = {"other", + "repeater", + "mac-bridge", + "wlan-access-point", + "router", + "telephone", + "docsis-cable-device", + "station-only", + "c-vlan-component", + "s-vlan-component", + "tpmr"}; + gboolean first = TRUE; + GString * str; + int i; + + if (!value) + return g_strdup("none"); + + str = g_string_new(""); + + for (i = 0; i < G_N_ELEMENTS(names); i++) { + if (value & (1 << i)) { + if (!first) + g_string_append_c(str, ','); + + first = FALSE; + value &= ~(1 << i); + g_string_append(str, names[i]); + } + } + + if (value) { + if (!first) + g_string_append_c(str, ','); + g_string_append(str, "reserved"); + } + + return g_string_free(str, FALSE); +} + +static void +command_done(GObject *object, GAsyncResult *res, gpointer user_data) +{ + GTask * task = G_TASK(res); + NmCli * nmc = user_data; + gs_free_error GError *error = NULL; + + if (!g_task_propagate_boolean(task, &error)) { + nmc->return_value = error->code; + g_string_assign(nmc->return_text, error->message); + } + + if (!nmc->should_wait) + g_main_loop_quit(loop); +} + +typedef struct { + const NMCCommand *cmd; + int argc; + char ** argv; + GTask * task; +} CmdCall; + +static void +call_cmd(NmCli *nmc, GTask *task, const NMCCommand *cmd, int argc, const char *const *argv); + +static void +got_client(GObject *source_object, GAsyncResult *res, gpointer user_data) +{ + gs_unref_object GTask *task = NULL; + gs_free_error GError *error = NULL; + CmdCall * call = user_data; + NmCli * nmc; + + nm_assert(NM_IS_CLIENT(source_object)); + + task = g_steal_pointer(&call->task); + nmc = g_task_get_task_data(task); + + nmc->should_wait--; + + if (!g_async_initable_init_finish(G_ASYNC_INITABLE(source_object), res, &error)) { + g_object_unref(source_object); + g_task_return_new_error(task, + NMCLI_ERROR, + NMC_RESULT_ERROR_UNKNOWN, + _("Error: Could not create NMClient object: %s."), + error->message); + } else { + nmc->client = NM_CLIENT(source_object); + call_cmd(nmc, + g_steal_pointer(&task), + call->cmd, + call->argc, + (const char *const *) call->argv); + } + + g_strfreev(call->argv); + nm_g_slice_free(call); +} + +static void +call_cmd(NmCli *nmc, GTask *task, const NMCCommand *cmd, int argc, const char *const *argv) +{ + CmdCall *call; + + if (nmc->client || !cmd->needs_client) { + /* Check whether NetworkManager is running */ + if (cmd->needs_nm_running && !nm_client_get_nm_running(nmc->client)) { + g_task_return_new_error(task, + NMCLI_ERROR, + NMC_RESULT_ERROR_NM_NOT_RUNNING, + _("Error: NetworkManager is not running.")); + } else { + cmd->func(cmd, nmc, argc, argv); + g_task_return_boolean(task, TRUE); + } + + g_object_unref(task); + } else { + nm_assert(nmc->client == NULL); + + nmc->should_wait++; + call = g_slice_new(CmdCall); + *call = (CmdCall){ + .cmd = cmd, + .argc = argc, + .argv = nm_utils_strv_dup(argv, argc, TRUE), + .task = task, + }; + nmc_client_new_async(NULL, + got_client, + call, + NM_CLIENT_INSTANCE_FLAGS, + (guint) NM_CLIENT_INSTANCE_FLAGS_NO_AUTO_FETCH_PERMISSIONS, + NULL); + } +} + +static void +nmc_complete_help(const char *prefix) +{ + nmc_complete_strings(prefix, "help"); + if (*prefix == '-') + nmc_complete_strings(prefix, "-help", "--help"); +} + +/** + * nmc_do_cmd: + * @nmc: Client instance + * @cmds: Command table + * @cmd: Command + * @argc: Argument count + * @argv: Arguments vector. Must be a global variable. + * + * Picks the right callback to handle command from the command table. + * If --help argument follows and the usage callback is specified for the command + * it calls the usage callback. + * + * The command table is terminated with a %NULL command. The terminating + * entry's handlers are called if the command is empty. + * + * The argument vector needs to be a pointer to the global arguments vector that is + * never freed, since the command handler will be called asynchronously and there's + * no callback to free the memory in (for simplicity). + */ +void +nmc_do_cmd(NmCli *nmc, const NMCCommand cmds[], const char *cmd, int argc, const char *const *argv) +{ + const NMCCommand *c; + gs_unref_object GTask *task = NULL; + + task = nm_g_task_new(NULL, NULL, nmc_do_cmd, command_done, nmc); + g_task_set_task_data(task, nmc, NULL); + + if (argc == 0 && nmc->complete) { + g_task_return_boolean(task, TRUE); + return; + } + + if (argc == 1 && nmc->complete) { + for (c = cmds; c->cmd; ++c) { + if (!*cmd || matches(cmd, c->cmd)) + g_print("%s\n", c->cmd); + } + nmc_complete_help(cmd); + g_task_return_boolean(task, TRUE); + return; + } + + for (c = cmds; c->cmd; ++c) { + if (cmd && matches(cmd, c->cmd)) + break; + } + + if (c->cmd) { + /* A valid command was specified. */ + if (c->usage && argc == 2 && nmc->complete) + nmc_complete_help(*(argv + 1)); + if (!nmc->complete && c->usage && nmc_arg_is_help(*(argv + 1))) { + c->usage(); + g_task_return_boolean(task, TRUE); + } else { + call_cmd(nmc, g_steal_pointer(&task), c, argc, (const char *const *) argv); + } + } else if (cmd) { + /* Not a known command. */ + if (nmc_arg_is_help(cmd) && c->usage) { + c->usage(); + g_task_return_boolean(task, TRUE); + } else { + g_task_return_new_error( + task, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: argument '%s' not understood. Try passing --help instead."), + cmd); + } + } else if (c->func) { + /* No command, run the default handler. */ + call_cmd(nmc, g_steal_pointer(&task), c, argc, (const char *const *) argv); + } else { + /* No command and no default handler. */ + g_task_return_new_error(task, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: missing argument. Try passing --help.")); + } +} + +/** + * nmc_complete_strings: + * @prefix: a string to match + * @nargs: the number of elements in @args. Or -1 if @args is a NULL terminated + * strv array. + * @args: the argument list. If @nargs is not -1, then some elements may + * be %NULL to indicate to silently skip the values. + * + * Prints all the matching candidates for completion. Useful when there's + * no better way to suggest completion other than a hardcoded string list. + */ +void +nmc_complete_strv(const char *prefix, gssize nargs, const char *const *args) +{ + gsize i, n; + + if (prefix && !prefix[0]) + prefix = NULL; + + if (nargs < 0) { + nm_assert(nargs == -1); + n = NM_PTRARRAY_LEN(args); + } else + n = (gsize) nargs; + + for (i = 0; i < n; i++) { + const char *candidate = args[i]; + + if (!candidate) + continue; + if (prefix && !matches(prefix, candidate)) + continue; + + g_print("%s\n", candidate); + } +} + +/** + * nmc_complete_bool: + * @prefix: a string to match + * @...: a %NULL-terminated list of candidate strings + * + * Prints all the matching possible boolean values for completion. + */ +void +nmc_complete_bool(const char *prefix) +{ + nmc_complete_strings(prefix, "true", "yes", "on", "false", "no", "off"); +} + +/** + * nmc_error_get_simple_message: + * @error: a GError + * + * Returns a simplified message for some errors hard to understand. + */ +const char * +nmc_error_get_simple_message(GError *error) +{ + /* Return a clear message instead of the obscure D-Bus policy error */ + if (g_error_matches(error, G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED)) + return _("access denied"); + if (g_error_matches(error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)) + return _("NetworkManager is not running"); + else + return error->message; +} + +/*****************************************************************************/ + +NM_UTILS_LOOKUP_STR_DEFINE(nm_connectivity_to_string, + NMConnectivityState, + NM_UTILS_LOOKUP_DEFAULT(N_("unknown")), + NM_UTILS_LOOKUP_ITEM(NM_CONNECTIVITY_NONE, N_("none")), + NM_UTILS_LOOKUP_ITEM(NM_CONNECTIVITY_PORTAL, N_("portal")), + NM_UTILS_LOOKUP_ITEM(NM_CONNECTIVITY_LIMITED, N_("limited")), + NM_UTILS_LOOKUP_ITEM(NM_CONNECTIVITY_FULL, N_("full")), + NM_UTILS_LOOKUP_ITEM_IGNORE(NM_CONNECTIVITY_UNKNOWN), ); diff --git a/src/nmcli/common.h b/src/nmcli/common.h new file mode 100644 index 00000000..a479a455 --- /dev/null +++ b/src/nmcli/common.h @@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2012 - 2014 Red Hat, Inc. + */ + +#ifndef NMC_COMMON_H +#define NMC_COMMON_H + +#include "nmcli.h" +#include "libnmc-base/nm-secret-agent-simple.h" + +gboolean print_ip_config(NMIPConfig * cfg, + int addr_family, + const NmcConfig *nmc_config, + const char * one_field); + +gboolean print_dhcp_config(NMDhcpConfig * dhcp, + int addr_family, + const NmcConfig *nmc_config, + const char * one_field); + +NMConnection *nmc_find_connection(const GPtrArray *connections, + const char * filter_type, + const char * filter_val, + GPtrArray ** out_result, + gboolean complete); + +NMActiveConnection *nmc_find_active_connection(const GPtrArray *active_cons, + const char * filter_type, + const char * filter_val, + GPtrArray ** out_result, + gboolean complete); + +void nmc_secrets_requested(NMSecretAgentSimple *agent, + const char * request_id, + const char * title, + const char * msg, + GPtrArray * secrets, + gpointer user_data); + +char *nmc_unique_connection_name(const GPtrArray *connections, const char *try_name); + +void nmc_cleanup_readline(void); +char *nmc_readline(const NmcConfig *nmc_config, const char *prompt_fmt, ...) G_GNUC_PRINTF(2, 3); +char *nmc_readline_echo(const NmcConfig *nmc_config, gboolean echo_on, const char *prompt_fmt, ...) + G_GNUC_PRINTF(3, 4); +NmcCompEntryFunc nmc_rl_compentry_func_wrap(const char *const *values); +char * nmc_rl_gen_func_basic(const char *text, int state, const char *const *words); +char * nmc_rl_gen_func_ifnames(const char *text, int state); +gboolean nmc_get_in_readline(void); +void nmc_set_in_readline(gboolean in_readline); + +/* for pre-filling a string to readline prompt */ +extern char *nmc_rl_pre_input_deftext; +int nmc_rl_set_deftext(void); + +char *nmc_parse_lldp_capabilities(guint value); + +void +nmc_do_cmd(NmCli *nmc, const NMCCommand cmds[], const char *cmd, int argc, const char *const *argv); + +void nmc_complete_strv(const char *prefix, gssize nargs, const char *const *args); + +#define nmc_complete_strings(prefix, ...) \ + nmc_complete_strv((prefix), NM_NARG(__VA_ARGS__), (const char *const[]){__VA_ARGS__}) + +void nmc_complete_bool(const char *prefix); + +const char *nmc_error_get_simple_message(GError *error); + +extern const NmcMetaGenericInfo *const metagen_ip4_config[]; +extern const NmcMetaGenericInfo *const metagen_ip6_config[]; +extern const NmcMetaGenericInfo *const metagen_dhcp_config[]; + +const char *nm_connectivity_to_string(NMConnectivityState connectivity); + +#endif /* NMC_COMMON_H */ diff --git a/src/nmcli/connections.c b/src/nmcli/connections.c new file mode 100644 index 00000000..9f700cae --- /dev/null +++ b/src/nmcli/connections.c @@ -0,0 +1,9654 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include "connections.h" + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <signal.h> +#include <readline/readline.h> +#include <readline/history.h> +#include <fcntl.h> + +#include "libnm-glib-aux/nm-dbus-aux.h" +#include "libnmc-base/nm-client-utils.h" +#include "libnmc-base/nm-vpn-helpers.h" +#include "libnmc-setting/nm-meta-setting-access.h" +#include "libnmc-base/nm-secret-agent-simple.h" + +#include "utils.h" +#include "common.h" +#include "settings.h" +#include "devices.h" +#include "polkit-agent.h" + +/*****************************************************************************/ + +typedef enum { + PROPERTY_INF_FLAG_NONE = 0x0, + PROPERTY_INF_FLAG_DISABLED = 0x1, /* Don't ask due to runtime decision. */ + PROPERTY_INF_FLAG_ENABLED = + 0x2, /* Override NM_META_PROPERTY_INF_FLAG_DONT_ASK due to runtime decision. */ + PROPERTY_INF_FLAG_ALL = 0x3, +} PropertyInfFlags; + +typedef char *(*CompEntryFunc)(const char *, int); + +typedef struct _OptionInfo { + const NMMetaSettingInfoEditor *setting_info; + const char * property; + const char * option; + gboolean (*check_and_set)(NmCli * nmc, + NMConnection * connection, + const struct _OptionInfo *option, + const char * value, + GError ** error); + CompEntryFunc generator_func; +} OptionInfo; + +/* define some prompts for connection editor */ +#define EDITOR_PROMPT_SETTING _("Setting name? ") +#define EDITOR_PROMPT_PROPERTY _("Property name? ") +#define EDITOR_PROMPT_CON_TYPE _("Enter connection type: ") + +/* define some other prompts */ + +#define PROMPT_CONNECTION _("Connection (name, UUID, or path): ") +#define PROMPT_VPN_CONNECTION _("VPN connection (name, UUID, or path): ") +#define PROMPT_CONNECTIONS _("Connection(s) (name, UUID, or path): ") +#define PROMPT_ACTIVE_CONNECTIONS _("Connection(s) (name, UUID, path or apath): ") + +#define BASE_PROMPT "nmcli> " + +/*****************************************************************************/ + +static NM_UTILS_LOOKUP_STR_DEFINE( + active_connection_state_to_string, + NMActiveConnectionState, + NM_UTILS_LOOKUP_DEFAULT(N_("unknown")), + NM_UTILS_LOOKUP_ITEM(NM_ACTIVE_CONNECTION_STATE_ACTIVATING, N_("activating")), + NM_UTILS_LOOKUP_ITEM(NM_ACTIVE_CONNECTION_STATE_ACTIVATED, N_("activated")), + NM_UTILS_LOOKUP_ITEM(NM_ACTIVE_CONNECTION_STATE_DEACTIVATING, N_("deactivating")), + NM_UTILS_LOOKUP_ITEM(NM_ACTIVE_CONNECTION_STATE_DEACTIVATED, N_("deactivated")), + NM_UTILS_LOOKUP_ITEM_IGNORE(NM_ACTIVE_CONNECTION_STATE_UNKNOWN), ); + +static NM_UTILS_LOOKUP_STR_DEFINE( + vpn_connection_state_to_string, + NMVpnConnectionState, + NM_UTILS_LOOKUP_DEFAULT(N_("unknown")), + NM_UTILS_LOOKUP_ITEM(NM_VPN_CONNECTION_STATE_PREPARE, N_("VPN connecting (prepare)")), + NM_UTILS_LOOKUP_ITEM(NM_VPN_CONNECTION_STATE_NEED_AUTH, + N_("VPN connecting (need authentication)")), + NM_UTILS_LOOKUP_ITEM(NM_VPN_CONNECTION_STATE_CONNECT, N_("VPN connecting")), + NM_UTILS_LOOKUP_ITEM(NM_VPN_CONNECTION_STATE_IP_CONFIG_GET, + N_("VPN connecting (getting IP configuration)")), + NM_UTILS_LOOKUP_ITEM(NM_VPN_CONNECTION_STATE_ACTIVATED, N_("VPN connected")), + NM_UTILS_LOOKUP_ITEM(NM_VPN_CONNECTION_STATE_FAILED, N_("VPN connection failed")), + NM_UTILS_LOOKUP_ITEM(NM_VPN_CONNECTION_STATE_DISCONNECTED, N_("VPN disconnected")), + NM_UTILS_LOOKUP_ITEM_IGNORE(NM_VPN_CONNECTION_STATE_UNKNOWN), ); + +/*****************************************************************************/ + +typedef struct { + NmCli *nmc; + char * orig_id; + char * orig_uuid; + char * new_id; +} AddConnectionInfo; + +static AddConnectionInfo * +_add_connection_info_new(NmCli *nmc, NMConnection *orig_connection, NMConnection *new_connection) +{ + AddConnectionInfo *info; + + info = g_slice_new(AddConnectionInfo); + *info = (AddConnectionInfo){ + .nmc = nmc, + .orig_id = orig_connection ? g_strdup(nm_connection_get_id(orig_connection)) : NULL, + .orig_uuid = orig_connection ? g_strdup(nm_connection_get_uuid(orig_connection)) : NULL, + .new_id = g_strdup(nm_connection_get_id(new_connection)), + }; + return info; +} + +static void +_add_connection_info_free(AddConnectionInfo *info) +{ + g_free(info->orig_id); + g_free(info->orig_uuid); + g_free(info->new_id); + nm_g_slice_free(info); +} + +NM_AUTO_DEFINE_FCN(AddConnectionInfo *, + _nm_auto_free_add_connection_info, + _add_connection_info_free); + +#define nm_auto_free_add_connection_info nm_auto(_nm_auto_free_add_connection_info) + +/*****************************************************************************/ + +/* Essentially a version of nm_setting_connection_get_connection_type() that + * prefers an alias instead of the settings name when in pretty print mode. + * That is so that we print "wifi" instead of "802-11-wireless" in "nmcli c". */ +static const char * +connection_type_to_display(const char *type, NMMetaAccessorGetType get_type) +{ + const NMMetaSettingInfoEditor *editor; + int i; + + nm_assert( + NM_IN_SET(get_type, NM_META_ACCESSOR_GET_TYPE_PRETTY, NM_META_ACCESSOR_GET_TYPE_PARSABLE)); + + if (!type) + return NULL; + + if (get_type != NM_META_ACCESSOR_GET_TYPE_PRETTY) + return type; + + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) { + editor = &nm_meta_setting_infos_editor[i]; + if (nm_streq(type, editor->general->setting_name)) + return editor->alias ?: type; + } + return type; +} + +static int +active_connection_get_state_ord(NMActiveConnection *active) +{ + /* returns an integer related to @active's state, that can be used for sorting + * active connections based on their activation state. */ + if (!active) + return -2; + + switch (nm_active_connection_get_state(active)) { + case NM_ACTIVE_CONNECTION_STATE_UNKNOWN: + return 0; + case NM_ACTIVE_CONNECTION_STATE_DEACTIVATED: + return 1; + case NM_ACTIVE_CONNECTION_STATE_DEACTIVATING: + return 2; + case NM_ACTIVE_CONNECTION_STATE_ACTIVATING: + return 3; + case NM_ACTIVE_CONNECTION_STATE_ACTIVATED: + return 4; + } + return -1; +} + +int +nmc_active_connection_cmp(NMActiveConnection *ac_a, NMActiveConnection *ac_b) +{ + NMSettingIPConfig * s_ip; + NMRemoteConnection *conn; + NMIPConfig * da_ip; + NMIPConfig * db_ip; + int da_num_addrs; + int db_num_addrs; + int cmp = 0; + + /* Non-active sort last. */ + NM_CMP_SELF(ac_a, ac_b); + NM_CMP_DIRECT(active_connection_get_state_ord(ac_b), active_connection_get_state_ord(ac_a)); + + /* Shared connections (likely hotspots) go on the top if possible */ + conn = nm_active_connection_get_connection(ac_a); + s_ip = conn ? nm_connection_get_setting_ip6_config(NM_CONNECTION(conn)) : NULL; + if (s_ip + && strcmp(nm_setting_ip_config_get_method(s_ip), NM_SETTING_IP6_CONFIG_METHOD_SHARED) == 0) + cmp++; + conn = nm_active_connection_get_connection(ac_b); + s_ip = conn ? nm_connection_get_setting_ip6_config(NM_CONNECTION(conn)) : NULL; + if (s_ip + && strcmp(nm_setting_ip_config_get_method(s_ip), NM_SETTING_IP6_CONFIG_METHOD_SHARED) == 0) + cmp--; + NM_CMP_RETURN(cmp); + + conn = nm_active_connection_get_connection(ac_a); + s_ip = conn ? nm_connection_get_setting_ip4_config(NM_CONNECTION(conn)) : NULL; + if (s_ip + && strcmp(nm_setting_ip_config_get_method(s_ip), NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) + cmp++; + conn = nm_active_connection_get_connection(ac_b); + s_ip = conn ? nm_connection_get_setting_ip4_config(NM_CONNECTION(conn)) : NULL; + if (s_ip + && strcmp(nm_setting_ip_config_get_method(s_ip), NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) + cmp--; + NM_CMP_RETURN(cmp); + + /* VPNs go next */ + NM_CMP_DIRECT(!!nm_active_connection_get_vpn(ac_a), !!nm_active_connection_get_vpn(ac_b)); + + /* Default devices are prioritized */ + NM_CMP_DIRECT(nm_active_connection_get_default(ac_a), nm_active_connection_get_default(ac_b)); + + /* Default IPv6 devices are prioritized */ + NM_CMP_DIRECT(nm_active_connection_get_default6(ac_a), nm_active_connection_get_default6(ac_b)); + + /* Sort by number of addresses. */ + da_ip = nm_active_connection_get_ip4_config(ac_a); + da_num_addrs = da_ip ? nm_ip_config_get_addresses(da_ip)->len : 0; + db_ip = nm_active_connection_get_ip4_config(ac_b); + db_num_addrs = db_ip ? nm_ip_config_get_addresses(db_ip)->len : 0; + + da_ip = nm_active_connection_get_ip6_config(ac_a); + da_num_addrs += da_ip ? nm_ip_config_get_addresses(da_ip)->len : 0; + db_ip = nm_active_connection_get_ip6_config(ac_b); + db_num_addrs += db_ip ? nm_ip_config_get_addresses(db_ip)->len : 0; + + NM_CMP_DIRECT(da_num_addrs, db_num_addrs); + + return 0; +} + +static char * +get_ac_device_string(NMActiveConnection *active) +{ + GString * dev_str; + const GPtrArray *devices; + guint i; + + if (!active) + return NULL; + + /* Get devices of the active connection */ + dev_str = g_string_new(NULL); + devices = nm_active_connection_get_devices(active); + for (i = 0; i < devices->len; i++) { + NMDevice * device = g_ptr_array_index(devices, i); + const char *dev_iface = nm_device_get_iface(device); + + if (dev_iface) { + g_string_append(dev_str, dev_iface); + g_string_append_c(dev_str, ','); + } + } + if (dev_str->len > 0) + g_string_truncate(dev_str, dev_str->len - 1); /* Cut off last ',' */ + + return g_string_free(dev_str, FALSE); +} + +/*****************************************************************************/ + +/* FIXME: The same or similar code for VPN info appears also in nm-applet (applet-dialogs.c), + * and in gnome-control-center as well. It could probably be shared somehow. */ + +static const char * +get_vpn_connection_type(NMConnection *connection) +{ + NMSettingVpn *s_vpn; + const char * type, *p; + + s_vpn = nm_connection_get_setting_vpn(connection); + if (!s_vpn) + return NULL; + + /* The service type is in form of "org.freedesktop.NetworkManager.vpnc". + * Extract end part after last dot, e.g. "vpnc" + */ + type = nm_setting_vpn_get_service_type(nm_connection_get_setting_vpn(connection)); + if (!type) + return NULL; + p = strrchr(type, '.'); + return p ? p + 1 : type; +} + +/* VPN parameters can be found at: + * http://git.gnome.org/browse/network-manager-openvpn/tree/src/nm-openvpn-service.h + * http://git.gnome.org/browse/network-manager-vpnc/tree/src/nm-vpnc-service.h + * http://git.gnome.org/browse/network-manager-pptp/tree/src/nm-pptp-service.h + * http://git.gnome.org/browse/network-manager-openconnect/tree/src/nm-openconnect-service.h + * http://git.gnome.org/browse/network-manager-openswan/tree/src/nm-openswan-service.h + * See also 'properties' directory in these plugins. + */ +static const char * +find_vpn_gateway_key(const char *vpn_type) +{ + if (vpn_type) { + if (nm_streq(vpn_type, "openvpn")) + return "remote"; + if (nm_streq(vpn_type, "vpnc")) + return "IPSec gateway"; + if (nm_streq(vpn_type, "pptp")) + return "gateway"; + if (nm_streq(vpn_type, "openconnect")) + return "gateway"; + if (nm_streq(vpn_type, "openswan")) + return "right"; + if (nm_streq(vpn_type, "libreswan")) + return "right"; + if (nm_streq(vpn_type, "ssh")) + return "remote"; + if (nm_streq(vpn_type, "l2tp")) + return "gateway"; + } + return NULL; +} + +static const char * +find_vpn_username_key(const char *vpn_type) +{ + if (vpn_type) { + if (nm_streq(vpn_type, "openvpn")) + return "username"; + if (nm_streq(vpn_type, "vpnc")) + return "Xauth username"; + if (nm_streq(vpn_type, "pptp")) + return "user"; + if (nm_streq(vpn_type, "openconnect")) + return "username"; + if (nm_streq(vpn_type, "openswan")) + return "leftxauthusername"; + if (nm_streq(vpn_type, "libreswan")) + return "leftxauthusername"; + if (nm_streq(vpn_type, "l2tp")) + return "user"; + } + return NULL; +} + +enum VpnDataItem { VPN_DATA_ITEM_GATEWAY, VPN_DATA_ITEM_USERNAME }; + +static const char * +get_vpn_data_item(NMConnection *connection, enum VpnDataItem vpn_data_item) +{ + const char *type; + const char *key = NULL; + + type = get_vpn_connection_type(connection); + + switch (vpn_data_item) { + case VPN_DATA_ITEM_GATEWAY: + key = find_vpn_gateway_key(type); + break; + case VPN_DATA_ITEM_USERNAME: + key = find_vpn_username_key(type); + break; + default: + break; + } + + if (!key) + return NULL; + return nm_setting_vpn_get_data_item(nm_connection_get_setting_vpn(connection), key); +} + +/*****************************************************************************/ + +typedef struct { + NMConnection * connection; + NMActiveConnection *primary_active; + GPtrArray * all_active; + bool show_active_fields; +} MetagenConShowRowData; + +static MetagenConShowRowData * +_metagen_con_show_row_data_new_for_connection(NMRemoteConnection *connection, + gboolean show_active_fields) +{ + MetagenConShowRowData *row_data; + + row_data = g_slice_new0(MetagenConShowRowData); + row_data->connection = g_object_ref(NM_CONNECTION(connection)); + row_data->show_active_fields = show_active_fields; + return row_data; +} + +static MetagenConShowRowData * +_metagen_con_show_row_data_new_for_active_connection(NMRemoteConnection *connection, + NMActiveConnection *active, + gboolean show_active_fields) +{ + MetagenConShowRowData *row_data; + + row_data = g_slice_new0(MetagenConShowRowData); + if (connection) + row_data->connection = g_object_ref(NM_CONNECTION(connection)); + row_data->primary_active = g_object_ref(active); + row_data->show_active_fields = show_active_fields; + return row_data; +} + +static void +_metagen_con_show_row_data_add_active_connection(MetagenConShowRowData *row_data, + NMActiveConnection * active) +{ + if (!row_data->primary_active) { + row_data->primary_active = g_object_ref(active); + return; + } + if (!row_data->all_active) { + row_data->all_active = g_ptr_array_new_with_free_func(g_object_unref); + g_ptr_array_add(row_data->all_active, g_object_ref(row_data->primary_active)); + } + g_ptr_array_add(row_data->all_active, g_object_ref(active)); +} + +static void +_metagen_con_show_row_data_init_primary_active(MetagenConShowRowData *row_data) +{ + NMActiveConnection *ac, *best_ac; + guint i; + + if (!row_data->all_active) + return; + + best_ac = row_data->all_active->pdata[0]; + for (i = 1; i < row_data->all_active->len; i++) { + ac = row_data->all_active->pdata[i]; + + if (active_connection_get_state_ord(ac) > active_connection_get_state_ord(best_ac)) + best_ac = ac; + } + + if (row_data->primary_active != best_ac) { + g_object_unref(row_data->primary_active); + row_data->primary_active = g_object_ref(best_ac); + } + nm_clear_pointer(&row_data->all_active, g_ptr_array_unref); +} + +static void +_metagen_con_show_row_data_destroy(gpointer data) +{ + MetagenConShowRowData *row_data = data; + + if (!row_data) + return; + + g_clear_object(&row_data->connection); + g_clear_object(&row_data->primary_active); + nm_clear_pointer(&row_data->all_active, g_ptr_array_unref); + g_slice_free(MetagenConShowRowData, row_data); +} + +static const char * +_con_show_fcn_get_id(NMConnection *c, NMActiveConnection *ac) +{ + NMSettingConnection *s_con = NULL; + const char * s; + + if (c) + s_con = nm_connection_get_setting_connection(c); + + s = s_con ? nm_setting_connection_get_id(s_con) : NULL; + if (!s && ac) { + /* note that if we have no s_con, that usually means that the user has no permissions + * to see the connection. We still fall to get the ID from the active-connection, + * which exposes it despite the user having no permissions. + * + * That might be unexpected, because the user is shown an ID, which he later + * is unable to resolve in other operations. */ + s = nm_active_connection_get_id(ac); + } + return s; +} + +static const char * +_con_show_fcn_get_type(NMConnection *c, NMActiveConnection *ac, NMMetaAccessorGetType get_type) +{ + NMSettingConnection *s_con = NULL; + const char * s; + + if (c) + s_con = nm_connection_get_setting_connection(c); + + s = s_con ? nm_setting_connection_get_connection_type(s_con) : NULL; + if (!s && ac) { + /* see _con_show_fcn_get_id() for why we fallback to get the value + * from @ac. */ + s = nm_active_connection_get_connection_type(ac); + } + return connection_type_to_display(s, get_type); +} + +static gconstpointer _metagen_con_show_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + const MetagenConShowRowData *row_data = target; + NMConnection * c = row_data->connection; + NMActiveConnection * ac = row_data->primary_active; + NMSettingConnection * s_con = NULL; + const char * s; + char * s_mut; + + NMC_HANDLE_COLOR(nmc_active_connection_state_to_color(ac)); + + if (c) + s_con = nm_connection_get_setting_connection(c); + + if (!row_data->show_active_fields) { + /* we are not supposed to show any fields of the active connection. + * We only tracked the primary_active to get the coloring right. + * From now on, there is no active connection. */ + ac = NULL; + + /* in this mode, we expect that we are called only with connections that + * have a [connection] setting and a UUID. Otherwise, the connection is + * effectively invisible to the user, and should be hidden. + * + * But in that case, we expect that the caller pre-filtered this row out. + * So assert(). */ + nm_assert(s_con); + nm_assert(nm_setting_connection_get_uuid(s_con)); + } + + nm_assert( + NM_IN_SET(get_type, NM_META_ACCESSOR_GET_TYPE_PRETTY, NM_META_ACCESSOR_GET_TYPE_PARSABLE)); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_CON_SHOW_NAME: + return _con_show_fcn_get_id(c, ac); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_UUID: + s = s_con ? nm_setting_connection_get_uuid(s_con) : NULL; + if (!s && ac) { + /* see _con_show_fcn_get_id() for why we fallback to get the value + * from @ac. */ + s = nm_active_connection_get_uuid(ac); + } + return s; + case NMC_GENERIC_INFO_TYPE_CON_SHOW_TYPE: + return _con_show_fcn_get_type(c, ac, get_type); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_TIMESTAMP: + case NMC_GENERIC_INFO_TYPE_CON_SHOW_TIMESTAMP_REAL: + if (!s_con) + return NULL; + { + guint64 timestamp; + time_t timestamp_real; + + timestamp = nm_setting_connection_get_timestamp(s_con); + + if (info->info_type == NMC_GENERIC_INFO_TYPE_CON_SHOW_TIMESTAMP) + return (*out_to_free = g_strdup_printf("%" G_GUINT64_FORMAT, timestamp)); + else { + struct tm localtime_result; + + if (!timestamp) { + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) + return _("never"); + return "never"; + } + timestamp_real = timestamp; + s_mut = g_malloc0(128); + strftime(s_mut, 127, "%c", localtime_r(×tamp_real, &localtime_result)); + return (*out_to_free = s_mut); + } + } + case NMC_GENERIC_INFO_TYPE_CON_SHOW_AUTOCONNECT: + if (!s_con) + return NULL; + return nmc_meta_generic_get_bool(nm_setting_connection_get_autoconnect(s_con), get_type); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_AUTOCONNECT_PRIORITY: + if (!s_con) + return NULL; + return (*out_to_free = + g_strdup_printf("%d", nm_setting_connection_get_autoconnect_priority(s_con))); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_READONLY: + if (!s_con) + return NULL; + return nmc_meta_generic_get_bool(nm_setting_connection_get_read_only(s_con), get_type); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_DBUS_PATH: + if (!c) + return NULL; + return nm_connection_get_path(c); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_ACTIVE: + return nmc_meta_generic_get_bool(!!ac, get_type); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_DEVICE: + if (ac) + return (*out_to_free = get_ac_device_string(ac)); + return NULL; + case NMC_GENERIC_INFO_TYPE_CON_SHOW_STATE: + return nmc_meta_generic_get_str_i18n( + ac ? active_connection_state_to_string(nm_active_connection_get_state(ac)) : NULL, + get_type); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_ACTIVE_PATH: + if (ac) + return nm_object_get_path(NM_OBJECT(ac)); + return NULL; + case NMC_GENERIC_INFO_TYPE_CON_SHOW_SLAVE: + if (!s_con) + return NULL; + return nm_setting_connection_get_slave_type(s_con); + case NMC_GENERIC_INFO_TYPE_CON_SHOW_FILENAME: + if (!NM_IS_REMOTE_CONNECTION(c)) + return NULL; + return nm_remote_connection_get_filename(NM_REMOTE_CONNECTION(c)); + default: + break; + } + + g_return_val_if_reached(NULL); +} + +const NmcMetaGenericInfo *const metagen_con_show[_NMC_GENERIC_INFO_TYPE_CON_SHOW_NUM + 1] = { +#define _METAGEN_CON_SHOW(type, name) \ + [type] = NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_con_show_get_fcn) + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_NAME, "NAME"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_UUID, "UUID"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_TYPE, "TYPE"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_TIMESTAMP, "TIMESTAMP"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_TIMESTAMP_REAL, "TIMESTAMP-REAL"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_AUTOCONNECT, "AUTOCONNECT"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_AUTOCONNECT_PRIORITY, "AUTOCONNECT-PRIORITY"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_READONLY, "READONLY"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_DBUS_PATH, "DBUS-PATH"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_ACTIVE, "ACTIVE"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_DEVICE, "DEVICE"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_STATE, "STATE"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_ACTIVE_PATH, "ACTIVE-PATH"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_SLAVE, "SLAVE"), + _METAGEN_CON_SHOW(NMC_GENERIC_INFO_TYPE_CON_SHOW_FILENAME, "FILENAME"), +}; +#define NMC_FIELDS_CON_SHOW_COMMON "NAME,UUID,TYPE,DEVICE" + +/*****************************************************************************/ + +static gconstpointer _metagen_con_active_general_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMActiveConnection * ac = target; + NMConnection * c; + NMSettingConnection *s_con = NULL; + NMDevice * dev; + guint i; + const char * s; + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + nm_assert( + NM_IN_SET(get_type, NM_META_ACCESSOR_GET_TYPE_PRETTY, NM_META_ACCESSOR_GET_TYPE_PARSABLE)); + + c = NM_CONNECTION(nm_active_connection_get_connection(ac)); + if (c) + s_con = nm_connection_get_setting_connection(c); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_NAME: + return nm_active_connection_get_id(ac); + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_UUID: + return nm_active_connection_get_uuid(ac); + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEVICES: + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_IP_IFACE: + { + GString * str = NULL; + const GPtrArray *devices; + + s = NULL; + devices = nm_active_connection_get_devices(ac); + if (devices) { + for (i = 0; i < devices->len; i++) { + NMDevice * device = g_ptr_array_index(devices, i); + const char *iface; + + if (info->info_type == NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEVICES) { + iface = nm_device_get_iface(device); + } else { + iface = nm_device_get_ip_iface(device); + } + + if (!iface) + continue; + if (!s) { + s = iface; + continue; + } + if (!str) + str = g_string_new(s); + g_string_append_c(str, ','); + g_string_append(str, iface); + } + } + if (str) + return (*out_to_free = g_string_free(str, FALSE)); + return s; + } + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_STATE: + return nmc_meta_generic_get_str_i18n( + active_connection_state_to_string(nm_active_connection_get_state(ac)), + get_type); + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEFAULT: + return nmc_meta_generic_get_bool(nm_active_connection_get_default(ac), get_type); + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEFAULT6: + return nmc_meta_generic_get_bool(nm_active_connection_get_default6(ac), get_type); + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_SPEC_OBJECT: + return nm_active_connection_get_specific_object_path(ac); + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_VPN: + return nmc_meta_generic_get_bool(NM_IS_VPN_CONNECTION(ac), get_type); + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DBUS_PATH: + return nm_object_get_path(NM_OBJECT(ac)); + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_CON_PATH: + return c ? nm_connection_get_path(c) : NULL; + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_ZONE: + /* this is really ugly, because the zone is not a property of the active-connection, + * but the settings-connection profile. There is no guarantee, that they agree. */ + return s_con ? nm_setting_connection_get_zone(s_con) : NULL; + case NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_MASTER_PATH: + dev = nm_active_connection_get_master(ac); + return dev ? nm_object_get_path(NM_OBJECT(dev)) : NULL; + default: + break; + } + + g_return_val_if_reached(NULL); +} + +const NmcMetaGenericInfo + *const metagen_con_active_general[_NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_NUM + 1] = { +#define _METAGEN_CON_ACTIVE_GENERAL(type, name) \ + [type] = \ + NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_con_active_general_get_fcn) + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_NAME, "NAME"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_UUID, "UUID"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEVICES, "DEVICES"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_IP_IFACE, "IP-IFACE"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_STATE, "STATE"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEFAULT, "DEFAULT"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEFAULT6, "DEFAULT6"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_SPEC_OBJECT, + "SPEC-OBJECT"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_VPN, "VPN"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DBUS_PATH, + "DBUS-PATH"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_CON_PATH, "CON-PATH"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_ZONE, "ZONE"), + _METAGEN_CON_ACTIVE_GENERAL(NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_MASTER_PATH, + "MASTER-PATH"), +}; + +/*****************************************************************************/ + +static gconstpointer _metagen_con_active_vpn_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMActiveConnection * ac = target; + NMConnection * c; + NMSettingVpn * s_vpn = NULL; + NMVpnConnectionState vpn_state; + guint i; + const char * s; + char ** arr = NULL; + + nm_assert(NM_IS_VPN_CONNECTION(ac)); + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + nm_assert( + NM_IN_SET(get_type, NM_META_ACCESSOR_GET_TYPE_PRETTY, NM_META_ACCESSOR_GET_TYPE_PARSABLE)); + + c = NM_CONNECTION(nm_active_connection_get_connection(ac)); + if (c) + s_vpn = nm_connection_get_setting_vpn(c); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_CON_VPN_TYPE: + return c ? get_vpn_connection_type(c) : NULL; + case NMC_GENERIC_INFO_TYPE_CON_VPN_USERNAME: + if (s_vpn && (s = nm_setting_vpn_get_user_name(s_vpn))) + return s; + return c ? get_vpn_data_item(c, VPN_DATA_ITEM_USERNAME) : NULL; + case NMC_GENERIC_INFO_TYPE_CON_VPN_GATEWAY: + return c ? get_vpn_data_item(c, VPN_DATA_ITEM_GATEWAY) : NULL; + case NMC_GENERIC_INFO_TYPE_CON_VPN_BANNER: + s = nm_vpn_connection_get_banner(NM_VPN_CONNECTION(ac)); + if (s) + return (*out_to_free = g_strescape(s, "")); + return NULL; + case NMC_GENERIC_INFO_TYPE_CON_VPN_VPN_STATE: + vpn_state = nm_vpn_connection_get_vpn_state(NM_VPN_CONNECTION(ac)); + return (*out_to_free = + nmc_meta_generic_get_enum_with_detail(NMC_META_GENERIC_GET_ENUM_TYPE_DASH, + vpn_state, + vpn_connection_state_to_string(vpn_state), + get_type)); + case NMC_GENERIC_INFO_TYPE_CON_VPN_CFG: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + if (s_vpn) { + gs_free char **arr2 = NULL; + guint n; + + arr2 = (char **) nm_setting_vpn_get_data_keys(s_vpn, &n); + if (!n) + goto arr_out; + + nm_assert(arr2 && !arr2[n]); + for (i = 0; i < n; i++) { + const char *k = arr2[i]; + const char *v; + + nm_assert(k); + v = nm_setting_vpn_get_data_item(s_vpn, k); + /* update the arr array in-place. Previously it contained + * the constant keys, now it contains the strdup'ed output text. */ + arr2[i] = g_strdup_printf("%s = %s", k, v); + } + + arr = g_steal_pointer(&arr2); + } + goto arr_out; + default: + break; + } + + g_return_val_if_reached(NULL); + +arr_out: + NM_SET_OUT(out_is_default, !arr || !arr[0]); + *out_flags |= NM_META_ACCESSOR_GET_OUT_FLAGS_STRV; + *out_to_free = arr; + return arr; +} + +const NmcMetaGenericInfo + *const metagen_con_active_vpn[_NMC_GENERIC_INFO_TYPE_CON_ACTIVE_VPN_NUM + 1] = { +#define _METAGEN_CON_ACTIVE_VPN(type, name) \ + [type] = NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_con_active_vpn_get_fcn) + _METAGEN_CON_ACTIVE_VPN(NMC_GENERIC_INFO_TYPE_CON_VPN_TYPE, "TYPE"), + _METAGEN_CON_ACTIVE_VPN(NMC_GENERIC_INFO_TYPE_CON_VPN_USERNAME, "USERNAME"), + _METAGEN_CON_ACTIVE_VPN(NMC_GENERIC_INFO_TYPE_CON_VPN_GATEWAY, "GATEWAY"), + _METAGEN_CON_ACTIVE_VPN(NMC_GENERIC_INFO_TYPE_CON_VPN_BANNER, "BANNER"), + _METAGEN_CON_ACTIVE_VPN(NMC_GENERIC_INFO_TYPE_CON_VPN_VPN_STATE, "VPN-STATE"), + _METAGEN_CON_ACTIVE_VPN(NMC_GENERIC_INFO_TYPE_CON_VPN_CFG, "CFG"), +}; + +/*****************************************************************************/ + +#define NMC_FIELDS_SETTINGS_NAMES_ALL \ + NM_SETTING_CONNECTION_SETTING_NAME \ + "," NM_SETTING_MATCH_SETTING_NAME "," NM_SETTING_WIRED_SETTING_NAME \ + "," NM_SETTING_VETH_SETTING_NAME "," NM_SETTING_802_1X_SETTING_NAME \ + "," NM_SETTING_WIRELESS_SETTING_NAME "," NM_SETTING_WIRELESS_SECURITY_SETTING_NAME \ + "," NM_SETTING_IP4_CONFIG_SETTING_NAME "," NM_SETTING_IP6_CONFIG_SETTING_NAME \ + "," NM_SETTING_SERIAL_SETTING_NAME "," NM_SETTING_WIFI_P2P_SETTING_NAME \ + "," NM_SETTING_PPP_SETTING_NAME "," NM_SETTING_PPPOE_SETTING_NAME \ + "," NM_SETTING_ADSL_SETTING_NAME "," NM_SETTING_GSM_SETTING_NAME \ + "," NM_SETTING_CDMA_SETTING_NAME "," NM_SETTING_BLUETOOTH_SETTING_NAME \ + "," NM_SETTING_OLPC_MESH_SETTING_NAME "," NM_SETTING_VPN_SETTING_NAME \ + "," NM_SETTING_INFINIBAND_SETTING_NAME "," NM_SETTING_BOND_SETTING_NAME \ + "," NM_SETTING_VLAN_SETTING_NAME "," NM_SETTING_BRIDGE_SETTING_NAME \ + "," NM_SETTING_BRIDGE_PORT_SETTING_NAME "," NM_SETTING_TEAM_SETTING_NAME \ + "," NM_SETTING_TEAM_PORT_SETTING_NAME "," NM_SETTING_OVS_BRIDGE_SETTING_NAME \ + "," NM_SETTING_OVS_INTERFACE_SETTING_NAME "," NM_SETTING_OVS_PATCH_SETTING_NAME \ + "," NM_SETTING_OVS_PORT_SETTING_NAME "," NM_SETTING_DCB_SETTING_NAME \ + "," NM_SETTING_TUN_SETTING_NAME "," NM_SETTING_IP_TUNNEL_SETTING_NAME \ + "," NM_SETTING_MACSEC_SETTING_NAME "," NM_SETTING_MACVLAN_SETTING_NAME \ + "," NM_SETTING_VXLAN_SETTING_NAME "," NM_SETTING_VRF_SETTING_NAME \ + "," NM_SETTING_WPAN_SETTING_NAME "," NM_SETTING_6LOWPAN_SETTING_NAME \ + "," NM_SETTING_WIREGUARD_SETTING_NAME "," NM_SETTING_PROXY_SETTING_NAME \ + "," NM_SETTING_TC_CONFIG_SETTING_NAME "," NM_SETTING_SRIOV_SETTING_NAME \ + "," NM_SETTING_ETHTOOL_SETTING_NAME "," NM_SETTING_OVS_DPDK_SETTING_NAME \ + "," NM_SETTING_HOSTNAME_SETTING_NAME /* NM_SETTING_DUMMY_SETTING_NAME NM_SETTING_WIMAX_SETTING_NAME */ + +const NmcMetaGenericInfo *const nmc_fields_con_active_details_groups[] = { + NMC_META_GENERIC_WITH_NESTED("GENERAL", metagen_con_active_general), /* 0 */ + NMC_META_GENERIC_WITH_NESTED("IP4", metagen_ip4_config), /* 1 */ + NMC_META_GENERIC_WITH_NESTED("DHCP4", metagen_dhcp_config), /* 2 */ + NMC_META_GENERIC_WITH_NESTED("IP6", metagen_ip6_config), /* 3 */ + NMC_META_GENERIC_WITH_NESTED("DHCP6", metagen_dhcp_config), /* 4 */ + NMC_META_GENERIC_WITH_NESTED("VPN", metagen_con_active_vpn), /* 5 */ + NULL, +}; + +/* Pseudo group names for 'connection show <con>' */ +/* e.g.: nmcli -f profile con show my-eth0 */ +/* e.g.: nmcli -f active con show my-eth0 */ +#define CON_SHOW_DETAIL_GROUP_PROFILE "profile" +#define CON_SHOW_DETAIL_GROUP_ACTIVE "active" + +static guint progress_id = 0; /* ID of event source for displaying progress */ + +/* for readline TAB completion in editor */ +typedef struct { + NmCli * nmc; + char * con_type; + NMConnection *connection; + NMSetting * setting; + const char * property; + char ** words; +} TabCompletionInfo; + +static TabCompletionInfo nmc_tab_completion; + +/*****************************************************************************/ + +static void +usage(void) +{ + g_printerr( + _("Usage: nmcli connection { COMMAND | help }\n\n" + "COMMAND := { show | up | down | add | modify | clone | edit | delete | monitor | reload " + "| load | import | export }\n\n" + " show [--active] [--order <order spec>]\n" + " show [--active] [id | uuid | path | apath] <ID> ...\n\n" + " up [[id | uuid | path] <ID>] [ifname <ifname>] [ap <BSSID>] [passwd-file <file with " + "passwords>]\n\n" + " down [id | uuid | path | apath] <ID> ...\n\n" + " add COMMON_OPTIONS TYPE_SPECIFIC_OPTIONS SLAVE_OPTIONS IP_OPTIONS [-- " + "([+|-]<setting>.<property> <value>)+]\n\n" + " modify [--temporary] [id | uuid | path] <ID> ([+|-]<setting>.<property> <value>)+\n\n" + " clone [--temporary] [id | uuid | path ] <ID> <new name>\n\n" + " edit [id | uuid | path] <ID>\n" + " edit [type <new_con_type>] [con-name <new_con_name>]\n\n" + " delete [id | uuid | path] <ID>\n\n" + " monitor [id | uuid | path] <ID> ...\n\n" + " reload\n\n" + " load <filename> [ <filename>... ]\n\n" + " import [--temporary] type <type> file <file to import>\n\n" + " export [id | uuid | path] <ID> [<output file>]\n\n")); +} + +static void +usage_connection_show(void) +{ + g_printerr( + _("Usage: nmcli connection show { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [--active] [--order <order spec>]\n" + "\n" + "List in-memory and on-disk connection profiles, some of which may also be\n" + "active if a device is using that connection profile. Without a parameter, all\n" + "profiles are listed. When --active option is specified, only the active\n" + "profiles are shown. --order allows custom connection ordering (see manual page).\n" + "\n" + "ARGUMENTS := [--active] [id | uuid | path | apath] <ID> ...\n" + "\n" + "Show details for specified connections. By default, both static configuration\n" + "and active connection data are displayed. It is possible to filter the output\n" + "using global '--fields' option. Refer to the manual page for more information.\n" + "When --active option is specified, only the active profiles are taken into\n" + "account. Use global --show-secrets option to reveal associated secrets as well.\n")); +} + +static void +usage_connection_up(void) +{ + g_printerr(_("Usage: nmcli connection up { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [id | uuid | path] <ID> [ifname <ifname>] [ap <BSSID>] [nsp <name>] " + "[passwd-file <file with passwords>]\n" + "\n" + "Activate a connection on a device. The profile to activate is identified by its\n" + "name, UUID or D-Bus path.\n" + "\n" + "ARGUMENTS := ifname <ifname> [ap <BSSID>] [nsp <name>] [passwd-file <file with " + "passwords>]\n" + "\n" + "Activate a device with a connection. The connection profile is selected\n" + "automatically by NetworkManager.\n" + "\n" + "ifname - specifies the device to active the connection on\n" + "ap - specifies AP to connect to (only valid for Wi-Fi)\n" + "nsp - specifies NSP to connect to (only valid for WiMAX)\n" + "passwd-file - file with password(s) required to activate the connection\n\n")); +} + +static void +usage_connection_down(void) +{ + g_printerr(_("Usage: nmcli connection down { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [id | uuid | path | apath] <ID> ...\n" + "\n" + "Deactivate a connection from a device (without preventing the device from\n" + "further auto-activation). The profile to deactivate is identified by its name,\n" + "UUID or D-Bus path.\n\n")); +} + +static void +usage_connection_add(void) +{ + g_printerr(_("Usage: nmcli connection add { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := COMMON_OPTIONS TYPE_SPECIFIC_OPTIONS SLAVE_OPTIONS IP_OPTIONS [-- " + "([+|-]<setting>.<property> <value>)+]\n\n" + " COMMON_OPTIONS:\n" + " type <type>\n" + " ifname <interface name> | \"*\"\n" + " [con-name <connection name>]\n" + " [autoconnect yes|no]\n" + " [save yes|no]\n" + " [master <master (ifname, or connection UUID or name)>]\n" + " [slave-type <master connection type>]\n\n" + " TYPE_SPECIFIC_OPTIONS:\n" + " ethernet: [mac <MAC address>]\n" + " [cloned-mac <cloned MAC address>]\n" + " [mtu <MTU>]\n\n" + " wifi: ssid <SSID>\n" + " [mac <MAC address>]\n" + " [cloned-mac <cloned MAC address>]\n" + " [mtu <MTU>]\n" + " [mode infrastructure|ap|adhoc]\n\n" + " wimax: [mac <MAC address>]\n" + " [nsp <NSP>]\n\n" + " pppoe: username <PPPoE username>\n" + " [password <PPPoE password>]\n" + " [service <PPPoE service name>]\n" + " [mtu <MTU>]\n" + " [mac <MAC address>]\n\n" + " gsm: apn <APN>\n" + " [user <username>]\n" + " [password <password>]\n\n" + " cdma: [user <username>]\n" + " [password <password>]\n\n" + " infiniband: [mac <MAC address>]\n" + " [mtu <MTU>]\n" + " [transport-mode datagram | connected]\n" + " [parent <ifname>]\n" + " [p-key <IPoIB P_Key>]\n\n" + " bluetooth: [addr <bluetooth address>]\n" + " [bt-type panu|nap|dun-gsm|dun-cdma]\n\n" + " vlan: dev <parent device (connection UUID, ifname, or MAC)>\n" + " id <VLAN ID>\n" + " [flags <VLAN flags>]\n" + " [ingress <ingress priority mapping>]\n" + " [egress <egress priority mapping>]\n" + " [mtu <MTU>]\n\n" + " bond: [mode balance-rr (0) | active-backup (1) | balance-xor (2) | " + "broadcast (3) |\n" + " 802.3ad (4) | balance-tlb (5) | balance-alb (6)]\n" + " [primary <ifname>]\n" + " [miimon <num>]\n" + " [downdelay <num>]\n" + " [updelay <num>]\n" + " [arp-interval <num>]\n" + " [arp-ip-target <num>]\n" + " [lacp-rate slow (0) | fast (1)]\n\n" + " bond-slave: master <master (ifname, or connection UUID or name)>\n\n" + " team: [config <file>|<raw JSON data>]\n\n" + " team-slave: master <master (ifname, or connection UUID or name)>\n" + " [config <file>|<raw JSON data>]\n\n" + " bridge: [stp yes|no]\n" + " [priority <num>]\n" + " [forward-delay <2-30>]\n" + " [hello-time <1-10>]\n" + " [max-age <6-40>]\n" + " [ageing-time <0-1000000>]\n" + " [multicast-snooping yes|no]\n" + " [mac <MAC address>]\n\n" + " bridge-slave: master <master (ifname, or connection UUID or name)>\n" + " [priority <0-63>]\n" + " [path-cost <1-65535>]\n" + " [hairpin yes|no]\n\n" + " vpn: vpn-type " + "vpnc|openvpn|pptp|openconnect|openswan|libreswan|ssh|l2tp|iodine|...\n" + " [user <username>]\n\n" + " olpc-mesh: ssid <SSID>\n" + " [channel <1-13>]\n" + " [dhcp-anycast <MAC address>]\n\n" + " adsl: username <username>\n" + " protocol pppoa|pppoe|ipoatm\n" + " [password <password>]\n" + " [encapsulation vcmux|llc]\n\n" + " tun: mode tun|tap\n" + " [owner <UID>]\n" + " [group <GID>]\n" + " [pi yes|no]\n" + " [vnet-hdr yes|no]\n" + " [multi-queue yes|no]\n\n" + " ip-tunnel: mode ipip|gre|sit|isatap|vti|ip6ip6|ipip6|ip6gre|vti6\n" + " remote <remote endpoint IP>\n" + " [local <local endpoint IP>]\n" + " [dev <parent device (ifname or connection UUID)>]\n\n" + " macsec: dev <parent device (connection UUID, ifname, or MAC)>\n" + " mode <psk|eap>\n" + " [cak <key> ckn <key>]\n" + " [encrypt yes|no]\n" + " [port 1-65534]\n\n\n" + " macvlan: dev <parent device (connection UUID, ifname, or MAC)>\n" + " mode vepa|bridge|private|passthru|source\n" + " [tap yes|no]\n\n" + " vxlan: id <VXLAN ID>\n" + " [remote <IP of multicast group or remote address>]\n" + " [local <source IP>]\n" + " [dev <parent device (ifname or connection UUID)>]\n" + " [source-port-min <0-65535>]\n" + " [source-port-max <0-65535>]\n" + " [destination-port <0-65535>]\n\n" + " wpan: [short-addr <0x0000-0xffff>]\n" + " [pan-id <0x0000-0xffff>]\n" + " [page <default|0-31>]\n" + " [channel <default|0-26>]\n" + " [mac <MAC address>]\n\n" + " 6lowpan: dev <parent device (connection UUID, ifname, or MAC)>\n" + " dummy:\n\n" + " SLAVE_OPTIONS:\n" + " bridge: [priority <0-63>]\n" + " [path-cost <1-65535>]\n" + " [hairpin yes|no]\n\n" + " team: [config <file>|<raw JSON data>]\n\n" + " IP_OPTIONS:\n" + " [ip4 <IPv4 address>] [gw4 <IPv4 gateway>]\n" + " [ip6 <IPv6 address>] [gw6 <IPv6 gateway>]\n\n")); +} + +static void +usage_connection_modify(void) +{ + g_printerr( + _("Usage: nmcli connection modify { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [id | uuid | path] <ID> ([+|-]<setting>.<property> <value>)+\n" + "\n" + "Modify one or more properties of the connection profile.\n" + "The profile is identified by its name, UUID or D-Bus path. For multi-valued\n" + "properties you can use optional '+' or '-' prefix to the property name.\n" + "The '+' sign allows appending items instead of overwriting the whole value.\n" + "The '-' sign allows removing selected items instead of the whole value.\n" + "\n" + "ARGUMENTS := remove <setting>\n" + "\n" + "Remove a setting from the connection profile.\n" + "\n" + "Examples:\n" + "nmcli con mod home-wifi wifi.ssid rakosnicek\n" + "nmcli con mod em1-1 ipv4.method manual ipv4.addr \"192.168.1.2/24, 10.10.1.5/8\"\n" + "nmcli con mod em1-1 +ipv4.dns 8.8.4.4\n" + "nmcli con mod em1-1 -ipv4.dns 1\n" + "nmcli con mod em1-1 -ipv6.addr \"abbe::cafe/56\"\n" + "nmcli con mod bond0 +bond.options mii=500\n" + "nmcli con mod bond0 -bond.options downdelay\n" + "nmcli con mod em1-1 remove sriov\n\n")); +} + +static void +usage_connection_clone(void) +{ + g_printerr(_("Usage: nmcli connection clone { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [--temporary] [id | uuid | path] <ID> <new name>\n" + "\n" + "Clone an existing connection profile. The newly created connection will be\n" + "the exact copy of the <ID>, except the uuid property (will be generated) and\n" + "id (provided as <new name> argument).\n\n")); +} + +static void +usage_connection_edit(void) +{ + g_printerr(_("Usage: nmcli connection edit { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [id | uuid | path] <ID>\n" + "\n" + "Edit an existing connection profile in an interactive editor.\n" + "The profile is identified by its name, UUID or D-Bus path\n" + "\n" + "ARGUMENTS := [type <new connection type>] [con-name <new connection name>]\n" + "\n" + "Add a new connection profile in an interactive editor.\n\n")); +} + +static void +usage_connection_delete(void) +{ + g_printerr(_("Usage: nmcli connection delete { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [id | uuid | path] <ID>\n" + "\n" + "Delete a connection profile.\n" + "The profile is identified by its name, UUID or D-Bus path.\n\n")); +} + +static void +usage_connection_monitor(void) +{ + g_printerr(_("Usage: nmcli connection monitor { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [id | uuid | path] <ID> ...\n" + "\n" + "Monitor connection profile activity.\n" + "This command prints a line whenever the specified connection changes.\n" + "Monitors all connection profiles in case none is specified.\n\n")); +} + +static void +usage_connection_reload(void) +{ + g_printerr(_("Usage: nmcli connection reload { help }\n" + "\n" + "Reload all connection files from disk.\n\n")); +} + +static void +usage_connection_load(void) +{ + g_printerr(_("Usage: nmcli connection load { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := <filename> [<filename>...]\n" + "\n" + "Load/reload one or more connection files from disk. Use this after manually\n" + "editing a connection file to ensure that NetworkManager is aware of its latest\n" + "state.\n\n")); +} + +static void +usage_connection_import(void) +{ + g_printerr( + _("Usage: nmcli connection import { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [--temporary] type <type> file <file to import>\n" + "\n" + "Import an external/foreign configuration as a NetworkManager connection profile.\n" + "The type of the input file is specified by type option.\n" + "Only VPN configurations are supported at the moment. The configuration\n" + "is imported by NetworkManager VPN plugins.\n\n")); +} + +static void +usage_connection_export(void) +{ + g_printerr(_("Usage: nmcli connection export { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [id | uuid | path] <ID> [<output file>]\n" + "\n" + "Export a connection. Only VPN connections are supported at the moment.\n" + "The data are directed to standard output or to a file if a name is given.\n\n")); +} + +static void +quit(void) +{ + if (nm_clear_g_source(&progress_id)) + nmc_terminal_erase_line(); + g_main_loop_quit(loop); +} + +static char * +construct_header_name(const char *base, const char *spec) +{ + if (spec == NULL) + return g_strdup(base); + + return g_strdup_printf("%s (%s)", base, spec); +} + +static int +get_ac_for_connection_cmp(gconstpointer pa, gconstpointer pb) +{ + NMActiveConnection *ac_a = *((NMActiveConnection *const *) pa); + NMActiveConnection *ac_b = *((NMActiveConnection *const *) pb); + + NM_CMP_RETURN(nmc_active_connection_cmp(ac_a, ac_b)); + NM_CMP_DIRECT_STRCMP0(nm_active_connection_get_id(ac_a), nm_active_connection_get_id(ac_b)); + NM_CMP_DIRECT_STRCMP0(nm_active_connection_get_connection_type(ac_a), + nm_active_connection_get_connection_type(ac_b)); + NM_CMP_DIRECT_STRCMP0(nm_object_get_path(NM_OBJECT(ac_a)), nm_object_get_path(NM_OBJECT(ac_b))); + + g_return_val_if_reached(0); +} + +static NMActiveConnection * +get_ac_for_connection(const GPtrArray *active_cons, + NMConnection * connection, + GPtrArray ** out_result) +{ + guint i; + NMActiveConnection *best_candidate = NULL; + GPtrArray * result = out_result ? *out_result : NULL; + + for (i = 0; i < active_cons->len; i++) { + NMActiveConnection *candidate = g_ptr_array_index(active_cons, i); + NMRemoteConnection *con; + + con = nm_active_connection_get_connection(candidate); + if (NM_CONNECTION(con) != connection) + continue; + + if (!out_result) + return candidate; + if (!result) + result = g_ptr_array_new_with_free_func(g_object_unref); + g_ptr_array_add(result, g_object_ref(candidate)); + } + + if (result) { + g_ptr_array_sort(result, get_ac_for_connection_cmp); + best_candidate = result->pdata[0]; + } + + NM_SET_OUT(out_result, result); + return best_candidate; +} + +typedef struct { + GMainLoop * loop; + NMConnection *local; + const char * setting_name; +} GetSecretsData; + +static void +got_secrets(GObject *source_object, GAsyncResult *res, gpointer user_data) +{ + NMRemoteConnection *remote = NM_REMOTE_CONNECTION(source_object); + GetSecretsData * data = user_data; + gs_unref_variant GVariant *secrets = NULL; + + secrets = nm_remote_connection_get_secrets_finish(remote, res, NULL); + if (secrets) { + gs_free_error GError *error = NULL; + + if (!nm_connection_update_secrets(data->local, NULL, secrets, &error) && error) { + g_printerr(_("Error updating secrets for %s: %s\n"), + data->setting_name, + error->message); + } + } + + g_main_loop_quit(data->loop); +} + +/* Put secrets into local connection. */ +static void +update_secrets_in_connection(NMRemoteConnection *remote, NMConnection *local) +{ + GetSecretsData data = { + 0, + }; + GType setting_type; + int i; + + data.local = local; + data.loop = g_main_loop_new(NULL, FALSE); + + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) { + setting_type = nm_meta_setting_infos[i].get_setting_gtype(); + if (!nm_connection_get_setting(NM_CONNECTION(remote), setting_type)) + continue; + if (!nm_meta_setting_info_editor_has_secrets( + nm_meta_setting_info_editor_find_by_gtype(setting_type))) + continue; + data.setting_name = nm_meta_setting_infos[i].setting_name; + nm_remote_connection_get_secrets_async(remote, + nm_meta_setting_infos[i].setting_name, + NULL, + got_secrets, + &data); + g_main_loop_run(data.loop); + } + + g_main_loop_unref(data.loop); +} + +static gboolean +nmc_connection_profile_details(NMConnection *connection, NmCli *nmc) +{ + GError * error = NULL; + GArray * print_settings_array; + GPtrArray * prop_array = NULL; + guint i; + char * fields_str; + char * fields_all = NMC_FIELDS_SETTINGS_NAMES_ALL; + char * fields_common = NMC_FIELDS_SETTINGS_NAMES_ALL; + const char *base_hdr = _("Connection profile details"); + gboolean was_output = FALSE; + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) + fields_str = fields_common; + else if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "all") == 0) + fields_str = fields_all; + else + fields_str = nmc->required_fields; + + print_settings_array = + parse_output_fields(fields_str, + (const NMMetaAbstractInfo *const *) nm_meta_setting_infos_editor_p(), + TRUE, + &prop_array, + &error); + if (error) { + g_string_printf(nmc->return_text, _("Error: 'connection show': %s"), error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + g_assert(print_settings_array); + + /* Main header */ + { + gs_free char *header_name = NULL; + gs_free NmcOutputField *row = NULL; + gs_unref_array GArray *out_indices = NULL; + + header_name = construct_header_name(base_hdr, nm_connection_get_id(connection)); + out_indices = parse_output_fields( + NMC_FIELDS_SETTINGS_NAMES_ALL, + (const NMMetaAbstractInfo *const *) nm_meta_setting_infos_editor_p(), + FALSE, + NULL, + NULL); + + row = g_new0(NmcOutputField, _NM_META_SETTING_TYPE_NUM + 1); + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) + row[i].info = (const NMMetaAbstractInfo *) &nm_meta_setting_infos_editor[i]; + + print_required_fields(&nmc->nmc_config, + &nmc->pager_data, + NMC_OF_FLAG_MAIN_HEADER_ONLY, + out_indices, + header_name, + 0, + row); + } + + /* Loop through the required settings and print them. */ + for (i = 0; i < print_settings_array->len; i++) { + NMSetting * setting; + int section_idx = g_array_index(print_settings_array, int, i); + const char *prop_name = (const char *) g_ptr_array_index(prop_array, i); + + if (NM_IN_SET(nmc->nmc_config.print_output, NMC_PRINT_NORMAL, NMC_PRINT_PRETTY) + && !nmc->nmc_config.multiline_output && was_output) + g_print("\n"); /* Empty line */ + + was_output = FALSE; + + setting = nm_connection_get_setting_by_name( + connection, + nm_meta_setting_infos_editor[section_idx].general->setting_name); + if (setting) { + setting_details(&nmc->nmc_config, setting, prop_name); + was_output = TRUE; + } + } + + g_array_free(print_settings_array, TRUE); + if (prop_array) + g_ptr_array_free(prop_array, TRUE); + + return TRUE; +} + +NMMetaColor +nmc_active_connection_state_to_color(NMActiveConnection *ac) +{ + NMActiveConnectionState state; + + if (!ac) + return NM_META_COLOR_CONNECTION_UNKNOWN; + + if (NM_FLAGS_HAS(nm_active_connection_get_state_flags(ac), NM_ACTIVATION_STATE_FLAG_EXTERNAL)) + return NM_META_COLOR_CONNECTION_EXTERNAL; + + state = nm_active_connection_get_state(ac); + + if (state == NM_ACTIVE_CONNECTION_STATE_ACTIVATING) + return NM_META_COLOR_CONNECTION_ACTIVATING; + else if (state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED) + return NM_META_COLOR_CONNECTION_ACTIVATED; + else if (state > NM_ACTIVE_CONNECTION_STATE_ACTIVATED) + return NM_META_COLOR_CONNECTION_DISCONNECTING; + else + return NM_META_COLOR_CONNECTION_UNKNOWN; +} + +static gboolean +nmc_active_connection_details(NMActiveConnection *acon, NmCli *nmc) +{ + GError * error = NULL; + GArray * print_groups; + GPtrArray * group_fields = NULL; + int i; + const char *fields_str = NULL; + const char *base_hdr = _("Activate connection details"); + gboolean was_output = FALSE; + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) { + /* pass */ + } else if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "all") == 0) { + /* pass */ + } else + fields_str = nmc->required_fields; + + print_groups = parse_output_fields( + fields_str, + (const NMMetaAbstractInfo *const *) nmc_fields_con_active_details_groups, + TRUE, + &group_fields, + &error); + if (error) { + g_string_printf(nmc->return_text, _("Error: 'connection show': %s"), error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + g_assert(print_groups); + + /* Main header */ + { + gs_free char *header_name = NULL; + gs_free NmcOutputField *row = NULL; + gs_unref_array GArray *out_indices = NULL; + + header_name = construct_header_name(base_hdr, nm_active_connection_get_uuid(acon)); + out_indices = parse_output_fields( + NULL, + (const NMMetaAbstractInfo *const *) nmc_fields_con_active_details_groups, + FALSE, + NULL, + NULL); + + row = g_new0(NmcOutputField, G_N_ELEMENTS(nmc_fields_con_active_details_groups) + 1); + for (i = 0; nmc_fields_con_active_details_groups[i]; i++) + row[i].info = (const NMMetaAbstractInfo *) nmc_fields_con_active_details_groups[i]; + + print_required_fields(&nmc->nmc_config, + &nmc->pager_data, + NMC_OF_FLAG_MAIN_HEADER_ONLY, + out_indices, + header_name, + 0, + row); + } + + /* Loop through the groups and print them. */ + for (i = 0; i < print_groups->len; i++) { + int group_idx = g_array_index(print_groups, int, i); + char *group_fld = (char *) g_ptr_array_index(group_fields, i); + + if (NM_IN_SET(nmc->nmc_config.print_output, NMC_PRINT_NORMAL, NMC_PRINT_PRETTY) + && !nmc->nmc_config.multiline_output && was_output) + g_print("\n"); + + was_output = FALSE; + + if (nmc_fields_con_active_details_groups[group_idx]->nested == metagen_con_active_general) { + gs_free char *f = NULL; + + if (group_fld) + f = g_strdup_printf("GENERAL.%s", group_fld); + + nmc_print(&nmc->nmc_config, + (gpointer[]){acon, NULL}, + NULL, + NULL, + NMC_META_GENERIC_GROUP("GENERAL", metagen_con_active_general, N_("GROUP")), + f, + NULL); + was_output = TRUE; + continue; + } + + /* IP4 */ + if (g_ascii_strcasecmp(nmc_fields_con_active_details_groups[group_idx]->name, + nmc_fields_con_active_details_groups[1]->name) + == 0) { + gboolean b1 = FALSE; + NMIPConfig *cfg4 = nm_active_connection_get_ip4_config(acon); + + b1 = print_ip_config(cfg4, AF_INET, &nmc->nmc_config, group_fld); + was_output = was_output || b1; + } + + /* DHCP4 */ + if (g_ascii_strcasecmp(nmc_fields_con_active_details_groups[group_idx]->name, + nmc_fields_con_active_details_groups[2]->name) + == 0) { + gboolean b1 = FALSE; + NMDhcpConfig *dhcp4 = nm_active_connection_get_dhcp4_config(acon); + + b1 = print_dhcp_config(dhcp4, AF_INET, &nmc->nmc_config, group_fld); + was_output = was_output || b1; + } + + /* IP6 */ + if (g_ascii_strcasecmp(nmc_fields_con_active_details_groups[group_idx]->name, + nmc_fields_con_active_details_groups[3]->name) + == 0) { + gboolean b1 = FALSE; + NMIPConfig *cfg6 = nm_active_connection_get_ip6_config(acon); + + b1 = print_ip_config(cfg6, AF_INET6, &nmc->nmc_config, group_fld); + was_output = was_output || b1; + } + + /* DHCP6 */ + if (g_ascii_strcasecmp(nmc_fields_con_active_details_groups[group_idx]->name, + nmc_fields_con_active_details_groups[4]->name) + == 0) { + gboolean b1 = FALSE; + NMDhcpConfig *dhcp6 = nm_active_connection_get_dhcp6_config(acon); + + b1 = print_dhcp_config(dhcp6, AF_INET6, &nmc->nmc_config, group_fld); + was_output = was_output || b1; + } + + if (nmc_fields_con_active_details_groups[group_idx]->nested == metagen_con_active_vpn) { + if (NM_IS_VPN_CONNECTION(acon)) { + nmc_print(&nmc->nmc_config, + (gpointer[]){acon, NULL}, + NULL, + NULL, + NMC_META_GENERIC_GROUP("VPN", metagen_con_active_vpn, N_("NAME")), + group_fld, + NULL); + was_output = TRUE; + } + continue; + } + } + + g_array_free(print_groups, TRUE); + if (group_fields) + g_ptr_array_free(group_fields, TRUE); + + return TRUE; +} + +static gboolean +split_required_fields_for_con_show(const char *input, + char ** profile_flds, + char ** active_flds, + GError ** error) +{ + gs_free const char **fields = NULL; + const char *const * iter; + nm_auto_free_gstring GString *str1 = NULL; + nm_auto_free_gstring GString *str2 = NULL; + gboolean group_profile = FALSE; + gboolean group_active = FALSE; + gboolean do_free; + + if (!input) { + *profile_flds = NULL; + *active_flds = NULL; + return TRUE; + } + + str1 = g_string_new(NULL); + str2 = g_string_new(NULL); + + fields = nm_utils_strsplit_set_with_empty(input, ","); + for (iter = fields; iter && *iter; iter++) { + char * s_mutable = (char *) (*iter); + char * dot; + gboolean is_all; + gboolean is_common; + gboolean found; + int i; + + g_strstrip(s_mutable); + dot = strchr(s_mutable, '.'); + if (dot) + *dot = '\0'; + + is_all = !dot && g_ascii_strcasecmp(s_mutable, "all") == 0; + is_common = !dot && g_ascii_strcasecmp(s_mutable, "common") == 0; + + found = FALSE; + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) { + if (is_all || is_common + || !g_ascii_strcasecmp(s_mutable, nm_meta_setting_infos[i].setting_name)) { + if (dot) + *dot = '.'; + g_string_append(str1, s_mutable); + g_string_append_c(str1, ','); + found = TRUE; + break; + } + } + if (found) + continue; + + for (i = 0; nmc_fields_con_active_details_groups[i]; i++) { + if (is_all || is_common + || !g_ascii_strcasecmp(s_mutable, nmc_fields_con_active_details_groups[i]->name)) { + if (dot) + *dot = '.'; + g_string_append(str2, s_mutable); + g_string_append_c(str2, ','); + found = TRUE; + break; + } + } + if (!found) { + if (dot) + *dot = '.'; + if (!g_ascii_strcasecmp(s_mutable, CON_SHOW_DETAIL_GROUP_PROFILE)) + group_profile = TRUE; + else if (!g_ascii_strcasecmp(s_mutable, CON_SHOW_DETAIL_GROUP_ACTIVE)) + group_active = TRUE; + else { + gs_free char *allowed1 = nm_meta_abstract_infos_get_names_str( + (const NMMetaAbstractInfo *const *) nm_meta_setting_infos_editor_p(), + NULL); + gs_free char *allowed2 = nm_meta_abstract_infos_get_names_str( + (const NMMetaAbstractInfo *const *) nmc_fields_con_active_details_groups, + NULL); + + g_set_error(error, + NMCLI_ERROR, + 0, + _("invalid field '%s'; allowed fields: %s and %s, or %s,%s"), + s_mutable, + allowed1, + allowed2, + CON_SHOW_DETAIL_GROUP_PROFILE, + CON_SHOW_DETAIL_GROUP_ACTIVE); + return FALSE; + } + } + } + + /* Handle pseudo groups: profile, active */ + if (group_profile) { + if (str1->len > 0) { + g_set_error(error, + NMCLI_ERROR, + 0, + _("'%s' has to be alone"), + CON_SHOW_DETAIL_GROUP_PROFILE); + return FALSE; + } + g_string_assign(str1, "all,"); + } + if (group_active) { + if (str2->len > 0) { + g_set_error(error, + NMCLI_ERROR, + 0, + _("'%s' has to be alone"), + CON_SHOW_DETAIL_GROUP_ACTIVE); + return FALSE; + } + g_string_assign(str2, "all,"); + } + + if (str1->len > 0) + g_string_truncate(str1, str1->len - 1); + if (str2->len > 0) + g_string_truncate(str2, str2->len - 1); + + do_free = (str1->len == 0); + *profile_flds = g_string_free(g_steal_pointer(&str1), do_free); + do_free = (str2->len == 0); + *active_flds = g_string_free(g_steal_pointer(&str2), do_free); + return TRUE; +} + +typedef enum { + NMC_SORT_ACTIVE = 1, + NMC_SORT_ACTIVE_INV = -1, + NMC_SORT_NAME = 2, + NMC_SORT_NAME_INV = -2, + NMC_SORT_TYPE = 3, + NMC_SORT_TYPE_INV = -3, + NMC_SORT_PATH = 4, + NMC_SORT_PATH_INV = -4, +} NmcSortOrder; + +typedef struct { + NmCli * nmc; + const GArray *order; + gboolean show_active_fields; +} ConShowSortInfo; + +static int +con_show_get_items_cmp(gconstpointer pa, gconstpointer pb, gpointer user_data) +{ + const ConShowSortInfo * sort_info = user_data; + const MetagenConShowRowData *row_data_a = *((const MetagenConShowRowData *const *) pa); + const MetagenConShowRowData *row_data_b = *((const MetagenConShowRowData *const *) pb); + NMConnection * c_a = row_data_a->connection; + NMConnection * c_b = row_data_b->connection; + NMActiveConnection * ac_a = row_data_a->primary_active; + NMActiveConnection * ac_b = row_data_b->primary_active; + NMActiveConnection * ac_a_effective = sort_info->show_active_fields ? ac_a : NULL; + NMActiveConnection * ac_b_effective = sort_info->show_active_fields ? ac_b : NULL; + + /* first sort active-connections which are invisible, i.e. that have no connection */ + if (!c_a && c_b) + return -1; + if (!c_b && c_a) + return 1; + + /* we have two connections... */ + if (c_a && c_b && c_a != c_b) { + const NmcSortOrder * order_arr; + guint i, order_len; + NMMetaAccessorGetType get_type = + nmc_print_output_to_accessor_get_type(sort_info->nmc->nmc_config.print_output); + + if (sort_info->order) { + order_arr = &g_array_index(sort_info->order, NmcSortOrder, 0); + order_len = sort_info->order->len; + } else { + static const NmcSortOrder def[] = {NMC_SORT_ACTIVE, NMC_SORT_NAME, NMC_SORT_PATH}; + + /* Note: the default order does not consider whether a column is shown. + * That means, the selection of the output fields, does not affect the + * order (although there could be an argument that it should). */ + order_arr = def; + order_len = G_N_ELEMENTS(def); + } + + for (i = 0; i < order_len; i++) { + NmcSortOrder item = order_arr[i]; + + switch (item) { + case NMC_SORT_ACTIVE: + NM_CMP_RETURN(nmc_active_connection_cmp(ac_b, ac_a)); + break; + case NMC_SORT_ACTIVE_INV: + NM_CMP_RETURN(nmc_active_connection_cmp(ac_a, ac_b)); + break; + + case NMC_SORT_TYPE: + NM_CMP_DIRECT_STRCMP0(_con_show_fcn_get_type(c_a, ac_a_effective, get_type), + _con_show_fcn_get_type(c_b, ac_b_effective, get_type)); + break; + case NMC_SORT_TYPE_INV: + NM_CMP_DIRECT_STRCMP0(_con_show_fcn_get_type(c_b, ac_b_effective, get_type), + _con_show_fcn_get_type(c_a, ac_a_effective, get_type)); + break; + + case NMC_SORT_NAME: + NM_CMP_RETURN(nm_utf8_collate0(_con_show_fcn_get_id(c_a, ac_a_effective), + _con_show_fcn_get_id(c_b, ac_b_effective))); + break; + case NMC_SORT_NAME_INV: + NM_CMP_RETURN(nm_utf8_collate0(_con_show_fcn_get_id(c_b, ac_b_effective), + _con_show_fcn_get_id(c_a, ac_a_effective))); + break; + + case NMC_SORT_PATH: + NM_CMP_RETURN(nm_utils_dbus_path_cmp(nm_connection_get_path(c_a), + nm_connection_get_path(c_b))); + break; + + case NMC_SORT_PATH_INV: + NM_CMP_RETURN(nm_utils_dbus_path_cmp(nm_connection_get_path(c_b), + nm_connection_get_path(c_a))); + break; + + default: + nm_assert_not_reached(); + break; + } + } + + NM_CMP_DIRECT_STRCMP0(nm_connection_get_uuid(c_a), nm_connection_get_uuid(c_b)); + NM_CMP_DIRECT_STRCMP0(nm_connection_get_path(c_a), nm_connection_get_path(c_b)); + } + + NM_CMP_DIRECT_STRCMP0(nm_object_get_path(NM_OBJECT(ac_a)), nm_object_get_path(NM_OBJECT(ac_b))); + + g_return_val_if_reached(0); +} + +static GPtrArray * +con_show_get_items(NmCli *nmc, gboolean active_only, gboolean show_active_fields, GArray *order) +{ + gs_unref_hashtable GHashTable *row_hash = NULL; + GHashTableIter hiter; + GPtrArray * result; + const GPtrArray * arr; + NMRemoteConnection * c; + MetagenConShowRowData * row_data; + guint i; + const ConShowSortInfo sort_info = { + .nmc = nmc, + .order = order, + .show_active_fields = show_active_fields, + }; + + row_hash = g_hash_table_new(nm_direct_hash, NULL); + + arr = nm_client_get_connections(nmc->client); + for (i = 0; i < arr->len; i++) { + /* Note: libnm will not expose connection that are invisible + * to the user but currently inactive. + * + * That differs from get-active-connection(). If an invisible connection + * is active, we can get its NMActiveConnection. We can even obtain + * the corresponding NMRemoteConnection (although, of course it has + * no visible settings). + * + * I think this inconsistency is a bug in libnm. Anyway, the result is, + * that we print invisible connections if they are active, but otherwise + * we exclude them. */ + c = arr->pdata[i]; + g_hash_table_insert(row_hash, + c, + _metagen_con_show_row_data_new_for_connection(c, show_active_fields)); + } + + arr = nm_client_get_active_connections(nmc->client); + for (i = 0; i < arr->len; i++) { + NMActiveConnection *ac = arr->pdata[i]; + + c = nm_active_connection_get_connection(ac); + if (!show_active_fields && !c) { + /* the active connection has no connection, and we don't show + * any active fields. Skip this row. */ + continue; + } + + row_data = c ? g_hash_table_lookup(row_hash, c) : NULL; + + if (show_active_fields || !c) { + /* the active connection either has no connection (in which we create a + * connection-less row), or we are interested in showing each active + * connection in its own row. Add a row. */ + if (row_data) { + /* we create a rowdata for this connection earlier. We drop it, because this + * connection is tracked via the rowdata of the active connection. */ + g_hash_table_remove(row_hash, c); + _metagen_con_show_row_data_destroy(row_data); + } + row_data = + _metagen_con_show_row_data_new_for_active_connection(c, ac, show_active_fields); + g_hash_table_insert(row_hash, ac, row_data); + continue; + } + + /* we add the active connection to the row for the referenced + * connection. We need to group them this way, to print the proper + * color (activated or not) based on primary_active. */ + if (!row_data) { + /* this is unexpected. The active connection references a connection that + * seemingly no longer exists. It's a bug in libnm. Add a row nonetheless. */ + row_data = _metagen_con_show_row_data_new_for_connection(c, show_active_fields); + g_hash_table_insert(row_hash, c, row_data); + } + _metagen_con_show_row_data_add_active_connection(row_data, ac); + } + + result = g_ptr_array_new_with_free_func(_metagen_con_show_row_data_destroy); + + g_hash_table_iter_init(&hiter, row_hash); + while (g_hash_table_iter_next(&hiter, NULL, (gpointer *) &row_data)) { + if (active_only && !row_data->primary_active) { + /* We only print connections that are active. Skip this row. */ + _metagen_con_show_row_data_destroy(row_data); + continue; + } + if (!show_active_fields) { + NMSettingConnection *s_con; + + nm_assert(NM_IS_REMOTE_CONNECTION(row_data->connection)); + s_con = nm_connection_get_setting_connection(row_data->connection); + if (!s_con || !nm_setting_connection_get_uuid(s_con)) { + /* we are in a mode, where we only print rows for connection. + * For that we require that all rows are visible to the user, + * meaning: the have a [connection] setting and a UUID. + * + * Otherwise, this connection is likely invisible to the user. + * Skip it. */ + _metagen_con_show_row_data_destroy(row_data); + continue; + } + _metagen_con_show_row_data_init_primary_active(row_data); + } else + nm_assert(!row_data->all_active); + g_ptr_array_add(result, row_data); + } + + g_ptr_array_sort_with_data(result, con_show_get_items_cmp, (gpointer) &sort_info); + return result; +} + +static GArray * +parse_preferred_connection_order(const char *order, GError **error) +{ + gs_free const char **strv = NULL; + const char *const * iter; + const char * str; + GArray * order_arr; + NmcSortOrder val; + gboolean inverse, unique; + guint i; + + strv = nm_utils_strsplit_set(order, ":"); + if (!strv) { + g_set_error(error, NMCLI_ERROR, 0, _("incorrect string '%s' of '--order' option"), order); + return NULL; + } + + order_arr = g_array_sized_new(FALSE, FALSE, sizeof(NmcSortOrder), 4); + for (iter = strv; iter && *iter; iter++) { + str = *iter; + inverse = FALSE; + if (str[0] == '-') + inverse = TRUE; + if (str[0] == '+' || str[0] == '-') + str++; + + if (matches(str, "active")) + val = inverse ? NMC_SORT_ACTIVE_INV : NMC_SORT_ACTIVE; + else if (matches(str, "name")) + val = inverse ? NMC_SORT_NAME_INV : NMC_SORT_NAME; + else if (matches(str, "type")) + val = inverse ? NMC_SORT_TYPE_INV : NMC_SORT_TYPE; + else if (matches(str, "path")) + val = inverse ? NMC_SORT_PATH_INV : NMC_SORT_PATH; + else { + g_array_unref(order_arr); + order_arr = NULL; + g_set_error(error, NMCLI_ERROR, 0, _("incorrect item '%s' in '--order' option"), *iter); + break; + } + /* Check for duplicates and ignore them. */ + unique = TRUE; + for (i = 0; i < order_arr->len; i++) { + if (abs(g_array_index(order_arr, NmcSortOrder, i)) - abs(val) == 0) { + unique = FALSE; + break; + } + } + + /* Value is ok and unique, add it to the array */ + if (unique) + g_array_append_val(order_arr, val); + } + + return order_arr; +} + +static NMConnection * +get_connection(NmCli * nmc, + int * argc, + const char *const **argv, + const char ** out_selector, + const char ** out_value, + GPtrArray ** out_result, + GError ** error) +{ + const GPtrArray *connections; + NMConnection * connection = NULL; + const char * selector = NULL; + + NM_SET_OUT(out_selector, NULL); + NM_SET_OUT(out_value, NULL); + + if (*argc == 0) { + g_set_error_literal(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("No connection specified")); + return NULL; + } + + if (*argc == 1 && nmc->complete) + nmc_complete_strings(**argv, "id", "uuid", "path", "filename"); + + if (NM_IN_STRSET(**argv, "id", "uuid", "path", "filename")) { + if (*argc == 1) { + if (!nmc->complete) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("%s argument is missing"), + selector); + return NULL; + } + } else { + selector = **argv; + (*argv)++; + (*argc)--; + } + } + + NM_SET_OUT(out_selector, selector); + NM_SET_OUT(out_value, **argv); + + connections = nm_client_get_connections(nmc->client); + connection = + nmc_find_connection(connections, selector, **argv, out_result, *argc == 1 && nmc->complete); + if (!connection) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_NOT_FOUND, + _("unknown connection '%s'"), + **argv); + } + + next_arg(nmc, argc, argv, NULL); + return connection; +} + +static void +do_connections_show(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gs_free_error GError *err = NULL; + gs_free char * profile_flds = NULL; + gs_free char * active_flds = NULL; + gboolean active_only = FALSE; + gs_unref_array GArray *order = NULL; + guint i; + int option; + + /* check connection show options [--active] [--order <order spec>] */ + while ((option = next_arg(nmc, &argc, &argv, "--active", "--order", NULL)) > 0) { + switch (option) { + case 1: /* --active */ + active_only = TRUE; + break; + case 2: /* --order */ + argc--; + argv++; + if (!argc) { + g_set_error_literal(&err, NMCLI_ERROR, 0, _("'--order' argument is missing")); + goto finish; + } + order = parse_preferred_connection_order(*argv, &err); + if (err) + goto finish; + break; + default: + g_assert_not_reached(); + break; + } + } + + if (argc == 0) { + const char * fields_str = NULL; + gs_unref_ptrarray GPtrArray *items = NULL; + gs_free NMMetaSelectionResultList *selection = NULL; + gboolean show_active_fields = TRUE; + + if (nmc->complete) + goto finish; + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) + fields_str = NMC_FIELDS_CON_SHOW_COMMON; + else if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "all") == 0) { + /* pass */ + } else + fields_str = nmc->required_fields; + + /* determine whether the user wants to see any fields that are related to active-connections + * (e.g. the apath, the current state, or the device where the profile is active). + * + * If that's the case, then we will show one line for each active connection. In case + * a profile has multiple active connections, it will be listed multiple times. + * If that's not the case, we filter out these duplicate lines. */ + selection = nm_meta_selection_create_parse_list( + (const NMMetaAbstractInfo *const *) metagen_con_show, + fields_str, + FALSE, + NULL); + if (selection && selection->num > 0) { + show_active_fields = FALSE; + for (i = 0; i < selection->num; i++) { + const NmcMetaGenericInfo *info = + (const NmcMetaGenericInfo *) selection->items[i].info; + + if (NM_IN_SET(info->info_type, + NMC_GENERIC_INFO_TYPE_CON_SHOW_DEVICE, + NMC_GENERIC_INFO_TYPE_CON_SHOW_STATE, + NMC_GENERIC_INFO_TYPE_CON_SHOW_ACTIVE, + NMC_GENERIC_INFO_TYPE_CON_SHOW_ACTIVE_PATH)) { + show_active_fields = TRUE; + break; + } + } + } + + nm_cli_spawn_pager(&nmc->nmc_config, &nmc->pager_data); + + items = con_show_get_items(nmc, active_only, show_active_fields, order); + g_ptr_array_add(items, NULL); + if (!nmc_print(&nmc->nmc_config, + items->pdata, + NULL, + active_only ? _("NetworkManager active profiles") + : _("NetworkManager connection profiles"), + (const NMMetaAbstractInfo *const *) metagen_con_show, + fields_str, + &err)) + goto finish; + } else { + gboolean new_line = FALSE; + gboolean without_fields = (nmc->required_fields == NULL); + const GPtrArray *active_cons = nm_client_get_active_connections(nmc->client); + + /* multiline mode is default for 'connection show <ID>' */ + if (!nmc->mode_specified) + nmc->nmc_config_mutable.multiline_output = TRUE; + + /* Split required fields into the settings and active ones. */ + if (!split_required_fields_for_con_show(nmc->required_fields, + &profile_flds, + &active_flds, + &err)) + goto finish; + + nm_clear_g_free(&nmc->required_fields); + + /* Before printing the connections check if we have a "--show-secret" + * option after the connection ids */ + if (!nmc->nmc_config.show_secrets && !nmc->complete) { + int argc_cp = argc; + const char *const *argv_cp = argv; + + do { + if (NM_IN_STRSET(*argv_cp, "id", "uuid", "path", "filename", "apath")) { + argc_cp--; + argv_cp++; + } + } while (next_arg(nmc, &argc_cp, &argv_cp, NULL) != -1); + } + + while (argc > 0) { + const GPtrArray *connections; + gboolean res; + NMConnection * con; + gs_unref_object NMActiveConnection *explicit_acon = NULL; + const char * selector = NULL; + gs_unref_ptrarray GPtrArray *found_cons = NULL; + gboolean explicit_acon_handled = FALSE; + guint i_found_cons; + + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "id", "uuid", "path", "filename", "apath"); + + if (NM_IN_STRSET(*argv, "id", "uuid", "path", "filename", "apath")) { + selector = *argv; + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, + _("Error: %s argument is missing."), + *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + } + + /* Try to find connection by id, uuid or path first */ + connections = nm_client_get_connections(nmc->client); + con = nmc_find_connection(connections, + selector, + *argv, + &found_cons, + argc == 1 && nmc->complete); + if (!con && NM_IN_STRSET(selector, NULL, "apath")) { + /* Try apath too */ + explicit_acon = nmc_find_active_connection(active_cons, + "apath", + *argv, + NULL, + argc == 1 && nmc->complete); + if (explicit_acon) { + if (!selector + && !nm_streq0(*argv, nm_object_get_path(NM_OBJECT(explicit_acon)))) { + /* we matched the apath based on the last component alone (note the full D-Bus path). + * That is how nmc_find_active_connection() works, if you pass in a selector. + * Reject it. */ + explicit_acon = NULL; + } + nm_g_object_ref(explicit_acon); + } + } + + if (!con && !explicit_acon) { + g_string_printf(nmc->return_text, + _("Error: %s - no such connection profile."), + *argv); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + goto finish; + } + + /* Print connection details: + * Usually we have both static and active connection. + * But when a connection is private to a user, another user + * may see only the active connection. + */ + + if (nmc->complete) { + next_arg(nmc, &argc, &argv, NULL); + continue; + } + + explicit_acon_handled = FALSE; + i_found_cons = 0; + for (;;) { + gs_unref_ptrarray GPtrArray *found_acons = NULL; + + if (explicit_acon) { + if (explicit_acon_handled) + break; + explicit_acon_handled = TRUE; + /* the user referenced an "apath". In this case, we can only have at most one connection + * and one apath. */ + con = NM_CONNECTION(nm_active_connection_get_connection(explicit_acon)); + } else { + if (i_found_cons >= found_cons->len) + break; + con = found_cons->pdata[i_found_cons++]; + get_ac_for_connection(active_cons, con, &found_acons); + } + + if (active_only && !explicit_acon && !found_acons) { + /* this connection is not interesting, we only print active ones. */ + continue; + } + + nm_assert(explicit_acon || con); + + if (new_line) + g_print("\n"); + new_line = TRUE; + + if (without_fields || profile_flds) { + if (con) { + nmc->required_fields = profile_flds; + if (nmc->nmc_config.show_secrets) + update_secrets_in_connection(NM_REMOTE_CONNECTION(con), con); + res = nmc_connection_profile_details(con, nmc); + nmc->required_fields = NULL; + if (!res) + goto finish; + } + } + + if (without_fields || active_flds) { + guint l = explicit_acon ? 1 : (found_acons ? found_acons->len : 0); + + for (i = 0; i < l; i++) { + NMActiveConnection *acon; + + if (i > 0) { + /* if there are multiple active connections, separate them with newline. + * that is a bit odd, because we already separate connections with newlines, + * and commonly don't separate the connection from the first active connection. */ + g_print("\n"); + } + + if (explicit_acon) + acon = explicit_acon; + else + acon = found_acons->pdata[i]; + + nmc->required_fields = active_flds; + res = nmc_active_connection_details(acon, nmc); + nmc->required_fields = NULL; + if (!res) + goto finish; + } + } + } + + next_arg(nmc, &argc, &argv, NULL); + } + } + +finish: + if (err) { + g_string_printf(nmc->return_text, _("Error: %s."), err->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + } +} + +static NMActiveConnection * +get_default_active_connection(NmCli *nmc, NMDevice **device) +{ + NMActiveConnection *default_ac = NULL; + NMDevice * non_default_device = NULL; + NMActiveConnection *non_default_ac = NULL; + const GPtrArray * connections; + guint i; + + g_return_val_if_fail(nmc, NULL); + g_return_val_if_fail(device, NULL); + g_return_val_if_fail(*device == NULL, NULL); + + connections = nm_client_get_active_connections(nmc->client); + for (i = 0; i < connections->len; i++) { + NMActiveConnection *candidate = g_ptr_array_index(connections, i); + const GPtrArray * devices; + + devices = nm_active_connection_get_devices(candidate); + if (!devices->len) + continue; + + if (nm_active_connection_get_default(candidate)) { + if (!default_ac) { + *device = g_ptr_array_index(devices, 0); + default_ac = candidate; + } + } else { + if (!non_default_ac) { + non_default_device = g_ptr_array_index(devices, 0); + non_default_ac = candidate; + } + } + } + + /* Prefer the default connection if one exists, otherwise return the first + * non-default connection. + */ + if (!default_ac && non_default_ac) { + default_ac = non_default_ac; + *device = non_default_device; + } + return default_ac; +} + +/* Find a device to activate the connection on. + * IN: connection: connection to activate + * iface: device interface name to use (optional) + * ap: access point to use (optional; valid just for 802-11-wireless) + * nsp: Network Service Provider to use (option; valid only for wimax) + * OUT: device: found device + * spec_object: specific_object path of NMAccessPoint + * RETURNS: TRUE when a device is found, FALSE otherwise. + */ +static gboolean +find_device_for_connection(NmCli * nmc, + NMConnection *connection, + const char * iface, + const char * ap, + const char * nsp, + NMDevice ** device, + const char ** spec_object, + GError ** error) +{ + NMSettingConnection *s_con; + const char * con_type; + guint i, j; + + g_return_val_if_fail(nmc, FALSE); + g_return_val_if_fail(iface || ap || nsp, FALSE); + g_return_val_if_fail(device && *device == NULL, FALSE); + g_return_val_if_fail(spec_object && *spec_object == NULL, FALSE); + g_return_val_if_fail(error == NULL || *error == NULL, FALSE); + + s_con = nm_connection_get_setting_connection(connection); + g_assert(s_con); + con_type = nm_setting_connection_get_connection_type(s_con); + + if (strcmp(con_type, NM_SETTING_VPN_SETTING_NAME) == 0) { + /* VPN connections */ + NMActiveConnection *active = NULL; + if (iface) { + *device = nm_client_get_device_by_iface(nmc->client, iface); + if (*device) + active = nm_device_get_active_connection(*device); + + if (!active) { + g_set_error(error, NMCLI_ERROR, 0, _("no active connection on device '%s'"), iface); + return FALSE; + } + *spec_object = nm_object_get_path(NM_OBJECT(active)); + return TRUE; + } else { + active = get_default_active_connection(nmc, device); + if (!active) { + g_set_error_literal(error, NMCLI_ERROR, 0, _("no active connection or device")); + return FALSE; + } + *spec_object = nm_object_get_path(NM_OBJECT(active)); + return TRUE; + } + } else { + /* Other connections */ + NMDevice * found_device = NULL; + const GPtrArray *devices = nm_client_get_devices(nmc->client); + + for (i = 0; i < devices->len && !found_device; i++) { + NMDevice *dev = g_ptr_array_index(devices, i); + + if (iface) { + const char *dev_iface = nm_device_get_iface(dev); + if (!nm_streq0(dev_iface, iface)) + continue; + + if (!nm_device_connection_compatible(dev, connection, error)) { + g_prefix_error(error, + _("device '%s' not compatible with connection '%s': "), + iface, + nm_setting_connection_get_id(s_con)); + return FALSE; + } + + } else { + if (!nm_device_connection_compatible(dev, connection, NULL)) + continue; + } + + found_device = dev; + if (ap && nm_streq(con_type, NM_SETTING_WIRELESS_SETTING_NAME) + && NM_IS_DEVICE_WIFI(dev)) { + gs_free char * bssid_up = g_ascii_strup(ap, -1); + const GPtrArray *aps = nm_device_wifi_get_access_points(NM_DEVICE_WIFI(dev)); + found_device = + NULL; /* Mark as not found; set to the device again later, only if AP matches */ + + for (j = 0; j < aps->len; j++) { + NMAccessPoint *candidate_ap = g_ptr_array_index(aps, j); + const char * candidate_bssid = nm_access_point_get_bssid(candidate_ap); + + if (nm_streq0(bssid_up, candidate_bssid)) { + found_device = dev; + *spec_object = nm_object_get_path(NM_OBJECT(candidate_ap)); + break; + } + } + } + } + + if (!found_device) { + if (iface) { + g_set_error(error, + NMCLI_ERROR, + 0, + _("device '%s' not compatible with connection '%s'"), + iface, + nm_setting_connection_get_id(s_con)); + } else { + g_set_error(error, + NMCLI_ERROR, + 0, + _("no device found for connection '%s'"), + nm_setting_connection_get_id(s_con)); + } + return FALSE; + } + + *device = found_device; + return TRUE; + } +} + +typedef struct { + NmCli * nmc; + NMDevice * device; + NMActiveConnection *active; +} ActivateConnectionInfo; + +static void +active_connection_hint(GString *return_text, NMActiveConnection *active, NMDevice *device) +{ + NMRemoteConnection * connection; + nm_auto_free_gstring GString *hint = NULL; + const GPtrArray * devices; + guint i; + + if (!active) + return; + + if (!nm_streq(NM_CONFIG_DEFAULT_LOGGING_BACKEND, "journal")) + return; + + connection = nm_active_connection_get_connection(active); + g_return_if_fail(connection); + + hint = g_string_new("journalctl -xe "); + g_string_append_printf(hint, + "NM_CONNECTION=%s", + nm_connection_get_uuid(NM_CONNECTION(connection))); + + if (device) + g_string_append_printf(hint, " + NM_DEVICE=%s", nm_device_get_iface(device)); + else { + devices = nm_active_connection_get_devices(active); + for (i = 0; i < devices->len; i++) { + g_string_append_printf(hint, + " + NM_DEVICE=%s", + nm_device_get_iface(NM_DEVICE(g_ptr_array_index(devices, i)))); + } + } + + g_string_append(return_text, "\n"); + g_string_append_printf(return_text, _("Hint: use '%s' to get more details."), hint->str); +} + +static void activate_connection_info_finish(ActivateConnectionInfo *info); + +static void +check_activated(ActivateConnectionInfo *info) +{ + NMActiveConnectionState ac_state; + NmCli * nmc = info->nmc; + const char * reason = NULL; + + ac_state = nmc_activation_get_effective_state(info->active, info->device, &reason); + switch (ac_state) { + case NM_ACTIVE_CONNECTION_STATE_ACTIVATED: + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + nmc_terminal_erase_line(); + if (reason) { + g_print(_("Connection successfully activated (%s) (D-Bus active path: %s)\n"), + reason, + nm_object_get_path(NM_OBJECT(info->active))); + } else { + g_print(_("Connection successfully activated (D-Bus active path: %s)\n"), + nm_object_get_path(NM_OBJECT(info->active))); + } + activate_connection_info_finish(info); + break; + case NM_ACTIVE_CONNECTION_STATE_DEACTIVATED: + nm_assert(reason); + g_string_printf(nmc->return_text, _("Error: Connection activation failed: %s"), reason); + active_connection_hint(nmc->return_text, info->active, info->device); + nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION; + activate_connection_info_finish(info); + break; + case NM_ACTIVE_CONNECTION_STATE_ACTIVATING: + if (nmc->secret_agent) { + NMRemoteConnection *connection = nm_active_connection_get_connection(info->active); + + nm_secret_agent_simple_enable(nmc->secret_agent, + nm_connection_get_path(NM_CONNECTION(connection))); + } + break; + default: + break; + } +} + +static void +device_state_cb(NMDevice *device, GParamSpec *pspec, ActivateConnectionInfo *info) +{ + check_activated(info); +} + +static void +active_connection_state_cb(NMActiveConnection * active, + NMActiveConnectionState state, + NMActiveConnectionStateReason reason, + ActivateConnectionInfo * info) +{ + check_activated(info); +} + +static void +set_nmc_error_timeout(NmCli *nmc) +{ + g_string_printf(nmc->return_text, _("Error: Timeout expired (%d seconds)"), nmc->timeout); + nmc->return_value = NMC_RESULT_ERROR_TIMEOUT_EXPIRED; +} + +static gboolean +activate_connection_timeout_cb(gpointer user_data) +{ + ActivateConnectionInfo *info = user_data; + + /* Time expired -> exit nmcli */ + set_nmc_error_timeout(info->nmc); + activate_connection_info_finish(info); + return FALSE; +} + +static gboolean +progress_cb(gpointer user_data) +{ + const char *str = (const char *) user_data; + + nmc_terminal_show_progress(str); + + return TRUE; +} + +static gboolean +progress_active_connection_cb(gpointer user_data) +{ + NMActiveConnection * active = user_data; + const char * str; + NMDevice * device; + NMActiveConnectionState ac_state; + const GPtrArray * ac_devs; + + ac_state = nm_active_connection_get_state(active); + + if (ac_state == NM_ACTIVE_CONNECTION_STATE_ACTIVATING) { + /* If the connection is activating, the device state + * is more interesting. */ + ac_devs = nm_active_connection_get_devices(active); + device = ac_devs->len > 0 ? g_ptr_array_index(ac_devs, 0) : NULL; + } else { + device = NULL; + } + + str = device ? gettext(nmc_device_state_to_string_with_external(device)) + : active_connection_state_to_string(ac_state); + + nmc_terminal_show_progress(str); + + return TRUE; +} + +static void +activate_connection_info_finish(ActivateConnectionInfo *info) +{ + if (info->device) { + g_signal_handlers_disconnect_by_func(info->device, G_CALLBACK(device_state_cb), info); + g_object_unref(info->device); + } + + if (info->active) { + g_signal_handlers_disconnect_by_func(info->active, + G_CALLBACK(active_connection_state_cb), + info); + g_object_unref(info->active); + } + + g_free(info); + quit(); +} + +static void +activate_connection_cb(GObject *client, GAsyncResult *result, gpointer user_data) +{ + ActivateConnectionInfo *info = (ActivateConnectionInfo *) user_data; + NmCli * nmc = info->nmc; + NMDevice * device = info->device; + NMActiveConnection * active; + NMActiveConnectionState state; + const GPtrArray * ac_devs; + GError * error = NULL; + + info->active = active = nm_client_activate_connection_finish(NM_CLIENT(client), result, &error); + + if (error) { + g_string_printf(nmc->return_text, + _("Error: Connection activation failed: %s"), + error->message); + g_error_free(error); + active_connection_hint(nmc->return_text, info->active, info->device); + nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION; + activate_connection_info_finish(info); + } else { + state = nm_active_connection_get_state(active); + if (!device && !nm_active_connection_get_vpn(active)) { + /* device could be NULL for virtual devices. Fill it here. */ + ac_devs = nm_active_connection_get_devices(active); + device = ac_devs->len > 0 ? g_ptr_array_index(ac_devs, 0) : NULL; + if (device) + info->device = g_object_ref(device); + } + + if (nmc->nowait_flag || state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED) { + /* User doesn't want to wait or already activated */ + if (state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED) { + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + nmc_terminal_erase_line(); + g_print(_("Connection successfully activated (D-Bus active path: %s)\n"), + nm_object_get_path(NM_OBJECT(active))); + } + activate_connection_info_finish(info); + } else { + /* Monitor the active connection and device (if available) states */ + g_signal_connect(active, "state-changed", G_CALLBACK(active_connection_state_cb), info); + if (device) + g_signal_connect(device, + "notify::" NM_DEVICE_STATE, + G_CALLBACK(device_state_cb), + info); + /* Both active_connection_state_cb () and device_state_cb () will just + * call check_activated (info). So, just call it once directly after + * connecting on both the signals of the objects and skip the call to + * the callbacks. + */ + check_activated(info); + + /* Start progress indication showing VPN states */ + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) { + if (progress_id) + g_source_remove(progress_id); + progress_id = g_timeout_add(120, progress_active_connection_cb, active); + } + + /* Start timer not to loop forever when signals are not emitted */ + g_timeout_add_seconds(nmc->timeout, activate_connection_timeout_cb, info); + } + } +} + +static gboolean +nmc_activate_connection(NmCli * nmc, + NMConnection * connection, + const char * ifname, + const char * ap, + const char * nsp, + const char * pwds, + GAsyncReadyCallback callback, + GError ** error) +{ + ActivateConnectionInfo *info; + + GHashTable *pwds_hash; + NMDevice * device = NULL; + const char *spec_object = NULL; + gboolean device_found; + + g_return_val_if_fail(nmc, FALSE); + g_return_val_if_fail(error == NULL || *error == NULL, FALSE); + + if (connection && (ifname || ap || nsp)) { + gs_free_error GError *local = NULL; + + device_found = find_device_for_connection(nmc, + connection, + ifname, + ap, + nsp, + &device, + &spec_object, + &local); + + /* Virtual connection may not have their interfaces created yet */ + if (!device_found && !nm_connection_is_virtual(connection)) { + g_set_error(error, NMCLI_ERROR, NMC_RESULT_ERROR_CON_ACTIVATION, "%s", local->message); + return FALSE; + } + } else if (ifname) { + device = nm_client_get_device_by_iface(nmc->client, ifname); + if (!device) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_NOT_FOUND, + _("unknown device '%s'."), + ifname); + return FALSE; + } + } else if (!connection) { + g_set_error_literal(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_NOT_FOUND, + _("neither a valid connection nor device given")); + return FALSE; + } + + /* Parse passwords given in passwords file */ + { + gs_free_error GError *local = NULL; + gssize error_line; + + pwds_hash = nmc_utils_read_passwd_file(pwds, &error_line, &local); + if (!pwds_hash) { + if (error_line >= 0) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("invalid passwd-file '%s' at line %zd: %s"), + pwds, + error_line, + local->message); + } else { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("invalid passwd-file '%s': %s"), + pwds, + local->message); + } + return FALSE; + } + } + + if (nmc->pwds_hash) + g_hash_table_destroy(nmc->pwds_hash); + nmc->pwds_hash = pwds_hash; + + nmc->secret_agent = nm_secret_agent_simple_new("nmcli-connect"); + if (nmc->secret_agent) { + g_signal_connect(nmc->secret_agent, + NM_SECRET_AGENT_SIMPLE_REQUEST_SECRETS, + G_CALLBACK(nmc_secrets_requested), + nmc); + } + + info = g_malloc0(sizeof(ActivateConnectionInfo)); + info->nmc = nmc; + if (device) + info->device = g_object_ref(device); + + nm_client_activate_connection_async(nmc->client, + connection, + device, + spec_object, + NULL, + callback, + info); + return TRUE; +} + +static void +do_connection_up(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMConnection *connection = NULL; + const char * ifname = NULL; + const char * ap = NULL; + const char * nsp = NULL; + const char * pwds = NULL; + gs_free_error GError *error = NULL; + gs_strfreev char ** arg_arr = NULL; + int arg_num; + const char *const ** argv_ptr; + int * argc_ptr; + + /* + * Set default timeout for connection activation. + * Activation can take quite a long time, use 90 seconds. + */ + if (nmc->timeout == -1) + nmc->timeout = 90; + + next_arg(nmc, &argc, &argv, NULL); + argv_ptr = &argv; + argc_ptr = &argc; + + if (argc == 0 && nmc->ask) { + gs_free char *line = NULL; + + /* nmc_do_cmd() should not call this with argc=0. */ + g_assert(!nmc->complete); + + line = nmc_readline(&nmc->nmc_config, PROMPT_CONNECTION); + nmc_string_to_arg_array(line, NULL, TRUE, &arg_arr, &arg_num); + argv_ptr = (const char *const **) &arg_arr; + argc_ptr = &arg_num; + } + + if (argc > 0 && strcmp(*argv, "ifname") != 0) { + connection = get_connection(nmc, argc_ptr, argv_ptr, NULL, NULL, NULL, &error); + if (!connection) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + } + + while (argc > 0) { + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "ifname", "ap", "passwd-file"); + + if (strcmp(*argv, "ifname") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + ifname = *argv; + if (argc == 1 && nmc->complete) + nmc_complete_device(nmc->client, ifname, ap != NULL); + } else if (strcmp(*argv, "ap") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + ap = *argv; + if (argc == 1 && nmc->complete) + nmc_complete_bssid(nmc->client, ifname, ap); + } else if (strcmp(*argv, "passwd-file") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (argc == 1 && nmc->complete) + nmc->return_value = NMC_RESULT_COMPLETE_FILE; + + pwds = *argv; + } else if (!nmc->complete) { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + next_arg(nmc, &argc, &argv, NULL); + } + + if (nmc->complete) + return; + + /* Use nowait_flag instead of should_wait because exiting has to be postponed till + * active_connection_state_cb() is called. That gives NM time to check our permissions + * and we can follow activation progress. + */ + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + if (!nmc_activate_connection(nmc, + connection, + ifname, + ap, + nsp, + pwds, + activate_connection_cb, + &error)) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->should_wait--; + nmc->return_value = error->code; + return; + } + + /* Start progress indication */ + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + progress_id = g_timeout_add(120, progress_cb, _("preparing")); +} + +/*****************************************************************************/ + +typedef struct { + NmCli *nmc; + /* a list of object that is relevant for the callback. The object + * type differs, and depends on the type of callback. */ + GPtrArray * obj_list; + guint timeout_id; + GCancellable *cancellable; +} ConnectionCbInfo; + +static void +connection_removed_cb(NMClient *client, NMConnection *connection, ConnectionCbInfo *info); + +static void down_active_connection_state_cb(NMActiveConnection *active, + GParamSpec * pspec, + ConnectionCbInfo * info); + +static void +connection_cb_info_obj_list_destroy(ConnectionCbInfo *info, gpointer obj) +{ + nm_assert(info); + nm_assert(info->obj_list); + nm_assert(G_IS_OBJECT(obj)); + + g_signal_handlers_disconnect_by_func(obj, down_active_connection_state_cb, info); + g_object_unref(obj); +} + +static gssize +connection_cb_info_obj_list_idx(ConnectionCbInfo *info, gpointer obj) +{ + guint i; + + nm_assert(info); + nm_assert(info->obj_list); + nm_assert(G_IS_OBJECT(obj)); + + for (i = 0; i < info->obj_list->len; i++) { + if (info->obj_list->pdata[i] == obj) + return i; + } + return -1; +} + +static gpointer +connection_cb_info_obj_list_has(ConnectionCbInfo *info, gpointer obj) +{ + gssize idx; + + idx = connection_cb_info_obj_list_idx(info, obj); + if (idx >= 0) + return info->obj_list->pdata[idx]; + return NULL; +} + +static gpointer +connection_cb_info_obj_list_steal(ConnectionCbInfo *info, gpointer obj) +{ + gssize idx; + + idx = connection_cb_info_obj_list_idx(info, obj); + if (idx >= 0) { + g_ptr_array_remove_index(info->obj_list, idx); + return obj; + } + return NULL; +} + +static void +connection_cb_info_finish(ConnectionCbInfo *info, gpointer obj) +{ + if (obj) { + obj = connection_cb_info_obj_list_steal(info, obj); + if (obj) + connection_cb_info_obj_list_destroy(info, obj); + } else { + while (info->obj_list->len > 0) { + obj = info->obj_list->pdata[info->obj_list->len - 1]; + g_ptr_array_remove_index(info->obj_list, info->obj_list->len - 1); + connection_cb_info_obj_list_destroy(info, obj); + } + } + + if (info->obj_list->len > 0) + return; + + nm_clear_g_source(&info->timeout_id); + nm_clear_g_cancellable(&info->cancellable); + g_ptr_array_free(info->obj_list, TRUE); + + g_signal_handlers_disconnect_by_func(info->nmc->client, connection_removed_cb, info); + + g_slice_free(ConnectionCbInfo, info); + + quit(); +} + +/*****************************************************************************/ + +static void +connection_removed_cb(NMClient *client, NMConnection *connection, ConnectionCbInfo *info) +{ + if (!connection_cb_info_obj_list_has(info, connection)) + return; + g_print(_("Connection '%s' (%s) successfully deleted.\n"), + nm_connection_get_id(connection), + nm_connection_get_uuid(connection)); + connection_cb_info_finish(info, connection); +} + +static void +down_active_connection_state_cb(NMActiveConnection *active, + GParamSpec * pspec, + ConnectionCbInfo * info) +{ + if (nm_active_connection_get_state(active) < NM_ACTIVE_CONNECTION_STATE_DEACTIVATED) + return; + + if (info->nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + nmc_terminal_erase_line(); + g_print(_("Connection '%s' successfully deactivated (D-Bus active path: %s)\n"), + nm_active_connection_get_id(active), + nm_object_get_path(NM_OBJECT(active))); + + g_signal_handlers_disconnect_by_func(G_OBJECT(active), down_active_connection_state_cb, info); + connection_cb_info_finish(info, active); +} + +static gboolean +connection_op_timeout_cb(gpointer user_data) +{ + ConnectionCbInfo *info = user_data; + + set_nmc_error_timeout(info->nmc); + connection_cb_info_finish(info, NULL); + return G_SOURCE_REMOVE; +} + +static void +do_connection_down(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMActiveConnection *active; + ConnectionCbInfo * info = NULL; + const GPtrArray * active_cons; + gs_strfreev char ** arg_arr = NULL; + const char *const * arg_ptr; + int arg_num; + guint i; + gs_unref_ptrarray GPtrArray *found_active_cons = NULL; + + if (nmc->timeout == -1) + nmc->timeout = 10; + + next_arg(nmc, &argc, &argv, NULL); + arg_ptr = argv; + arg_num = argc; + + if (argc == 0) { + /* nmc_do_cmd() should not call this with argc=0. */ + g_assert(!nmc->complete); + + if (nmc->ask) { + gs_free char *line = NULL; + + line = nmc_readline(&nmc->nmc_config, PROMPT_ACTIVE_CONNECTIONS); + nmc_string_to_arg_array(line, NULL, TRUE, &arg_arr, &arg_num); + arg_ptr = (const char *const *) arg_arr; + } + if (arg_num == 0) { + g_string_printf(nmc->return_text, _("Error: No connection specified.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + } + + /* Get active connections */ + active_cons = nm_client_get_active_connections(nmc->client); + while (arg_num > 0) { + const char *selector = NULL; + + if (arg_num == 1 && nmc->complete) + nmc_complete_strings(*arg_ptr, "id", "uuid", "path", "filename", "apath"); + + if (NM_IN_STRSET(*arg_ptr, "id", "uuid", "path", "filename", "apath")) { + selector = *arg_ptr; + arg_num--; + arg_ptr++; + if (!arg_num) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), selector); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + } + + active = nmc_find_active_connection(active_cons, + selector, + *arg_ptr, + &found_active_cons, + arg_num == 1 && nmc->complete); + if (!active) { + if (!nmc->complete) + g_printerr(_("Error: '%s' is not an active connection.\n"), *arg_ptr); + g_string_printf(nmc->return_text, _("Error: not all active connections found.")); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + } + + next_arg(nmc->ask ? NULL : nmc, &arg_num, &arg_ptr, NULL); + } + + if (!found_active_cons) { + g_string_printf(nmc->return_text, _("Error: no active connection provided.")); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + return; + } + nm_assert(found_active_cons->len > 0); + + if (nmc->complete) + return; + + if (nmc->timeout > 0) { + nmc->should_wait++; + + info = g_slice_new0(ConnectionCbInfo); + info->nmc = nmc; + info->obj_list = g_ptr_array_sized_new(found_active_cons->len); + for (i = 0; i < found_active_cons->len; i++) { + active = found_active_cons->pdata[i]; + g_ptr_array_add(info->obj_list, g_object_ref(active)); + g_signal_connect(active, + "notify::" NM_ACTIVE_CONNECTION_STATE, + G_CALLBACK(down_active_connection_state_cb), + info); + } + info->timeout_id = g_timeout_add_seconds(nmc->timeout, connection_op_timeout_cb, info); + } + + for (i = 0; i < found_active_cons->len; i++) { + GError *error = NULL; + + active = found_active_cons->pdata[i]; + + if (!nm_client_deactivate_connection(nmc->client, active, NULL, &error)) { + g_print(_("Connection '%s' deactivation failed: %s\n"), + nm_active_connection_get_id(active), + error->message); + g_clear_error(&error); + + if (info) { + /* coverity thinks that info might be freed already while we still iterate + * the loop. But it cannot, because connection_cb_info_finish() only does some + * kind of ref-counting that ensures info stays alive long enough. */ + + /* coverity[pass_freed_arg] */ + g_signal_handlers_disconnect_by_func(active, down_active_connection_state_cb, info); + + connection_cb_info_finish(info, active); + } + } + } +} + +/*****************************************************************************/ + +/* + * Return the most appropriate name for the connection of a type 'name' possibly with given 'slave_type' + * if exists, else return the 'name'. The returned string must not be freed. + */ +static const char * +get_name_alias_toplevel(const char *name, const char *slave_type) +{ + const NMMetaSettingInfoEditor *setting_info; + + if (slave_type) { + const char *slave_name; + + if (nm_meta_setting_info_valid_parts_for_slave_type(slave_type, &slave_name)) + return slave_name ?: name; + return name; + } + + setting_info = nm_meta_setting_info_editor_find_by_name(name, FALSE); + if (setting_info) + return setting_info->alias ?: setting_info->general->setting_name; + + return name; +} + +/* + * Construct a string with names and aliases from the arrays formatted as: + * "name (alias), name, name (alias), name, name" + * + * Returns: string; the caller is responsible for freeing it. + */ +static char * +get_valid_options_string(const NMMetaSettingValidPartItem *const *array, + const NMMetaSettingValidPartItem *const *array_slv) +{ + const NMMetaSettingValidPartItem *const *iter = array; + GString * str; + int i; + + str = g_string_sized_new(150); + + for (i = 0; i < 2; i++, iter = array_slv) { + for (; iter && *iter; iter++) { + const NMMetaSettingInfoEditor *setting_info = (*iter)->setting_info; + + if (str->len) + g_string_append(str, ", "); + if (setting_info->alias) + g_string_append_printf(str, + "%s (%s)", + setting_info->general->setting_name, + setting_info->alias); + else + g_string_append(str, setting_info->general->setting_name); + } + } + return g_string_free(str, FALSE); +} + +static char * +get_valid_options_string_toplevel(void) +{ + GString *str; + int i; + + str = g_string_sized_new(150); + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) { + const NMMetaSettingInfoEditor *setting_info = &nm_meta_setting_infos_editor[i]; + + if (!setting_info->valid_parts) + continue; + + if (str->len) + g_string_append(str, ", "); + if (setting_info->alias) + g_string_append_printf(str, + "%s (%s)", + setting_info->general->setting_name, + setting_info->alias); + else + g_string_append(str, setting_info->general->setting_name); + } + + if (str->len) + g_string_append(str, ", "); + g_string_append(str, "bond-slave, bridge-slave, team-slave"); + + return g_string_free(str, FALSE); +} + +static const NMMetaSettingValidPartItem *const * +get_valid_settings_array(const char *con_type) +{ + const NMMetaSettingInfoEditor *setting_info; + + /* No connection type yet? Return settings for a generic connection + * (just the "connection" setting), which always makes sense. */ + if (!con_type) + return nm_meta_setting_info_valid_parts_default; + + setting_info = nm_meta_setting_info_editor_find_by_name(con_type, FALSE); + if (setting_info) + return setting_info->valid_parts ?: NM_PTRARRAY_EMPTY(const NMMetaSettingValidPartItem *); + return NULL; +} + +static char * +_construct_property_name(const char * setting_name, + const char * property_name, + NMMetaAccessorModifier modifier) +{ + return g_strdup_printf("%s%s.%s\n", + (modifier == NM_META_ACCESSOR_MODIFIER_ADD + ? "+" + : (modifier == NM_META_ACCESSOR_MODIFIER_DEL ? "-" : "")), + setting_name, + property_name); +} + +/* get_valid_properties_string: + * @array: base properties for the current connection type + * @array_slv: slave properties (or ipv4/ipv6 ones) for the current connection type + * @modifier: to prepend to each element of the returned list + * @prefix: only properties matching the prefix will be returned + * @postfix: required prefix on the property args; if a empty string is passed, is + * assumed that the @prefix is a shortcut, so it should not be completed + * but left as is (and an additional check for shortcut ambiguity is performed) + * + * Returns a list of properties compatible with the current connection type + * for the shell autocompletion functionality. + * + * Returns: list of property.arg elements + */ +static char * +get_valid_properties_string(const NMMetaSettingValidPartItem *const *array, + const NMMetaSettingValidPartItem *const *array_slv, + NMMetaAccessorModifier modifier, + const char * prefix, + const char * postfix) +{ + const NMMetaSettingValidPartItem *const *iter = array; + const char * prop_name = NULL; + GString * str; + guint i, j; + gboolean full_match = FALSE; + + g_return_val_if_fail(prefix, NULL); + + str = g_string_sized_new(1024); + + for (i = 0; i < 2; i++, iter = array_slv) { + for (; !full_match && iter && *iter; iter++) { + const NMMetaSettingInfoEditor *setting_info = (*iter)->setting_info; + + if (!(g_str_has_prefix(setting_info->general->setting_name, prefix)) + && (!setting_info->alias || !g_str_has_prefix(setting_info->alias, prefix))) { + continue; + } + + /* If postix (so prefix is terminated by a dot), check + * that prefix is not ambiguous */ + if (postfix) { + /* If we have a perfect match, no need to look for others + * prefix and no check on ambiguity should be performed. + * Moreover, erase previous matches from output string */ + if (nm_streq(prefix, setting_info->general->setting_name) + || nm_streq0(prefix, setting_info->alias)) { + g_string_erase(str, 0, -1); + full_match = TRUE; + } else if (prop_name) + return g_string_free(str, TRUE); + prop_name = prefix; + } else + prop_name = setting_info->general->setting_name; + + /* Search the array with the arguments of the current property */ + for (j = 0; j < setting_info->properties_num; j++) { + gs_free char *ss1 = NULL; + const char * arg_name; + + arg_name = setting_info->properties[j]->property_name; + + /* If required, expand the alias too */ + if (!postfix && setting_info->alias) { + gs_free char *ss2 = NULL; + + ss2 = _construct_property_name(setting_info->alias, arg_name, modifier); + g_string_append(str, ss2); + } + + if (postfix && !g_str_has_prefix(arg_name, postfix)) + continue; + + ss1 = _construct_property_name(prop_name, arg_name, modifier); + g_string_append(str, ss1); + } + } + } + return g_string_free(str, FALSE); +} + +/* + * Check if 'val' is valid string in either array->name or array->alias for + * both array parameters (array & array_slv). + * It accepts shorter string provided they are not ambiguous. + * 'val' == NULL doesn't hurt. + * + * Returns: pointer to array->name string or NULL on failure. + * The returned string must not be freed. + */ +static const char * +check_valid_name(const char * val, + const NMMetaSettingValidPartItem *const *array, + const NMMetaSettingValidPartItem *const *array_slv, + GError ** error) +{ + const NMMetaSettingValidPartItem *const *iter; + gs_unref_ptrarray GPtrArray *tmp_arr = NULL; + const char * str; + GError * tmp_err = NULL; + int i; + + g_return_val_if_fail(array, NULL); + + /* Create a temporary array that can be used in nmc_string_is_valid() */ + tmp_arr = g_ptr_array_sized_new(32); + iter = array; + for (i = 0; i < 2; i++, iter = array_slv) { + for (; iter && *iter; iter++) { + const NMMetaSettingInfoEditor *setting_info = (*iter)->setting_info; + + g_ptr_array_add(tmp_arr, (gpointer) setting_info->general->setting_name); + if (setting_info->alias) + g_ptr_array_add(tmp_arr, (gpointer) setting_info->alias); + } + } + g_ptr_array_add(tmp_arr, (gpointer) NULL); + + /* Check string validity */ + str = nmc_string_is_valid(val, (const char **) tmp_arr->pdata, &tmp_err); + if (!str) { + if (nm_g_error_matches(tmp_err, NM_UTILS_ERROR, NM_UTILS_ERROR_AMBIGUOUS)) + g_propagate_error(error, tmp_err); + else { + /* We want to handle aliases, so construct own error message */ + gs_free char *err_str = NULL; + + err_str = get_valid_options_string(array, array_slv); + g_set_error(error, 1, 0, _("'%s' not among [%s]"), val, err_str); + g_clear_error(&tmp_err); + } + return NULL; + } + + /* Return a pointer to the found string in passed 'array' */ + iter = array; + for (i = 0; i < 2; i++, iter = array_slv) { + for (; iter && *iter; iter++) { + const NMMetaSettingInfoEditor *setting_info = (*iter)->setting_info; + + if (nm_streq(setting_info->general->setting_name, str) + || nm_streq0(setting_info->alias, str)) { + return setting_info->general->setting_name; + } + } + } + + /* We should not really come here */ + g_set_error(error, 1, 0, _("Unknown error")); + return NULL; +} + +static const char * +check_valid_name_toplevel(const char *val, const char **slave_type, GError **error) +{ + gs_unref_ptrarray GPtrArray * tmp_arr = NULL; + const NMMetaSettingInfoEditor *setting_info; + gs_free_error GError *tmp_err = NULL; + const char * str; + int i; + + NM_SET_OUT(slave_type, NULL); + + /* Create a temporary array that can be used in nmc_string_is_valid() */ + tmp_arr = g_ptr_array_sized_new(32); + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) { + setting_info = &nm_meta_setting_infos_editor[i]; + g_ptr_array_add(tmp_arr, (gpointer) setting_info->general->setting_name); + if (setting_info->alias) + g_ptr_array_add(tmp_arr, (gpointer) setting_info->alias); + } + g_ptr_array_add(tmp_arr, "bond-slave"); + g_ptr_array_add(tmp_arr, "bridge-slave"); + g_ptr_array_add(tmp_arr, "team-slave"); + g_ptr_array_add(tmp_arr, (gpointer) NULL); + + /* Check string validity */ + str = nmc_string_is_valid(val, (const char **) tmp_arr->pdata, &tmp_err); + if (!str) { + if (nm_g_error_matches(tmp_err, NM_UTILS_ERROR, NM_UTILS_ERROR_AMBIGUOUS)) + g_propagate_error(error, g_steal_pointer(&tmp_err)); + else { + /* We want to handle aliases, so construct own error message */ + gs_free char *err_str = NULL; + + err_str = get_valid_options_string_toplevel(); + g_set_error(error, 1, 0, _("'%s' not among [%s]"), val, err_str); + } + return NULL; + } + + if (nm_streq(str, "bond-slave")) { + NM_SET_OUT(slave_type, NM_SETTING_BOND_SETTING_NAME); + return NM_SETTING_WIRED_SETTING_NAME; + } else if (nm_streq(str, "bridge-slave")) { + NM_SET_OUT(slave_type, NM_SETTING_BRIDGE_SETTING_NAME); + return NM_SETTING_WIRED_SETTING_NAME; + } else if (nm_streq(str, "team-slave")) { + NM_SET_OUT(slave_type, NM_SETTING_TEAM_SETTING_NAME); + return NM_SETTING_WIRED_SETTING_NAME; + } + + setting_info = nm_meta_setting_info_editor_find_by_name(str, TRUE); + if (setting_info) + return setting_info->general->setting_name; + + /* We should not really come here */ + g_set_error(error, 1, 0, _("Unknown error")); + return NULL; +} + +static gboolean +is_setting_mandatory(NMConnection *connection, NMSetting *setting) +{ + NMSettingConnection * s_con; + const char * c_type; + const NMMetaSettingValidPartItem *const *item; + const char * name; + const char * s_type; + guint i; + + s_con = nm_connection_get_setting_connection(connection); + g_assert(s_con); + c_type = nm_setting_connection_get_connection_type(s_con); + s_type = nm_setting_connection_get_slave_type(s_con); + + name = nm_setting_get_name(setting); + + for (i = 0; i < 2; i++) { + if (i == 0) + item = get_valid_settings_array(c_type); + else + item = nm_meta_setting_info_valid_parts_for_slave_type(s_type, NULL); + for (; item && *item; item++) { + if (!strcmp(name, (*item)->setting_info->general->setting_name)) + return (*item)->mandatory; + } + } + + return FALSE; +} + +/*****************************************************************************/ + +static const char * +_strip_master_prefix(const char *master, const char *(**func)(NMConnection *) ) +{ + if (!master) + return NULL; + + if (g_str_has_prefix(master, "ifname/")) { + master = master + strlen("ifname/"); + if (func) + *func = nm_connection_get_interface_name; + } else if (g_str_has_prefix(master, "uuid/")) { + master = master + strlen("uuid/"); + if (func) + *func = nm_connection_get_uuid; + } else if (g_str_has_prefix(master, "id/")) { + master = master + strlen("id/"); + if (func) + *func = nm_connection_get_id; + } + return master; +} + +/* normalized_master_for_slave: + * @connections: list af all connections + * @master: UUID, ifname or ID of the master connection + * @type: virtual connection type (bond, team, bridge, ...) or %NULL + * @out_type: type of the connection that matched + * + * Check whether master is a valid interface name, UUID or ID of some connection, + * possibly of a specified @type. + * First UUID and ifname are checked. If they don't match, ID is checked + * and replaced by UUID on a match. + * + * Returns: identifier of master connection if found, %NULL otherwise + */ +static const char * +normalized_master_for_slave(const GPtrArray *connections, + const char * master, + const char * type, + const char ** out_type) +{ + NMConnection * connection; + NMSettingConnection *s_con; + const char * con_type = NULL, *id, *uuid, *ifname; + guint i; + const char * found_by_id = NULL; + const char * out_type_by_id = NULL; + const char * out_master = NULL; + const char *(*func)(NMConnection *) = NULL; + + if (!master) + return NULL; + + master = _strip_master_prefix(master, &func); + for (i = 0; i < connections->len; i++) { + connection = NM_CONNECTION(connections->pdata[i]); + s_con = nm_connection_get_setting_connection(connection); + g_assert(s_con); + con_type = nm_setting_connection_get_connection_type(s_con); + if (type && g_strcmp0(con_type, type) != 0) + continue; + if (func) { + /* There was a prefix; only compare to that type. */ + if (g_strcmp0(master, func(connection)) == 0) { + if (out_type) + *out_type = con_type; + if (func == nm_connection_get_id) + out_master = nm_connection_get_uuid(connection); + else + out_master = master; + break; + } + } else { + id = nm_connection_get_id(connection); + uuid = nm_connection_get_uuid(connection); + ifname = nm_connection_get_interface_name(connection); + if (g_strcmp0(master, uuid) == 0 || g_strcmp0(master, ifname) == 0) { + out_master = master; + if (out_type) + *out_type = con_type; + break; + } + if (!found_by_id && g_strcmp0(master, id) == 0) { + out_type_by_id = con_type; + found_by_id = uuid; + } + } + } + + if (!out_master) { + out_master = found_by_id; + if (out_type) + *out_type = out_type_by_id; + } + + if (!out_master) { + g_print(_("Warning: master='%s' doesn't refer to any existing profile.\n"), master); + out_master = master; + if (out_type) + *out_type = type; + } + + return out_master; +} + +#define WORD_YES "yes" +#define WORD_NO "no" +static const char * +prompt_yes_no(gboolean default_yes, char *delim) +{ + static char prompt[128] = {0}; + + if (!delim) + delim = ""; + + snprintf(prompt, + sizeof(prompt), + "(%s/%s) [%s]%s ", + WORD_YES, + WORD_NO, + default_yes ? WORD_YES : WORD_NO, + delim); + + return prompt; +} + +static NMSetting * +is_setting_valid(NMConnection * connection, + const NMMetaSettingValidPartItem *const *valid_settings_main, + const NMMetaSettingValidPartItem *const *valid_settings_slave, + const char * setting) +{ + const char *setting_name; + + if (!(setting_name = + check_valid_name(setting, valid_settings_main, valid_settings_slave, NULL))) + return NULL; + return nm_connection_get_setting_by_name(connection, setting_name); +} + +static char * +is_property_valid(NMSetting *setting, const char *property, GError **error) +{ + gs_strfreev char **valid_props = NULL; + const char * prop_name; + + valid_props = nmc_setting_get_valid_properties(setting); + prop_name = nmc_string_is_valid(property, (const char **) valid_props, error); + return g_strdup(prop_name); +} + +static char * +unique_master_iface_ifname(const GPtrArray *connections, const char *try_name) +{ + char *new_name; + guint num = 0; + guint i; + + new_name = g_strdup(try_name); + +again: + for (i = 0; i < connections->len; i++) { + NMConnection *connection = connections->pdata[i]; + + if (nm_streq0(new_name, nm_connection_get_interface_name(connection))) { + num++; + g_free(new_name); + new_name = g_strdup_printf("%s%u", try_name, num); + goto again; + } + } + return new_name; +} + +static void +set_default_interface_name(NmCli *nmc, NMSettingConnection *s_con) +{ + const char *default_name; + const char *con_type; + + if (nm_setting_connection_get_interface_name(s_con)) + return; + + con_type = nm_setting_connection_get_connection_type(s_con); + + /* Set a sensible bond/team/bridge interface name by default */ + if (nm_streq0(con_type, NM_SETTING_BOND_SETTING_NAME)) + default_name = "nm-bond"; + else if (nm_streq0(con_type, NM_SETTING_TEAM_SETTING_NAME)) + default_name = "nm-team"; + else if (nm_streq0(con_type, NM_SETTING_BRIDGE_SETTING_NAME)) + default_name = "nm-bridge"; + else + default_name = NULL; + + if (default_name) { + const GPtrArray *connections; + gs_free char * ifname = NULL; + + connections = nm_client_get_connections(nmc->client); + ifname = unique_master_iface_ifname(connections, default_name); + g_object_set(s_con, NM_SETTING_CONNECTION_INTERFACE_NAME, ifname, NULL); + } +} + +/*****************************************************************************/ + +static PropertyInfFlags +_dynamic_options_set(const NMMetaAbstractInfo *abstract_info, + PropertyInfFlags mask, + PropertyInfFlags set) +{ + static GHashTable *cache = NULL; + gpointer p; + PropertyInfFlags v, v2; + + if (G_UNLIKELY(!cache)) + cache = g_hash_table_new(nm_direct_hash, NULL); + + if (g_hash_table_lookup_extended(cache, (gpointer) abstract_info, NULL, &p)) + v = GPOINTER_TO_UINT(p); + else + v = 0; + + v2 = (v & ~mask) | (mask & set); + if (v != v2) + g_hash_table_insert(cache, (gpointer) abstract_info, GUINT_TO_POINTER(v2)); + + return v2; +} + +static PropertyInfFlags +_dynamic_options_get(const NMMetaAbstractInfo *abstract_info) +{ + return _dynamic_options_set(abstract_info, 0, 0); +} + +/*****************************************************************************/ + +static gboolean +_meta_property_needs_bond_hack(const NMMetaPropertyInfo *property_info) +{ + /* hack: the bond property data is handled special and not generically. + * Eventually, get rid of explicitly checking whether we handle a bond. */ + if (!property_info) + g_return_val_if_reached(FALSE); + return property_info->property_typ_data + && property_info->property_typ_data->nested == &nm_meta_property_typ_data_bond; +} + +static char ** +_meta_abstract_complete(const NMMetaAbstractInfo *abstract_info, const char *text) +{ + const char *const * values; + char ** values_to_free = NULL; + const NMMetaOperationContext ctx = { + .connection = nmc_tab_completion.connection, + }; + + values = nm_meta_abstract_info_complete(abstract_info, + nmc_meta_environment, + (gpointer) nmc_meta_environment_arg, + &ctx, + text, + NULL, + &values_to_free); + if (values) + return values_to_free ?: g_strdupv((char **) values); + return NULL; +} + +static char * +_meta_abstract_generator(const char *text, int state) +{ + if (nmc_tab_completion.words) { + return nmc_rl_gen_func_basic(text, state, (const char *const *) nmc_tab_completion.words); + } + + return NULL; +} + +static void +_meta_abstract_get(const NMMetaAbstractInfo * abstract_info, + const NMMetaSettingInfoEditor **out_setting_info, + const char ** out_setting_name, + const char ** out_property_name, + const char ** out_option, + NMMetaPropertyInfFlags * out_inf_flags, + const char ** out_prompt, + const char ** out_def_hint) +{ + const NMMetaPropertyInfo *info = (const NMMetaPropertyInfo *) abstract_info; + + NM_SET_OUT(out_option, info->property_alias); + NM_SET_OUT(out_setting_info, info->setting_info); + NM_SET_OUT(out_setting_name, info->setting_info->general->setting_name); + NM_SET_OUT(out_property_name, info->property_name); + NM_SET_OUT(out_option, info->property_alias); + NM_SET_OUT(out_inf_flags, info->inf_flags); + NM_SET_OUT(out_prompt, info->prompt); + NM_SET_OUT(out_def_hint, info->def_hint); +} + +static const OptionInfo *_meta_abstract_get_option_info(const NMMetaAbstractInfo *abstract_info); + +/* + * Mark options in option_info as relevant. + * The questionnaire (for --ask) will ask for them. + */ +static void +enable_options(const char *setting_name, const char *property, const char *const *opts) +{ + const NMMetaPropertyInfo *property_info; + + property_info = nm_meta_property_info_find_by_name(setting_name, property); + + if (!property_info) + g_return_if_reached(); + + if (_meta_property_needs_bond_hack(property_info)) { + guint i; + + for (i = 0; i < nm_meta_property_typ_data_bond.nested_len; i++) { + const NMMetaNestedPropertyInfo *bi = &nm_meta_property_typ_data_bond.nested[i]; + + if (bi->base.inf_flags & NM_META_PROPERTY_INF_FLAG_DONT_ASK && bi->base.property_alias + && g_strv_contains(opts, bi->base.property_alias)) + _dynamic_options_set((const NMMetaAbstractInfo *) bi, + PROPERTY_INF_FLAG_ENABLED, + PROPERTY_INF_FLAG_ENABLED); + } + return; + } + + if (!property_info->is_cli_option) + g_return_if_reached(); + + if (property_info->inf_flags & NM_META_PROPERTY_INF_FLAG_DONT_ASK + && property_info->property_alias && g_strv_contains(opts, property_info->property_alias)) + _dynamic_options_set((const NMMetaAbstractInfo *) property_info, + PROPERTY_INF_FLAG_ENABLED, + PROPERTY_INF_FLAG_ENABLED); +} + +/* + * Mark options in option_info as irrelevant (because we learned they make no sense + * or they have been set via different means). + * The questionnaire (for --ask) will not ask for them. + */ +static void +disable_options(const char *setting_name, const char *property) +{ + const NMMetaPropertyInfo * property_infos_local[2]; + const NMMetaPropertyInfo *const *property_infos; + guint p; + + if (property) { + const NMMetaPropertyInfo *pi; + + pi = nm_meta_property_info_find_by_name(setting_name, property); + if (!pi) + g_return_if_reached(); + if (!_meta_property_needs_bond_hack(pi) && !pi->is_cli_option) + return; + property_infos_local[0] = pi; + property_infos_local[1] = NULL; + property_infos = property_infos_local; + } else { + const NMMetaSettingInfoEditor *setting_info; + + setting_info = nm_meta_setting_info_editor_find_by_name(setting_name, FALSE); + if (!setting_info) + g_return_if_reached(); + property_infos = setting_info->properties; + if (!property_infos) + return; + } + + for (p = 0; property_infos[p]; p++) { + const NMMetaPropertyInfo *property_info = property_infos[p]; + + if (_meta_property_needs_bond_hack(property_info)) { + guint i; + + for (i = 0; i < nm_meta_property_typ_data_bond.nested_len; i++) { + const NMMetaNestedPropertyInfo *bi = &nm_meta_property_typ_data_bond.nested[i]; + + _dynamic_options_set((const NMMetaAbstractInfo *) bi, + PROPERTY_INF_FLAG_DISABLED, + PROPERTY_INF_FLAG_DISABLED); + } + nm_assert(p == 0 && !property_infos[1]); + } else { + if (property_info->is_cli_option) + _dynamic_options_set((const NMMetaAbstractInfo *) property_info, + PROPERTY_INF_FLAG_DISABLED, + PROPERTY_INF_FLAG_DISABLED); + } + } +} + +/* + * Reset marks done with enable_options() and disable_options(). + * Ensures correct operation in case more than one connection is added in a single + * nmcli session. + */ +static void +reset_options(void) +{ + NMMetaSettingType s; + + for (s = 0; s < _NM_META_SETTING_TYPE_NUM; s++) { + const NMMetaPropertyInfo *const *property_infos; + guint p; + + property_infos = nm_meta_setting_infos_editor[s].properties; + if (!property_infos) + continue; + for (p = 0; property_infos[p]; p++) { + const NMMetaPropertyInfo *property_info = property_infos[p]; + + if (_meta_property_needs_bond_hack(property_info)) { + guint i; + + for (i = 0; i < nm_meta_property_typ_data_bond.nested_len; i++) { + const NMMetaNestedPropertyInfo *bi = &nm_meta_property_typ_data_bond.nested[i]; + + _dynamic_options_set((const NMMetaAbstractInfo *) bi, PROPERTY_INF_FLAG_ALL, 0); + } + } else { + if (property_info->is_cli_option) + _dynamic_options_set((const NMMetaAbstractInfo *) property_info, + PROPERTY_INF_FLAG_ALL, + 0); + } + } + } +} + +static gboolean +set_property(NMClient * client, + NMConnection * connection, + const char * setting_name, + const char * property, + const char * value, + NMMetaAccessorModifier modifier, + GError ** error) +{ + gs_free char *property_name = NULL; + gs_free_error GError *local = NULL; + NMSetting * setting; + + nm_assert(setting_name && setting_name[0]); + nm_assert(NM_IN_SET(modifier, + NM_META_ACCESSOR_MODIFIER_SET, + NM_META_ACCESSOR_MODIFIER_ADD, + NM_META_ACCESSOR_MODIFIER_DEL)); + + setting = nm_connection_get_setting_by_name(connection, setting_name); + if (!setting) { + setting = nm_meta_setting_info_editor_new_setting( + nm_meta_setting_info_editor_find_by_name(setting_name, FALSE), + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + nm_connection_add_setting(connection, setting); + } + + property_name = is_property_valid(setting, property, &local); + if (!property_name) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: invalid property '%s': %s."), + property, + local->message); + return FALSE; + } + + if (!nmc_setting_set_property(client, + setting, + property_name, + ((modifier == NM_META_ACCESSOR_MODIFIER_DEL && !value) + ? NM_META_ACCESSOR_MODIFIER_SET + : modifier), + value, + &local)) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: failed to %s %s.%s: %s."), + (modifier != NM_META_ACCESSOR_MODIFIER_DEL ? "modify" : "remove a value from"), + setting_name, + property, + local->message); + return FALSE; + } + + /* Don't ask for this property in interactive mode. */ + disable_options(setting_name, property_name); + + return TRUE; +} + +static gboolean +set_option(NmCli * nmc, + NMConnection * connection, + const NMMetaAbstractInfo *abstract_info, + const char * value, + GError ** error) +{ + const char * setting_name, *property_name, *option_name; + NMMetaPropertyInfFlags inf_flags; + const OptionInfo * option; + + option = _meta_abstract_get_option_info(abstract_info); + + _dynamic_options_set(abstract_info, PROPERTY_INF_FLAG_DISABLED, PROPERTY_INF_FLAG_DISABLED); + + _meta_abstract_get(abstract_info, + NULL, + &setting_name, + &property_name, + &option_name, + &inf_flags, + NULL, + NULL); + if (option && option->check_and_set) { + return option->check_and_set(nmc, connection, option, value, error); + } else { + set_property(nmc->client, + connection, + setting_name, + property_name, + value, + !value ? NM_META_ACCESSOR_MODIFIER_DEL + : (inf_flags & NM_META_PROPERTY_INF_FLAG_MULTI + ? NM_META_ACCESSOR_MODIFIER_ADD + : NM_META_ACCESSOR_MODIFIER_SET), + error); + } + + return TRUE; +} + +/* + * Return relevant NameItem[] tables for given connection (based on connection type + * and slave type. + */ +static gboolean +con_settings(NMConnection * connection, + const NMMetaSettingValidPartItem *const **type_settings, + const NMMetaSettingValidPartItem *const **slv_settings, + GError ** error) +{ + const char * con_type; + NMSettingConnection *s_con; + + g_return_val_if_fail(type_settings, FALSE); + g_return_val_if_fail(slv_settings, FALSE); + + s_con = nm_connection_get_setting_connection(connection); + g_assert(s_con); + + con_type = nm_setting_connection_get_slave_type(s_con); + *slv_settings = nm_meta_setting_info_valid_parts_for_slave_type(con_type, NULL); + if (!*slv_settings) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: invalid slave type; %s."), + con_type); + return FALSE; + } + + con_type = nm_setting_connection_get_connection_type(s_con); + *type_settings = get_valid_settings_array(con_type); + if (!*type_settings) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: invalid connection type; %s."), + con_type); + return FALSE; + } + + return TRUE; +} + +/* + * Make sure all required settings are in place (should be called when + * it's possible that a type is already set). + */ +static void +ensure_settings(NMConnection *connection, const NMMetaSettingValidPartItem *const *item) +{ + NMSetting *setting; + + for (; item && *item; item++) { + if (!(*item)->mandatory) + continue; + if (nm_connection_get_setting_by_name(connection, + (*item)->setting_info->general->setting_name)) + continue; + setting = nm_meta_setting_info_editor_new_setting((*item)->setting_info, + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + nm_connection_add_setting(connection, setting); + } +} + +/*****************************************************************************/ + +static char * +gen_func_bool_values_l10n(const char *text, int state) +{ + const char *words[] = {WORD_YES, WORD_NO, NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static char * +gen_func_bt_type(const char *text, int state) +{ + const char *words[] = {"panu", "nap", "dun-gsm", "dun-cdma", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static char * +gen_func_bond_mode(const char *text, int state) +{ + const char *words[] = {"balance-rr", + "active-backup", + "balance-xor", + "broadcast", + "802.3ad", + "balance-tlb", + "balance-alb", + NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} +static char * +gen_func_bond_mon_mode(const char *text, int state) +{ + const char *words[] = {"miimon", "arp", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} +static char * +gen_func_bond_lacp_rate(const char *text, int state) +{ + const char *words[] = {"slow", "fast", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +/*****************************************************************************/ + +static gboolean +set_connection_type(NmCli * nmc, + NMConnection * con, + const OptionInfo *option, + const char * value, + GError ** error) +{ + const NMMetaSettingValidPartItem *const *type_settings; + const NMMetaSettingValidPartItem *const *slv_settings; + GError * local = NULL; + const char * master[] = {"master", NULL}; + const char * slave_type = NULL; + + value = check_valid_name_toplevel(value, &slave_type, &local); + if (!value) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: bad connection type: %s"), + local->message); + g_clear_error(&local); + return FALSE; + } + + if (slave_type) { + if (!set_property(nmc->client, + con, + NM_SETTING_CONNECTION_SETTING_NAME, + NM_SETTING_CONNECTION_SLAVE_TYPE, + slave_type, + NM_META_ACCESSOR_MODIFIER_SET, + error)) { + return FALSE; + } + enable_options(NM_SETTING_CONNECTION_SETTING_NAME, NM_SETTING_CONNECTION_MASTER, master); + } + + /* ifname is mandatory for all connection types except virtual ones (bond, team, bridge, vlan) */ + if ((strcmp(value, NM_SETTING_BOND_SETTING_NAME) == 0) + || (strcmp(value, NM_SETTING_TEAM_SETTING_NAME) == 0) + || (strcmp(value, NM_SETTING_BRIDGE_SETTING_NAME) == 0) + || (strcmp(value, NM_SETTING_VLAN_SETTING_NAME) == 0)) { + disable_options(NM_SETTING_CONNECTION_SETTING_NAME, NM_SETTING_CONNECTION_INTERFACE_NAME); + } + + if (!set_property(nmc->client, + con, + option->setting_info->general->setting_name, + option->property, + value, + NM_META_ACCESSOR_MODIFIER_SET, + error)) + return FALSE; + + if (!con_settings(con, &type_settings, &slv_settings, error)) + return FALSE; + + ensure_settings(con, slv_settings); + ensure_settings(con, type_settings); + + return TRUE; +} + +static gboolean +set_connection_iface(NmCli * nmc, + NMConnection * con, + const OptionInfo *option, + const char * value, + GError ** error) +{ + if (value) { + /* Special value of '*' means no specific interface name */ + if (strcmp(value, "*") == 0) + value = NULL; + } + + return set_property(nmc->client, + con, + option->setting_info->general->setting_name, + option->property, + value, + NM_META_ACCESSOR_MODIFIER_SET, + error); +} + +static gboolean +set_connection_master(NmCli * nmc, + NMConnection * con, + const OptionInfo *option, + const char * value, + GError ** error) +{ + const GPtrArray * connections; + NMSettingConnection *s_con; + const char * slave_type; + + s_con = nm_connection_get_setting_connection(con); + g_return_val_if_fail(s_con, FALSE); + + if (!value) { + g_set_error_literal(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: master is required")); + return FALSE; + } + + slave_type = nm_setting_connection_get_slave_type(s_con); + connections = nm_client_get_connections(nmc->client); + value = normalized_master_for_slave(connections, value, slave_type, &slave_type); + + if (!set_property(nmc->client, + con, + NM_SETTING_CONNECTION_SETTING_NAME, + NM_SETTING_CONNECTION_SLAVE_TYPE, + slave_type, + NM_META_ACCESSOR_MODIFIER_SET, + error)) { + return FALSE; + } + + return set_property(nmc->client, + con, + option->setting_info->general->setting_name, + option->property, + value, + NM_META_ACCESSOR_MODIFIER_SET, + error); +} + +static gboolean +set_bond_option(NmCli * nmc, + NMConnection * con, + const OptionInfo *option, + const char * value, + GError ** error) +{ + NMSettingBond *s_bond; + gboolean success; + gs_free char * name = NULL; + char * p; + + s_bond = nm_connection_get_setting_bond(con); + g_return_val_if_fail(s_bond, FALSE); + + name = g_strdup(option->option); + for (p = name; p[0]; p++) { + if (p[0] == '-') + p[0] = '_'; + } + + if (nm_str_is_empty(value)) { + nm_setting_bond_remove_option(s_bond, name); + success = TRUE; + } else + success = _nm_meta_setting_bond_add_option(NM_SETTING(s_bond), name, value, error); + + if (!success) + return FALSE; + + if (success) { + if (nm_streq(name, NM_SETTING_BOND_OPTION_MODE)) { + value = nmc_bond_validate_mode(value, error); + if (nm_streq(value, "active-backup")) { + enable_options(NM_SETTING_BOND_SETTING_NAME, + NM_SETTING_BOND_OPTIONS, + NM_MAKE_STRV("primary")); + } + } + } + + return success; +} + +static gboolean +set_bond_monitoring_mode(NmCli * nmc, + NMConnection * con, + const OptionInfo *option, + const char * value, + GError ** error) +{ + NMSettingBond *s_bond; + gs_free char * monitor_mode = NULL; + const char * miimon_opts[] = {"miimon", "downdelay", "updelay", NULL}; + const char * arp_opts[] = {"arp-interval", "arp-ip-target", NULL}; + + s_bond = nm_connection_get_setting_bond(con); + g_return_val_if_fail(s_bond, FALSE); + + if (value) { + monitor_mode = g_strdup(value); + g_strstrip(monitor_mode); + } else { + monitor_mode = g_strdup(NM_META_TEXT_WORD_MIIMON); + } + + if (matches(monitor_mode, NM_META_TEXT_WORD_MIIMON)) + enable_options(NM_SETTING_BOND_SETTING_NAME, NM_SETTING_BOND_OPTIONS, miimon_opts); + else if (matches(monitor_mode, NM_META_TEXT_WORD_ARP)) + enable_options(NM_SETTING_BOND_SETTING_NAME, NM_SETTING_BOND_OPTIONS, arp_opts); + else { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: '%s' is not a valid monitoring mode; use '%s' or '%s'.\n"), + monitor_mode, + NM_META_TEXT_WORD_MIIMON, + NM_META_TEXT_WORD_ARP); + return FALSE; + } + + return TRUE; +} + +static gboolean +set_bluetooth_type(NmCli * nmc, + NMConnection * con, + const OptionInfo *option, + const char * value, + GError ** error) +{ + NMSetting *setting; + + if (!value) + return TRUE; + + /* 'dun' type requires adding 'gsm' or 'cdma' setting */ + if (!strcmp(value, NM_SETTING_BLUETOOTH_TYPE_DUN) + || !strcmp(value, NM_SETTING_BLUETOOTH_TYPE_DUN "-gsm")) { + value = NM_SETTING_BLUETOOTH_TYPE_DUN; + setting = nm_meta_setting_info_editor_new_setting( + &nm_meta_setting_infos_editor[NM_META_SETTING_TYPE_GSM], + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + nm_connection_add_setting(con, setting); + } else if (!strcmp(value, NM_SETTING_BLUETOOTH_TYPE_DUN "-cdma")) { + value = NM_SETTING_BLUETOOTH_TYPE_DUN; + setting = nm_setting_cdma_new(); + nm_connection_add_setting(con, setting); + } else if (!strcmp(value, NM_SETTING_BLUETOOTH_TYPE_PANU) + || !strcmp(value, NM_SETTING_BLUETOOTH_TYPE_NAP)) { + /* no op */ + } else { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: 'bt-type': '%s' not valid; use [%s, %s, %s (%s), %s]."), + value, + NM_SETTING_BLUETOOTH_TYPE_PANU, + NM_SETTING_BLUETOOTH_TYPE_NAP, + NM_SETTING_BLUETOOTH_TYPE_DUN, + NM_SETTING_BLUETOOTH_TYPE_DUN "-gsm", + NM_SETTING_BLUETOOTH_TYPE_DUN "-cdma"); + return FALSE; + } + + return set_property(nmc->client, + con, + option->setting_info->general->setting_name, + option->property, + value, + NM_META_ACCESSOR_MODIFIER_SET, + error); +} + +static gboolean +set_ip4_address(NmCli * nmc, + NMConnection * con, + const OptionInfo *option, + const char * value, + GError ** error) +{ + NMSettingIPConfig *s_ip4; + + if (!value) + return TRUE; + + s_ip4 = nm_connection_get_setting_ip4_config(con); + if (!s_ip4) { + s_ip4 = (NMSettingIPConfig *) nm_setting_ip4_config_new(); + nm_connection_add_setting(con, NM_SETTING(s_ip4)); + g_object_set(s_ip4, NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP4_CONFIG_METHOD_MANUAL, NULL); + } + return set_property(nmc->client, + con, + option->setting_info->general->setting_name, + option->property, + value, + NM_META_ACCESSOR_MODIFIER_ADD, + error); +} + +static gboolean +set_ip6_address(NmCli * nmc, + NMConnection * con, + const OptionInfo *option, + const char * value, + GError ** error) +{ + NMSettingIPConfig *s_ip6; + + if (!value) + return TRUE; + + s_ip6 = nm_connection_get_setting_ip6_config(con); + if (!s_ip6) { + s_ip6 = (NMSettingIPConfig *) nm_setting_ip6_config_new(); + nm_connection_add_setting(con, NM_SETTING(s_ip6)); + g_object_set(s_ip6, NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL); + } + return set_property(nmc->client, + con, + option->setting_info->general->setting_name, + option->property, + value, + NM_META_ACCESSOR_MODIFIER_ADD, + error); +} + +/*****************************************************************************/ + +static const OptionInfo * +_meta_abstract_get_option_info(const NMMetaAbstractInfo *abstract_info) +{ + static const OptionInfo option_info[] = { +#define OPTION_INFO(name, property_name_, property_alias_, check_and_set_, generator_func_) \ + { \ + .setting_info = &nm_meta_setting_infos_editor[NM_META_SETTING_TYPE_##name], \ + .property = property_name_, \ + .option = property_alias_, \ + .check_and_set = check_and_set_, \ + .generator_func = generator_func_, \ + } + OPTION_INFO(CONNECTION, NM_SETTING_CONNECTION_TYPE, "type", set_connection_type, NULL), + OPTION_INFO(CONNECTION, + NM_SETTING_CONNECTION_INTERFACE_NAME, + "ifname", + set_connection_iface, + NULL), + OPTION_INFO(CONNECTION, + NM_SETTING_CONNECTION_MASTER, + "master", + set_connection_master, + NULL), + OPTION_INFO(BLUETOOTH, + NM_SETTING_BLUETOOTH_TYPE, + "bt-type", + set_bluetooth_type, + gen_func_bt_type), + OPTION_INFO(BOND, NM_SETTING_BOND_OPTIONS, "mode", set_bond_option, gen_func_bond_mode), + OPTION_INFO(BOND, + NM_SETTING_BOND_OPTIONS, + "primary", + set_bond_option, + nmc_rl_gen_func_ifnames), + OPTION_INFO(BOND, + NM_SETTING_BOND_OPTIONS, + NULL, + set_bond_monitoring_mode, + gen_func_bond_mon_mode), + OPTION_INFO(BOND, NM_SETTING_BOND_OPTIONS, "miimon", set_bond_option, NULL), + OPTION_INFO(BOND, NM_SETTING_BOND_OPTIONS, "downdelay", set_bond_option, NULL), + OPTION_INFO(BOND, NM_SETTING_BOND_OPTIONS, "updelay", set_bond_option, NULL), + OPTION_INFO(BOND, NM_SETTING_BOND_OPTIONS, "arp-interval", set_bond_option, NULL), + OPTION_INFO(BOND, NM_SETTING_BOND_OPTIONS, "arp-ip-target", set_bond_option, NULL), + OPTION_INFO(BOND, + NM_SETTING_BOND_OPTIONS, + "lacp-rate", + set_bond_option, + gen_func_bond_lacp_rate), + OPTION_INFO(IP4_CONFIG, NM_SETTING_IP_CONFIG_ADDRESSES, "ip4", set_ip4_address, NULL), + OPTION_INFO(IP6_CONFIG, NM_SETTING_IP_CONFIG_ADDRESSES, "ip6", set_ip6_address, NULL), + {0}, + }; + const char * property_name, *option; + const NMMetaSettingInfoEditor *setting_info; + const OptionInfo * candidate; + + _meta_abstract_get(abstract_info, + &setting_info, + NULL, + &property_name, + &option, + NULL, + NULL, + NULL); + + for (candidate = option_info; candidate->setting_info; candidate++) { + if (candidate->setting_info == setting_info && nm_streq0(candidate->property, property_name) + && nm_streq0(candidate->option, option)) { + return candidate; + } + } + return NULL; +} + +static gboolean +option_relevant(NMConnection *connection, const NMMetaAbstractInfo *abstract_info) +{ + const char * setting_name; + NMMetaPropertyInfFlags inf_flags; + + _meta_abstract_get(abstract_info, NULL, &setting_name, NULL, NULL, &inf_flags, NULL, NULL); + + if ((inf_flags & NM_META_PROPERTY_INF_FLAG_DONT_ASK) + && !(_dynamic_options_get(abstract_info) & PROPERTY_INF_FLAG_ENABLED)) + return FALSE; + if (_dynamic_options_get(abstract_info) & PROPERTY_INF_FLAG_DISABLED) + return FALSE; + if (!nm_connection_get_setting_by_name(connection, setting_name)) + return FALSE; + return TRUE; +} + +/*****************************************************************************/ + +static void +complete_property_name(NmCli * nmc, + NMConnection * connection, + NMMetaAccessorModifier modifier, + const char * prefix, + const char * postfix) +{ + NMSettingConnection * s_con; + const NMMetaSettingValidPartItem *const *valid_settings_main; + const NMMetaSettingValidPartItem *const *valid_settings_slave; + const char * connection_type = NULL; + const char * slave_type = NULL; + gs_free char * word_list = NULL; + NMMetaSettingType s; + + connection_type = nm_connection_get_connection_type(connection); + s_con = nm_connection_get_setting_connection(connection); + if (s_con) + slave_type = nm_setting_connection_get_slave_type(s_con); + valid_settings_main = get_valid_settings_array(connection_type); + valid_settings_slave = nm_meta_setting_info_valid_parts_for_slave_type(slave_type, NULL); + + word_list = get_valid_properties_string(valid_settings_main, + valid_settings_slave, + modifier, + prefix, + postfix); + if (word_list) + g_print("%s", word_list); + + if (modifier != NM_META_ACCESSOR_MODIFIER_SET) + return; + + for (s = 0; s < _NM_META_SETTING_TYPE_NUM; s++) { + const NMMetaPropertyInfo *const *property_infos; + guint p; + + if (!nm_connection_get_setting_by_name( + connection, + nm_meta_setting_infos_editor[s].general->setting_name)) + continue; + + property_infos = nm_meta_setting_infos_editor[s].properties; + if (!property_infos) + continue; + for (p = 0; property_infos[p]; p++) { + const NMMetaPropertyInfo *property_info = property_infos[p]; + + if (_meta_property_needs_bond_hack(property_info)) { + guint i; + + for (i = 0; i < nm_meta_property_typ_data_bond.nested_len; i++) { + const NMMetaNestedPropertyInfo *bi = &nm_meta_property_typ_data_bond.nested[i]; + + if (!bi->base.property_alias + || !g_str_has_prefix(bi->base.property_alias, prefix)) + continue; + g_print("%s\n", bi->base.property_alias); + } + } else { + if (!property_info->is_cli_option) + continue; + if (!property_info->property_alias + || !g_str_has_prefix(property_info->property_alias, prefix)) + continue; + g_print("%s\n", property_info->property_alias); + } + } + } +} + +static void +run_rl_generator(rl_compentry_func_t *generator_func, const char *prefix) +{ + int state = 0; + char *str; + + while ((str = generator_func(prefix, state))) { + g_print("%s\n", str); + g_free(str); + if (state == 0) + state = 1; + } +} + +static gboolean +complete_option(NmCli * nmc, + const NMMetaAbstractInfo *abstract_info, + const char * prefix, + NMConnection * context_connection) +{ + const OptionInfo * candidate; + const char *const * values; + gs_strfreev char ** values_to_free = NULL; + gboolean complete_filename = FALSE; + const NMMetaOperationContext ctx = { + .connection = context_connection, + }; + + values = nm_meta_abstract_info_complete(abstract_info, + nmc_meta_environment, + (gpointer) nmc_meta_environment_arg, + &ctx, + prefix, + &complete_filename, + &values_to_free); + if (complete_filename) { + nmc->return_value = NMC_RESULT_COMPLETE_FILE; + return TRUE; + } + if (values) { + for (; values[0]; values++) + g_print("%s\n", values[0]); + return TRUE; + } + + candidate = _meta_abstract_get_option_info(abstract_info); + if (candidate && candidate->generator_func) { + run_rl_generator(candidate->generator_func, prefix); + return TRUE; + } + + return FALSE; +} + +static void +complete_existing_setting(NmCli *nmc, NMConnection *connection, const char *prefix) +{ + gs_free NMSetting ** settings = NULL; + const NMMetaSettingInfoEditor *editor; + guint i; + + settings = nm_connection_get_settings(connection, NULL); + for (i = 0; settings && settings[i]; i++) { + editor = nm_meta_setting_info_editor_find_by_setting(settings[i]); + + if (!prefix || g_str_has_prefix(editor->general->setting_name, prefix)) + g_print("%s\n", editor->general->setting_name); + + if (editor->alias) { + if (!prefix || g_str_has_prefix(editor->alias, prefix)) + g_print("%s\n", editor->alias); + } + } +} + +static void +complete_property(NmCli * nmc, + const char * setting_name, + const char * property, + const char * prefix, + NMConnection *connection) +{ + const NMMetaPropertyInfo *property_info; + + property_info = nm_meta_property_info_find_by_name(setting_name, property); + if (property_info) + complete_option(nmc, (const NMMetaAbstractInfo *) property_info, prefix, connection); +} + +/*****************************************************************************/ + +static gboolean +connection_remove_setting(NMConnection *connection, NMSetting *setting, GError **error) +{ + gboolean mandatory; + + g_return_val_if_fail(setting, FALSE); + + mandatory = is_setting_mandatory(connection, setting); + if (!mandatory) { + nm_connection_remove_setting(connection, G_OBJECT_TYPE(setting)); + return TRUE; + } + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: setting '%s' is mandatory and cannot be removed."), + nm_setting_get_name(setting)); + return FALSE; +} + +static gboolean +get_value(const char ** value, + int * argc, + const char *const **argv, + const char * option, + GError ** error) +{ + if (!**argv) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: value for '%s' is missing."), + option); + return FALSE; + } + + /* Empty string will reset the value to default */ + if (**argv[0] == '\0') + *value = NULL; + else + *value = *argv[0]; + + (*argc)--; + (*argv)++; + return TRUE; +} + +gboolean +nmc_process_connection_properties(NmCli * nmc, + NMConnection * connection, + int * argc, + const char *const **argv, + gboolean allow_setting_removal, + GError ** error) +{ + /* First check if we have a slave-type, as this would mean we will not + * have ip properties but possibly others, slave-type specific. + */ + /* Go through arguments and set properties */ + do { + const NMMetaSettingValidPartItem *const *type_settings; + const NMMetaSettingValidPartItem *const *slv_settings; + NMMetaAccessorModifier modifier; + const char * option_orig; + const char * option; + const char * value = NULL; + const char * tmp; + const NMMetaAbstractInfo * chosen = NULL; + const char * chosen_setting_name = NULL; + const char * chosen_option = NULL; + NMMetaSettingType s; + + if (!con_settings(connection, &type_settings, &slv_settings, error)) + return FALSE; + + ensure_settings(connection, slv_settings); + ensure_settings(connection, type_settings); + + if (*argc <= 0) { + g_set_error_literal(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: <setting>.<property> argument is missing.")); + return FALSE; + } + + nm_assert(argv); + nm_assert(*argv); + nm_assert(**argv); + + option_orig = **argv; + + switch (option_orig[0]) { + case '+': + modifier = NM_META_ACCESSOR_MODIFIER_ADD; + option = &option_orig[1]; + break; + case '-': + modifier = NM_META_ACCESSOR_MODIFIER_DEL; + option = &option_orig[1]; + break; + default: + modifier = NM_META_ACCESSOR_MODIFIER_SET; + option = option_orig; + break; + } + + if (allow_setting_removal && modifier == NM_META_ACCESSOR_MODIFIER_SET + && nm_streq(option, "remove")) { + NMSetting * ss; + const char *setting_name; + + (*argc)--; + (*argv)++; + + if (*argc == 1 && nmc->complete) { + complete_existing_setting(nmc, connection, value); + return TRUE; + } + + if (!*argc) { + g_set_error_literal(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: missing setting.")); + return FALSE; + } + + setting_name = **argv; + (*argc)--; + (*argv)++; + + ss = is_setting_valid(connection, type_settings, slv_settings, setting_name); + if (!ss) { + if (!check_valid_name(setting_name, type_settings, slv_settings, NULL)) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: invalid setting argument '%s'."), + setting_name); + return FALSE; + } + continue; + } + + if (!connection_remove_setting(connection, ss, error)) + return FALSE; + + continue; + } + + if ((tmp = strchr(option, '.'))) { + gs_free char *option_sett = g_strndup(option, tmp - option); + const char * option_prop = &tmp[1]; + const char * option_sett_expanded; + GError * local = NULL; + + /* This seems like a <setting>.<property> (such as "connection.id" or "bond.mode"), + * optionally prefixed with "+| or "-". */ + + if (*argc == 1 && nmc->complete) + complete_property_name(nmc, connection, modifier, option_sett, option_prop); + + option_sett_expanded = + check_valid_name(option_sett, type_settings, slv_settings, &local); + if (!option_sett_expanded) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: invalid or not allowed setting '%s': %s."), + option_sett, + local->message); + g_clear_error(&local); + return FALSE; + } + + (*argc)--; + (*argv)++; + if (!get_value(&value, argc, argv, option_orig, error)) + return FALSE; + + if (!*argc && nmc->complete) { + complete_property(nmc, option_sett, option_prop, value ?: "", connection); + return TRUE; + } + + if (!set_property(nmc->client, + connection, + option_sett_expanded, + option_prop, + value, + modifier, + error)) + return FALSE; + + continue; + } + + /* Let's see if this is an property alias (such as "id", "mode", "type" or "con-name")*/ + for (s = 0; s < _NM_META_SETTING_TYPE_NUM; s++) { + const NMMetaPropertyInfo *const *property_infos; + guint p; + + if (!check_valid_name(nm_meta_setting_infos[s].setting_name, + type_settings, + slv_settings, + NULL)) + continue; + + property_infos = nm_meta_setting_infos_editor[s].properties; + if (!property_infos) + continue; + for (p = 0; property_infos[p]; p++) { + const NMMetaPropertyInfo *property_info = property_infos[p]; + + if (_meta_property_needs_bond_hack(property_info)) { + guint i; + + for (i = 0; i < nm_meta_property_typ_data_bond.nested_len; i++) { + const NMMetaNestedPropertyInfo *bi = + &nm_meta_property_typ_data_bond.nested[i]; + + if (!nm_streq0(bi->base.property_alias, option)) + continue; + if (chosen) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: '%s' is ambiguous (%s.%s or %s.%s)."), + option, + chosen_setting_name, + chosen_option, + nm_meta_setting_infos[s].setting_name, + option); + return FALSE; + } + chosen_setting_name = nm_meta_setting_infos[s].setting_name; + chosen_option = option; + chosen = (const NMMetaAbstractInfo *) bi; + } + } else { + if (!property_info->is_cli_option) + continue; + if (!nm_streq0(property_info->property_alias, option)) + continue; + if (chosen) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: '%s' is ambiguous (%s.%s or %s.%s)."), + option, + chosen_setting_name, + chosen_option, + nm_meta_setting_infos[s].setting_name, + option); + return FALSE; + } + chosen_setting_name = nm_meta_setting_infos[s].setting_name; + chosen_option = option; + chosen = (const NMMetaAbstractInfo *) property_info; + } + } + } + + if (!chosen) { + if (*argc == 1 && nmc->complete) { + if (allow_setting_removal && g_str_has_prefix("remove", option)) + g_print("remove\n"); + complete_property_name(nmc, connection, modifier, option, NULL); + } + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: invalid <setting>.<property> '%s'."), + option); + return FALSE; + } + + if (*argc == 1 && nmc->complete) + complete_property_name(nmc, connection, modifier, option, NULL); + + (*argc)--; + (*argv)++; + if (!get_value(&value, argc, argv, option_orig, error)) + return FALSE; + + if (!*argc && nmc->complete) + complete_option(nmc, chosen, value ?: "", connection); + + if (!set_option(nmc, connection, chosen, value, error)) + return FALSE; + + } while (*argc); + + return TRUE; +} + +static void +add_connection_cb(GObject *client, GAsyncResult *result, gpointer user_data) +{ + nm_auto_free_add_connection_info AddConnectionInfo *info = user_data; + NmCli * nmc = info->nmc; + NMRemoteConnection * connection; + GError * error = NULL; + const GPtrArray * connections; + guint i, found; + + connection = nm_client_add_connection2_finish(NM_CLIENT(client), result, NULL, &error); + if (error) { + g_string_printf(nmc->return_text, + _("Error: Failed to add '%s' connection: %s"), + info->new_id, + error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION; + } else { + connections = nm_client_get_connections(nmc->client); + if (connections) { + found = 0; + for (i = 0; i < connections->len; i++) { + NMConnection *candidate = NM_CONNECTION(connections->pdata[i]); + + if ((NMConnection *) connection == candidate) + continue; + if (nm_streq0(nm_connection_get_id(candidate), info->new_id)) + found++; + } + if (found > 0) { + g_printerr(g_dngettext(GETTEXT_PACKAGE, + "Warning: There is another connection with the name '%1$s'. " + "Reference the connection by its uuid '%2$s'\n", + "Warning: There are %3$u other connections with the name " + "'%1$s'. Reference the connection by its uuid '%2$s'\n", + found), + info->new_id, + nm_connection_get_uuid(NM_CONNECTION(connection)), + found); + } + } + + /* We print here human readable text, but as scripts might parse this output + * (with LANG=C), this is important to not change in the future. At least + * not unless called with a new command line flag, that requests a different output. + * + * That means, be very careful if you change this message, it might break + * scripts!! + * + * This is true for many messages that the user might parse. But this one + * seems in particular interesting for a user to parse. */ + g_print(_("Connection '%s' (%s) successfully added.\n"), + nm_connection_get_id(NM_CONNECTION(connection)), + nm_connection_get_uuid(NM_CONNECTION(connection))); + g_object_unref(connection); + } + + quit(); +} + +static void +add_connection(NMClient * client, + NMConnection * connection, + gboolean temporary, + GAsyncReadyCallback callback, + gpointer user_data) +{ + nm_client_add_connection2(client, + nm_connection_to_dbus(connection, NM_CONNECTION_SERIALIZE_ALL), + temporary ? NM_SETTINGS_ADD_CONNECTION2_FLAG_IN_MEMORY + : NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK, + NULL, + TRUE, + NULL, + callback, + user_data); +} + +static void +update_connection(NMRemoteConnection *connection, + gboolean temporary, + GAsyncReadyCallback callback, + gpointer user_data) +{ + nm_remote_connection_commit_changes_async(connection, !temporary, NULL, callback, user_data); +} + +static gboolean +is_single_word(const char *line) +{ + size_t n1, n2, n3; + + n1 = strspn(line, " \t"); + n2 = strcspn(line + n1, " \t\0") + n1; + n3 = strspn(line + n2, " \t"); + + if (n3 == 0) + return TRUE; + else + return FALSE; +} + +static char ** +nmcli_con_add_tab_completion(const char *text, int start, int end) +{ + NMMetaSettingType s; + char ** match_array = NULL; + rl_compentry_func_t * generator_func = NULL; + gs_free char * no = g_strdup_printf("[%s]: ", _("no")); + gs_free char * yes = g_strdup_printf("[%s]: ", _("yes")); + const NMMetaAbstractInfo *info; + + /* Disable readline's default filename completion */ + rl_attempted_completion_over = 1; + + /* Restore standard append character to space */ + rl_completion_append_character = '\x00'; + + if (!is_single_word(rl_line_buffer)) + return NULL; + + for (s = 0; s < _NM_META_SETTING_TYPE_NUM; s++) { + const NMMetaPropertyInfo *const *property_infos; + guint p; + + property_infos = nm_meta_setting_infos_editor[s].properties; + if (!property_infos) + continue; + for (p = 0; property_infos[p]; p++) { + const NMMetaPropertyInfo *property_info = property_infos[p]; + + if (_meta_property_needs_bond_hack(property_info)) { + guint i; + + for (i = 0; i < nm_meta_property_typ_data_bond.nested_len; i++) { + const NMMetaNestedPropertyInfo *bi = &nm_meta_property_typ_data_bond.nested[i]; + + if (bi->base.prompt && g_str_has_prefix(rl_prompt, bi->base.prompt)) { + goto next; + } + } + } else { + if (property_info->prompt && g_str_has_prefix(rl_prompt, property_info->prompt)) { + info = (const NMMetaAbstractInfo *) property_info; + nmc_tab_completion.words = _meta_abstract_complete(info, text); + if (nmc_tab_completion.words) { + match_array = rl_completion_matches(text, _meta_abstract_generator); + nm_clear_pointer(&nmc_tab_completion.words, g_strfreev); + } + return match_array; + } + } + } + } + +next: + if (g_str_has_prefix(rl_prompt, NM_META_TEXT_PROMPT_BT_TYPE)) + generator_func = gen_func_bt_type; + else if (g_str_has_prefix(rl_prompt, NM_META_TEXT_PROMPT_BOND_MODE)) + generator_func = gen_func_bond_mode; + else if (g_str_has_prefix(rl_prompt, NM_META_TEXT_PROMPT_BOND_MON_MODE)) + generator_func = gen_func_bond_mon_mode; + else if (g_str_has_suffix(rl_prompt, yes) || g_str_has_suffix(rl_prompt, no)) + generator_func = gen_func_bool_values_l10n; + + if (generator_func) + match_array = rl_completion_matches(text, generator_func); + + return match_array; +} + +static void +ask_option(NmCli *nmc, NMConnection *connection, const NMMetaAbstractInfo *abstract_info) +{ + char * value; + GError * error = NULL; + gs_free char * prompt = NULL; + gboolean multi; + const char * opt_prompt, *opt_def_hint; + NMMetaPropertyInfFlags inf_flags; + + _meta_abstract_get(abstract_info, + NULL, + NULL, + NULL, + NULL, + &inf_flags, + &opt_prompt, + &opt_def_hint); + prompt = + g_strjoin("", gettext(opt_prompt), opt_def_hint ? " " : "", opt_def_hint ?: "", ": ", NULL); + + multi = NM_FLAGS_HAS(inf_flags, NM_META_PROPERTY_INF_FLAG_MULTI); + + if (multi) + g_print(_("You can specify this option more than once. Press <Enter> when you're done.\n")); + +again: + value = nmc_readline(&nmc->nmc_config, "%s", prompt); + if (multi && !value) + return; + + if (!set_option(nmc, connection, abstract_info, value, &error)) { + g_printerr("%s\n", error->message); + g_clear_error(&error); + goto again; + } + + if (multi && value) + goto again; +} + +static NMMetaSettingType +connection_get_base_meta_setting_type(NMConnection *connection) +{ + const char * connection_type; + NMSetting * base_setting; + const NMMetaSettingInfoEditor *editor; + + connection_type = nm_connection_get_connection_type(connection); + nm_assert(connection_type); + base_setting = nm_connection_get_setting_by_name(connection, connection_type); + nm_assert(base_setting); + editor = nm_meta_setting_info_editor_find_by_setting(base_setting); + nm_assert(editor); + + return editor - nm_meta_setting_infos_editor; +} + +static void +questionnaire_mandatory_ask_setting(NmCli *nmc, NMConnection *connection, NMMetaSettingType type) +{ + const NMMetaSettingInfoEditor *editor; + const NMMetaPropertyInfo * property_info; + guint p; + + editor = &nm_meta_setting_infos_editor[type]; + if (!editor->properties) + return; + + for (p = 0; editor->properties[p]; p++) { + property_info = editor->properties[p]; + + if (_meta_property_needs_bond_hack(property_info)) { + guint i; + + for (i = 0; i < nm_meta_property_typ_data_bond.nested_len; i++) { + const NMMetaNestedPropertyInfo *bi = &nm_meta_property_typ_data_bond.nested[i]; + + if (!option_relevant(connection, (const NMMetaAbstractInfo *) bi)) + continue; + if ((bi->base.inf_flags & NM_META_PROPERTY_INF_FLAG_REQD) + || (_dynamic_options_get((const NMMetaAbstractInfo *) bi) + & PROPERTY_INF_FLAG_ENABLED)) + ask_option(nmc, connection, (const NMMetaAbstractInfo *) bi); + } + } else { + if (!property_info->is_cli_option) + continue; + + if (!option_relevant(connection, (const NMMetaAbstractInfo *) property_info)) + continue; + if ((property_info->inf_flags & NM_META_PROPERTY_INF_FLAG_REQD) + || (_dynamic_options_get((const NMMetaAbstractInfo *) property_info) + & PROPERTY_INF_FLAG_ENABLED)) + ask_option(nmc, connection, (const NMMetaAbstractInfo *) property_info); + } + } +} + +static void +questionnaire_mandatory(NmCli *nmc, NMConnection *connection) +{ + NMMetaSettingType s, base; + + /* First ask connection properties */ + questionnaire_mandatory_ask_setting(nmc, connection, NM_META_SETTING_TYPE_CONNECTION); + + /* Ask properties of the base setting */ + base = connection_get_base_meta_setting_type(connection); + questionnaire_mandatory_ask_setting(nmc, connection, base); + + /* Remaining settings */ + for (s = 0; s < _NM_META_SETTING_TYPE_NUM; s++) { + if (!NM_IN_SET(s, NM_META_SETTING_TYPE_CONNECTION, base)) + questionnaire_mandatory_ask_setting(nmc, connection, s); + } +} + +static gboolean +want_provide_opt_args(const NmcConfig *nmc_config, const char *type, guint num) +{ + gs_free char *answer = NULL; + + /* Ask for optional arguments. */ + g_print(ngettext("There is %d optional setting for %s.\n", + "There are %d optional settings for %s.\n", + num), + (int) num, + type); + answer = nmc_readline( + nmc_config, + ngettext("Do you want to provide it? %s", "Do you want to provide them? %s", num), + prompt_yes_no(TRUE, NULL)); + nm_strstrip(answer); + return !answer || matches(answer, WORD_YES); +} + +static gboolean +questionnaire_one_optional(NmCli *nmc, NMConnection *connection) +{ + NMMetaSettingType base; + gs_unref_ptrarray GPtrArray *infos = NULL; + guint i, j; + gboolean already_confirmed = FALSE; + NMMetaSettingType s_asking = NM_META_SETTING_TYPE_UNKNOWN; + NMMetaSettingType settings[_NM_META_SETTING_TYPE_NUM]; + + base = connection_get_base_meta_setting_type(connection); + + i = 0; + settings[i++] = NM_META_SETTING_TYPE_CONNECTION; + settings[i++] = base; + for (j = 0; j < _NM_META_SETTING_TYPE_NUM; j++) { + if (!NM_IN_SET(j, NM_META_SETTING_TYPE_CONNECTION, base)) + settings[i++] = j; + } + + infos = g_ptr_array_new(); + + /* Find first setting with relevant options and count them. */ +again: + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) { + const NMMetaPropertyInfo *const *property_infos; + guint p; + + if (s_asking != NM_META_SETTING_TYPE_UNKNOWN && settings[i] != s_asking) + continue; + + property_infos = nm_meta_setting_infos_editor[settings[i]].properties; + if (!property_infos) + continue; + for (p = 0; property_infos[p]; p++) { + const NMMetaPropertyInfo *property_info = property_infos[p]; + + if (_meta_property_needs_bond_hack(property_info)) { + for (j = 0; j < nm_meta_property_typ_data_bond.nested_len; j++) { + const NMMetaNestedPropertyInfo *bi = &nm_meta_property_typ_data_bond.nested[j]; + + if (!option_relevant(connection, (const NMMetaAbstractInfo *) bi)) + continue; + g_ptr_array_add(infos, (gpointer) bi); + } + } else { + if (!property_info->is_cli_option) + continue; + if (!option_relevant(connection, (const NMMetaAbstractInfo *) property_info)) + continue; + g_ptr_array_add(infos, (gpointer) property_info); + } + } + if (infos->len) { + s_asking = settings[i]; + break; + } + } + + if (infos->len) { + const NMMetaSettingInfoEditor *setting_info = NULL; + + _meta_abstract_get(infos->pdata[0], &setting_info, NULL, NULL, NULL, NULL, NULL, NULL); + + /* Now ask for the settings. */ + if (already_confirmed + || want_provide_opt_args(&nmc->nmc_config, _(setting_info->pretty_name), infos->len)) { + ask_option(nmc, connection, infos->pdata[0]); + already_confirmed = TRUE; + /* asking for an option may enable other options. Create the list again. */ + g_ptr_array_set_size(infos, 0); + goto again; + } + } + + if (s_asking == NM_META_SETTING_TYPE_UNKNOWN) + return FALSE; + + /* Make sure we won't ask again. */ + disable_options(nm_meta_setting_infos[s_asking].setting_name, NULL); + return TRUE; +} + +static void +do_connection_add(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gs_unref_object NMConnection *connection = NULL; + NMSettingConnection * s_con; + gs_free_error GError *error = NULL; + gboolean save_bool = TRUE; + gboolean seen_dash_dash = FALSE; + NMMetaSettingType s; + + next_arg(nmc, &argc, &argv, NULL); + + rl_attempted_completion_function = nmcli_con_add_tab_completion; + + nmc->return_value = NMC_RESULT_SUCCESS; + + connection = nm_simple_connection_new(); + + s_con = (NMSettingConnection *) nm_setting_connection_new(); + nm_connection_add_setting(connection, NM_SETTING(s_con)); + +read_properties: + g_clear_error(&error); + /* Get the arguments from the command line if any */ + if (argc && !nmc_process_connection_properties(nmc, connection, &argc, &argv, FALSE, &error)) { + if (g_strcmp0(*argv, "--") == 0 && !seen_dash_dash) { + /* This is for compatibility with older nmcli that required + * options and properties to be separated with "--" */ + seen_dash_dash = TRUE; + next_arg(nmc, &argc, &argv, NULL); + goto read_properties; + } else if (g_strcmp0(*argv, "save") == 0) { + /* It would be better if "save" was a separate argument and not + * mixed with properties, but there's not much we can do about it now. */ + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, + _("Error: value for '%s' argument is required."), + "save"); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + g_clear_error(&error); + if (!nmc_string_to_bool(*argv, &save_bool, &error)) { + g_string_printf(nmc->return_text, _("Error: 'save': %s."), error->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + next_arg(nmc, &argc, &argv, NULL); + goto read_properties; + } + + g_string_assign(nmc->return_text, error->message); + nmc->return_value = error->code; + goto finish; + } + + if (nmc->complete) + goto finish; + + /* Now ask user for the rest of the mandatory options. */ + if (nmc->ask) + questionnaire_mandatory(nmc, connection); + + /* Traditionally, we didn't ask for these options for ethernet slaves. They don't + * make much sense, since these are likely to be set by the master anyway. */ + if (nm_setting_connection_get_slave_type(s_con)) { + disable_options(NM_SETTING_WIRED_SETTING_NAME, NM_SETTING_WIRED_MTU); + disable_options(NM_SETTING_WIRED_SETTING_NAME, NM_SETTING_WIRED_MAC_ADDRESS); + disable_options(NM_SETTING_WIRED_SETTING_NAME, NM_SETTING_WIRED_CLONED_MAC_ADDRESS); + } + + /* Connection id is special in that it's required but we don't insist + * on getting it from the user -- we just make up something sensible. */ + if (!nm_setting_connection_get_id(s_con)) { + const char *ifname = nm_setting_connection_get_interface_name(s_con); + const char *type = nm_setting_connection_get_connection_type(s_con); + const char *slave_type = nm_setting_connection_get_slave_type(s_con); + + /* If only bother when there's a type, which is not guaranteed at this point. + * Otherwise, the validation will fail anyway. */ + if (type) { + gs_free char * try_name = NULL; + gs_free char * default_name = NULL; + const GPtrArray *connections; + + connections = nm_client_get_connections(nmc->client); + try_name = + ifname ? g_strdup_printf("%s-%s", get_name_alias_toplevel(type, slave_type), ifname) + : g_strdup(get_name_alias_toplevel(type, slave_type)); + default_name = nmc_unique_connection_name(connections, try_name); + g_object_set(s_con, NM_SETTING_CONNECTION_ID, default_name, NULL); + } + } + + /* For some software connection types we generate the interface name for the user. */ + set_default_interface_name(nmc, s_con); + + /* Now see if there's something optional that needs to be asked for. + * Keep asking until there's no more things to ask for. */ + do { + /* This ensures all settings that make sense are present. */ + nm_connection_normalize(connection, NULL, NULL, NULL); + } while (nmc->ask && questionnaire_one_optional(nmc, connection)); + + /* Mandatory settings. No good reason to check this other than guarding the user + * from doing something that's not likely to make sense (such as missing ifname + * on a bond/bridge/team, etc.). Added just to preserve traditional behavior, it + * perhaps is a good idea to just remove this. */ + for (s = 0; s < _NM_META_SETTING_TYPE_NUM; s++) { + const NMMetaPropertyInfo *const *property_infos; + guint p; + + property_infos = nm_meta_setting_infos_editor[s].properties; + if (!property_infos) + continue; + for (p = 0; property_infos[p]; p++) { + const NMMetaPropertyInfo *property_info = property_infos[p]; + + if (_meta_property_needs_bond_hack(property_info)) { + guint i; + + for (i = 0; i < nm_meta_property_typ_data_bond.nested_len; i++) { + const NMMetaNestedPropertyInfo *bi = &nm_meta_property_typ_data_bond.nested[i]; + + if (!option_relevant(connection, (const NMMetaAbstractInfo *) bi)) + continue; + if (bi->base.inf_flags & NM_META_PROPERTY_INF_FLAG_REQD) { + g_string_printf(nmc->return_text, + _("Error: '%s' argument is required."), + bi->base.property_alias); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + } + } else { + if (!property_info->is_cli_option) + continue; + if (!option_relevant(connection, (const NMMetaAbstractInfo *) property_info)) + continue; + if (property_info->inf_flags & NM_META_PROPERTY_INF_FLAG_REQD) { + g_string_printf(nmc->return_text, + _("Error: '%s' argument is required."), + property_info->property_alias); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + } + } + } + + add_connection(nmc->client, + connection, + !save_bool, + add_connection_cb, + _add_connection_info_new(nmc, NULL, connection)); + nmc->should_wait++; + +finish: + reset_options(); +} + +/*****************************************************************************/ +/* Functions for readline TAB completion in editor */ + +static void +uuid_display_hook(char **array, int len, int max_len) +{ + const GPtrArray *connections; + NMConnection * con; + int i, max = 0; + char * tmp; + const char * id; + for (i = 1; i <= len; i++) { + connections = nm_client_get_connections(nmc_tab_completion.nmc->client); + con = nmc_find_connection(connections, "uuid", array[i], NULL, FALSE); + id = con ? nm_connection_get_id(con) : NULL; + if (id) { + tmp = g_strdup_printf("%s (%s)", array[i], id); + g_free(array[i]); + array[i] = tmp; + if (max < strlen(id)) + max = strlen(id); + } + } + rl_display_match_list(array, len, max_len + max + 3); + rl_forced_update_display(); +} + +static char * +gen_nmcli_cmds_menu(const char *text, int state) +{ + const char *words[] = {"goto", + "set", + "remove", + "describe", + "print", + "verify", + "save", + "activate", + "back", + "help", + "quit", + "nmcli", + NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static char * +gen_nmcli_cmds_submenu(const char *text, int state) +{ + const char *words[] = + {"set", "add", "change", "remove", "describe", "print", "back", "help", "quit", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static char * +gen_cmd_nmcli(const char *text, int state) +{ + const char *words[] = {"status-line", "save-confirmation", "show-secrets", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static char * +gen_func_bool_values(const char *text, int state) +{ + const char *words[] = {"yes", "no", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static char * +gen_cmd_verify0(const char *text, int state) +{ + const char *words[] = {"all", "fix", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static char * +gen_cmd_print0(const char *text, int state) +{ + static char **words = NULL; + char * ret = NULL; + + if (!state) { + GVariant * settings; + GVariantIter iter; + const char * setting_name; + int i = 0; + + settings = nm_connection_to_dbus(nmc_tab_completion.connection, + NM_CONNECTION_SERIALIZE_WITH_NON_SECRET); + words = g_new(char *, g_variant_n_children(settings) + 2); + g_variant_iter_init(&iter, settings); + while (g_variant_iter_next(&iter, "{&s@a{sv}}", &setting_name, NULL)) + words[i++] = g_strdup(setting_name); + words[i++] = g_strdup("all"); + words[i] = NULL; + g_variant_unref(settings); + } + + if (words) { + ret = nmc_rl_gen_func_basic(text, state, (const char **) words); + if (ret == NULL) { + g_strfreev(words); + words = NULL; + } + } + return ret; +} + +static char * +gen_cmd_print2(const char *text, int state) +{ + const char *words[] = {"setting", "connection", "all", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static char * +gen_cmd_save(const char *text, int state) +{ + const char *words[] = {"persistent", "temporary", NULL}; + return nmc_rl_gen_func_basic(text, state, words); +} + +static rl_compentry_func_t * +gen_connection_types(const char *text) +{ + gs_free char ** values = NULL; + const NMMetaSettingInfoEditor *editor; + GPtrArray * array; + int i; + + array = g_ptr_array_new(); + + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) { + editor = &nm_meta_setting_infos_editor[i]; + if (!editor->valid_parts) + continue; + g_ptr_array_add(array, (gpointer) nm_meta_setting_infos[i].setting_name); + if (editor->alias) + g_ptr_array_add(array, (gpointer) editor->alias); + } + + g_ptr_array_add(array, "bond-slave"); + g_ptr_array_add(array, "bridge-slave"); + g_ptr_array_add(array, "team-slave"); + g_ptr_array_add(array, NULL); + + values = (char **) g_ptr_array_free(array, FALSE); + + return nmc_rl_compentry_func_wrap((const char *const *) values); +} + +static char * +gen_setting_names(const char *text, int state) +{ + static int list_idx, len, is_slv; + const char * s_name, *a_name; + const NMMetaSettingValidPartItem *const *valid_settings_arr; + NMSettingConnection * s_con; + const char * s_type = NULL; + + if (!state) { + list_idx = 0; + len = strlen(text); + is_slv = 0; + } + + if (!is_slv) { + valid_settings_arr = get_valid_settings_array(nmc_tab_completion.con_type); + if (list_idx >= NM_PTRARRAY_LEN(valid_settings_arr)) + return NULL; + for (; valid_settings_arr[list_idx];) { + const NMMetaSettingInfoEditor *setting_info = + valid_settings_arr[list_idx]->setting_info; + + a_name = setting_info->alias; + s_name = setting_info->general->setting_name; + list_idx++; + if (len == 0 && a_name) + return g_strdup_printf("%s (%s)", s_name, a_name); + if (a_name && !strncmp(text, a_name, len)) + return g_strdup(a_name); + if (s_name && !strncmp(text, s_name, len)) + return g_strdup(s_name); + } + + /* Let's give a try to parameters related to slave type */ + list_idx = 0; + is_slv = 1; + } + + /* is_slv */ + s_con = nm_connection_get_setting_connection(nmc_tab_completion.connection); + if (s_con) + s_type = nm_setting_connection_get_slave_type(s_con); + valid_settings_arr = nm_meta_setting_info_valid_parts_for_slave_type(s_type, NULL); + + if (list_idx < NM_PTRARRAY_LEN(valid_settings_arr)) { + while (valid_settings_arr[list_idx]) { + const NMMetaSettingInfoEditor *setting_info = + valid_settings_arr[list_idx]->setting_info; + + a_name = setting_info->alias; + s_name = setting_info->general->setting_name; + list_idx++; + if (len == 0 && a_name) + return g_strdup_printf("%s (%s)", s_name, a_name); + if (a_name && !strncmp(text, a_name, len)) + return g_strdup(a_name); + if (s_name && !strncmp(text, s_name, len)) + return g_strdup(s_name); + } + } + + return NULL; +} + +static char * +gen_property_names(const char *text, int state) +{ + NMSetting * setting = NULL; + char ** valid_props = NULL; + char * ret = NULL; + const char * line = rl_line_buffer; + const char * setting_name; + char ** strv = NULL; + const NMMetaSettingValidPartItem *const *valid_settings_main; + const NMMetaSettingValidPartItem *const *valid_settings_slave; + const char * p1; + const char * slv_type; + + /* Try to get the setting from 'line' - setting_name.property */ + p1 = strchr(line, '.'); + if (p1) { + while (p1 > line && !g_ascii_isspace(*p1)) + p1--; + + strv = g_strsplit(p1 + 1, ".", 2); + + valid_settings_main = get_valid_settings_array(nmc_tab_completion.con_type); + + /* Support autocompletion of slave-connection parameters + * guessing the slave type from the setting name already + * typed (or autocompleted) */ + if (nm_streq0(strv[0], NM_SETTING_TEAM_PORT_SETTING_NAME)) + slv_type = NM_SETTING_TEAM_SETTING_NAME; + else if (nm_streq0(strv[0], NM_SETTING_BRIDGE_PORT_SETTING_NAME)) + slv_type = NM_SETTING_BRIDGE_SETTING_NAME; + else + slv_type = NULL; + valid_settings_slave = nm_meta_setting_info_valid_parts_for_slave_type(slv_type, NULL); + + setting_name = check_valid_name(strv[0], valid_settings_main, valid_settings_slave, NULL); + if (setting_name) { + setting = nm_meta_setting_info_editor_new_setting( + nm_meta_setting_info_editor_find_by_name(setting_name, FALSE), + NM_META_ACCESSOR_SETTING_INIT_TYPE_DEFAULT); + } + } + + if (!setting) { + /* Else take the current setting, if any */ + setting = nmc_tab_completion.setting ? g_object_ref(nmc_tab_completion.setting) : NULL; + } + + if (setting) { + valid_props = nmc_setting_get_valid_properties(setting); + ret = nmc_rl_gen_func_basic(text, state, (const char **) valid_props); + } + + g_strfreev(strv); + g_strfreev(valid_props); + if (setting) + g_object_unref(setting); + return ret; +} + +static char * +gen_compat_devices(const char *text, int state) +{ + guint i, j = 0; + const GPtrArray *devices; + const char ** compatible_devices; + char * ret; + + devices = nm_client_get_devices(nmc_tab_completion.nmc->client); + if (devices->len == 0) + return NULL; + + compatible_devices = g_new(const char *, devices->len + 1); + for (i = 0; i < devices->len; i++) { + NMDevice * dev = g_ptr_array_index(devices, i); + const char *ifname = nm_device_get_iface(dev); + NMDevice * device = NULL; + const char *spec_object = NULL; + + if (find_device_for_connection(nmc_tab_completion.nmc, + nmc_tab_completion.connection, + ifname, + NULL, + NULL, + &device, + &spec_object, + NULL)) { + compatible_devices[j++] = ifname; + } + } + compatible_devices[j] = NULL; + + ret = nmc_rl_gen_func_basic(text, state, compatible_devices); + + g_free(compatible_devices); + return ret; +} + +static const char ** +_create_vpn_array(const GPtrArray *connections, gboolean uuid) +{ + int c, idx = 0; + const char **array; + + if (connections->len < 1) + return NULL; + + array = g_new(const char *, connections->len + 1); + for (c = 0; c < connections->len; c++) { + NMConnection *connection = NM_CONNECTION(connections->pdata[c]); + const char * type = nm_connection_get_connection_type(connection); + + if (g_strcmp0(type, NM_SETTING_VPN_SETTING_NAME) == 0) + array[idx++] = + uuid ? nm_connection_get_uuid(connection) : nm_connection_get_id(connection); + } + array[idx] = NULL; + return array; +} + +static char * +gen_vpn_uuids(const char *text, int state) +{ + const GPtrArray *connections; + const char ** uuids; + char * ret; + + connections = nm_client_get_connections(nm_cli_global_readline->client); + if (connections->len < 1) + return NULL; + + uuids = _create_vpn_array(connections, TRUE); + ret = nmc_rl_gen_func_basic(text, state, uuids); + g_free(uuids); + return ret; +} + +static char * +gen_vpn_ids(const char *text, int state) +{ + const GPtrArray *connections; + const char ** ids; + char * ret; + + connections = nm_client_get_connections(nm_cli_global_readline->client); + if (connections->len < 1) + return NULL; + + ids = _create_vpn_array(connections, FALSE); + ret = nmc_rl_gen_func_basic(text, state, ids); + g_free(ids); + return ret; +} + +static rl_compentry_func_t * +get_gen_func_cmd_nmcli(const char *str) +{ + if (!str) + return NULL; + if (matches(str, "status-line")) + return gen_func_bool_values; + if (matches(str, "save-confirmation")) + return gen_func_bool_values; + if (matches(str, "show-secrets")) + return gen_func_bool_values; + return NULL; +} + +/* + * Helper function parsing line for completion. + * IN: + * line : the whole line to be parsed + * end : the position of cursor in the line + * cmd : command to match + * OUT: + * cw_num : is set to the word number being completed (1, 2, 3, 4). + * prev_word : returns the previous word (so that we have some context). + * + * Returns TRUE when the first word of the 'line' matches 'cmd'. + * + * Examples: + * line="rem" cmd="remove" -> TRUE cw_num=1 + * line="set con" cmd="set" -> TRUE cw_num=2 + * line="go ipv4.method" cmd="goto" -> TRUE cw_num=2 + * line=" des eth.mtu " cmd="describe" -> TRUE cw_num=3 + * line=" bla ipv4.method" cmd="goto" -> FALSE + */ +static gboolean +should_complete_cmd(const char *line, int end, const char *cmd, int *cw_num, char **prev_word) +{ + char * tmp; + const char *word1, *word2, *word3; + size_t n1, n2, n3, n4, n5, n6; + gboolean word1_done, word2_done, word3_done; + gboolean ret = FALSE; + + if (!line) + return FALSE; + + tmp = g_strdup(line); + + n1 = strspn(tmp, " \t"); + n2 = strcspn(tmp + n1, " \t\0") + n1; + n3 = strspn(tmp + n2, " \t") + n2; + n4 = strcspn(tmp + n3, " \t\0") + n3; + n5 = strspn(tmp + n4, " \t") + n4; + n6 = strcspn(tmp + n5, " \t\0") + n5; + + word1_done = end > n2; + word2_done = end > n4; + word3_done = end > n6; + tmp[n2] = tmp[n4] = tmp[n6] = '\0'; + + word1 = tmp[n1] ? tmp + n1 : NULL; + word2 = tmp[n3] ? tmp + n3 : NULL; + word3 = tmp[n5] ? tmp + n5 : NULL; + + if (!word1_done) { + if (cw_num) + *cw_num = 1; + if (prev_word) + *prev_word = NULL; + } else if (!word2_done) { + if (cw_num) + *cw_num = 2; + if (prev_word) + *prev_word = g_strdup(word1); + } else if (!word3_done) { + if (cw_num) + *cw_num = 3; + if (prev_word) + *prev_word = g_strdup(word2); + } else { + if (cw_num) + *cw_num = 4; + if (prev_word) + *prev_word = g_strdup(word3); + } + + if (word1 && matches(word1, cmd)) + ret = TRUE; + + g_free(tmp); + return ret; +} + +/* + * extract_setting_and_property: + * prompt: (in) (allow-none): prompt string, or NULL + * line: (in) (allow-none): line, or NULL + * setting: (out) (transfer full) (array zero-terminated=1): + * return location for setting name + * property: (out) (transfer full) (array zero-terminated=1): + * return location for property name + * + * Extract setting and property names from prompt and/or line. + */ +static void +extract_setting_and_property(const char *prompt, const char *line, char **setting, char **property) +{ + char *prop = NULL; + char *sett = NULL; + + if (prompt) { + /* prompt looks like this: + * "nmcli 802-1x>" or "nmcli 802-1x.pac-file>" */ + const char *p1, *p2, *dot; + size_t num1, num2; + p1 = strchr(prompt, ' '); + if (p1) { + dot = strchr(++p1, '.'); + if (dot) { + p2 = dot + 1; + num1 = strcspn(p1, "."); + num2 = strcspn(p2, ">"); + sett = num1 > 0 ? g_strndup(p1, num1) : NULL; + prop = num2 > 0 ? g_strndup(p2, num2) : NULL; + } else { + num1 = strcspn(p1, ">"); + sett = num1 > 0 ? g_strndup(p1, num1) : NULL; + } + } + } + + if (line) { + /* line looks like this: + * " set 802-1x.pac-file ..." or " set pac-file ..." */ + const char *p1, *p2, *dot; + size_t n1, n2, n3, n4; + size_t num1, num2, len; + n1 = strspn(line, " \t"); /* white-space */ + n2 = strcspn(line + n1, " \t\0") + n1; /* command */ + n3 = strspn(line + n2, " \t") + n2; /* white-space */ + n4 = strcspn(line + n3, " \t\0") + n3; /* setting/property */ + p1 = line + n3; + len = n4 - n3; + + dot = strchr(p1, '.'); + if (dot && dot < p1 + len) { + p2 = dot + 1; + num1 = strcspn(p1, "."); + num2 = len > num1 + 1 ? len - num1 - 1 : 0; + sett = num1 > 0 ? g_strndup(p1, num1) : sett; + prop = num2 > 0 ? g_strndup(p2, num2) : prop; + } else { + if (!prop) + prop = len > 0 ? g_strndup(p1, len) : NULL; + } + } + + if (setting) + *setting = sett; + else + g_free(sett); + if (property) + *property = prop; + else + g_free(prop); +} + +static void +get_setting_and_property(const char *prompt, + const char *line, + NMSetting **setting_out, + char ** property_out) +{ + const NMMetaSettingValidPartItem *const *valid_settings_main; + const NMMetaSettingValidPartItem *const *valid_settings_slave; + gs_unref_object NMSetting *setting = NULL; + gs_free char * property = NULL; + NMSettingConnection * s_con; + gs_free char * sett = NULL; + gs_free char * prop = NULL; + const char * s_type = NULL; + const char * setting_name; + + extract_setting_and_property(prompt, line, &sett, &prop); + + if (sett) { + /* Is this too much (and useless?) effort for an unlikely case? */ + s_con = nm_connection_get_setting_connection(nmc_tab_completion.connection); + if (s_con) + s_type = nm_setting_connection_get_slave_type(s_con); + + valid_settings_main = get_valid_settings_array(nmc_tab_completion.con_type); + valid_settings_slave = nm_meta_setting_info_valid_parts_for_slave_type(s_type, NULL); + + setting_name = check_valid_name(sett, valid_settings_main, valid_settings_slave, NULL); + setting = nm_meta_setting_info_editor_new_setting( + nm_meta_setting_info_editor_find_by_name(setting_name, FALSE), + NM_META_ACCESSOR_SETTING_INIT_TYPE_DEFAULT); + } else + setting = nm_g_object_ref(nmc_tab_completion.setting); + + if (setting && prop) + property = is_property_valid(setting, prop, NULL); + else + property = g_strdup(nmc_tab_completion.property); + + *setting_out = g_steal_pointer(&setting); + *property_out = g_steal_pointer(&property); +} + +static gboolean +_get_and_check_property(const char * prompt, + const char * line, + const char **array, + const char **array_multi, + gboolean * multi) +{ + gs_free char *prop = NULL; + gboolean found = FALSE; + + extract_setting_and_property(prompt, line, NULL, &prop); + if (prop) { + if (array) + found = !!nmc_string_is_valid(prop, array, NULL); + if (array_multi && multi) + *multi = !!nmc_string_is_valid(prop, array_multi, NULL); + } + return found; +} + +static gboolean +should_complete_files(const char *prompt, const char *line) +{ + const char *file_properties[] = {/* '802-1x' properties */ + "ca-cert", + "ca-path", + "client-cert", + "pac-file", + "phase2-ca-cert", + "phase2-ca-path", + "phase2-client-cert", + "private-key", + "phase2-private-key", + /* 'team' and 'team-port' properties */ + "config", + /* 'proxy' properties */ + "pac-script", + NULL}; + return _get_and_check_property(prompt, line, file_properties, NULL, NULL); +} + +static gboolean +should_complete_vpn_uuids(const char *prompt, const char *line) +{ + const char *uuid_properties[] = {/* 'connection' properties */ + "secondaries", + NULL}; + return _get_and_check_property(prompt, line, uuid_properties, NULL, NULL); +} + +static const char *const * +get_allowed_property_values(char ***out_to_free) +{ + gs_unref_object NMSetting *setting = NULL; + gs_free char * property = NULL; + const char *const * avals = NULL; + + get_setting_and_property(rl_prompt, rl_line_buffer, &setting, &property); + if (setting && property) + avals = nmc_setting_get_property_allowed_values(setting, property, out_to_free); + return avals; +} + +static gboolean +should_complete_property_values(const char *prompt, const char *line, gboolean *multi) +{ + gs_strfreev char **to_free = NULL; + + /* properties allowing multiple values */ + const char *multi_props[] = {/* '802-1x' properties */ + NM_SETTING_802_1X_EAP, + /* '802-11-wireless-security' properties */ + NM_SETTING_WIRELESS_SECURITY_PROTO, + NM_SETTING_WIRELESS_SECURITY_PAIRWISE, + NM_SETTING_WIRELESS_SECURITY_GROUP, + /* 'bond' properties */ + NM_SETTING_BOND_OPTIONS, + /* 'ethernet' properties */ + NM_SETTING_WIRED_S390_OPTIONS, + NULL}; + _get_and_check_property(prompt, line, NULL, multi_props, multi); + return !!get_allowed_property_values(&to_free); +} + +static gboolean +_setting_property_is_boolean(NMSetting *setting, const char *property_name) +{ + const GParamSpec *pspec; + + nm_assert(NM_IS_SETTING(setting)); + nm_assert(property_name); + + pspec = g_object_class_find_property(G_OBJECT_GET_CLASS(setting), property_name); + return pspec && pspec->value_type == G_TYPE_BOOLEAN; +} + +static gboolean +should_complete_boolean(const char *prompt, const char *line) +{ + gs_unref_object NMSetting *setting = NULL; + gs_free char * property = NULL; + + get_setting_and_property(prompt, line, &setting, &property); + return setting && property && _setting_property_is_boolean(setting, property); +} + +static char * +gen_property_values(const char *text, int state) +{ + gs_strfreev char **to_free = NULL; + const char *const *avals; + + avals = get_allowed_property_values(&to_free); + if (!avals) + return NULL; + return nmc_rl_gen_func_basic(text, state, avals); +} + +/* from readline */ +extern int rl_complete_with_tilde_expansion; + +/* + * Attempt to complete on the contents of TEXT. START and END show the + * region of TEXT that contains the word to complete. We can use the + * entire line in case we want to do some simple parsing. Return the + * array of matches, or NULL if there aren't any. + */ +static char ** +nmcli_editor_tab_completion(const char *text, int start, int end) +{ + rl_compentry_func_t *generator_func = NULL; + const char * line = rl_line_buffer; + gs_free char * prompt_tmp = NULL; + gs_free char * word = NULL; + char ** match_array = NULL; + size_t n1; + int num; + + /* Restore standard append character to space */ + rl_completion_append_character = ' '; + + /* Restore standard function for displaying matches */ + rl_completion_display_matches_hook = NULL; + + /* Disable default filename completion */ + rl_attempted_completion_over = 1; + + /* Enable tilde expansion when filenames are completed */ + rl_complete_with_tilde_expansion = 1; + + /* Filter out possible ANSI color escape sequences */ + prompt_tmp = nmc_filter_out_colors((const char *) rl_prompt); + + /* Find the first non-space character */ + n1 = strspn(line, " \t"); + + /* Choose the right generator function */ + if (strcmp(prompt_tmp, EDITOR_PROMPT_CON_TYPE) == 0) + generator_func = gen_connection_types(text); + else if (strcmp(prompt_tmp, EDITOR_PROMPT_SETTING) == 0) + generator_func = gen_setting_names; + else if (strcmp(prompt_tmp, EDITOR_PROMPT_PROPERTY) == 0) + generator_func = gen_property_names; + else if (g_str_has_suffix(rl_prompt, prompt_yes_no(TRUE, NULL)) + || g_str_has_suffix(rl_prompt, prompt_yes_no(FALSE, NULL))) + generator_func = gen_func_bool_values_l10n; + else if (g_str_has_prefix(prompt_tmp, "nmcli")) { + if (!strchr(prompt_tmp, '.')) { + int level = g_str_has_prefix(prompt_tmp, "nmcli>") ? 0 : 1; + const char *dot = strchr(line, '.'); + gboolean multi; + + /* Main menu - level 0,1 */ + if (start == n1) + generator_func = gen_nmcli_cmds_menu; + else { + if (should_complete_cmd(line, end, "goto", &num, NULL) && num <= 2) { + if (level == 0 && (!dot || dot >= line + end)) + generator_func = gen_setting_names; + else + generator_func = gen_property_names; + } else if (should_complete_cmd(line, end, "set", &num, NULL)) { + if (num < 3) { + if (level == 0 && (!dot || dot >= line + end)) { + generator_func = gen_setting_names; + rl_completion_append_character = '.'; + } else + generator_func = gen_property_names; + } else { + if (num == 3 && should_complete_files(NULL, line)) + rl_attempted_completion_over = 0; + else if (should_complete_vpn_uuids(NULL, line)) { + rl_completion_display_matches_hook = uuid_display_hook; + generator_func = gen_vpn_uuids; + } else if (should_complete_property_values(NULL, line, &multi) + && (num == 3 || multi)) { + generator_func = gen_property_values; + } else if (should_complete_boolean(NULL, line) && num == 3) + generator_func = gen_func_bool_values; + } + } else if ((should_complete_cmd(line, end, "remove", &num, NULL) + || should_complete_cmd(line, end, "describe", &num, NULL)) + && num <= 2) { + if (level == 0 && (!dot || dot >= line + end)) { + generator_func = gen_setting_names; + rl_completion_append_character = '.'; + } else + generator_func = gen_property_names; + } else if (should_complete_cmd(line, end, "nmcli", &num, &word)) { + if (num < 3) + generator_func = gen_cmd_nmcli; + else if (num == 3) + generator_func = get_gen_func_cmd_nmcli(word); + } else if (should_complete_cmd(line, end, "print", &num, NULL) && num <= 2) { + if (level == 0 && (!dot || dot >= line + end)) + generator_func = gen_cmd_print0; + else + generator_func = gen_property_names; + } else if (should_complete_cmd(line, end, "verify", &num, NULL) && num <= 2) { + generator_func = gen_cmd_verify0; + } else if (should_complete_cmd(line, end, "activate", &num, NULL) && num <= 2) { + generator_func = gen_compat_devices; + } else if (should_complete_cmd(line, end, "save", &num, NULL) && num <= 2) { + generator_func = gen_cmd_save; + } else if (should_complete_cmd(line, end, "help", &num, NULL) && num <= 2) + generator_func = gen_nmcli_cmds_menu; + } + } else { + /* Submenu - level 2 */ + if (start == n1) + generator_func = gen_nmcli_cmds_submenu; + else { + gboolean multi; + + if (should_complete_cmd(line, end, "add", &num, NULL) + || should_complete_cmd(line, end, "set", &num, NULL)) { + if (num <= 2 && should_complete_files(prompt_tmp, line)) + rl_attempted_completion_over = 0; + else if (should_complete_vpn_uuids(prompt_tmp, line)) { + rl_completion_display_matches_hook = uuid_display_hook; + generator_func = gen_vpn_uuids; + } else if (should_complete_property_values(prompt_tmp, NULL, &multi) + && (num <= 2 || multi)) { + generator_func = gen_property_values; + } else if (should_complete_boolean(prompt_tmp, NULL) && num <= 2) + generator_func = gen_func_bool_values; + } + if (should_complete_cmd(line, end, "print", &num, NULL) && num <= 2) + generator_func = gen_cmd_print2; + else if (should_complete_cmd(line, end, "help", &num, NULL) && num <= 2) + generator_func = gen_nmcli_cmds_submenu; + } + } + } + + if (generator_func) + match_array = rl_completion_matches(text, generator_func); + + return match_array; +} + +#define NMCLI_EDITOR_HISTORY ".nmcli-history" + +static void +load_history_cmds(const char *uuid) +{ + GKeyFile *kf; + char * filename; + char ** keys; + char * line; + size_t i; + GError * err = NULL; + + filename = g_build_filename(g_get_home_dir(), NMCLI_EDITOR_HISTORY, NULL); + kf = g_key_file_new(); + if (!g_key_file_load_from_file(kf, filename, G_KEY_FILE_KEEP_COMMENTS, &err)) { + if (g_error_matches(err, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_PARSE)) + g_print("Warning: %s parse error: %s\n", filename, err->message); + g_key_file_free(kf); + g_free(filename); + return; + } + keys = g_key_file_get_keys(kf, uuid, NULL, NULL); + for (i = 0; keys && keys[i]; i++) { + line = g_key_file_get_string(kf, uuid, keys[i], NULL); + if (line && *line) + add_history(line); + g_free(line); + } + g_strfreev(keys); + g_key_file_free(kf); + g_free(filename); +} + +static void +save_history_cmds(const char *uuid) +{ + nm_auto_unref_keyfile GKeyFile *kf = NULL; + gs_free_error GError *error = NULL; + gs_free char * filename = NULL; + gs_free char * data = NULL; + HIST_ENTRY ** hist; + gsize len; + gsize i; + + hist = history_list(); + if (!hist) + return; + + filename = g_build_filename(g_get_home_dir(), NMCLI_EDITOR_HISTORY, NULL); + + kf = g_key_file_new(); + + if (!g_key_file_load_from_file(kf, filename, G_KEY_FILE_KEEP_COMMENTS, &error)) { + if (!g_error_matches(error, G_FILE_ERROR, G_FILE_ERROR_NOENT) + && !g_error_matches(error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_NOT_FOUND)) { + g_print("Warning: %s parse error: %s\n", filename, error->message); + return; + } + g_clear_error(&error); + } + + /* Remove previous history group and save new history entries */ + g_key_file_remove_group(kf, uuid, NULL); + for (i = 0; hist[i]; i++) { + char key[100]; + + nm_sprintf_buf(key, "%zd", i); + g_key_file_set_string(kf, uuid, key, hist[i]->line); + } + + /* Write history to file */ + data = g_key_file_to_data(kf, &len, NULL); + if (data) + g_file_set_contents(filename, data, len, NULL); +} + +/*****************************************************************************/ + +static void +editor_show_connection(NMConnection *connection, NmCli *nmc) +{ + nmc->nmc_config_mutable.print_output = NMC_PRINT_PRETTY; + nmc->nmc_config_mutable.multiline_output = TRUE; + nmc->nmc_config_mutable.escape_values = 0; + + nmc_connection_profile_details(connection, nmc); +} + +static void +editor_show_setting(NMSetting *setting, NmCli *nmc) +{ + g_print(_("['%s' setting values]\n"), nm_setting_get_name(setting)); + + nmc->nmc_config_mutable.print_output = NMC_PRINT_NORMAL; + nmc->nmc_config_mutable.multiline_output = TRUE; + nmc->nmc_config_mutable.escape_values = 0; + + setting_details(&nmc->nmc_config, setting, NULL); +} + +typedef enum { + NMC_EDITOR_MAIN_CMD_UNKNOWN = 0, + NMC_EDITOR_MAIN_CMD_GOTO, + NMC_EDITOR_MAIN_CMD_REMOVE, + NMC_EDITOR_MAIN_CMD_SET, + NMC_EDITOR_MAIN_CMD_DESCRIBE, + NMC_EDITOR_MAIN_CMD_PRINT, + NMC_EDITOR_MAIN_CMD_VERIFY, + NMC_EDITOR_MAIN_CMD_SAVE, + NMC_EDITOR_MAIN_CMD_ACTIVATE, + NMC_EDITOR_MAIN_CMD_BACK, + NMC_EDITOR_MAIN_CMD_HELP, + NMC_EDITOR_MAIN_CMD_NMCLI, + NMC_EDITOR_MAIN_CMD_QUIT, +} NmcEditorMainCmd; + +static void +_split_cmd(const char *cmd, char **out_arg0, const char **out_argr) +{ + gs_free char *arg0 = NULL; + const char * argr = NULL; + gsize l; + + NM_SET_OUT(out_arg0, NULL); + NM_SET_OUT(out_argr, NULL); + + if (!cmd) + return; + while (nm_utils_is_separator(cmd[0])) + cmd++; + if (!cmd[0]) + return; + + l = strcspn(cmd, " \t"); + arg0 = g_strndup(cmd, l); + cmd += l; + if (cmd[0]) { + while (nm_utils_is_separator(cmd[0])) + cmd++; + if (cmd[0]) + argr = cmd; + } + + NM_SET_OUT(out_arg0, g_steal_pointer(&arg0)); + NM_SET_OUT(out_argr, argr); +} + +static NmcEditorMainCmd +parse_editor_main_cmd(const char *cmd, char **cmd_arg) +{ + NmcEditorMainCmd editor_cmd = NMC_EDITOR_MAIN_CMD_UNKNOWN; + gs_free char * cmd_arg0 = NULL; + const char * cmd_argr; + + _split_cmd(cmd, &cmd_arg0, &cmd_argr); + if (!cmd_arg0) + goto fail; + + if (matches(cmd_arg0, "goto")) + editor_cmd = NMC_EDITOR_MAIN_CMD_GOTO; + else if (matches(cmd_arg0, "remove")) + editor_cmd = NMC_EDITOR_MAIN_CMD_REMOVE; + else if (matches(cmd_arg0, "set")) + editor_cmd = NMC_EDITOR_MAIN_CMD_SET; + else if (matches(cmd_arg0, "describe")) + editor_cmd = NMC_EDITOR_MAIN_CMD_DESCRIBE; + else if (matches(cmd_arg0, "print")) + editor_cmd = NMC_EDITOR_MAIN_CMD_PRINT; + else if (matches(cmd_arg0, "verify")) + editor_cmd = NMC_EDITOR_MAIN_CMD_VERIFY; + else if (matches(cmd_arg0, "save")) + editor_cmd = NMC_EDITOR_MAIN_CMD_SAVE; + else if (matches(cmd_arg0, "activate")) + editor_cmd = NMC_EDITOR_MAIN_CMD_ACTIVATE; + else if (matches(cmd_arg0, "back")) + editor_cmd = NMC_EDITOR_MAIN_CMD_BACK; + else if (matches(cmd_arg0, "help") || strcmp(cmd_arg0, "?") == 0) + editor_cmd = NMC_EDITOR_MAIN_CMD_HELP; + else if (matches(cmd_arg0, "quit")) + editor_cmd = NMC_EDITOR_MAIN_CMD_QUIT; + else if (matches(cmd_arg0, "nmcli")) + editor_cmd = NMC_EDITOR_MAIN_CMD_NMCLI; + else + goto fail; + + NM_SET_OUT(cmd_arg, g_strdup(cmd_argr)); + return editor_cmd; +fail: + NM_SET_OUT(cmd_arg, NULL); + return NMC_EDITOR_MAIN_CMD_UNKNOWN; +} + +static void +editor_main_usage(void) +{ + g_print("------------------------------------------------------------------------------\n"); + /* TRANSLATORS: do not translate command names and keywords before :: + * However, you should translate terms enclosed in <>. + */ + g_print(_("---[ Main menu ]---\n" + "goto [<setting> | <prop>] :: go to a setting or property\n" + "remove <setting>[.<prop>] | <prop> :: remove setting or reset property value\n" + "set [<setting>.<prop> <value>] :: set property value\n" + "describe [<setting>.<prop>] :: describe property\n" + "print [all | <setting>[.<prop>]] :: print the connection\n" + "verify [all | fix] :: verify the connection\n" + "save [persistent|temporary] :: save the connection\n" + "activate [<ifname>] [/<ap>|<nsp>] :: activate the connection\n" + "back :: go one level up (back)\n" + "help/? [<command>] :: print this help\n" + "nmcli <conf-option> <value> :: nmcli configuration\n" + "quit :: exit nmcli\n")); + g_print("------------------------------------------------------------------------------\n"); +} + +static void +editor_main_help(const char *command) +{ + if (!command) + editor_main_usage(); + else { + /* detailed command descriptions */ + NmcEditorMainCmd cmd = parse_editor_main_cmd(command, NULL); + + switch (cmd) { + case NMC_EDITOR_MAIN_CMD_GOTO: + g_print(_("goto <setting>[.<prop>] | <prop> :: enter setting/property for editing\n\n" + "This command enters into a setting or property for editing it.\n\n" + "Examples: nmcli> goto connection\n" + " nmcli connection> goto secondaries\n" + " nmcli> goto ipv4.addresses\n")); + break; + case NMC_EDITOR_MAIN_CMD_REMOVE: + g_print( + _("remove <setting>[.<prop>] :: remove setting or reset property value\n\n" + "This command removes an entire setting from the connection, or if a property\n" + "is given, resets that property to the default value.\n\n" + "Examples: nmcli> remove wifi-sec\n" + " nmcli> remove eth.mtu\n")); + break; + case NMC_EDITOR_MAIN_CMD_SET: + g_print(_("set [<setting>.<prop> <value>] :: set property value\n\n" + "This command sets property value.\n\n" + "Example: nmcli> set con.id My connection\n")); + break; + case NMC_EDITOR_MAIN_CMD_DESCRIBE: + g_print(_("describe [<setting>.<prop>] :: describe property\n\n" + "Shows property description. You can consult nm-settings(5) " + "manual page to see all NM settings and properties.\n")); + break; + case NMC_EDITOR_MAIN_CMD_PRINT: + g_print(_("print [all] :: print setting or connection values\n\n" + "Shows current property or the whole connection.\n\n" + "Example: nmcli ipv4> print all\n")); + break; + case NMC_EDITOR_MAIN_CMD_VERIFY: + g_print( + _("verify [all | fix] :: verify setting or connection validity\n\n" + "Verifies whether the setting or connection is valid and can be saved later.\n" + "It indicates invalid values on error. Some errors may be fixed automatically\n" + "by 'fix' option.\n\n" + "Examples: nmcli> verify\n" + " nmcli> verify fix\n" + " nmcli bond> verify\n")); + break; + case NMC_EDITOR_MAIN_CMD_SAVE: + g_print( + _("save [persistent|temporary] :: save the connection\n\n" + "Sends the connection profile to NetworkManager that either will save it\n" + "persistently, or will only keep it in memory. 'save' without an argument\n" + "means 'save persistent'.\n" + "Note that once you save the profile persistently those settings are saved\n" + "across reboot or restart. Subsequent changes can also be temporary or\n" + "persistent, but any temporary changes will not persist across reboot or\n" + "restart. If you want to fully remove the persistent connection, the connection\n" + "profile must be deleted.\n")); + break; + case NMC_EDITOR_MAIN_CMD_ACTIVATE: + g_print(_("activate [<ifname>] [/<ap>|<nsp>] :: activate the connection\n\n" + "Activates the connection.\n\n" + "Available options:\n" + "<ifname> - device the connection will be activated on\n" + "/<ap>|<nsp> - AP (Wi-Fi) or NSP (WiMAX) (prepend with / when <ifname> is " + "not specified)\n")); + break; + case NMC_EDITOR_MAIN_CMD_BACK: + g_print(_("back :: go to upper menu level\n\n")); + break; + case NMC_EDITOR_MAIN_CMD_HELP: + g_print(_("help/? [<command>] :: help for the nmcli commands\n\n")); + break; + case NMC_EDITOR_MAIN_CMD_NMCLI: + g_print(_("nmcli [<conf-option> <value>] :: nmcli configuration\n\n" + "Configures nmcli. The following options are available:\n" + "status-line yes | no [default: no]\n" + "save-confirmation yes | no [default: yes]\n" + "show-secrets yes | no [default: no]\n" + "prompt-color <color> | <0-8> [default: 0]\n" + "%s" /* color table description */ + "\n" + "Examples: nmcli> nmcli status-line yes\n" + " nmcli> nmcli save-confirmation no\n" + " nmcli> nmcli prompt-color 3\n"), + " 0 = normal\n" + " 1 = \33[30mblack\33[0m\n" + " 2 = \33[31mred\33[0m\n" + " 3 = \33[32mgreen\33[0m\n" + " 4 = \33[33myellow\33[0m\n" + " 5 = \33[34mblue\33[0m\n" + " 6 = \33[35mmagenta\33[0m\n" + " 7 = \33[36mcyan\33[0m\n" + " 8 = \33[37mwhite\33[0m\n"); + break; + case NMC_EDITOR_MAIN_CMD_QUIT: + g_print(_("quit :: exit nmcli\n\n" + "This command exits nmcli. When the connection being edited " + "is not saved, the user is asked to confirm the action.\n")); + break; + default: + g_print(_("Unknown command: '%s'\n"), command); + break; + } + } +} + +typedef enum { + NMC_EDITOR_SUB_CMD_UNKNOWN = 0, + NMC_EDITOR_SUB_CMD_SET, + NMC_EDITOR_SUB_CMD_ADD, + NMC_EDITOR_SUB_CMD_CHANGE, + NMC_EDITOR_SUB_CMD_REMOVE, + NMC_EDITOR_SUB_CMD_DESCRIBE, + NMC_EDITOR_SUB_CMD_PRINT, + NMC_EDITOR_SUB_CMD_BACK, + NMC_EDITOR_SUB_CMD_HELP, + NMC_EDITOR_SUB_CMD_QUIT +} NmcEditorSubCmd; + +static NmcEditorSubCmd +parse_editor_sub_cmd(const char *cmd, char **cmd_arg) +{ + NmcEditorSubCmd editor_cmd = NMC_EDITOR_SUB_CMD_UNKNOWN; + gs_free char * cmd_arg0 = NULL; + const char * cmd_argr; + + _split_cmd(cmd, &cmd_arg0, &cmd_argr); + if (!cmd_arg0) + goto fail; + + if (matches(cmd_arg0, "set")) + editor_cmd = NMC_EDITOR_SUB_CMD_SET; + else if (matches(cmd_arg0, "add")) + editor_cmd = NMC_EDITOR_SUB_CMD_ADD; + else if (matches(cmd_arg0, "change")) + editor_cmd = NMC_EDITOR_SUB_CMD_CHANGE; + else if (matches(cmd_arg0, "remove")) + editor_cmd = NMC_EDITOR_SUB_CMD_REMOVE; + else if (matches(cmd_arg0, "describe")) + editor_cmd = NMC_EDITOR_SUB_CMD_DESCRIBE; + else if (matches(cmd_arg0, "print")) + editor_cmd = NMC_EDITOR_SUB_CMD_PRINT; + else if (matches(cmd_arg0, "back")) + editor_cmd = NMC_EDITOR_SUB_CMD_BACK; + else if (matches(cmd_arg0, "help") || strcmp(cmd_arg0, "?") == 0) + editor_cmd = NMC_EDITOR_SUB_CMD_HELP; + else if (matches(cmd_arg0, "quit")) + editor_cmd = NMC_EDITOR_SUB_CMD_QUIT; + else + goto fail; + + NM_SET_OUT(cmd_arg, g_strdup(cmd_argr)); + return editor_cmd; +fail: + NM_SET_OUT(cmd_arg, NULL); + return NMC_EDITOR_SUB_CMD_UNKNOWN; +} + +static void +editor_sub_help(void) +{ + g_print("------------------------------------------------------------------------------\n"); + /* TRANSLATORS: do not translate command names and keywords before :: + * However, you should translate terms enclosed in <>. + */ + g_print(_("---[ Property menu ]---\n" + "set [<value>] :: set new value\n" + "add [<value>] :: add new option to the property\n" + "change :: change current value\n" + "remove [<index> | <option>] :: delete the value\n" + "describe :: describe property\n" + "print [setting | connection] :: print property (setting/connection) value(s)\n" + "back :: go to upper level\n" + "help/? [<command>] :: print this help or command description\n" + "quit :: exit nmcli\n")); + g_print("------------------------------------------------------------------------------\n"); +} + +static void +editor_sub_usage(const char *command) +{ + if (!command) + editor_sub_help(); + else { + /* detailed command descriptions */ + NmcEditorSubCmd cmdsub = parse_editor_sub_cmd(command, NULL); + + switch (cmdsub) { + case NMC_EDITOR_SUB_CMD_SET: + g_print(_("set [<value>] :: set new value\n\n" + "This command sets provided <value> to this property\n")); + break; + case NMC_EDITOR_SUB_CMD_ADD: + g_print(_("add [<value>] :: append new value to the property\n\n" + "This command adds provided <value> to this property, if " + "the property is of a container type. For single-valued " + "properties the property value is replaced (same as 'set').\n")); + break; + case NMC_EDITOR_SUB_CMD_CHANGE: + g_print(_("change :: change current value\n\n" + "Displays current value and allows editing it.\n")); + break; + case NMC_EDITOR_SUB_CMD_REMOVE: + g_print(_( + "remove [<value>|<index>|<option name>] :: delete the value\n\n" + "Removes the property value. For single-valued properties, this sets the\n" + "property back to its default value. For container-type properties, this removes\n" + "all the values of that property or you can specify an argument to remove just\n" + "a single item or option. The argument is either a value or index of the item to\n" + "remove, or an option name (for properties with named options).\n\n" + "Examples: nmcli ipv4.dns> remove 8.8.8.8\n" + " nmcli ipv4.dns> remove 2\n" + " nmcli bond.options> remove downdelay\n\n")); + break; + case NMC_EDITOR_SUB_CMD_DESCRIBE: + g_print(_("describe :: describe property\n\n" + "Shows property description. You can consult nm-settings(5) " + "manual page to see all NM settings and properties.\n")); + break; + case NMC_EDITOR_SUB_CMD_PRINT: + g_print(_("print [property|setting|connection] :: print property (setting, " + "connection) value(s)\n\n" + "Shows property value. Providing an argument you can also display " + "values for the whole setting or connection.\n")); + break; + case NMC_EDITOR_SUB_CMD_BACK: + g_print(_("back :: go to upper menu level\n\n")); + break; + case NMC_EDITOR_SUB_CMD_HELP: + g_print(_("help/? [<command>] :: help for nmcli commands\n\n")); + break; + case NMC_EDITOR_SUB_CMD_QUIT: + g_print(_("quit :: exit nmcli\n\n" + "This command exits nmcli. When the connection being edited " + "is not saved, the user is asked to confirm the action.\n")); + break; + default: + g_print(_("Unknown command: '%s'\n"), command); + break; + } + } +} + +/*****************************************************************************/ + +typedef struct { + NMDevice * device; + NMActiveConnection *ac; + guint monitor_id; + NmCli * nmc; +} MonitorACInfo; + +static gboolean nmc_editor_cb_called; +static GError * nmc_editor_error; +static MonitorACInfo *nmc_editor_monitor_ac; + +static void +editor_connection_changed_cb(NMConnection *connection, gboolean *changed) +{ + *changed = TRUE; +} + +/* + * Store 'error' to shared 'nmc_editor_error' and monitoring info to + * 'nmc_editor_monitor_ac' and signal the condition so that + * the 'editor-thread' thread could process that. + */ +static void +set_info_and_signal_editor_thread(GError *error, MonitorACInfo *monitor_ac_info) +{ + nmc_editor_cb_called = TRUE; + nmc_editor_error = error ? g_error_copy(error) : NULL; + nmc_editor_monitor_ac = monitor_ac_info; +} + +static void +add_connection_editor_cb(GObject *client, GAsyncResult *result, gpointer user_data) +{ + gs_unref_object NMRemoteConnection *connection = NULL; + gs_free_error GError *error = NULL; + + connection = nm_client_add_connection2_finish(NM_CLIENT(client), result, NULL, &error); + set_info_and_signal_editor_thread(error, NULL); +} + +static void +update_connection_editor_cb(GObject *connection, GAsyncResult *result, gpointer user_data) +{ + GError *error = NULL; + + nm_remote_connection_commit_changes_finish(NM_REMOTE_CONNECTION(connection), result, &error); + set_info_and_signal_editor_thread(error, NULL); + g_clear_error(&error); +} + +static gboolean +progress_activation_editor_cb(gpointer user_data) +{ + MonitorACInfo * info = (MonitorACInfo *) user_data; + NMDevice * device = info->device; + NMActiveConnection * ac = info->ac; + NMActiveConnectionState ac_state; + NMDeviceState dev_state; + + if (!device || !ac) + goto finish; + + ac_state = nm_active_connection_get_state(ac); + dev_state = nm_device_get_state(device); + + nmc_terminal_show_progress(gettext(nmc_device_state_to_string_with_external(device))); + + if (ac_state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED + || dev_state == NM_DEVICE_STATE_ACTIVATED) { + nmc_terminal_erase_line(); + g_print(_("Connection successfully activated (D-Bus active path: %s)\n"), + nm_object_get_path(NM_OBJECT(ac))); + goto finish; + } else if (ac_state == NM_ACTIVE_CONNECTION_STATE_DEACTIVATED + || dev_state == NM_DEVICE_STATE_FAILED) { + nmc_terminal_erase_line(); + g_print(_("Error: Connection activation failed.\n")); + goto finish; + } + + if (info->nmc->secret_agent) { + NMRemoteConnection *connection; + + connection = nm_active_connection_get_connection(ac); + nm_secret_agent_simple_enable(info->nmc->secret_agent, + nm_object_get_path(NM_OBJECT(connection))); + } + + return G_SOURCE_CONTINUE; + +finish: + nm_g_object_unref(device); + nm_g_object_unref(ac); + info->monitor_id = 0; + return G_SOURCE_REMOVE; +} + +static void +activate_connection_editor_cb(GObject *client, GAsyncResult *result, gpointer user_data) +{ + ActivateConnectionInfo *info = (ActivateConnectionInfo *) user_data; + NMDevice * device = info->device; + const GPtrArray * ac_devs; + MonitorACInfo * monitor_ac_info = NULL; + NMActiveConnection * active; + GError * error = NULL; + + active = nm_client_activate_connection_finish(NM_CLIENT(client), result, &error); + + if (!error) { + if (!device) { + ac_devs = nm_active_connection_get_devices(active); + device = ac_devs->len > 0 ? g_ptr_array_index(ac_devs, 0) : NULL; + } + if (device) { + monitor_ac_info = g_malloc0(sizeof(MonitorACInfo)); + monitor_ac_info->device = g_object_ref(device); + monitor_ac_info->ac = active; + monitor_ac_info->monitor_id = + g_timeout_add(120, progress_activation_editor_cb, monitor_ac_info); + monitor_ac_info->nmc = info->nmc; + } else + g_object_unref(active); + } + + nm_g_object_unref(info->device); + g_free(info); + + set_info_and_signal_editor_thread(error, monitor_ac_info); + g_clear_error(&error); +} + +/*****************************************************************************/ + +static void +print_property_description(NMSetting *setting, const char *prop_name) +{ + char *desc; + + desc = nmc_setting_get_property_desc(setting, prop_name); + if (desc) { + g_print("\n=== [%s] ===\n%s\n", prop_name, desc); + g_free(desc); + } +} + +static void +print_setting_description(NMSetting *setting) +{ + /* Show description of all properties */ + char **all_props; + int i; + + all_props = nmc_setting_get_valid_properties(setting); + g_print(("<<< %s >>>\n"), nm_setting_get_name(setting)); + for (i = 0; all_props && all_props[i]; i++) + print_property_description(setting, all_props[i]); + g_strfreev(all_props); +} + +static void +editor_show_status_line(NMConnection *connection, gboolean dirty, gboolean temp) +{ + NMSettingConnection *s_con; + const char * con_type, *con_id, *con_uuid; + + s_con = nm_connection_get_setting_connection(connection); + g_assert(s_con); + con_type = nm_setting_connection_get_connection_type(s_con); + con_id = nm_connection_get_id(connection); + con_uuid = nm_connection_get_uuid(connection); + + /* TRANSLATORS: status line in nmcli connection editor */ + g_print(_("[ Type: %s | Name: %s | UUID: %s | Dirty: %s | Temp: %s ]\n"), + con_type, + con_id, + con_uuid, + dirty ? _("yes") : _("no"), + temp ? _("yes") : _("no")); +} + +static gboolean +refresh_remote_connection(GWeakRef *weak, NMRemoteConnection **remote) +{ + gboolean previous; + + g_return_val_if_fail(remote, FALSE); + + previous = (*remote != NULL); + if (*remote) + g_object_unref(*remote); + *remote = g_weak_ref_get(weak); + + return (previous && !*remote); +} + +static gboolean +is_connection_dirty(NMConnection *connection, NMRemoteConnection *remote) +{ + return !nm_connection_compare(connection, + remote ? NM_CONNECTION(remote) : NULL, + NM_SETTING_COMPARE_FLAG_IGNORE_SECRETS + | NM_SETTING_COMPARE_FLAG_IGNORE_TIMESTAMP); +} + +static gboolean +confirm_quit(const NmcConfig *nmc_config) +{ + gs_free char *answer = NULL; + + answer = nmc_readline(nmc_config, + _("The connection is not saved. " + "Do you really want to quit? %s"), + prompt_yes_no(FALSE, NULL)); + nm_strstrip(answer); + return (answer && matches(answer, WORD_YES)); +} + +/* + * Submenu for detailed property editing + * Return: TRUE - continue; FALSE - should quit + */ +static gboolean +property_edit_submenu(NmCli * nmc, + NMConnection * connection, + NMRemoteConnection **rem_con, + GWeakRef * rem_con_weak, + NMSetting * curr_setting, + const char * prop_name) +{ + NmcEditorSubCmd cmdsub; + gboolean set_result; + GError * tmp_err = NULL; + gs_free char * prompt = NULL; + gboolean temp_changes; + + /* Set global variable for use in TAB completion */ + nmc_tab_completion.property = prop_name; + + prompt = nmc_colorize(&nmc->nmc_config, + NM_META_COLOR_PROMPT, + "nmcli %s.%s> ", + nm_setting_get_name(curr_setting), + prop_name); + + for (;;) { + gs_free char *cmd_property_user = NULL; + gs_free char *cmd_property_arg = NULL; + gs_free char *prop_val_user = NULL; + gboolean removed; + gboolean dirty; + + /* Get the remote connection again, it may have disappeared */ + removed = refresh_remote_connection(rem_con_weak, rem_con); + if (removed) { + g_print(_("The connection profile has been removed from another client. " + "You may type 'save' in the main menu to restore it.\n")); + } + + /* Connection is dirty? (not saved or differs from the saved) */ + dirty = is_connection_dirty(connection, *rem_con); + temp_changes = *rem_con ? nm_remote_connection_get_unsaved(*rem_con) : TRUE; + if (nmc->editor_status_line) + editor_show_status_line(connection, dirty, temp_changes); + + cmd_property_user = nmc_readline(&nmc->nmc_config, "%s", prompt); + if (!cmd_property_user || !*cmd_property_user) + continue; + g_strstrip(cmd_property_user); + cmdsub = parse_editor_sub_cmd(cmd_property_user, &cmd_property_arg); + + switch (cmdsub) { + case NMC_EDITOR_SUB_CMD_SET: + case NMC_EDITOR_SUB_CMD_ADD: + /* list, arrays,...: SET replaces the whole property value + * ADD adds the new value(s) + * single values: : both SET and ADD sets the new value + */ + if (!cmd_property_arg) { + gs_strfreev char **to_free = NULL; + const char *const *avals; + + avals = nmc_setting_get_property_allowed_values(curr_setting, prop_name, &to_free); + if (avals) { + gs_free char *avals_str = NULL; + + avals_str = nmc_util_strv_for_display(avals, FALSE); + g_print(_("Allowed values for '%s' property: %s\n"), prop_name, avals_str); + } + prop_val_user = nmc_readline(&nmc->nmc_config, _("Enter '%s' value: "), prop_name); + } else + prop_val_user = g_strdup(cmd_property_arg); + + set_result = nmc_setting_set_property(nmc->client, + curr_setting, + prop_name, + (cmdsub == NMC_EDITOR_SUB_CMD_SET) + ? NM_META_ACCESSOR_MODIFIER_SET + : NM_META_ACCESSOR_MODIFIER_ADD, + prop_val_user, + &tmp_err); + if (!set_result) { + g_print(_("Error: failed to set '%s' property: %s\n"), prop_name, tmp_err->message); + g_clear_error(&tmp_err); + } + break; + + case NMC_EDITOR_SUB_CMD_CHANGE: + rl_startup_hook = nmc_rl_set_deftext; + nmc_rl_pre_input_deftext = + nmc_setting_get_property_parsable(curr_setting, prop_name, NULL); + prop_val_user = nmc_readline(&nmc->nmc_config, _("Edit '%s' value: "), prop_name); + + if (!nmc_setting_set_property(nmc->client, + curr_setting, + prop_name, + NM_META_ACCESSOR_MODIFIER_SET, + prop_val_user, + &tmp_err)) { + g_print(_("Error: failed to set '%s' property: %s\n"), prop_name, tmp_err->message); + g_clear_error(&tmp_err); + } + break; + + case NMC_EDITOR_SUB_CMD_REMOVE: + if (!nmc_setting_set_property(nmc->client, + curr_setting, + prop_name, + (cmd_property_arg ? NM_META_ACCESSOR_MODIFIER_DEL + : NM_META_ACCESSOR_MODIFIER_SET), + cmd_property_arg, + &tmp_err)) { + g_print(_("Error: %s\n"), tmp_err->message); + g_clear_error(&tmp_err); + } + break; + + case NMC_EDITOR_SUB_CMD_DESCRIBE: + /* Show property description */ + print_property_description(curr_setting, prop_name); + break; + + case NMC_EDITOR_SUB_CMD_PRINT: + /* Print current connection settings/properties */ + if (cmd_property_arg) { + if (matches(cmd_property_arg, "setting")) + editor_show_setting(curr_setting, nmc); + else if (matches(cmd_property_arg, "connection") + || matches(cmd_property_arg, "all")) + editor_show_connection(connection, nmc); + else + g_print(_("Unknown command argument: '%s'\n"), cmd_property_arg); + } else { + gs_free char *prop_val = NULL; + + prop_val = nmc_setting_get_property(curr_setting, prop_name, NULL); + g_print("%s: %s\n", prop_name, prop_val); + } + break; + + case NMC_EDITOR_SUB_CMD_BACK: + /* Set global variable for use in TAB completion */ + nmc_tab_completion.property = NULL; + return TRUE; + + case NMC_EDITOR_SUB_CMD_HELP: + editor_sub_usage(cmd_property_arg); + break; + + case NMC_EDITOR_SUB_CMD_QUIT: + if (is_connection_dirty(connection, *rem_con)) { + if (confirm_quit(&nmc->nmc_config)) + return FALSE; + } else + return FALSE; + break; + + case NMC_EDITOR_SUB_CMD_UNKNOWN: + default: + g_print(_("Unknown command: '%s'\n"), cmd_property_user); + break; + } + } +} + +/* + * Split 'str' in the following format: [[[setting.]property] [value]] + * and return the components in 'setting', 'property' and 'value' + * Use g_free() to deallocate the returned strings. + */ +static void +split_editor_main_cmd_args(const char *str, char **setting, char **property, char **value) +{ + gs_free char *cmd_arg0 = NULL; + const char * cmd_argr; + const char * s; + + NM_SET_OUT(setting, NULL); + NM_SET_OUT(property, NULL); + NM_SET_OUT(value, NULL); + + _split_cmd(str, &cmd_arg0, &cmd_argr); + if (!cmd_arg0) + return; + + NM_SET_OUT(value, g_strdup(cmd_argr)); + s = strchr(cmd_arg0, '.'); + if (s && s > cmd_arg0) { + NM_SET_OUT(setting, g_strndup(cmd_arg0, s - cmd_arg0)); + NM_SET_OUT(property, g_strdup(&s[1])); + } else { + NM_SET_OUT(property, g_steal_pointer(&cmd_arg0)); + } +} + +static NMSetting * +create_setting_by_name(const char * name, + const NMMetaSettingValidPartItem *const *valid_settings_main, + const NMMetaSettingValidPartItem *const *valid_settings_slave) +{ + const char *setting_name; + NMSetting * setting = NULL; + + /* Get a valid setting name */ + setting_name = check_valid_name(name, valid_settings_main, valid_settings_slave, NULL); + + if (setting_name) { + setting = nm_meta_setting_info_editor_new_setting( + nm_meta_setting_info_editor_find_by_name(setting_name, FALSE), + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + } + return setting; +} + +static const char * +ask_check_setting(const NmcConfig * nmc_config, + const char * arg, + const NMMetaSettingValidPartItem *const *valid_settings_main, + const NMMetaSettingValidPartItem *const *valid_settings_slave, + const char * valid_settings_str) +{ + gs_free char *setting_name_user = NULL; + const char * setting_name; + GError * err = NULL; + + if (!arg) { + g_print(_("Available settings: %s\n"), valid_settings_str); + setting_name_user = nmc_readline(nmc_config, EDITOR_PROMPT_SETTING); + } else + setting_name_user = g_strdup(arg); + + nm_strstrip(setting_name_user); + + if (!(setting_name = check_valid_name(setting_name_user, + valid_settings_main, + valid_settings_slave, + &err))) { + g_print(_("Error: invalid setting name; %s\n"), err->message); + g_clear_error(&err); + } + return setting_name; +} + +static const char * +ask_check_property(const NmcConfig *nmc_config, + const char * arg, + const char ** valid_props, + const char * valid_props_str) +{ + gs_free_error GError *tmp_err = NULL; + gs_free char * prop_name_user = NULL; + const char * prop_name; + + if (!arg) { + g_print(_("Available properties: %s\n"), valid_props_str); + prop_name_user = nmc_readline(nmc_config, EDITOR_PROMPT_PROPERTY); + nm_strstrip(prop_name_user); + } else + prop_name_user = g_strdup(arg); + + prop_name = nmc_string_is_valid(prop_name_user, valid_props, &tmp_err); + if (!prop_name) + g_print(_("Error: property %s\n"), tmp_err->message); + + return prop_name; +} + +/* Copy timestamp from src do dst */ +static void +update_connection_timestamp(NMConnection *src, NMConnection *dst) +{ + NMSettingConnection *s_con_src, *s_con_dst; + + s_con_src = nm_connection_get_setting_connection(src); + s_con_dst = nm_connection_get_setting_connection(dst); + if (s_con_src && s_con_dst) { + guint64 timestamp = nm_setting_connection_get_timestamp(s_con_src); + + g_object_set(s_con_dst, NM_SETTING_CONNECTION_TIMESTAMP, timestamp, NULL); + } +} + +static gboolean +confirm_connection_saving(const NmcConfig *nmc_config, NMConnection *local, NMConnection *remote) +{ + NMSettingConnection *s_con_loc, *s_con_rem; + gboolean ac_local, ac_remote; + gboolean confirmed = TRUE; + + s_con_loc = nm_connection_get_setting_connection(local); + g_assert(s_con_loc); + ac_local = nm_setting_connection_get_autoconnect(s_con_loc); + + if (remote) { + s_con_rem = nm_connection_get_setting_connection(remote); + g_assert(s_con_rem); + ac_remote = nm_setting_connection_get_autoconnect(s_con_rem); + } else + ac_remote = FALSE; + + if (ac_local && !ac_remote) { + gs_free char *answer = NULL; + + answer = nmc_readline(nmc_config, + _("Saving the connection with 'autoconnect=yes'. " + "That might result in an immediate activation of the connection.\n" + "Do you still want to save? %s"), + prompt_yes_no(TRUE, NULL)); + nm_strstrip(answer); + confirmed = (!answer || matches(answer, WORD_YES)); + } + return confirmed; +} + +typedef struct { + guint level; + char * main_prompt; + NMSetting *curr_setting; + char ** valid_props; + char * valid_props_str; +} NmcEditorMenuContext; + +static void +menu_switch_to_level0(const NmcConfig * nmc_config, + NmcEditorMenuContext *menu_ctx, + const char * prompt) +{ + menu_ctx->level = 0; + g_free(menu_ctx->main_prompt); + menu_ctx->main_prompt = nmc_colorize(nmc_config, NM_META_COLOR_PROMPT, "%s", prompt); + menu_ctx->curr_setting = NULL; + g_strfreev(menu_ctx->valid_props); + menu_ctx->valid_props = NULL; + g_free(menu_ctx->valid_props_str); + menu_ctx->valid_props_str = NULL; +} + +static void +menu_switch_to_level1(const NmcConfig * nmc_config, + NmcEditorMenuContext *menu_ctx, + NMSetting * setting, + const char * setting_name) +{ + menu_ctx->level = 1; + g_free(menu_ctx->main_prompt); + menu_ctx->main_prompt = + nmc_colorize(nmc_config, NM_META_COLOR_PROMPT, "nmcli %s> ", setting_name); + menu_ctx->curr_setting = setting; + g_strfreev(menu_ctx->valid_props); + menu_ctx->valid_props = nmc_setting_get_valid_properties(menu_ctx->curr_setting); + g_free(menu_ctx->valid_props_str); + menu_ctx->valid_props_str = g_strjoinv(", ", menu_ctx->valid_props); +} + +static gboolean +editor_save_timeout(gpointer user_data) +{ + gboolean *timeout = user_data; + + *timeout = TRUE; + + return G_SOURCE_REMOVE; +} + +static gboolean +editor_menu_main(NmCli *nmc, NMConnection *connection, const char *connection_type) +{ + gs_unref_object NMRemoteConnection * rem_con = NULL; + NMSettingConnection * s_con; + NMRemoteConnection * con_tmp; + GWeakRef weak = {{NULL}}; + gboolean removed; + NmcEditorMainCmd cmd; + gboolean cmd_loop = TRUE; + const NMMetaSettingValidPartItem *const *valid_settings_main; + const NMMetaSettingValidPartItem *const *valid_settings_slave; + gs_free char * valid_settings_str = NULL; + const char * s_type = NULL; + gboolean temp_changes; + GError * err1 = NULL; + NmcEditorMenuContext menu_ctx = {0}; + + s_con = nm_connection_get_setting_connection(connection); + if (s_con) + s_type = nm_setting_connection_get_slave_type(s_con); + + valid_settings_main = get_valid_settings_array(connection_type); + valid_settings_slave = nm_meta_setting_info_valid_parts_for_slave_type(s_type, NULL); + + valid_settings_str = get_valid_options_string(valid_settings_main, valid_settings_slave); + g_print(_("You may edit the following settings: %s\n"), valid_settings_str); + + menu_ctx.main_prompt = nmc_colorize(&nmc->nmc_config, NM_META_COLOR_PROMPT, BASE_PROMPT); + + /* Get remote connection */ + con_tmp = nm_client_get_connection_by_uuid(nmc->client, nm_connection_get_uuid(connection)); + g_weak_ref_init(&weak, con_tmp); + rem_con = g_weak_ref_get(&weak); + + while (cmd_loop) { + gs_free char *cmd_user = NULL; + gs_free char *cmd_arg = NULL; + gs_free char *cmd_arg_s = NULL; + gs_free char *cmd_arg_p = NULL; + gs_free char *cmd_arg_v = NULL; + gboolean dirty; + + /* Connection is dirty? (not saved or differs from the saved) */ + dirty = is_connection_dirty(connection, rem_con); + temp_changes = rem_con ? nm_remote_connection_get_unsaved(rem_con) : TRUE; + if (nmc->editor_status_line) + editor_show_status_line(connection, dirty, temp_changes); + + cmd_user = nmc_readline(&nmc->nmc_config, "%s", menu_ctx.main_prompt); + + /* Get the remote connection again, it may have disappeared */ + removed = refresh_remote_connection(&weak, &rem_con); + if (removed) { + g_print(_("The connection profile has been removed from another client. " + "You may type 'save' to restore it.\n")); + } + + if (!cmd_user || !*cmd_user) + continue; + + g_strstrip(cmd_user); + + cmd = parse_editor_main_cmd(cmd_user, &cmd_arg); + + split_editor_main_cmd_args(cmd_arg, &cmd_arg_s, &cmd_arg_p, &cmd_arg_v); + switch (cmd) { + case NMC_EDITOR_MAIN_CMD_SET: + /* Set property value */ + if (!cmd_arg) { + if (menu_ctx.level == 1) { + gs_strfreev char **avals_to_free = NULL; + gs_free char * prop_val_user = NULL; + const char * prop_name; + const char *const *avals; + GError * tmp_err = NULL; + + prop_name = ask_check_property(&nmc->nmc_config, + cmd_arg, + (const char **) menu_ctx.valid_props, + menu_ctx.valid_props_str); + if (!prop_name) + break; + + avals = nmc_setting_get_property_allowed_values(menu_ctx.curr_setting, + prop_name, + &avals_to_free); + if (avals) { + gs_free char *avals_str = NULL; + + avals_str = nmc_util_strv_for_display(avals, FALSE); + g_print(_("Allowed values for '%s' property: %s\n"), prop_name, avals_str); + } + prop_val_user = + nmc_readline(&nmc->nmc_config, _("Enter '%s' value: "), prop_name); + + if (!nmc_setting_set_property(nmc->client, + menu_ctx.curr_setting, + prop_name, + NM_META_ACCESSOR_MODIFIER_ADD, + prop_val_user, + &tmp_err)) { + g_print(_("Error: failed to set '%s' property: %s\n"), + prop_name, + tmp_err->message); + g_clear_error(&tmp_err); + } + } else { + g_print(_("Error: no setting selected; valid are [%s]\n"), valid_settings_str); + g_print(_("use 'goto <setting>' first, or 'set <setting>.<property>'\n")); + } + } else { + gs_free char * prop_name = NULL; + gs_unref_object NMSetting *ss_created = NULL; + NMSetting * ss = NULL; + GError * tmp_err = NULL; + + if (cmd_arg_s) { + /* setting provided as "setting.property" */ + ss = is_setting_valid(connection, + valid_settings_main, + valid_settings_slave, + cmd_arg_s); + if (!ss) { + ss_created = create_setting_by_name(cmd_arg_s, + valid_settings_main, + valid_settings_slave); + ss = ss_created; + if (!ss) { + g_print(_("Error: invalid setting argument '%s'; valid are [%s]\n"), + cmd_arg_s, + valid_settings_str); + break; + } + } + } else { + if (menu_ctx.curr_setting) + ss = menu_ctx.curr_setting; + else { + g_print(_("Error: missing setting for '%s' property\n"), cmd_arg_p); + break; + } + } + + prop_name = is_property_valid(ss, cmd_arg_p, &tmp_err); + if (!prop_name) { + g_print(_("Error: invalid property: %s\n"), tmp_err->message); + g_clear_error(&tmp_err); + break; + } + + /* Ask for value */ + if (!cmd_arg_v) { + gs_strfreev char **avals_to_free = NULL; + const char *const *avals; + + avals = nmc_setting_get_property_allowed_values(ss, prop_name, &avals_to_free); + if (avals) { + gs_free char *avals_str = NULL; + + avals_str = nmc_util_strv_for_display(avals, FALSE); + g_print(_("Allowed values for '%s' property: %s\n"), prop_name, avals_str); + } + cmd_arg_v = nmc_readline(&nmc->nmc_config, _("Enter '%s' value: "), prop_name); + } + + /* setting a value in edit mode "appends". That seems unexpected behavior. */ + if (!nmc_setting_set_property(nmc->client, + ss, + prop_name, + cmd_arg_v ? NM_META_ACCESSOR_MODIFIER_ADD + : NM_META_ACCESSOR_MODIFIER_SET, + cmd_arg_v, + &tmp_err)) { + g_print(_("Error: failed to set '%s' property: %s\n"), + prop_name, + tmp_err->message); + g_clear_error(&tmp_err); + } + + if (ss_created) + nm_connection_add_setting(connection, g_steal_pointer(&ss_created)); + } + break; + + case NMC_EDITOR_MAIN_CMD_GOTO: + /* cmd_arg_s != NULL means 'setting.property' argument */ + if (menu_ctx.level == 0 || cmd_arg_s) { + /* in top level - no setting selected yet */ + const char *setting_name; + NMSetting * setting; + const char *user_arg = cmd_arg_s ?: cmd_arg_p; + + setting_name = ask_check_setting(&nmc->nmc_config, + user_arg, + valid_settings_main, + valid_settings_slave, + valid_settings_str); + if (!setting_name) + break; + + setting = nm_connection_get_setting_by_name(connection, setting_name); + if (!setting) { + const NMMetaSettingInfoEditor *setting_info; + + setting_info = nm_meta_setting_info_editor_find_by_name(setting_name, FALSE); + if (!setting_info) { + g_print(_("Error: unknown setting '%s'\n"), setting_name); + break; + } + + setting = nm_meta_setting_info_editor_new_setting( + setting_info, + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + + if (NM_IS_SETTING_WIRELESS(setting)) + nmc_setting_wireless_connect_handlers(NM_SETTING_WIRELESS(setting)); + else if (NM_IS_SETTING_IP4_CONFIG(setting)) + nmc_setting_ip4_connect_handlers(NM_SETTING_IP_CONFIG(setting)); + else if (NM_IS_SETTING_IP6_CONFIG(setting)) + nmc_setting_ip6_connect_handlers(NM_SETTING_IP_CONFIG(setting)); + else if (NM_IS_SETTING_PROXY(setting)) + nmc_setting_proxy_connect_handlers(NM_SETTING_PROXY(setting)); + + nm_connection_add_setting(connection, setting); + } + /* Set global variable for use in TAB completion */ + nmc_tab_completion.setting = setting; + + /* Switch to level 1 */ + menu_switch_to_level1(&nmc->nmc_config, &menu_ctx, setting, setting_name); + + if (!cmd_arg_s) { + g_print(_("You may edit the following properties: %s\n"), + menu_ctx.valid_props_str); + break; + } + } + if (menu_ctx.level == 1 || cmd_arg_s) { + /* level 1 - setting selected */ + const char *prop_name; + + prop_name = ask_check_property(&nmc->nmc_config, + cmd_arg_p, + (const char **) menu_ctx.valid_props, + menu_ctx.valid_props_str); + if (!prop_name) + break; + + /* submenu - level 2 - editing properties */ + cmd_loop = property_edit_submenu(nmc, + connection, + &rem_con, + &weak, + menu_ctx.curr_setting, + prop_name); + } + break; + + case NMC_EDITOR_MAIN_CMD_REMOVE: + /* Remove setting from connection, or delete value of a property */ + if (!cmd_arg) { + if (menu_ctx.level == 1) { + GError * tmp_err = NULL; + const char *prop_name; + + prop_name = ask_check_property(&nmc->nmc_config, + cmd_arg, + (const char **) menu_ctx.valid_props, + menu_ctx.valid_props_str); + if (!prop_name) + break; + + if (!nmc_setting_set_property(nmc->client, + menu_ctx.curr_setting, + prop_name, + NM_META_ACCESSOR_MODIFIER_SET, + NULL, + &tmp_err)) { + g_print(_("Error: failed to remove value of '%s': %s\n"), + prop_name, + tmp_err->message); + g_clear_error(&tmp_err); + } + } else + g_print(_("Error: no argument given; valid are [%s]\n"), valid_settings_str); + } else { + NMSetting *ss = NULL; + gboolean descr_all; + char * user_s; + + /* cmd_arg_s != NULL means argument is "setting.property" */ + descr_all = !cmd_arg_s && !menu_ctx.curr_setting; + user_s = descr_all ? cmd_arg_p : cmd_arg_s; + if (user_s) { + ss = is_setting_valid(connection, + valid_settings_main, + valid_settings_slave, + user_s); + if (!ss) { + if (check_valid_name(user_s, + valid_settings_main, + valid_settings_slave, + NULL)) { + g_print(_("Setting '%s' is not present in the connection.\n"), user_s); + } else { + g_print(_("Error: invalid setting argument '%s'; valid are [%s]\n"), + user_s, + valid_settings_str); + } + break; + } + } else + ss = menu_ctx.curr_setting; + + if (descr_all) { + gs_free_error GError *local = NULL; + + /* Remove setting from the connection */ + if (!connection_remove_setting(connection, ss, &local)) + g_print("%s\n", local->message); + + if (ss == menu_ctx.curr_setting) { + /* If we removed the setting we are in, go up */ + menu_switch_to_level0(&nmc->nmc_config, &menu_ctx, BASE_PROMPT); + nmc_tab_completion.setting = NULL; /* for TAB completion */ + } + } else { + gs_free char *prop_name = NULL; + gs_free_error GError *tmp_err = NULL; + + prop_name = is_property_valid(ss, cmd_arg_p, &tmp_err); + if (prop_name) { + if (!nmc_setting_set_property(nmc->client, + ss, + prop_name, + NM_META_ACCESSOR_MODIFIER_SET, + NULL, + &tmp_err)) { + g_print(_("Error: failed to remove value of '%s': %s\n"), + prop_name, + tmp_err->message); + } + } else { + NMSetting *s_tmp; + + /* If the string is not a property, try it as a setting */ + s_tmp = is_setting_valid(connection, + valid_settings_main, + valid_settings_slave, + cmd_arg_p); + if (s_tmp) { + gs_free_error GError *local = NULL; + + /* Remove setting from the connection */ + if (!connection_remove_setting(connection, s_tmp, &local)) + g_print("%s\n", local->message); + + /* coverity[copy_paste_error] - suppress Coverity COPY_PASTE_ERROR defect */ + if (ss == menu_ctx.curr_setting) { + /* If we removed the setting we are in, go up */ + menu_switch_to_level0(&nmc->nmc_config, &menu_ctx, BASE_PROMPT); + nmc_tab_completion.setting = NULL; /* for TAB completion */ + } + } else { + g_print(_("Error: %s properties, nor it is a setting name.\n"), + tmp_err->message); + } + } + } + } + break; + + case NMC_EDITOR_MAIN_CMD_DESCRIBE: + /* Print property description */ + if (!cmd_arg) { + if (menu_ctx.level == 1) { + const char *prop_name; + + prop_name = ask_check_property(&nmc->nmc_config, + cmd_arg, + (const char **) menu_ctx.valid_props, + menu_ctx.valid_props_str); + if (!prop_name) + break; + + /* Show property description */ + print_property_description(menu_ctx.curr_setting, prop_name); + } else { + g_print(_("Error: no setting selected; valid are [%s]\n"), valid_settings_str); + g_print(_("use 'goto <setting>' first, or 'describe <setting>.<property>'\n")); + } + } else { + gs_unref_object NMSetting *ss_free = NULL; + NMSetting * ss = NULL; + gboolean descr_all; + char * user_s; + + /* cmd_arg_s != NULL means argument is "setting.property" */ + descr_all = !cmd_arg_s && !menu_ctx.curr_setting; + user_s = descr_all ? cmd_arg_p : cmd_arg_s; + if (user_s) { + ss = is_setting_valid(connection, + valid_settings_main, + valid_settings_slave, + user_s); + if (!ss) { + ss = create_setting_by_name(user_s, + valid_settings_main, + valid_settings_slave); + if (!ss) { + g_print(_("Error: invalid setting argument '%s'; valid are [%s]\n"), + user_s, + valid_settings_str); + break; + } + ss_free = ss; + } + } else + ss = menu_ctx.curr_setting; + + if (!ss) { + g_print(_("Error: no setting selected; valid are [%s]\n"), valid_settings_str); + g_print(_("use 'goto <setting>' first, or 'describe <setting>.<property>'\n")); + } else if (descr_all) { + /* Show description for all properties */ + print_setting_description(ss); + } else { + gs_free_error GError *tmp_err = NULL; + gs_free char * prop_name = NULL; + + prop_name = is_property_valid(ss, cmd_arg_p, &tmp_err); + if (prop_name) { + /* Show property description */ + print_property_description(ss, prop_name); + } else { + /* If the string is not a property, try it as a setting */ + NMSetting *s_tmp; + + s_tmp = is_setting_valid(connection, + valid_settings_main, + valid_settings_slave, + cmd_arg_p); + if (s_tmp) + print_setting_description(s_tmp); + else { + g_print(_("Error: invalid property: %s, " + "neither a valid setting name.\n"), + tmp_err->message); + } + } + } + } + break; + + case NMC_EDITOR_MAIN_CMD_PRINT: + /* Print current connection settings/properties */ + if (cmd_arg) { + if (nm_streq(cmd_arg, "all")) + editor_show_connection(connection, nmc); + else { + NMSetting *ss = NULL; + gboolean whole_setting; + char * user_s; + + /* cmd_arg_s != NULL means argument is "setting.property" */ + whole_setting = !cmd_arg_s && !menu_ctx.curr_setting; + user_s = whole_setting ? cmd_arg_p : cmd_arg_s; + if (user_s) { + const char *s_name; + + s_name = check_valid_name(user_s, + valid_settings_main, + valid_settings_slave, + NULL); + if (!s_name) { + g_print(_("Error: unknown setting: '%s'\n"), user_s); + break; + } + ss = nm_connection_get_setting_by_name(connection, s_name); + if (!ss) { + g_print(_("Error: '%s' setting not present in the connection\n"), + s_name); + break; + } + } else + ss = menu_ctx.curr_setting; + + if (whole_setting) { + /* Print the whole setting */ + editor_show_setting(ss, nmc); + } else { + gs_free char *prop_name = NULL; + GError * err = NULL; + + prop_name = is_property_valid(ss, cmd_arg_p, &err); + if (prop_name) { + /* Print one property */ + gs_free char *prop_val = NULL; + + prop_val = nmc_setting_get_property(ss, prop_name, NULL); + g_print("%s.%s: %s\n", nm_setting_get_name(ss), prop_name, prop_val); + } else { + /* If the string is not a property, try it as a setting */ + NMSetting *s_tmp; + s_tmp = is_setting_valid(connection, + valid_settings_main, + valid_settings_slave, + cmd_arg_p); + if (s_tmp) { + /* Print the whole setting */ + editor_show_setting(s_tmp, nmc); + } else + g_print(_("Error: invalid property: %s%s\n"), + err->message, + cmd_arg_s ? "" : _(", neither a valid setting name")); + g_clear_error(&err); + } + } + } + } else { + if (menu_ctx.curr_setting) + editor_show_setting(menu_ctx.curr_setting, nmc); + else + editor_show_connection(connection, nmc); + } + break; + + case NMC_EDITOR_MAIN_CMD_VERIFY: + /* Verify current setting or the whole connection */ + if (cmd_arg && strcmp(cmd_arg, "all") && strcmp(cmd_arg, "fix")) { + g_print(_("Invalid verify option: %s\n"), cmd_arg); + break; + } + + if (menu_ctx.curr_setting && (!cmd_arg || strcmp(cmd_arg, "all") != 0)) { + gs_free_error GError *tmp_err = NULL; + + nm_setting_verify(menu_ctx.curr_setting, NULL, &tmp_err); + g_print(_("Verify setting '%s': %s\n"), + nm_setting_get_name(menu_ctx.curr_setting), + tmp_err ? tmp_err->message : "OK"); + } else { + gs_free_error GError *tmp_err = NULL; + gboolean fixed = TRUE; + gboolean modified; + gboolean valid; + + valid = nm_connection_verify(connection, &tmp_err); + if (!valid && nm_streq0(cmd_arg, "fix")) { + /* Try to fix normalizable errors */ + g_clear_error(&tmp_err); + fixed = nm_connection_normalize(connection, NULL, &modified, &tmp_err); + } + g_print(_("Verify connection: %s\n"), tmp_err ? tmp_err->message : "OK"); + if (!fixed) + g_print(_("The error cannot be fixed automatically.\n")); + } + break; + + case NMC_EDITOR_MAIN_CMD_SAVE: + /* Save the connection */ + if (nm_connection_verify(connection, &err1)) { + gboolean temporary = FALSE; + gboolean connection_changed; + nm_auto_unref_gsource GSource *source = NULL; + gboolean timeout = FALSE; + gulong handler_id = 0; + + /* parse argument */ + if (cmd_arg) { + if (matches(cmd_arg, "temporary")) + temporary = TRUE; + else if (matches(cmd_arg, "persistent")) + temporary = FALSE; + else { + g_print(_("Error: invalid argument '%s'\n"), cmd_arg); + break; + } + } + + /* Ask for save confirmation if the connection changes to autoconnect=yes */ + if (nmc->editor_save_confirmation) { + if (!confirm_connection_saving(&nmc->nmc_config, + connection, + NM_CONNECTION(rem_con))) + break; + } + + if (!rem_con) { + add_connection(nmc->client, + connection, + temporary, + add_connection_editor_cb, + NULL); + connection_changed = TRUE; + } else { + /* Save/update already saved (existing) connection */ + nm_connection_replace_settings_from_connection(NM_CONNECTION(rem_con), + connection); + update_connection(rem_con, temporary, update_connection_editor_cb, NULL); + + handler_id = g_signal_connect(rem_con, + NM_CONNECTION_CHANGED, + G_CALLBACK(editor_connection_changed_cb), + &connection_changed); + connection_changed = FALSE; + } + + source = g_timeout_source_new(10 * NM_UTILS_MSEC_PER_SEC); + g_source_set_callback(source, editor_save_timeout, &timeout, NULL); + g_source_attach(source, g_main_loop_get_context(loop)); + + while (!nmc_editor_cb_called && !timeout) + g_main_context_iteration(NULL, TRUE); + + if (!nmc_editor_error) { + while (!connection_changed && !timeout) + g_main_context_iteration(NULL, TRUE); + } + + if (handler_id) + g_signal_handler_disconnect(rem_con, handler_id); + g_source_destroy(source); + + if (nmc_editor_error) { + g_print(_("Error: Failed to save '%s' (%s) connection: %s\n"), + nm_connection_get_id(connection), + nm_connection_get_uuid(connection), + nmc_editor_error->message); + g_error_free(nmc_editor_error); + } else if (timeout) { + g_print(_("Error: Timeout saving '%s' (%s) connection\n"), + nm_connection_get_id(connection), + nm_connection_get_uuid(connection)); + } else { + g_print(!rem_con ? _("Connection '%s' (%s) successfully saved.\n") + : _("Connection '%s' (%s) successfully updated.\n"), + nm_connection_get_id(connection), + nm_connection_get_uuid(connection)); + + con_tmp = nm_client_get_connection_by_uuid(nmc->client, + nm_connection_get_uuid(connection)); + g_weak_ref_set(&weak, con_tmp); + refresh_remote_connection(&weak, &rem_con); + + /* Replace local connection with the remote one to be sure they are equal. + * This mitigates problems with plugins not preserving some properties or + * adding ipv{4,6} settings when not present. + */ + if (con_tmp) { + gs_free char *s_name = NULL; + + if (menu_ctx.curr_setting) + s_name = g_strdup(nm_setting_get_name(menu_ctx.curr_setting)); + + /* Update settings and secrets in the local connection */ + nm_connection_replace_settings_from_connection(connection, + NM_CONNECTION(con_tmp)); + update_secrets_in_connection(con_tmp, connection); + + /* Also update setting for menu context and TAB-completion */ + menu_ctx.curr_setting = + s_name ? nm_connection_get_setting_by_name(connection, s_name) : NULL; + nmc_tab_completion.setting = menu_ctx.curr_setting; + } + } + + nmc_editor_cb_called = FALSE; + nmc_editor_error = NULL; + } else { + g_print(_("Error: connection verification failed: %s\n"), + err1 ? err1->message : _("(unknown error)")); + g_print(_("You may try running 'verify fix' to fix errors.\n")); + } + + g_clear_error(&err1); + break; + + case NMC_EDITOR_MAIN_CMD_ACTIVATE: + { + GError * tmp_err = NULL; + const char *ifname = cmd_arg_p; + const char *ap_nsp = cmd_arg_v; + + /* When only AP/NSP is specified it is prepended with '/' */ + if (!cmd_arg_v) { + if (ifname && ifname[0] == '/') { + ap_nsp = ifname + 1; + ifname = NULL; + } + } else + ap_nsp = ap_nsp && ap_nsp[0] == '/' ? ap_nsp + 1 : ap_nsp; + + if (is_connection_dirty(connection, rem_con)) { + /* TRANSLATORS: do not translate 'save', leave it as it is */ + g_print(_("Error: connection is not saved. Type 'save' first.\n")); + break; + } + if (!nm_connection_verify(NM_CONNECTION(rem_con), &tmp_err)) { + g_print(_("Error: connection is not valid: %s\n"), tmp_err->message); + g_clear_error(&tmp_err); + break; + } + + nmc->nowait_flag = FALSE; + nmc->should_wait++; + nmc->nmc_config_mutable.print_output = NMC_PRINT_PRETTY; + if (!nmc_activate_connection(nmc, + NM_CONNECTION(rem_con), + ifname, + ap_nsp, + ap_nsp, + NULL, + activate_connection_editor_cb, + &tmp_err)) { + g_print(_("Error: Cannot activate connection: %s.\n"), tmp_err->message); + g_clear_error(&tmp_err); + break; + } + + while (!nmc_editor_cb_called) + g_main_context_iteration(NULL, TRUE); + + if (nmc_editor_error) { + g_print(_("Error: Failed to activate '%s' (%s) connection: %s\n"), + nm_connection_get_id(connection), + nm_connection_get_uuid(connection), + nmc_editor_error->message); + g_error_free(nmc_editor_error); + } else { + nmc_readline(&nmc->nmc_config, + _("Monitoring connection activation (press any key to continue)\n")); + } + + if (nmc_editor_monitor_ac) { + if (nmc_editor_monitor_ac->monitor_id) + g_source_remove(nmc_editor_monitor_ac->monitor_id); + g_free(nmc_editor_monitor_ac); + } + nmc_editor_cb_called = FALSE; + nmc_editor_error = NULL; + nmc_editor_monitor_ac = NULL; + + /* Update timestamp in local connection */ + update_connection_timestamp(NM_CONNECTION(rem_con), connection); + + } break; + + case NMC_EDITOR_MAIN_CMD_BACK: + /* Go back (up) an the menu */ + if (menu_ctx.level == 1) { + menu_switch_to_level0(&nmc->nmc_config, &menu_ctx, BASE_PROMPT); + nmc_tab_completion.setting = NULL; /* for TAB completion */ + } + break; + + case NMC_EDITOR_MAIN_CMD_HELP: + /* Print command help */ + editor_main_help(cmd_arg); + break; + + case NMC_EDITOR_MAIN_CMD_NMCLI: + if (cmd_arg_p && matches(cmd_arg_p, "status-line")) { + GError * tmp_err = NULL; + gboolean bb; + if (!nmc_string_to_bool(cmd_arg_v ? g_strstrip(cmd_arg_v) : "", &bb, &tmp_err)) { + g_print(_("Error: status-line: %s\n"), tmp_err->message); + g_clear_error(&tmp_err); + } else + nmc->editor_status_line = bb; + } else if (cmd_arg_p && matches(cmd_arg_p, "save-confirmation")) { + GError * tmp_err = NULL; + gboolean bb; + if (!nmc_string_to_bool(cmd_arg_v ? g_strstrip(cmd_arg_v) : "", &bb, &tmp_err)) { + g_print(_("Error: save-confirmation: %s\n"), tmp_err->message); + g_clear_error(&tmp_err); + } else + nmc->editor_save_confirmation = bb; + } else if (cmd_arg_p && matches(cmd_arg_p, "show-secrets")) { + GError * tmp_err = NULL; + gboolean bb; + if (!nmc_string_to_bool(cmd_arg_v ? g_strstrip(cmd_arg_v) : "", &bb, &tmp_err)) { + g_print(_("Error: show-secrets: %s\n"), tmp_err->message); + g_clear_error(&tmp_err); + } else + nmc->nmc_config_mutable.show_secrets = bb; + } else if (cmd_arg_p && matches(cmd_arg_p, "prompt-color")) { + g_debug("Ignoring erroneous --prompt-color argument. Use terminal-colors.d(5) to " + "set the prompt color.\n"); + } else if (!cmd_arg_p) { + g_print(_("Current nmcli configuration:\n")); + g_print("status-line: %s\n" + "save-confirmation: %s\n" + "show-secrets: %s\n", + nmc->editor_status_line ? "yes" : "no", + nmc->editor_save_confirmation ? "yes" : "no", + nmc->nmc_config.show_secrets ? "yes" : "no"); + } else + g_print(_("Invalid configuration option '%s'; allowed [%s]\n"), + cmd_arg_v ?: "", + "status-line, save-confirmation, show-secrets"); + + break; + + case NMC_EDITOR_MAIN_CMD_QUIT: + if (is_connection_dirty(connection, rem_con)) { + if (confirm_quit(&nmc->nmc_config)) + cmd_loop = FALSE; /* quit command loop */ + } else + cmd_loop = FALSE; /* quit command loop */ + break; + + case NMC_EDITOR_MAIN_CMD_UNKNOWN: + default: + g_print(_("Unknown command: '%s'\n"), cmd_user); + break; + } + } + + g_free(menu_ctx.main_prompt); + g_strfreev(menu_ctx.valid_props); + g_free(menu_ctx.valid_props_str); + g_weak_ref_clear(&weak); + + quit(); + + /* Save history file */ + save_history_cmds(nm_connection_get_uuid(connection)); + + return TRUE; +} + +static const char * +get_ethernet_device_name(NmCli *nmc) +{ + const GPtrArray *devices; + guint i; + + devices = nm_client_get_devices(nmc->client); + for (i = 0; i < devices->len; i++) { + NMDevice *dev = g_ptr_array_index(devices, i); + if (NM_IS_DEVICE_ETHERNET(dev)) + return nm_device_get_iface(dev); + } + return NULL; +} + +static void +editor_init_new_connection(NmCli *nmc, NMConnection *connection, const char *slave_type) +{ + NMSetting * setting, *base_setting; + NMSettingConnection *s_con; + const char * con_type; + + s_con = nm_connection_get_setting_connection(connection); + g_assert(s_con); + con_type = nm_setting_connection_get_connection_type(s_con); + + /* Initialize new connection according to its type using sensible defaults. */ + + nmc_setting_connection_connect_handlers(s_con, connection); + + if (slave_type) { + const char *dev_ifname = get_ethernet_device_name(nmc); + + /* For bond/team/bridge slaves add 'wired' setting */ + setting = nm_setting_wired_new(); + nm_connection_add_setting(connection, setting); + + g_object_set(s_con, + NM_SETTING_CONNECTION_TYPE, + NM_SETTING_WIRED_SETTING_NAME, + NM_SETTING_CONNECTION_MASTER, + dev_ifname ?: "eth0", + NM_SETTING_CONNECTION_SLAVE_TYPE, + slave_type, + NULL); + } else { + const NMMetaSettingInfoEditor *setting_info; + + /* Add a "base" setting to the connection by default */ + setting_info = nm_meta_setting_info_editor_find_by_name(con_type, FALSE); + if (!setting_info) + return; + base_setting = + nm_meta_setting_info_editor_new_setting(setting_info, + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + nm_connection_add_setting(connection, base_setting); + + set_default_interface_name(nmc, s_con); + + /* Set sensible initial VLAN values */ + if (g_strcmp0(con_type, NM_SETTING_VLAN_SETTING_NAME) == 0) { + const char *dev_ifname = get_ethernet_device_name(nmc); + + g_object_set(NM_SETTING_VLAN(base_setting), + NM_SETTING_VLAN_PARENT, + dev_ifname ?: "eth0", + NULL); + } + + setting = nm_meta_setting_info_editor_new_setting( + &nm_meta_setting_infos_editor[NM_META_SETTING_TYPE_IP4_CONFIG], + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + nm_connection_add_setting(connection, setting); + + setting = nm_meta_setting_info_editor_new_setting( + &nm_meta_setting_infos_editor[NM_META_SETTING_TYPE_IP6_CONFIG], + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + nm_connection_add_setting(connection, setting); + + setting = nm_meta_setting_info_editor_new_setting( + &nm_meta_setting_infos_editor[NM_META_SETTING_TYPE_PROXY], + NM_META_ACCESSOR_SETTING_INIT_TYPE_CLI); + nm_connection_add_setting(connection, setting); + } +} + +static void +editor_init_existing_connection(NMConnection *connection) +{ + NMSettingIPConfig * s_ip4, *s_ip6; + NMSettingProxy * s_proxy; + NMSettingWireless * s_wireless; + NMSettingConnection *s_con; + + /* FIXME: this approach of connecting handlers to do something is fundamentally + * flawed. See the comment in nmc_setting_ip6_connect_handlers(). */ + + s_ip4 = nm_connection_get_setting_ip4_config(connection); + s_ip6 = nm_connection_get_setting_ip6_config(connection); + s_proxy = nm_connection_get_setting_proxy(connection); + s_wireless = nm_connection_get_setting_wireless(connection); + s_con = nm_connection_get_setting_connection(connection); + + if (s_ip4) + nmc_setting_ip4_connect_handlers(s_ip4); + if (s_ip6) + nmc_setting_ip6_connect_handlers(s_ip6); + if (s_proxy) + nmc_setting_proxy_connect_handlers(s_proxy); + if (s_wireless) + nmc_setting_wireless_connect_handlers(s_wireless); + if (s_con) + nmc_setting_connection_connect_handlers(s_con, connection); +} + +static void +nmc_complete_connection_type(const char *prefix) +{ + guint i; + + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) { + const NMMetaSettingInfoEditor *setting_info = &nm_meta_setting_infos_editor[i]; + + if (!*prefix || matches(prefix, setting_info->general->setting_name)) + g_print("%s\n", setting_info->general->setting_name); + if (setting_info->alias && (!*prefix || matches(prefix, setting_info->alias))) + g_print("%s\n", setting_info->alias); + } +} + +static void +do_connection_edit(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + const GPtrArray *connections; + gs_unref_object NMConnection *connection = NULL; + NMSettingConnection * s_con; + const char * connection_type; + const char * type = NULL; + const char * con_name = NULL; + const char * con = NULL; + const char * con_id = NULL; + const char * con_uuid = NULL; + const char * con_path = NULL; + const char * con_filename = NULL; + const char * selector = NULL; + gs_free_error GError *error = NULL; + GError * err1 = NULL; + nmc_arg_t exp_args[] = {{"type", TRUE, &type, FALSE}, + {"con-name", TRUE, &con_name, FALSE}, + {"id", TRUE, &con_id, FALSE}, + {"uuid", TRUE, &con_uuid, FALSE}, + {"path", TRUE, &con_path, FALSE}, + {"filename", TRUE, &con_filename, FALSE}, + {NULL}}; + + next_arg(nmc, &argc, &argv, NULL); + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "type", "con-name", "id", "uuid", "path", "filename"); + + nmc->return_value = NMC_RESULT_SUCCESS; + + if (argc == 1) + con = *argv; + else { + if (!nmc_parse_args(exp_args, TRUE, &argc, &argv, &error)) { + g_string_assign(nmc->return_text, error->message); + nmc->return_value = error->code; + return; + } + } + + /* Setup some readline completion stuff */ + /* Set a pointer to an alternative function to create matches */ + rl_attempted_completion_function = nmcli_editor_tab_completion; + /* Use ' ' and '.' as word break characters */ + rl_completer_word_break_characters = ". "; + + connections = nm_client_get_connections(nmc->client); + + if (!con) { + if (con_id && !con_uuid && !con_path && !con_filename) { + con = con_id; + selector = "id"; + } else if (con_uuid && !con_id && !con_path && !con_filename) { + con = con_uuid; + selector = "uuid"; + } else if (con_path && !con_id && !con_uuid && !con_filename) { + con = con_path; + selector = "path"; + } else if (con_filename && !con_path && !con_id && !con_uuid) { + con = con_filename; + selector = "filename"; + } else if (!con_path && !con_id && !con_uuid && !con_filename) { + /* no-op */ + } else { + g_string_printf( + nmc->return_text, + _("Error: only one of 'id', 'filename', uuid, or 'path' can be provided.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + } + + if (con) { + /* Existing connection */ + NMConnection *found_con; + + found_con = nmc_find_connection(connections, selector, con, NULL, nmc->complete); + if (nmc->complete) + return; + + if (!found_con) { + g_string_printf(nmc->return_text, _("Error: Unknown connection '%s'."), con); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + return; + } + + /* Duplicate the connection and use that so that we need not + * differentiate existing vs. new later + */ + connection = nm_simple_connection_new_clone(found_con); + + /* Merge secrets into the connection */ + update_secrets_in_connection(NM_REMOTE_CONNECTION(found_con), connection); + + s_con = nm_connection_get_setting_connection(connection); + connection_type = nm_setting_connection_get_connection_type(s_con); + + if (type) + g_print(_("Warning: editing existing connection '%s'; 'type' argument is ignored\n"), + nm_connection_get_id(connection)); + if (con_name) + g_print( + _("Warning: editing existing connection '%s'; 'con-name' argument is ignored\n"), + nm_connection_get_id(connection)); + + /* Load previously saved history commands for the connection */ + load_history_cmds(nm_connection_get_uuid(connection)); + + editor_init_existing_connection(connection); + } else { + const char * slave_type = NULL; + gs_free char *uuid = NULL; + gs_free char *default_name = NULL; + gs_free char *tmp_str = NULL; + + /* New connection */ + if (nmc->complete) { + if (type && argc == 0) + nmc_complete_connection_type(type); + return; + } + + connection_type = check_valid_name_toplevel(type, &slave_type, &err1); + tmp_str = get_valid_options_string_toplevel(); + + while (!connection_type) { + gs_free char *type_ask = NULL; + + if (!type) + g_print(_("Valid connection types: %s\n"), tmp_str); + else + g_print(_("Error: invalid connection type; %s\n"), err1->message); + g_clear_error(&err1); + + type_ask = nmc_readline(&nmc->nmc_config, EDITOR_PROMPT_CON_TYPE); + type = type_ask = nm_strstrip(type_ask); + connection_type = check_valid_name_toplevel(type_ask, &slave_type, &err1); + } + nm_clear_g_free(&tmp_str); + + connection = nm_simple_connection_new(); + + s_con = (NMSettingConnection *) nm_setting_connection_new(); + uuid = nm_utils_uuid_generate(); + if (con_name) + default_name = g_strdup(con_name); + else { + default_name = + nmc_unique_connection_name(connections, + get_name_alias_toplevel(connection_type, NULL)); + } + + g_object_set(s_con, + NM_SETTING_CONNECTION_ID, + default_name, + NM_SETTING_CONNECTION_UUID, + uuid, + NM_SETTING_CONNECTION_TYPE, + connection_type, + NULL); + nm_connection_add_setting(connection, NM_SETTING(s_con)); + + /* Initialize the new connection so that it is valid from the start */ + editor_init_new_connection(nmc, connection, slave_type); + } + + /* nmcli runs the editor */ + nmc->nmc_config_mutable.in_editor = TRUE; + + g_print("\n"); + g_print(_("===| nmcli interactive connection editor |===")); + g_print("\n\n"); + if (con) + g_print(_("Editing existing '%s' connection: '%s'"), connection_type, con); + else + g_print(_("Adding a new '%s' connection"), connection_type); + g_print("\n\n"); + /* TRANSLATORS: do not translate 'help', leave it as it is */ + g_print(_("Type 'help' or '?' for available commands.")); + g_print("\n"); + /* TRANSLATORS: do not translate 'print', leave it as it is */ + g_print(_("Type 'print' to show all the connection properties.")); + g_print("\n"); + /* TRANSLATORS: do not translate 'describe', leave it as it is */ + g_print(_("Type 'describe [<setting>.<prop>]' for detailed property description.")); + g_print("\n\n"); + + nmc_tab_completion.nmc = nmc; + nmc_tab_completion.con_type = g_strdup(connection_type); + nmc_tab_completion.connection = connection; + + /* Run menu loop */ + editor_menu_main(nmc, connection, connection_type); + + nmc_tab_completion.nmc = NULL; + nm_clear_g_free(&nmc_tab_completion.con_type); + nmc_tab_completion.connection = NULL; + + return; +} + +static void +modify_connection_cb(GObject *connection, GAsyncResult *result, gpointer user_data) +{ + NmCli * nmc = user_data; + gs_free_error GError *error = NULL; + + if (!nm_remote_connection_commit_changes_finish(NM_REMOTE_CONNECTION(connection), + result, + &error)) { + g_string_printf(nmc->return_text, + _("Error: Failed to modify connection '%s': %s"), + nm_connection_get_id(NM_CONNECTION(connection)), + error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } else { + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) { + g_print(_("Connection '%s' (%s) successfully modified.\n"), + nm_connection_get_id(NM_CONNECTION(connection)), + nm_connection_get_uuid(NM_CONNECTION(connection))); + } + } + quit(); +} + +static void +do_connection_modify(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMConnection * connection = NULL; + NMRemoteConnection *rc = NULL; + gs_free_error GError *error = NULL; + gboolean temporary = FALSE; + + if (next_arg(nmc, &argc, &argv, "--temporary", NULL) > 0) { + temporary = TRUE; + next_arg(nmc, &argc, &argv, NULL); + } + + connection = get_connection(nmc, &argc, &argv, NULL, NULL, NULL, &error); + if (!connection) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + + rc = nm_client_get_connection_by_uuid(nmc->client, nm_connection_get_uuid(connection)); + if (!rc) { + g_string_printf(nmc->return_text, + _("Error: Unknown connection '%s'."), + nm_connection_get_uuid(connection)); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + return; + } + + if (!nmc_process_connection_properties(nmc, NM_CONNECTION(rc), &argc, &argv, TRUE, &error)) { + g_string_assign(nmc->return_text, error->message); + nmc->return_value = error->code; + return; + } + + if (nmc->complete) + return; + + update_connection(rc, temporary, modify_connection_cb, nmc); + nmc->should_wait++; +} + +static void +clone_connection_cb(GObject *client, GAsyncResult *result, gpointer user_data) +{ + nm_auto_free_add_connection_info AddConnectionInfo *info = user_data; + NmCli * nmc = info->nmc; + gs_unref_object NMRemoteConnection *connection = NULL; + gs_free_error GError *error = NULL; + + connection = nm_client_add_connection2_finish(NM_CLIENT(client), result, NULL, &error); + if (error) { + g_string_printf(nmc->return_text, + _("Error: Failed to add '%s' connection: %s"), + info->new_id, + error->message); + nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION; + } else { + g_print(_("%s (%s) cloned as %s (%s).\n"), + info->orig_id, + info->orig_uuid, + nm_connection_get_id(NM_CONNECTION(connection)), + nm_connection_get_uuid(NM_CONNECTION(connection))); + } + + quit(); +} + +static void +do_connection_clone(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMConnection * connection = NULL; + gs_unref_object NMConnection *new_connection = NULL; + const char * new_name; + gs_free char * new_name_free = NULL; + gs_free char * uuid = NULL; + gboolean temporary = FALSE; + gs_strfreev char ** arg_arr = NULL; + int arg_num; + const char *const ** argv_ptr; + int * argc_ptr; + GError * error = NULL; + + if (next_arg(nmc, &argc, &argv, "--temporary", NULL) > 0) { + temporary = TRUE; + next_arg(nmc, &argc, &argv, NULL); + } + + argv_ptr = &argv; + argc_ptr = &argc; + + if (argc == 0 && nmc->ask) { + gs_free char *line = NULL; + + /* nmc_do_cmd() should not call this with argc=0. */ + g_assert(!nmc->complete); + + line = nmc_readline(&nmc->nmc_config, PROMPT_CONNECTION); + nmc_string_to_arg_array(line, NULL, TRUE, &arg_arr, &arg_num); + argv_ptr = (const char *const **) &arg_arr; + argc_ptr = &arg_num; + } + + connection = get_connection(nmc, argc_ptr, argv_ptr, NULL, NULL, NULL, &error); + if (!connection) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + + if (nmc->complete) + return; + + if (argv[0]) + new_name = *argv; + else if (nmc->ask) { + new_name = new_name_free = nmc_readline(&nmc->nmc_config, _("New connection name: ")); + } else { + g_string_printf(nmc->return_text, _("Error: <new name> argument is missing.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (next_arg(nmc->ask ? NULL : nmc, argc_ptr, argv_ptr, NULL) == 0) { + g_string_printf(nmc->return_text, _("Error: unknown extra argument: '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + new_connection = nm_simple_connection_new_clone(connection); + + uuid = nm_utils_uuid_generate(); + g_object_set(nm_connection_get_setting_connection(new_connection), + NM_SETTING_CONNECTION_ID, + new_name, + NM_SETTING_CONNECTION_UUID, + uuid, + NULL); + + update_secrets_in_connection(NM_REMOTE_CONNECTION(connection), new_connection); + + add_connection(nmc->client, + new_connection, + temporary, + clone_connection_cb, + _add_connection_info_new(nmc, connection, new_connection)); + nmc->should_wait++; +} + +static void +delete_cb(GObject *con, GAsyncResult *result, gpointer user_data) +{ + ConnectionCbInfo *info = (ConnectionCbInfo *) user_data; + GError * error = NULL; + + if (!nm_remote_connection_delete_finish(NM_REMOTE_CONNECTION(con), result, &error)) { + if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + return; + g_string_printf(info->nmc->return_text, _("Error: not all connections deleted.")); + g_printerr(_("Error: Connection deletion failed: %s\n"), error->message); + g_error_free(error); + info->nmc->return_value = NMC_RESULT_ERROR_CON_DEL; + connection_cb_info_finish(info, con); + } else { + if (info->nmc->nowait_flag) + connection_cb_info_finish(info, con); + } +} + +static void +do_connection_delete(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMConnection * connection; + ConnectionCbInfo * info = NULL; + gs_strfreev char ** arg_arr = NULL; + const char *const * arg_ptr; + guint i; + int arg_num; + nm_auto_free_gstring GString *invalid_cons = NULL; + gs_unref_ptrarray GPtrArray *found_cons = NULL; + GError * error = NULL; + + if (nmc->timeout == -1) + nmc->timeout = 10; + + next_arg(nmc, &argc, &argv, NULL); + arg_ptr = argv; + arg_num = argc; + + if (argc == 0) { + if (nmc->ask) { + gs_free char *line = NULL; + + /* nmc_do_cmd() should not call this with argc=0. */ + g_assert(!nmc->complete); + + line = nmc_readline(&nmc->nmc_config, PROMPT_CONNECTIONS); + nmc_string_to_arg_array(line, NULL, TRUE, &arg_arr, &arg_num); + arg_ptr = (const char *const *) arg_arr; + } + if (arg_num == 0) { + g_string_printf(nmc->return_text, _("Error: No connection specified.")); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + goto finish; + } + } + + while (arg_num > 0) { + const char *cur_selector, *cur_value; + + connection = + get_connection(nmc, &arg_num, &arg_ptr, &cur_selector, &cur_value, &found_cons, &error); + if (!connection) { + if (!nmc->complete) + g_printerr(_("Error: %s.\n"), error->message); + g_string_printf(nmc->return_text, _("Error: not all connections found.")); + nmc->return_value = error->code; + g_clear_error(&error); + + if (nmc->return_value != NMC_RESULT_ERROR_NOT_FOUND) + goto finish; + + if (!invalid_cons) + invalid_cons = g_string_new(NULL); + if (cur_selector) + g_string_append_printf(invalid_cons, "%s '%s', ", cur_selector, cur_value); + else + g_string_append_printf(invalid_cons, "'%s', ", cur_value); + } + } + + if (!found_cons) { + if (!invalid_cons) { + g_string_printf(nmc->return_text, _("Error: No connection specified.")); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + } + goto finish; + } + + if (nmc->complete) + goto finish; + + info = g_slice_new0(ConnectionCbInfo); + info->nmc = nmc; + info->obj_list = g_ptr_array_sized_new(found_cons->len); + for (i = 0; i < found_cons->len; i++) { + connection = found_cons->pdata[i]; + g_ptr_array_add(info->obj_list, g_object_ref(connection)); + } + info->timeout_id = g_timeout_add_seconds(nmc->timeout, connection_op_timeout_cb, info); + info->cancellable = g_cancellable_new(); + + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + g_signal_connect(nmc->client, + NM_CLIENT_CONNECTION_REMOVED, + G_CALLBACK(connection_removed_cb), + info); + + for (i = 0; i < found_cons->len; i++) { + nm_remote_connection_delete_async(NM_REMOTE_CONNECTION(found_cons->pdata[i]), + info->cancellable, + delete_cb, + info); + } + +finish: + if (invalid_cons) { + g_string_truncate(invalid_cons, invalid_cons->len - 2); /* truncate trailing ", " */ + g_string_printf(nmc->return_text, + _("Error: cannot delete unknown connection(s): %s."), + invalid_cons->str); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + } +} + +static void +connection_changed(NMConnection *connection, NmCli *nmc) +{ + g_print(_("%s: connection profile changed\n"), nm_connection_get_id(connection)); +} + +static void +connection_watch(NmCli *nmc, NMConnection *connection) +{ + nmc->should_wait++; + g_signal_connect(connection, NM_CONNECTION_CHANGED, G_CALLBACK(connection_changed), nmc); +} + +static void +connection_unwatch(NmCli *nmc, NMConnection *connection) +{ + if (g_signal_handlers_disconnect_by_func(connection, G_CALLBACK(connection_changed), nmc)) + nmc->should_wait--; + + /* Terminate if all the watched connections disappeared. */ + if (!nmc->should_wait) + quit(); +} + +static void +connection_added(NMClient *client, NMRemoteConnection *con, NmCli *nmc) +{ + NMConnection *connection = NM_CONNECTION(con); + + g_print(_("%s: connection profile created\n"), nm_connection_get_id(connection)); + connection_watch(nmc, connection); +} + +static void +connection_removed(NMClient *client, NMRemoteConnection *con, NmCli *nmc) +{ + NMConnection *connection = NM_CONNECTION(con); + + g_print(_("%s: connection profile removed\n"), nm_connection_get_id(connection)); + connection_unwatch(nmc, connection); +} + +static void +do_connection_monitor(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + GError * error = NULL; + guint i; + gs_unref_ptrarray GPtrArray *found_cons = NULL; + const GPtrArray * connections = NULL; + + next_arg(nmc, &argc, &argv, NULL); + if (argc == 0) { + /* No connections specified. Monitor all. */ + + /* nmc_do_cmd() should not call this with argc=0. */ + g_assert(!nmc->complete); + + connections = nm_client_get_connections(nmc->client); + } else { + while (argc > 0) { + if (!get_connection(nmc, &argc, &argv, NULL, NULL, &found_cons, &error)) { + if (!nmc->complete) + g_printerr(_("Error: %s.\n"), error->message); + g_string_printf(nmc->return_text, _("Error: not all connections found.")); + nmc->return_value = error->code; + return; + } + + if (nmc->complete) + continue; + + connections = found_cons; + } + } + + if (nmc->complete) + return; + + for (i = 0; i < connections->len; i++) + connection_watch(nmc, connections->pdata[i]); + + if (argc == 0) { + /* We'll watch the connection additions too, never exit. */ + nmc->should_wait++; + g_signal_connect(nmc->client, + NM_CLIENT_CONNECTION_ADDED, + G_CALLBACK(connection_added), + nmc); + } + + g_signal_connect(nmc->client, + NM_CLIENT_CONNECTION_REMOVED, + G_CALLBACK(connection_removed), + nmc); +} + +static void +connection_reload_cb(GObject *source, GAsyncResult *result, gpointer user_data) +{ + NmCli * nmc = user_data; + gs_free_error GError *error = NULL; + gs_unref_variant GVariant *ret = NULL; + + ret = nm_dbus_call_finish(result, &error); + if (error) { + g_string_printf(nmc->return_text, + _("Error: failed to reload connections: %s."), + nmc_error_get_simple_message(error)); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } + + quit(); +} + +static void +do_connection_reload(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) + return; + + nmc->should_wait++; + nm_dbus_call(G_BUS_TYPE_SYSTEM, + NM_DBUS_SERVICE, + NM_DBUS_PATH_SETTINGS, + NM_DBUS_INTERFACE_SETTINGS, + "ReloadConnections", + g_variant_new("()"), + G_VARIANT_TYPE("(b)"), + NULL, + (nmc->timeout == -1 ? 90 : nmc->timeout) * 1000, + connection_reload_cb, + nmc); +} + +static void +do_connection_load(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + GError * error = NULL; + gs_free const char **filenames = NULL; + gs_strfreev char ** failures = NULL; + int i; + + next_arg(nmc, &argc, &argv, NULL); + if (argc == 0) { + g_string_printf(nmc->return_text, _("Error: No connection specified.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (nmc->complete) { + nmc->return_value = NMC_RESULT_COMPLETE_FILE; + return; + } + + filenames = (const char **) nm_utils_strv_dup(argv, argc, FALSE); + + nm_client_load_connections(nmc->client, (char **) filenames, &failures, NULL, &error); + if (error) { + g_string_printf(nmc->return_text, + _("Error: failed to load connection: %s."), + nmc_error_get_simple_message(error)); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + g_error_free(error); + } + + if (failures) { + for (i = 0; failures[i]; i++) + g_printerr(_("Could not load file '%s'\n"), failures[i]); + } +} + +#define PROMPT_IMPORT_FILE N_("File to import: ") + +static void +do_connection_import(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gs_free_error GError *error = NULL; + const char * type = NULL, *filename = NULL; + gs_free char * type_ask = NULL; + gs_free char * filename_ask = NULL; + gs_unref_object NMConnection *connection = NULL; + NMVpnEditorPlugin * plugin; + gs_free char * service_type = NULL; + gboolean temporary = FALSE; + + /* Check --temporary */ + if (next_arg(nmc, &argc, &argv, "--temporary", NULL) > 0) { + temporary = TRUE; + next_arg(nmc, &argc, &argv, NULL); + } + + if (argc == 0) { + /* nmc_do_cmd() should not call this with argc=0. */ + g_assert(!nmc->complete); + + if (nmc->ask) { + type_ask = + nmc_readline(&nmc->nmc_config, "%s: ", gettext(NM_META_TEXT_PROMPT_VPN_TYPE)); + type = nm_strstrip(type_ask); + filename_ask = nmc_readline(&nmc->nmc_config, gettext(PROMPT_IMPORT_FILE)); + filename = nm_strstrip(filename_ask); + } else { + g_string_printf(nmc->return_text, _("Error: No arguments provided.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + } + + while (argc > 0) { + if (argc == 1 && nmc->complete) { + nmc_complete_strings(*argv, type ? NULL : "type", filename ? NULL : "file"); + } + + if (strcmp(*argv, "type") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (argc == 1 && nmc->complete) { + nmc_complete_strings(*argv, "wireguard"); + complete_option(nmc, + (const NMMetaAbstractInfo *) nm_meta_property_info_vpn_service_type, + *argv, + NULL); + } + + if (!type) + type = *argv; + else + g_printerr(_("Warning: 'type' already specified, ignoring extra one.\n")); + + } else if (strcmp(*argv, "file") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + if (argc == 1 && nmc->complete) + nmc->return_value = NMC_RESULT_COMPLETE_FILE; + if (!filename) + filename = *argv; + else + g_printerr(_("Warning: 'file' already specified, ignoring extra one.\n")); + } else { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + next_arg(nmc, &argc, &argv, NULL); + } + + if (nmc->complete) + return; + + if (!type) { + g_string_printf(nmc->return_text, _("Error: 'type' argument is required.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + if (!filename) { + g_string_printf(nmc->return_text, _("Error: 'file' argument is required.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (nm_streq(type, "wireguard")) + connection = nm_vpn_wireguard_import(filename, &error); + else { + service_type = nm_vpn_plugin_info_list_find_service_type(nm_vpn_get_plugin_infos(), type); + if (!service_type) { + g_string_printf(nmc->return_text, _("Error: failed to find VPN plugin for %s."), type); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } + + /* Import VPN configuration */ + plugin = nm_vpn_get_editor_plugin(service_type, &error); + if (!plugin) { + g_string_printf(nmc->return_text, + _("Error: failed to load VPN plugin: %s."), + error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } + + connection = nm_vpn_editor_plugin_import(plugin, filename, &error); + } + + if (!connection) { + g_string_printf(nmc->return_text, + _("Error: failed to import '%s': %s."), + filename, + error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } + + add_connection(nmc->client, + connection, + temporary, + add_connection_cb, + _add_connection_info_new(nmc, NULL, connection)); + nmc->should_wait++; +} + +static void +do_connection_export(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMConnection * connection = NULL; + const char * out_name = NULL; + gs_free char * out_name_ask = NULL; + const char * path = NULL; + const char * type = NULL; + NMVpnEditorPlugin *plugin; + gs_free_error GError *error = NULL; + char tmpfile[] = "/tmp/nmcli-export-temp-XXXXXX"; + gs_strfreev char ** arg_arr = NULL; + int arg_num; + const char *const ** argv_ptr; + int * argc_ptr; + + next_arg(nmc, &argc, &argv, NULL); + argv_ptr = &argv; + argc_ptr = &argc; + + if (argc == 0 && nmc->ask) { + gs_free char *line = NULL; + + /* nmc_do_cmd() should not call this with argc=0. */ + g_assert(!nmc->complete); + + line = nmc_readline(&nmc->nmc_config, PROMPT_VPN_CONNECTION); + nmc_string_to_arg_array(line, NULL, TRUE, &arg_arr, &arg_num); + argv_ptr = (const char *const **) &arg_arr; + argc_ptr = &arg_num; + } + + connection = get_connection(nmc, argc_ptr, argv_ptr, NULL, NULL, NULL, &error); + if (!connection) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + goto finish; + } + + if (nmc->complete) + return; + + out_name = *argv; + + if (next_arg(nmc->ask ? NULL : nmc, argc_ptr, argv_ptr, NULL) == 0) { + g_string_printf(nmc->return_text, _("Error: unknown extra argument: '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + + if (!out_name && nmc->ask) { + out_name = out_name_ask = nmc_readline(&nmc->nmc_config, _("Output file name: ")); + } + + type = nm_connection_get_connection_type(connection); + if (g_strcmp0(type, NM_SETTING_VPN_SETTING_NAME) != 0) { + g_string_printf(nmc->return_text, _("Error: the connection is not VPN.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + type = nm_setting_vpn_get_service_type(nm_connection_get_setting_vpn(connection)); + + /* Export VPN configuration */ + plugin = nm_vpn_get_editor_plugin(type, &error); + if (!plugin) { + g_string_printf(nmc->return_text, + _("Error: failed to load VPN plugin: %s."), + error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + goto finish; + } + + if (out_name) + path = out_name; + else { + nm_auto_close int fd = -1; + + fd = g_mkstemp_full(tmpfile, O_RDWR | O_CLOEXEC, 0600); + if (fd == -1) { + g_string_printf(nmc->return_text, + _("Error: failed to create temporary file %s."), + tmpfile); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + goto finish; + } + path = tmpfile; + } + + if (!nm_vpn_editor_plugin_export(plugin, path, connection, &error)) { + g_string_printf(nmc->return_text, + _("Error: failed to export '%s': %s."), + nm_connection_get_id(connection), + error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + goto finish; + } + + /* No output file -> copy data to stdout */ + if (!out_name) { + gs_free char *contents = NULL; + gsize len = 0; + + if (!g_file_get_contents(path, &contents, &len, &error)) { + g_string_printf(nmc->return_text, + _("Error: failed to read temporary file '%s': %s."), + path, + error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + goto finish; + } + g_print("%s", contents); + } + +finish: + if (!out_name && path) + unlink(path); +} + +static char * +gen_func_connection_names(const char *text, int state) +{ + guint i; + const GPtrArray *connections; + const char ** connection_names; + char * ret; + + connections = nm_client_get_connections(nm_cli_global_readline->client); + if (connections->len == 0) + return NULL; + + connection_names = g_new(const char *, connections->len + 1); + for (i = 0; i < connections->len; i++) + connection_names[i] = nm_connection_get_id(NM_CONNECTION(connections->pdata[i])); + connection_names[i] = NULL; + + ret = nmc_rl_gen_func_basic(text, state, connection_names); + + g_free(connection_names); + return ret; +} + +static char * +gen_func_active_connection_names(const char *text, int state) +{ + guint i; + const GPtrArray *acs; + const char ** connections; + char * ret; + + if (!nm_cli_global_readline->client) + return NULL; + + acs = nm_client_get_active_connections(nm_cli_global_readline->client); + if (!acs || acs->len == 0) + return NULL; + + connections = g_new(const char *, acs->len + 1); + for (i = 0; i < acs->len; i++) + connections[i] = nm_active_connection_get_id(acs->pdata[i]); + connections[i] = NULL; + + ret = nmc_rl_gen_func_basic(text, state, connections); + + g_free(connections); + return ret; +} + +static char ** +nmcli_con_tab_completion(const char *text, int start, int end) +{ + char ** match_array = NULL; + rl_compentry_func_t * generator_func = NULL; + const NMMetaAbstractInfo *info; + + /* Disable readline's default filename completion */ + rl_attempted_completion_over = 1; + + if (g_strcmp0(rl_prompt, PROMPT_CONNECTION) == 0) { + /* Disable appending space after completion */ + rl_completion_append_character = '\0'; + + if (!is_single_word(rl_line_buffer)) + return NULL; + + generator_func = gen_func_connection_names; + } else if (g_strcmp0(rl_prompt, PROMPT_CONNECTIONS) == 0) { + generator_func = gen_func_connection_names; + } else if (g_strcmp0(rl_prompt, PROMPT_ACTIVE_CONNECTIONS) == 0) { + generator_func = gen_func_active_connection_names; + } else if (rl_prompt && g_str_has_prefix(rl_prompt, NM_META_TEXT_PROMPT_VPN_TYPE)) { + info = (const NMMetaAbstractInfo *) nm_meta_property_info_vpn_service_type; + nmc_tab_completion.words = _meta_abstract_complete(info, text); + generator_func = _meta_abstract_generator; + } else if (g_strcmp0(rl_prompt, PROMPT_IMPORT_FILE) == 0) { + rl_attempted_completion_over = 0; + rl_complete_with_tilde_expansion = 1; + } else if (g_strcmp0(rl_prompt, PROMPT_VPN_CONNECTION) == 0) { + generator_func = gen_vpn_ids; + } + + if (generator_func) + match_array = rl_completion_matches(text, generator_func); + + nm_clear_pointer(&nmc_tab_completion.words, g_strfreev); + return match_array; +} + +void +nmc_command_func_connection(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + static const NMCCommand cmds[] = { + {"show", do_connections_show, usage_connection_show, TRUE, TRUE}, + {"up", do_connection_up, usage_connection_up, TRUE, TRUE}, + {"down", do_connection_down, usage_connection_down, TRUE, TRUE}, + {"add", do_connection_add, usage_connection_add, TRUE, TRUE}, + {"edit", do_connection_edit, usage_connection_edit, TRUE, TRUE}, + {"delete", do_connection_delete, usage_connection_delete, TRUE, TRUE}, + {"reload", do_connection_reload, usage_connection_reload, FALSE, FALSE}, + {"load", do_connection_load, usage_connection_load, TRUE, TRUE}, + {"modify", do_connection_modify, usage_connection_modify, TRUE, TRUE}, + {"clone", do_connection_clone, usage_connection_clone, TRUE, TRUE}, + {"import", do_connection_import, usage_connection_import, TRUE, TRUE}, + {"export", do_connection_export, usage_connection_export, TRUE, TRUE}, + {"monitor", do_connection_monitor, usage_connection_monitor, TRUE, TRUE}, + {NULL, do_connections_show, usage, TRUE, TRUE}, + }; + + next_arg(nmc, &argc, &argv, NULL); + + nmc_start_polkit_agent_start_try(nmc); + + /* Set completion function for 'nmcli con' */ + rl_attempted_completion_function = nmcli_con_tab_completion; + + nmc_do_cmd(nmc, cmds, *argv, argc, argv); +} + +void +monitor_connections(NmCli *nmc) +{ + do_connection_monitor(NULL, nmc, 0, NULL); +} diff --git a/src/nmcli/connections.h b/src/nmcli/connections.h new file mode 100644 index 00000000..74c1fe00 --- /dev/null +++ b/src/nmcli/connections.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#ifndef NMC_CONNECTIONS_H +#define NMC_CONNECTIONS_H + +#include "nmcli.h" + +void monitor_connections(NmCli *nmc); + +gboolean nmc_process_connection_properties(NmCli * nmc, + NMConnection * connection, + int * argc, + const char *const **argv, + gboolean allow_remove_setting, + GError ** error); + +NMMetaColor nmc_active_connection_state_to_color(NMActiveConnection *ac); + +int nmc_active_connection_cmp(NMActiveConnection *ac_a, NMActiveConnection *ac_b); + +extern const NmcMetaGenericInfo *const metagen_con_show[]; +extern const NmcMetaGenericInfo *const metagen_con_active_general[]; +extern const NmcMetaGenericInfo *const metagen_con_active_vpn[]; +extern const NmcMetaGenericInfo *const nmc_fields_con_active_details_groups[]; + +#endif /* NMC_CONNECTIONS_H */ diff --git a/src/nmcli/devices.c b/src/nmcli/devices.c new file mode 100644 index 00000000..0cb347f5 --- /dev/null +++ b/src/nmcli/devices.c @@ -0,0 +1,5050 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include "devices.h" + +#include <stdio.h> +#include <stdlib.h> +#include <readline/readline.h> +#include <linux/if_ether.h> + +#include "libnm-glib-aux/nm-secret-utils.h" +#include "common.h" +#include "connections.h" +#include "libnmc-base/nm-client-utils.h" +#include "libnmc-base/nm-secret-agent-simple.h" +#include "polkit-agent.h" +#include "utils.h" + +/* define some prompts */ +#define PROMPT_INTERFACE _("Interface: ") +#define PROMPT_INTERFACES _("Interface(s): ") + +/*****************************************************************************/ + +static char * +ap_wpa_rsn_flags_to_string(NM80211ApSecurityFlags flags, NMMetaAccessorGetType get_type) +{ + char *flags_str[16]; + int i = 0; + + if (flags & NM_802_11_AP_SEC_PAIR_WEP40) + flags_str[i++] = "pair_wpe40"; + if (flags & NM_802_11_AP_SEC_PAIR_WEP104) + flags_str[i++] = "pair_wpe104"; + if (flags & NM_802_11_AP_SEC_PAIR_TKIP) + flags_str[i++] = "pair_tkip"; + if (flags & NM_802_11_AP_SEC_PAIR_CCMP) + flags_str[i++] = "pair_ccmp"; + if (flags & NM_802_11_AP_SEC_GROUP_WEP40) + flags_str[i++] = "group_wpe40"; + if (flags & NM_802_11_AP_SEC_GROUP_WEP104) + flags_str[i++] = "group_wpe104"; + if (flags & NM_802_11_AP_SEC_GROUP_TKIP) + flags_str[i++] = "group_tkip"; + if (flags & NM_802_11_AP_SEC_GROUP_CCMP) + flags_str[i++] = "group_ccmp"; + if (flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) + flags_str[i++] = "psk"; + if (flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) + flags_str[i++] = "802.1X"; + if (flags & NM_802_11_AP_SEC_KEY_MGMT_SAE) + flags_str[i++] = "sae"; + if (flags & NM_802_11_AP_SEC_KEY_MGMT_EAP_SUITE_B_192) + flags_str[i++] = "wpa-eap-suite-b-192"; + if (NM_FLAGS_ANY(flags, NM_802_11_AP_SEC_KEY_MGMT_OWE | NM_802_11_AP_SEC_KEY_MGMT_OWE_TM)) + flags_str[i++] = "owe"; + + /* Make sure you grow flags_str when adding items here. */ + nm_assert(i < G_N_ELEMENTS(flags_str)); + + if (i == 0) { + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) + return g_strdup(_("(none)")); + return g_strdup("(none)"); + } + + flags_str[i] = NULL; + return g_strjoinv(" ", flags_str); +} + +static NMMetaColor +wifi_signal_to_color(guint8 strength) +{ + if (strength > 80) + return NM_META_COLOR_WIFI_SIGNAL_EXCELLENT; + else if (strength > 55) + return NM_META_COLOR_WIFI_SIGNAL_GOOD; + else if (strength > 30) + return NM_META_COLOR_WIFI_SIGNAL_FAIR; + else if (strength > 5) + return NM_META_COLOR_WIFI_SIGNAL_POOR; + else + return NM_META_COLOR_WIFI_SIGNAL_UNKNOWN; +} + +/*****************************************************************************/ + +static gconstpointer _metagen_device_status_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMDevice * d = target; + NMActiveConnection *ac; + + NMC_HANDLE_COLOR(nmc_device_state_to_color(d)); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_DEVICE: + return nm_device_get_iface(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_TYPE: + return nm_device_get_type_description(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_STATE: + return nmc_meta_generic_get_str_i18n(nmc_device_state_to_string_with_external(d), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_IP4_CONNECTIVITY: + return nmc_meta_generic_get_str_i18n( + nm_connectivity_to_string(nm_device_get_connectivity(d, AF_INET)), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_IP6_CONNECTIVITY: + return nmc_meta_generic_get_str_i18n( + nm_connectivity_to_string(nm_device_get_connectivity(d, AF_INET6)), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_DBUS_PATH: + return nm_object_get_path(NM_OBJECT(d)); + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CONNECTION: + ac = nm_device_get_active_connection(d); + return ac ? nm_active_connection_get_id(ac) : NULL; + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CON_UUID: + ac = nm_device_get_active_connection(d); + return ac ? nm_active_connection_get_uuid(ac) : NULL; + case NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CON_PATH: + ac = nm_device_get_active_connection(d); + return ac ? nm_object_get_path(NM_OBJECT(ac)) : NULL; + default: + break; + } + + g_return_val_if_reached(NULL); +} + +const NmcMetaGenericInfo + *const metagen_device_status[_NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_NUM + 1] = { +#define _METAGEN_DEVICE_STATUS(type, name) \ + [type] = NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_device_status_get_fcn) + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_DEVICE, "DEVICE"), + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_TYPE, "TYPE"), + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_STATE, "STATE"), + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_IP4_CONNECTIVITY, + "IP4-CONNECTIVITY"), + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_IP6_CONNECTIVITY, + "IP6-CONNECTIVITY"), + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_DBUS_PATH, "DBUS-PATH"), + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CONNECTION, "CONNECTION"), + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CON_UUID, "CON-UUID"), + _METAGEN_DEVICE_STATUS(NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CON_PATH, "CON-PATH"), +}; + +/*****************************************************************************/ + +static gconstpointer _metagen_device_detail_general_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMDevice * d = target; + NMActiveConnection *ac; + NMDeviceStateReason state_reason; + NMConnectivityState connectivity; + const char * s; + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DEVICE: + return nm_device_get_iface(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_TYPE: + return nm_device_get_type_description(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_TYPE: + return G_OBJECT_TYPE_NAME(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DBUS_PATH: + return nm_object_get_path(NM_OBJECT(d)); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_VENDOR: + return nm_device_get_vendor(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PRODUCT: + return nm_device_get_product(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DRIVER: + s = nm_device_get_driver(d); + return s ?: nmc_meta_generic_get_unknown(get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DRIVER_VERSION: + return nm_device_get_driver_version(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_FIRMWARE_VERSION: + return nm_device_get_firmware_version(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_HWADDR: + s = nm_device_get_hw_address(d); + return s ?: nmc_meta_generic_get_unknown(get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_MTU: + return (*out_to_free = g_strdup_printf("%u", (guint) nm_device_get_mtu(d))); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_STATE: + return (*out_to_free = nmc_meta_generic_get_enum_with_detail( + NMC_META_GENERIC_GET_ENUM_TYPE_PARENTHESES, + nm_device_get_state(d), + nmc_device_state_to_string_with_external(d), + get_type)); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_REASON: + state_reason = nm_device_get_state_reason(d); + return (*out_to_free = nmc_meta_generic_get_enum_with_detail( + NMC_META_GENERIC_GET_ENUM_TYPE_PARENTHESES, + state_reason, + nmc_device_reason_to_string(state_reason), + get_type)); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP4_CONNECTIVITY: + connectivity = nm_device_get_connectivity(d, AF_INET); + return (*out_to_free = nmc_meta_generic_get_enum_with_detail( + NMC_META_GENERIC_GET_ENUM_TYPE_PARENTHESES, + connectivity, + nm_connectivity_to_string(connectivity), + get_type)); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP6_CONNECTIVITY: + connectivity = nm_device_get_connectivity(d, AF_INET6); + return (*out_to_free = nmc_meta_generic_get_enum_with_detail( + NMC_META_GENERIC_GET_ENUM_TYPE_PARENTHESES, + connectivity, + nm_connectivity_to_string(connectivity), + get_type)); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_UDI: + return nm_device_get_udi(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PATH: + return nm_device_get_path(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP_IFACE: + return nm_device_get_ip_iface(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IS_SOFTWARE: + return nmc_meta_generic_get_bool(nm_device_is_software(d), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_MANAGED: + return nmc_meta_generic_get_bool(nm_device_get_managed(d), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_AUTOCONNECT: + return nmc_meta_generic_get_bool(nm_device_get_autoconnect(d), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_FIRMWARE_MISSING: + return nmc_meta_generic_get_bool(nm_device_get_firmware_missing(d), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_PLUGIN_MISSING: + return nmc_meta_generic_get_bool(nm_device_get_nm_plugin_missing(d), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PHYS_PORT_ID: + return nm_device_get_physical_port_id(d); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CONNECTION: + ac = nm_device_get_active_connection(d); + return ac ? nm_active_connection_get_id(ac) : NULL; + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CON_UUID: + ac = nm_device_get_active_connection(d); + return ac ? nm_active_connection_get_uuid(ac) : NULL; + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CON_PATH: + ac = nm_device_get_active_connection(d); + return ac ? nm_object_get_path(NM_OBJECT(ac)) : NULL; + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_METERED: + return nmc_meta_generic_get_str_i18n(nmc_device_metered_to_string(nm_device_get_metered(d)), + get_type); + default: + break; + } + + g_return_val_if_reached(NULL); +} + +const NmcMetaGenericInfo + *const metagen_device_detail_general[_NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NUM + 1] = { +#define _METAGEN_DEVICE_DETAIL_GENERAL(type, name) \ + [type] = NMC_META_GENERIC(name, \ + .info_type = type, \ + .get_fcn = _metagen_device_detail_general_get_fcn) + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DEVICE, + "DEVICE"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_TYPE, "TYPE"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_TYPE, + "NM-TYPE"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DBUS_PATH, + "DBUS-PATH"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_VENDOR, + "VENDOR"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PRODUCT, + "PRODUCT"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DRIVER, + "DRIVER"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DRIVER_VERSION, + "DRIVER-VERSION"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_FIRMWARE_VERSION, + "FIRMWARE-VERSION"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_HWADDR, + "HWADDR"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_MTU, "MTU"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_STATE, "STATE"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_REASON, + "REASON"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP4_CONNECTIVITY, + "IP4-CONNECTIVITY"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP6_CONNECTIVITY, + "IP6-CONNECTIVITY"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_UDI, "UDI"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PATH, "PATH"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP_IFACE, + "IP-IFACE"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IS_SOFTWARE, + "IS-SOFTWARE"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_MANAGED, + "NM-MANAGED"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_AUTOCONNECT, + "AUTOCONNECT"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_FIRMWARE_MISSING, + "FIRMWARE-MISSING"), + _METAGEN_DEVICE_DETAIL_GENERAL( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_PLUGIN_MISSING, + "NM-PLUGIN-MISSING"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PHYS_PORT_ID, + "PHYS-PORT-ID"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CONNECTION, + "CONNECTION"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CON_UUID, + "CON-UUID"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CON_PATH, + "CON-PATH"), + _METAGEN_DEVICE_DETAIL_GENERAL(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_METERED, + "METERED"), +}; + +/*****************************************************************************/ + +static NMRemoteConnection ** +_device_get_available_connections(NMDevice *d, guint *out_len) +{ + NMRemoteConnection **avail_cons; + const GPtrArray * avail_cons_arr; + + avail_cons_arr = nm_device_get_available_connections(d); + if (!avail_cons_arr || avail_cons_arr->len == 0) { + *out_len = 0; + return NULL; + } + + avail_cons = (NMRemoteConnection **) nmc_objects_sort_by_path( + (const NMObject *const *) avail_cons_arr->pdata, + avail_cons_arr->len); + nm_assert(avail_cons_arr->len == NM_PTRARRAY_LEN(avail_cons)); + *out_len = avail_cons_arr->len; + return avail_cons; +} + +static gconstpointer _metagen_device_detail_connections_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMDevice *d = target; + gs_free NMRemoteConnection **avail_cons = NULL; + guint avail_cons_len; + guint i; + guint j; + char ** arr = NULL; + GString * str; + gboolean had_prefix; + gboolean has_prefix; + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CONNECTIONS_AVAILABLE_CONNECTIONS: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + + avail_cons = _device_get_available_connections(d, &avail_cons_len); + if (avail_cons_len == 0) + goto arr_out; + + arr = g_new(char *, avail_cons_len + 1); + j = 0; + for (i = 0; i < avail_cons_len; i++) { + NMRemoteConnection *ac = avail_cons[i]; + const char * ac_id = nm_connection_get_id(NM_CONNECTION(ac)); + const char * ac_uuid = nm_connection_get_uuid(NM_CONNECTION(ac)); + + if (!ac_id || !ac_uuid) { + const char *ac_path = nm_connection_get_path(NM_CONNECTION(ac)); + + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) { + arr[j++] = ac_path ? g_strdup_printf(_("<invisible> | %s"), ac_path) + : g_strdup(_("<invisible>")); + } else { + arr[j++] = ac_path ? g_strdup_printf("<invisible> | %s", ac_path) + : g_strdup("<invisible>"); + } + } else + arr[j++] = g_strdup_printf("%s | %s", ac_uuid, ac_id); + } + arr[j] = NULL; + goto arr_out; + + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CONNECTIONS_AVAILABLE_CONNECTION_PATHS: + + avail_cons = _device_get_available_connections(d, &avail_cons_len); + if (avail_cons_len == 0) + return NULL; + + str = g_string_new(NULL); + + had_prefix = FALSE; + for (i = 0; i < avail_cons_len; i++) { + NMRemoteConnection *ac = avail_cons[i]; + const char * p = nm_connection_get_path(NM_CONNECTION(ac)); + + if (!p) + continue; + + has_prefix = g_str_has_prefix(p, NM_DBUS_PATH_SETTINGS_CONNECTION "/") + && p[NM_STRLEN(NM_DBUS_PATH_SETTINGS_CONNECTION "/")]; + + if (str->len > 0) { + if (had_prefix && !has_prefix) + g_string_append_c(str, '}'); + g_string_append_c(str, ','); + } + + if (!has_prefix) + g_string_append(str, p); + else { + if (!had_prefix) + g_string_printf(str, "%s/{", NM_DBUS_PATH_SETTINGS_CONNECTION); + g_string_append(str, &p[NM_STRLEN(NM_DBUS_PATH_SETTINGS_CONNECTION "/")]); + } + had_prefix = has_prefix; + } + if (had_prefix) + g_string_append_c(str, '}'); + + return (*out_to_free = g_string_free(str, FALSE)); + + default: + break; + } + + g_return_val_if_reached(NULL); + +arr_out: + NM_SET_OUT(out_is_default, !arr || !arr[0]); + *out_flags |= NM_META_ACCESSOR_GET_OUT_FLAGS_STRV; + *out_to_free = arr; + return arr; +} + +const NmcMetaGenericInfo *const + metagen_device_detail_connections[_NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CONNECTIONS_NUM + 1] = { +#define _METAGEN_DEVICE_DETAIL_CONNECTIONS(type, name) \ + [type] = NMC_META_GENERIC(name, \ + .info_type = type, \ + .get_fcn = _metagen_device_detail_connections_get_fcn) + _METAGEN_DEVICE_DETAIL_CONNECTIONS( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CONNECTIONS_AVAILABLE_CONNECTION_PATHS, + "AVAILABLE-CONNECTION-PATHS"), + _METAGEN_DEVICE_DETAIL_CONNECTIONS( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CONNECTIONS_AVAILABLE_CONNECTIONS, + "AVAILABLE-CONNECTIONS"), +}; + +/*****************************************************************************/ + +static gconstpointer _metagen_device_detail_capabilities_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMDevice * d = target; + NMDeviceCapabilities caps; + guint32 speed; + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + caps = nm_device_get_capabilities(d); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_CARRIER_DETECT: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(caps, NM_DEVICE_CAP_CARRIER_DETECT), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_SPEED: + speed = 0; + if (NM_IS_DEVICE_ETHERNET(d)) { + /* Speed in Mb/s */ + speed = nm_device_ethernet_get_speed(NM_DEVICE_ETHERNET(d)); + } else if (NM_IS_DEVICE_WIFI(d)) { + /* Speed in b/s */ + speed = nm_device_wifi_get_bitrate(NM_DEVICE_WIFI(d)); + speed /= 1000; + } + + if (speed) { + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) + return (*out_to_free = g_strdup_printf(_("%u Mb/s"), (guint) speed)); + return (*out_to_free = g_strdup_printf("%u Mb/s", (guint) speed)); + } + return nmc_meta_generic_get_str_i18n(N_("unknown"), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_IS_SOFTWARE: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(caps, NM_DEVICE_CAP_IS_SOFTWARE), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_SRIOV: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(caps, NM_DEVICE_CAP_SRIOV), get_type); + default: + break; + } + + g_return_val_if_reached(NULL); +} + +const NmcMetaGenericInfo + *const metagen_device_detail_capabilities[_NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_NUM + + 1] = { +#define _METAGEN_DEVICE_DETAIL_CAPABILITIES(type, name) \ + [type] = NMC_META_GENERIC(name, \ + .info_type = type, \ + .get_fcn = _metagen_device_detail_capabilities_get_fcn) + _METAGEN_DEVICE_DETAIL_CAPABILITIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_CARRIER_DETECT, + "CARRIER-DETECT"), + _METAGEN_DEVICE_DETAIL_CAPABILITIES(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_SPEED, + "SPEED"), + _METAGEN_DEVICE_DETAIL_CAPABILITIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_IS_SOFTWARE, + "IS-SOFTWARE"), + _METAGEN_DEVICE_DETAIL_CAPABILITIES(NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_SRIOV, + "SRIOV"), +}; + +/*****************************************************************************/ + +static gconstpointer + _metagen_device_detail_wired_properties_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMDevice *d = target; + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIRED_PROPERTIES_CARRIER: + return nmc_meta_generic_get_bool_onoff( + nm_device_ethernet_get_carrier(NM_DEVICE_ETHERNET(d)), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIRED_PROPERTIES_S390_SUBCHANNELS: + if (!NM_FLAGS_HAS(get_flags, NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV)) + return NULL; + *out_flags |= NM_META_ACCESSOR_GET_OUT_FLAGS_STRV; + return nm_device_ethernet_get_s390_subchannels(NM_DEVICE_ETHERNET(d)); + default: + break; + } + + g_return_val_if_reached(NULL); +} + +const NmcMetaGenericInfo *const + metagen_device_detail_wired_properties[_NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIRED_PROPERTIES_NUM + + 1] = { +#define _METAGEN_DEVICE_DETAIL_WIRED_PROPERTIES(type, name) \ + [type] = NMC_META_GENERIC(name, \ + .info_type = type, \ + .get_fcn = _metagen_device_detail_wired_properties_get_fcn) + _METAGEN_DEVICE_DETAIL_WIRED_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIRED_PROPERTIES_CARRIER, + "CARRIER"), + _METAGEN_DEVICE_DETAIL_WIRED_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIRED_PROPERTIES_S390_SUBCHANNELS, + "S390-SUBCHANNELS"), +}; + +/*****************************************************************************/ + +static gconstpointer + _metagen_device_detail_wifi_properties_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMDevice * d = target; + NMDeviceWifiCapabilities wcaps; + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + wcaps = nm_device_wifi_get_capabilities(NM_DEVICE_WIFI(d)); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WEP: + return nmc_meta_generic_get_bool( + NM_FLAGS_ANY(wcaps, NM_WIFI_DEVICE_CAP_CIPHER_WEP40 | NM_WIFI_DEVICE_CAP_CIPHER_WEP104), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WPA: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_WPA), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WPA2: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_RSN), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_TKIP: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_CIPHER_TKIP), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_CCMP: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_CIPHER_CCMP), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_AP: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_AP), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_ADHOC: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_ADHOC), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_2GHZ: + return nmc_meta_generic_get_str_i18n( + NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_FREQ_VALID) + ? (NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_FREQ_2GHZ) ? N_("yes") : N_("no")) + : N_("unknown"), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_5GHZ: + return nmc_meta_generic_get_str_i18n( + NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_FREQ_VALID) + ? (NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_FREQ_5GHZ) ? N_("yes") : N_("no")) + : N_("unknown"), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_MESH: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_MESH), get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_IBSS_RSN: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(wcaps, NM_WIFI_DEVICE_CAP_IBSS_RSN), + get_type); + default: + break; + } + + g_return_val_if_reached(NULL); +} + +const NmcMetaGenericInfo *const + metagen_device_detail_wifi_properties[_NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_NUM + + 1] = { +#define _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES(type, name) \ + [type] = NMC_META_GENERIC(name, \ + .info_type = type, \ + .get_fcn = _metagen_device_detail_wifi_properties_get_fcn) + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WEP, + "WEP"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WPA, + "WPA"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WPA2, + "WPA2"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_TKIP, + "TKIP"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_CCMP, + "CCMP"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_AP, + "AP"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_ADHOC, + "ADHOC"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_2GHZ, + "2GHZ"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_5GHZ, + "5GHZ"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_MESH, + "MESH"), + _METAGEN_DEVICE_DETAIL_WIFI_PROPERTIES( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_IBSS_RSN, + "IBSS-RSN"), +}; + +/*****************************************************************************/ + +static gconstpointer + _metagen_device_detail_interface_flags_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMDevice * d = target; + NMDeviceInterfaceFlags flags; + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + flags = nm_device_get_interface_flags(d); + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_UP: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(flags, NM_DEVICE_INTERFACE_FLAG_UP), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_LOWER_UP: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(flags, NM_DEVICE_INTERFACE_FLAG_LOWER_UP), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_CARRIER: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(flags, NM_DEVICE_INTERFACE_FLAG_CARRIER), + get_type); + case NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_PROMISC: + return nmc_meta_generic_get_bool(NM_FLAGS_HAS(flags, NM_DEVICE_INTERFACE_FLAG_PROMISC), + get_type); + default: + break; + } + + g_return_val_if_reached(NULL); +} + +const NmcMetaGenericInfo *const + metagen_device_detail_interface_flags[_NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_NUM + + 1] = { +#define _METAGEN_DEVICE_DETAIL_INTERFACE_FLAGS(type, name) \ + [type] = NMC_META_GENERIC(name, \ + .info_type = type, \ + .get_fcn = _metagen_device_detail_interface_flags_get_fcn) + _METAGEN_DEVICE_DETAIL_INTERFACE_FLAGS( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_UP, + "UP"), + _METAGEN_DEVICE_DETAIL_INTERFACE_FLAGS( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_LOWER_UP, + "LOWER-UP"), + _METAGEN_DEVICE_DETAIL_INTERFACE_FLAGS( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_CARRIER, + "CARRIER"), + _METAGEN_DEVICE_DETAIL_INTERFACE_FLAGS( + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_PROMISC, + "PROMISC"), +}; + +/*****************************************************************************/ + +const NmcMetaGenericInfo *const metagen_device_detail_wimax_properties[] = { + NMC_META_GENERIC("CTR-FREQ"), + NMC_META_GENERIC("RSSI"), + NMC_META_GENERIC("CINR"), + NMC_META_GENERIC("TX-POW"), + NMC_META_GENERIC("BSID"), +}; + +/*****************************************************************************/ + +const NmcMetaGenericInfo *const nmc_fields_dev_wifi_list[] = { + NMC_META_GENERIC("NAME"), /* 0 */ + NMC_META_GENERIC("SSID"), /* 1 */ + NMC_META_GENERIC("SSID-HEX"), /* 2 */ + NMC_META_GENERIC("BSSID"), /* 3 */ + NMC_META_GENERIC("MODE"), /* 4 */ + NMC_META_GENERIC("CHAN"), /* 5 */ + NMC_META_GENERIC("FREQ"), /* 6 */ + NMC_META_GENERIC("RATE"), /* 7 */ + NMC_META_GENERIC("SIGNAL"), /* 8 */ + NMC_META_GENERIC("BARS"), /* 9 */ + NMC_META_GENERIC("SECURITY"), /* 10 */ + NMC_META_GENERIC("WPA-FLAGS"), /* 11 */ + NMC_META_GENERIC("RSN-FLAGS"), /* 12 */ + NMC_META_GENERIC("DEVICE"), /* 13 */ + NMC_META_GENERIC("ACTIVE"), /* 14 */ + NMC_META_GENERIC("IN-USE"), /* 15 */ + NMC_META_GENERIC("DBUS-PATH"), /* 16 */ + NULL, +}; +#define NMC_FIELDS_DEV_WIFI_LIST_COMMON "IN-USE,BSSID,SSID,MODE,CHAN,RATE,SIGNAL,BARS,SECURITY" +#define NMC_FIELDS_DEV_WIFI_LIST_FOR_DEV_LIST "NAME," NMC_FIELDS_DEV_WIFI_LIST_COMMON + +const NmcMetaGenericInfo *const nmc_fields_dev_wimax_list[] = { + NMC_META_GENERIC("NAME"), /* 0 */ + NMC_META_GENERIC("NSP"), /* 1 */ + NMC_META_GENERIC("SIGNAL"), /* 2 */ + NMC_META_GENERIC("TYPE"), /* 3 */ + NMC_META_GENERIC("DEVICE"), /* 4 */ + NMC_META_GENERIC("ACTIVE"), /* 5 */ + NMC_META_GENERIC("DBUS-PATH"), /* 6 */ + NULL, +}; +#define NMC_FIELDS_DEV_WIMAX_LIST_COMMON "NSP,SIGNAL,TYPE,DEVICE,ACTIVE" +#define NMC_FIELDS_DEV_WIMAX_LIST_FOR_DEV_LIST "NAME," NMC_FIELDS_DEV_WIMAX_LIST_COMMON + +const NmcMetaGenericInfo *const nmc_fields_dev_show_master_prop[] = { + NMC_META_GENERIC("NAME"), /* 0 */ + NMC_META_GENERIC("SLAVES"), /* 1 */ + NULL, +}; +#define NMC_FIELDS_DEV_SHOW_MASTER_PROP_COMMON "NAME,SLAVES" + +const NmcMetaGenericInfo *const nmc_fields_dev_show_team_prop[] = { + NMC_META_GENERIC("NAME"), /* 0 */ + NMC_META_GENERIC("SLAVES"), /* 1 */ + NMC_META_GENERIC("CONFIG"), /* 2 */ + NULL, +}; +#define NMC_FIELDS_DEV_SHOW_TEAM_PROP_COMMON "NAME,SLAVES,CONFIG" + +const NmcMetaGenericInfo *const nmc_fields_dev_show_vlan_prop[] = { + NMC_META_GENERIC("NAME"), /* 0 */ + NMC_META_GENERIC("PARENT"), /* 1 */ + NMC_META_GENERIC("ID"), /* 2 */ + NULL, +}; +#define NMC_FIELDS_DEV_SHOW_VLAN_PROP_COMMON "NAME,PARENT,ID" + +const NmcMetaGenericInfo *const nmc_fields_dev_show_bluetooth[] = { + NMC_META_GENERIC("NAME"), /* 0 */ + NMC_META_GENERIC("CAPABILITIES"), /* 1 */ + NULL, +}; +#define NMC_FIELDS_DEV_SHOW_BLUETOOTH_COMMON "NAME,CAPABILITIES" + +/* Available sections for 'device show' */ +const NmcMetaGenericInfo *const nmc_fields_dev_show_sections[] = { + NMC_META_GENERIC_WITH_NESTED("GENERAL", metagen_device_detail_general), /* 0 */ + NMC_META_GENERIC_WITH_NESTED("CAPABILITIES", metagen_device_detail_capabilities), /* 1 */ + NMC_META_GENERIC_WITH_NESTED("INTERFACE-FLAGS", metagen_device_detail_interface_flags), /* 2 */ + NMC_META_GENERIC_WITH_NESTED("WIFI-PROPERTIES", metagen_device_detail_wifi_properties), /* 3 */ + NMC_META_GENERIC_WITH_NESTED("AP", nmc_fields_dev_wifi_list + 1), /* 4 */ + NMC_META_GENERIC_WITH_NESTED("WIRED-PROPERTIES", + metagen_device_detail_wired_properties), /* 5 */ + NMC_META_GENERIC_WITH_NESTED("WIMAX-PROPERTIES", + metagen_device_detail_wimax_properties), /* 6 */ + NMC_META_GENERIC_WITH_NESTED("NSP", nmc_fields_dev_wimax_list + 1), /* 7 */ + NMC_META_GENERIC_WITH_NESTED("IP4", metagen_ip4_config), /* 8 */ + NMC_META_GENERIC_WITH_NESTED("DHCP4", metagen_dhcp_config), /* 9 */ + NMC_META_GENERIC_WITH_NESTED("IP6", metagen_ip6_config), /* 10 */ + NMC_META_GENERIC_WITH_NESTED("DHCP6", metagen_dhcp_config), /* 11 */ + NMC_META_GENERIC_WITH_NESTED("BOND", nmc_fields_dev_show_master_prop + 1), /* 12 */ + NMC_META_GENERIC_WITH_NESTED("TEAM", nmc_fields_dev_show_team_prop + 1), /* 13 */ + NMC_META_GENERIC_WITH_NESTED("BRIDGE", nmc_fields_dev_show_master_prop + 1), /* 14 */ + NMC_META_GENERIC_WITH_NESTED("VLAN", nmc_fields_dev_show_vlan_prop + 1), /* 15 */ + NMC_META_GENERIC_WITH_NESTED("BLUETOOTH", nmc_fields_dev_show_bluetooth + 1), /* 16 */ + NMC_META_GENERIC_WITH_NESTED("CONNECTIONS", metagen_device_detail_connections), /* 17 */ + NULL, +}; +#define NMC_FIELDS_DEV_SHOW_SECTIONS_COMMON \ + "GENERAL.DEVICE,GENERAL.TYPE,GENERAL.HWADDR,GENERAL.MTU,GENERAL.STATE," \ + "GENERAL.CONNECTION,GENERAL.CON-PATH,WIRED-PROPERTIES,IP4,IP6" + +const NmcMetaGenericInfo *const nmc_fields_dev_lldp_list[] = { + NMC_META_GENERIC("NAME"), /* 0 */ + NMC_META_GENERIC("DEVICE"), /* 1 */ + NMC_META_GENERIC("CHASSIS-ID"), /* 2 */ + NMC_META_GENERIC("PORT-ID"), /* 3 */ + NMC_META_GENERIC("PORT-DESCRIPTION"), /* 4 */ + NMC_META_GENERIC("SYSTEM-NAME"), /* 5 */ + NMC_META_GENERIC("SYSTEM-DESCRIPTION"), /* 6 */ + NMC_META_GENERIC("SYSTEM-CAPABILITIES"), /* 7 */ + NMC_META_GENERIC("IEEE-802-1-PVID"), /* 8 */ + NMC_META_GENERIC("IEEE-802-1-PPVID"), /* 9 */ + NMC_META_GENERIC("IEEE-802-1-PPVID-FLAGS"), /* 10 */ + NMC_META_GENERIC("IEEE-802-1-VID"), /* 11 */ + NMC_META_GENERIC("IEEE-802-1-VLAN-NAME"), /* 12 */ + NMC_META_GENERIC("DESTINATION"), /* 13 */ + NMC_META_GENERIC("CHASSIS-ID-TYPE"), /* 14 */ + NMC_META_GENERIC("PORT-ID-TYPE"), /* 15 */ + NULL, +}; +#define NMC_FIELDS_DEV_LLDP_LIST_COMMON \ + "DEVICE,CHASSIS-ID,PORT-ID,PORT-DESCRIPTION,SYSTEM-NAME,SYSTEM-DESCRIPTION," \ + "SYSTEM-CAPABILITIES" + +static guint progress_id = 0; /* ID of event source for displaying progress */ + +static void +usage(void) +{ + g_printerr(_("Usage: nmcli device { COMMAND | help }\n\n" + "COMMAND := { status | show | set | connect | reapply | modify | disconnect | " + "delete | monitor | wifi | lldp }\n\n" + " status\n\n" + " show [<ifname>]\n\n" + " set [ifname] <ifname> [autoconnect yes|no] [managed yes|no]\n\n" + " connect <ifname>\n\n" + " reapply <ifname>\n\n" + " modify <ifname> ([+|-]<setting>.<property> <value>)+\n\n" + " disconnect <ifname> ...\n\n" + " delete <ifname> ...\n\n" + " monitor <ifname> ...\n\n" + " wifi [list [ifname <ifname>] [bssid <BSSID>] [--rescan yes|no|auto]]\n\n" + " wifi connect <(B)SSID> [password <password>] [wep-key-type key|phrase] [ifname " + "<ifname>]\n" + " [bssid <BSSID>] [name <name>] [private yes|no] [hidden " + "yes|no]\n\n" + " wifi hotspot [ifname <ifname>] [con-name <name>] [ssid <SSID>] [band a|bg] " + "[channel <channel>] [password <password>]\n\n" + " wifi rescan [ifname <ifname>] [[ssid <SSID to scan>] ...]\n\n" + " wifi show-password [ifname <ifname>]\n\n" + " lldp [list [ifname <ifname>]]\n\n")); +} + +static void +usage_device_status(void) +{ + g_printerr( + _("Usage: nmcli device status { help }\n" + "\n" + "Show status for all devices.\n" + "By default, the following columns are shown:\n" + " DEVICE - interface name\n" + " TYPE - device type\n" + " STATE - device state\n" + " CONNECTION - connection activated on device (if any)\n" + "Displayed columns can be changed using '--fields' global option. 'status' is\n" + "the default command, which means 'nmcli device' calls 'nmcli device status'.\n\n")); +} + +static void +usage_device_show(void) +{ + g_printerr(_("Usage: nmcli device show { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [<ifname>]\n" + "\n" + "Show details of device(s).\n" + "The command lists details for all devices, or for a given device.\n\n")); +} + +static void +usage_device_connect(void) +{ + g_printerr(_("Usage: nmcli device connect { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := <ifname>\n" + "\n" + "Connect the device.\n" + "NetworkManager will try to find a suitable connection that will be activated.\n" + "It will also consider connections that are not set to auto-connect.\n\n")); +} + +static void +usage_device_reapply(void) +{ + g_printerr(_("Usage: nmcli device reapply { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := <ifname>\n" + "\n" + "Attempts to update device with changes to the currently active connection\n" + "made since it was last applied.\n\n")); +} + +static void +usage_device_modify(void) +{ + g_printerr(_( + "Usage: nmcli device modify { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := <ifname> ([+|-]<setting>.<property> <value>)+\n" + "\n" + "Modify one or more properties that are currently active on the device without modifying\n" + "the connection profile. The changes have immediate effect. For multi-valued\n" + "properties you can use optional '+' or '-' prefix to the property name.\n" + "The '+' sign allows appending items instead of overwriting the whole value.\n" + "The '-' sign allows removing selected items instead of the whole value.\n" + "\n" + "Examples:\n" + "nmcli dev mod em1 ipv4.method manual ipv4.addr \"192.168.1.2/24, 10.10.1.5/8\"\n" + "nmcli dev mod em1 +ipv4.dns 8.8.4.4\n" + "nmcli dev mod em1 -ipv4.dns 1\n" + "nmcli dev mod em1 -ipv6.addr \"abbe::cafe/56\"\n")); +} + +static void +usage_device_disconnect(void) +{ + g_printerr(_("Usage: nmcli device disconnect { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := <ifname> ...\n" + "\n" + "Disconnect devices.\n" + "The command disconnects the device and prevents it from auto-activating\n" + "further connections without user/manual intervention.\n\n")); +} + +static void +usage_device_delete(void) +{ + g_printerr(_("Usage: nmcli device delete { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := <ifname> ...\n" + "\n" + "Delete the software devices.\n" + "The command removes the interfaces. It only works for software devices\n" + "(like bonds, bridges, etc.). Hardware devices cannot be deleted by the\n" + "command.\n\n")); +} + +static void +usage_device_set(void) +{ + g_printerr(_("Usage: nmcli device set { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := DEVICE { PROPERTY [ PROPERTY ... ] }\n" + "DEVICE := [ifname] <ifname> \n" + "PROPERTY := { autoconnect { yes | no } |\n" + " { managed { yes | no }\n" + "\n" + "Modify device properties.\n\n")); +} + +static void +usage_device_monitor(void) +{ + g_printerr(_("Usage: nmcli device monitor { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [<ifname>] ...\n" + "\n" + "Monitor device activity.\n" + "This command prints a line whenever the specified devices change state.\n" + "Monitors all devices in case no interface is specified.\n\n")); +} + +static void +usage_device_wifi(void) +{ + g_printerr( + _("Usage: nmcli device wifi { ARGUMENTS | help }\n" + "\n" + "Perform operation on Wi-Fi devices.\n" + "\n" + "ARGUMENTS := [list [ifname <ifname>] [bssid <BSSID>] [--rescan yes|no|auto]]\n" + "\n" + "List available Wi-Fi access points. The 'ifname' and 'bssid' options can be\n" + "used to list APs for a particular interface, or with a specific BSSID. The\n" + "--rescan flag tells whether a new Wi-Fi scan should be triggered.\n" + "\n" + "ARGUMENTS := connect <(B)SSID> [password <password>] [wep-key-type key|phrase] [ifname " + "<ifname>]\n" + " [bssid <BSSID>] [name <name>] [private yes|no] [hidden yes|no]\n" + "\n" + "Connect to a Wi-Fi network specified by SSID or BSSID. The command finds a\n" + "matching connection or creates one and then activates it on a device. This\n" + "is a command-line counterpart of clicking an SSID in a GUI client. If a\n" + "connection for the network already exists, it is possible to bring up the\n" + "existing profile as follows: nmcli con up id <name>. Note that only open,\n" + "WEP and WPA-PSK networks are supported if no previous connection exists.\n" + "It is also assumed that IP configuration is obtained via DHCP.\n" + "\n" + "ARGUMENTS := hotspot [ifname <ifname>] [con-name <name>] [ssid <SSID>]\n" + " [band a|bg] [channel <channel>] [password <password>]\n" + "\n" + "Create a Wi-Fi hotspot. Use 'connection down' or 'device disconnect'\n" + "to stop the hotspot.\n" + "Parameters of the hotspot can be influenced by the optional parameters:\n" + "ifname - Wi-Fi device to use\n" + "con-name - name of the created hotspot connection profile\n" + "ssid - SSID of the hotspot\n" + "band - Wi-Fi band to use\n" + "channel - Wi-Fi channel to use\n" + "password - password to use for the hotspot\n" + "\n" + "ARGUMENTS := rescan [ifname <ifname>] [[ssid <SSID to scan>] ...]\n" + "\n" + "Request that NetworkManager immediately re-scan for available access points.\n" + "NetworkManager scans Wi-Fi networks periodically, but in some cases it might\n" + "be useful to start scanning manually. 'ssid' allows scanning for a specific\n" + "SSID, which is useful for APs with hidden SSIDs. More 'ssid' parameters can be\n" + "given. Note that this command does not show the APs,\n" + "use 'nmcli device wifi list' for that.\n\n")); +} + +static void +usage_device_lldp(void) +{ + g_printerr(_("Usage: nmcli device lldp { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [list [ifname <ifname>]]\n" + "\n" + "List neighboring devices discovered through LLDP. The 'ifname' option can be\n" + "used to list neighbors for a particular interface.\n\n")); +} + +static void +quit(void) +{ + if (nm_clear_g_source(&progress_id)) + nmc_terminal_erase_line(); + g_main_loop_quit(loop); +} + +static int +compare_devices(const void *a, const void *b) +{ + NMDevice * da = *(NMDevice **) a; + NMDevice * db = *(NMDevice **) b; + NMActiveConnection *da_ac = nm_device_get_active_connection(da); + NMActiveConnection *db_ac = nm_device_get_active_connection(db); + + NM_CMP_DIRECT(nm_device_get_state(db), nm_device_get_state(da)); + NM_CMP_RETURN(nmc_active_connection_cmp(db_ac, da_ac)); + NM_CMP_DIRECT_STRCMP0(nm_device_get_type_description(da), nm_device_get_type_description(db)); + NM_CMP_DIRECT_STRCMP0(nm_device_get_iface(da), nm_device_get_iface(db)); + NM_CMP_DIRECT_STRCMP0(nm_object_get_path(NM_OBJECT(da)), nm_object_get_path(NM_OBJECT(db))); + + g_return_val_if_reached(0); +} + +NMDevice ** +nmc_get_devices_sorted(NMClient *client) +{ + const GPtrArray *devs; + NMDevice ** sorted; + + devs = nm_client_get_devices(client); + + sorted = g_new(NMDevice *, devs->len + 1); + if (devs->len > 0) + memcpy(sorted, devs->pdata, devs->len * sizeof(NMDevice *)); + sorted[devs->len] = NULL; + + qsort(sorted, devs->len, sizeof(NMDevice *), compare_devices); + return sorted; +} + +static void +complete_device(NMDevice **devices, const char *prefix, gboolean wifi_only) +{ + int i; + + for (i = 0; devices[i]; i++) { + const char *iface = nm_device_get_iface(devices[i]); + + if (wifi_only && !NM_IS_DEVICE_WIFI(devices[i])) + continue; + + if (g_str_has_prefix(iface, prefix)) + g_print("%s\n", iface); + } +} + +void +nmc_complete_device(NMClient *client, const char *prefix, gboolean wifi_only) +{ + gs_free NMDevice **devices = NULL; + + devices = nmc_get_devices_sorted(client); + complete_device(devices, prefix, wifi_only); +} + +static GSList * +get_device_list(NmCli *nmc, int argc, const char *const *argv) +{ + int arg_num = argc; + gs_strfreev char **arg_arr = NULL; + const char *const *arg_ptr = argv; + NMDevice ** devices; + GSList * queue = NULL; + NMDevice * device; + int i; + + if (argc == 0) { + if (nmc->ask) { + gs_free char *line = NULL; + + line = nmc_readline(&nmc->nmc_config, PROMPT_INTERFACES); + nmc_string_to_arg_array(line, NULL, FALSE, &arg_arr, &arg_num); + arg_ptr = (const char *const *) arg_arr; + } + if (arg_num == 0) { + g_string_printf(nmc->return_text, _("Error: No interface specified.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto error; + } + } + + devices = nmc_get_devices_sorted(nmc->client); + while (arg_num > 0) { + if (arg_num == 1 && nmc->complete) + complete_device(devices, *arg_ptr, FALSE); + + device = NULL; + for (i = 0; devices[i]; i++) { + if (!g_strcmp0(nm_device_get_iface(devices[i]), *arg_ptr)) { + device = devices[i]; + break; + } + } + + if (device) { + if (!g_slist_find(queue, device)) + queue = g_slist_prepend(queue, device); + else + g_printerr(_("Warning: argument '%s' is duplicated.\n"), *arg_ptr); + } else { + if (!nmc->complete) + g_printerr(_("Error: Device '%s' not found.\n"), *arg_ptr); + g_string_printf(nmc->return_text, _("Error: not all devices found.")); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + } + + /* Take next argument */ + next_arg(nmc->ask ? NULL : nmc, &arg_num, &arg_ptr, NULL); + } + g_free(devices); + +error: + g_strfreev(arg_arr); + + return queue; +} + +static NMDevice * +get_device(NmCli *nmc, int *argc, const char *const **argv, GError **error) +{ + gs_free NMDevice **devices = NULL; + gs_free char * ifname_ask = NULL; + const char * ifname = NULL; + int i; + + if (*argc == 0) { + if (nmc->ask) { + ifname = ifname_ask = nmc_readline(&nmc->nmc_config, PROMPT_INTERFACE); + } + + if (!ifname_ask) { + g_set_error_literal(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("No interface specified")); + return NULL; + } + } else { + ifname = **argv; + next_arg(nmc, argc, argv, NULL); + } + + devices = nmc_get_devices_sorted(nmc->client); + for (i = 0; devices[i]; i++) { + if (!g_strcmp0(nm_device_get_iface(devices[i]), ifname)) + break; + } + + if (nmc->complete && !*argc) + complete_device(devices, ifname, FALSE); + + if (devices[i] == NULL) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_NOT_FOUND, + _("Device '%s' not found"), + ifname); + } + + return devices[i]; +} + +static int +compare_aps(gconstpointer a, gconstpointer b, gpointer user_data) +{ + NMAccessPoint *apa = *(NMAccessPoint **) a; + NMAccessPoint *apb = *(NMAccessPoint **) b; + + NM_CMP_DIRECT(nm_access_point_get_strength(apb), nm_access_point_get_strength(apa)); + NM_CMP_DIRECT(nm_access_point_get_frequency(apa), nm_access_point_get_frequency(apb)); + NM_CMP_DIRECT(nm_access_point_get_max_bitrate(apb), nm_access_point_get_max_bitrate(apa)); + + /* as fallback, just give it some stable order and use the D-Bus path (literally). */ + NM_CMP_DIRECT_STRCMP0(nm_object_get_path(NM_OBJECT(apa)), nm_object_get_path(NM_OBJECT(apb))); + + return 0; +} + +static GPtrArray * +sort_access_points(const GPtrArray *aps) +{ + GPtrArray *sorted; + guint i; + + g_return_val_if_fail(aps, NULL); + + sorted = g_ptr_array_sized_new(aps->len); + g_ptr_array_set_free_func(sorted, nm_g_object_unref); + for (i = 0; i < aps->len; i++) + g_ptr_array_add(sorted, g_object_ref(aps->pdata[i])); + g_ptr_array_sort_with_data(sorted, compare_aps, NULL); + return sorted; +} + +typedef struct { + NmCli * nmc; + int index; + guint32 output_flags; + const char *active_bssid; + const char *device; + GPtrArray * output_data; +} APInfo; + +static void +fill_output_access_point(gpointer data, gpointer user_data) +{ + NMAccessPoint * ap = NM_ACCESS_POINT(data); + APInfo * info = (APInfo *) user_data; + NmcOutputField * arr; + gboolean active = FALSE; + NM80211ApFlags flags; + NM80211ApSecurityFlags wpa_flags, rsn_flags; + guint32 freq, bitrate; + guint8 strength; + GBytes * ssid; + const char * bssid; + NM80211Mode mode; + char * channel_str; + char * freq_str; + char * ssid_str = NULL; + char * ssid_hex_str = NULL; + char * bitrate_str; + char * strength_str; + char * wpa_flags_str; + char * rsn_flags_str; + GString * security_str; + char * ap_name; + const char * sig_bars; + NMMetaColor color; + + if (info->active_bssid) { + const char *current_bssid = nm_access_point_get_bssid(ap); + if (current_bssid && !strcmp(current_bssid, info->active_bssid)) + active = TRUE; + } + + /* Get AP properties */ + flags = nm_access_point_get_flags(ap); + wpa_flags = nm_access_point_get_wpa_flags(ap); + rsn_flags = nm_access_point_get_rsn_flags(ap); + ssid = nm_access_point_get_ssid(ap); + bssid = nm_access_point_get_bssid(ap); + freq = nm_access_point_get_frequency(ap); + mode = nm_access_point_get_mode(ap); + bitrate = nm_access_point_get_max_bitrate(ap); + strength = MIN(nm_access_point_get_strength(ap), 100); + + /* Convert to strings */ + if (ssid) { + const guint8 *ssid_data; + gsize ssid_len; + + ssid_data = g_bytes_get_data(ssid, &ssid_len); + ssid_str = nm_utils_ssid_to_utf8(ssid_data, ssid_len); + ssid_hex_str = ssid_to_hex((const char *) ssid_data, ssid_len); + } + channel_str = g_strdup_printf("%u", nm_utils_wifi_freq_to_channel(freq)); + freq_str = g_strdup_printf(_("%u MHz"), freq); + bitrate_str = g_strdup_printf(_("%u Mbit/s"), bitrate / 1000); + strength_str = nm_strdup_int(strength); + wpa_flags_str = ap_wpa_rsn_flags_to_string(wpa_flags, NM_META_ACCESSOR_GET_TYPE_PRETTY); + rsn_flags_str = ap_wpa_rsn_flags_to_string(rsn_flags, NM_META_ACCESSOR_GET_TYPE_PRETTY); + sig_bars = nmc_wifi_strength_bars(strength); + + security_str = g_string_new(NULL); + + if ((flags & NM_802_11_AP_FLAGS_PRIVACY) && (wpa_flags == NM_802_11_AP_SEC_NONE) + && (rsn_flags == NM_802_11_AP_SEC_NONE)) { + g_string_append(security_str, "WEP "); + } + if (wpa_flags != NM_802_11_AP_SEC_NONE) { + g_string_append(security_str, "WPA1 "); + } + if ((rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) + || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { + g_string_append(security_str, "WPA2 "); + } + if (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_SAE) { + g_string_append(security_str, "WPA3 "); + } + if (NM_FLAGS_ANY(rsn_flags, NM_802_11_AP_SEC_KEY_MGMT_OWE | NM_802_11_AP_SEC_KEY_MGMT_OWE_TM)) { + g_string_append(security_str, "OWE "); + } + if ((wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) + || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { + g_string_append(security_str, "802.1X "); + } + + if (security_str->len > 0) + g_string_truncate(security_str, security_str->len - 1); /* Chop off last space */ + + arr = nmc_dup_fields_array((const NMMetaAbstractInfo *const *) nmc_fields_dev_wifi_list, + info->output_flags); + + ap_name = g_strdup_printf("AP[%d]", info->index++); /* AP */ + set_val_str(arr, 0, ap_name); + set_val_str(arr, 1, ssid_str); + set_val_str(arr, 2, ssid_hex_str); + set_val_strc(arr, 3, bssid); + set_val_strc(arr, + 4, + mode == NM_802_11_MODE_ADHOC ? _("Ad-Hoc") + : mode == NM_802_11_MODE_INFRA ? _("Infra") + : mode == NM_802_11_MODE_MESH ? _("Mesh") + : _("N/A")); + set_val_str(arr, 5, channel_str); + set_val_str(arr, 6, freq_str); + set_val_str(arr, 7, bitrate_str); + set_val_str(arr, 8, strength_str); + set_val_strc(arr, 9, sig_bars); + set_val_str(arr, 10, g_string_free(security_str, FALSE)); + set_val_str(arr, 11, wpa_flags_str); + set_val_str(arr, 12, rsn_flags_str); + set_val_strc(arr, 13, info->device); + set_val_strc(arr, 14, active ? _("yes") : _("no")); + set_val_strc(arr, 15, active ? "*" : " "); + set_val_strc(arr, 16, nm_object_get_path(NM_OBJECT(ap))); + + /* Set colors */ + color = wifi_signal_to_color(strength); + set_val_color_all(arr, color); + if (active) + arr[15].color = NM_META_COLOR_CONNECTION_ACTIVATED; + + g_ptr_array_add(info->output_data, arr); +} + +static char * +bluetooth_caps_to_string(NMBluetoothCapabilities caps) +{ + char *caps_str[8]; /* Enough space for caps and terminating NULL */ + char *ret_str; + int i = 0; + + if (caps & NM_BT_CAPABILITY_DUN) + caps_str[i++] = g_strdup("DUN"); + if (caps & NM_BT_CAPABILITY_NAP) + caps_str[i++] = g_strdup("NAP"); + + if (i == 0) + caps_str[i++] = g_strdup(_("(none)")); + + caps_str[i] = NULL; + + ret_str = g_strjoinv(" ", caps_str); + + i = 0; + while (caps_str[i]) + g_free(caps_str[i++]); + + return ret_str; +} + +static char * +construct_header_name(const char *base, const char *spec) +{ + if (spec == NULL) + return g_strdup(base); + + return g_strdup_printf("%s (%s)", base, spec); +} + +static gboolean +print_bond_bridge_info(NMDevice * device, + NmCli * nmc, + const char *group_prefix, + const char *one_field) +{ + const GPtrArray * slaves = NULL; + GString * slaves_str; + int idx; + const NMMetaAbstractInfo *const *tmpl; + NmcOutputField * arr; + NMC_OUTPUT_DATA_DEFINE_SCOPED(out); + + if (NM_IS_DEVICE_BOND(device)) + slaves = nm_device_bond_get_slaves(NM_DEVICE_BOND(device)); + else if (NM_IS_DEVICE_BRIDGE(device)) + slaves = nm_device_bridge_get_slaves(NM_DEVICE_BRIDGE(device)); + else + g_return_val_if_reached(FALSE); + + slaves_str = g_string_new(NULL); + for (idx = 0; slaves && idx < slaves->len; idx++) { + NMDevice * slave = g_ptr_array_index(slaves, idx); + const char *iface = nm_device_get_iface(slave); + + if (iface) { + g_string_append(slaves_str, iface); + g_string_append_c(slaves_str, ' '); + } + } + if (slaves_str->len > 0) + g_string_truncate(slaves_str, slaves_str->len - 1); /* Chop off last space */ + + tmpl = (const NMMetaAbstractInfo *const *) nmc_fields_dev_show_master_prop; + out_indices = parse_output_fields(one_field, tmpl, FALSE, NULL, NULL); + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_FIELD_NAMES); + g_ptr_array_add(out.output_data, arr); + + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_SECTION_PREFIX); + set_val_strc(arr, 0, group_prefix); /* i.e. BOND, TEAM, BRIDGE */ + set_val_str(arr, 1, g_string_free(slaves_str, FALSE)); + g_ptr_array_add(out.output_data, arr); + + print_data_prepare_width(out.output_data); + print_data(&nmc->nmc_config, &nmc->pager_data, out_indices, NULL, 0, &out); + + return TRUE; +} + +static char * +sanitize_team_config(const char *config) +{ + char *ret; + int i; + + if (!config) + return NULL; + + ret = g_strdup(config); + + for (i = 0; i < strlen(ret); i++) { + if (ret[i] == '\n') + ret[i] = ' '; + } + + return ret; +} + +static gboolean +print_team_info(NMDevice *device, NmCli *nmc, const char *group_prefix, const char *one_field) +{ + const GPtrArray * slaves = NULL; + GString * slaves_str; + int idx; + const NMMetaAbstractInfo *const *tmpl; + NmcOutputField * arr; + NMC_OUTPUT_DATA_DEFINE_SCOPED(out); + + if (NM_IS_DEVICE_TEAM(device)) + slaves = nm_device_team_get_slaves(NM_DEVICE_TEAM(device)); + else + g_return_val_if_reached(FALSE); + + slaves_str = g_string_new(NULL); + for (idx = 0; slaves && idx < slaves->len; idx++) { + NMDevice * slave = g_ptr_array_index(slaves, idx); + const char *iface = nm_device_get_iface(slave); + + if (iface) { + g_string_append(slaves_str, iface); + g_string_append_c(slaves_str, ' '); + } + } + if (slaves_str->len > 0) + g_string_truncate(slaves_str, slaves_str->len - 1); /* Chop off last space */ + + tmpl = (const NMMetaAbstractInfo *const *) nmc_fields_dev_show_team_prop; + out_indices = parse_output_fields(one_field, tmpl, FALSE, NULL, NULL); + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_FIELD_NAMES); + g_ptr_array_add(out.output_data, arr); + + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_SECTION_PREFIX); + set_val_strc(arr, 0, group_prefix); /* TEAM */ + set_val_str(arr, 1, g_string_free(slaves_str, FALSE)); + set_val_str(arr, 2, sanitize_team_config(nm_device_team_get_config(NM_DEVICE_TEAM(device)))); + g_ptr_array_add(out.output_data, arr); + + print_data_prepare_width(out.output_data); + print_data(&nmc->nmc_config, &nmc->pager_data, out_indices, NULL, 0, &out); + + return TRUE; +} + +static gboolean +show_device_info(NMDevice *device, NmCli *nmc) +{ + GError * error = NULL; + NMDeviceState state = NM_DEVICE_STATE_UNKNOWN; + GArray * sections_array; + int k; + const char * fields_str = NULL; + const NMMetaAbstractInfo *const *tmpl; + NmcOutputField * arr; + gboolean was_output = FALSE; + NMIPConfig * cfg4, *cfg6; + NMDhcpConfig * dhcp4, *dhcp6; + const char * base_hdr = _("Device details"); + GPtrArray * fields_in_section = NULL; + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) + fields_str = NMC_FIELDS_DEV_SHOW_SECTIONS_COMMON; + else if (g_ascii_strcasecmp(nmc->required_fields, "all") == 0) { + /* pass */ + } else + fields_str = nmc->required_fields; + + sections_array = + parse_output_fields(fields_str, + (const NMMetaAbstractInfo *const *) nmc_fields_dev_show_sections, + TRUE, + &fields_in_section, + &error); + if (error) { + g_string_printf(nmc->return_text, _("Error: 'device show': %s"), error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + + { + gs_unref_array GArray *out_indices = NULL; + gs_free char * header_name = NULL; + gs_free NmcOutputField *row = NULL; + int i; + + /* Main header (pretty only) */ + header_name = construct_header_name(base_hdr, nm_device_get_iface(device)); + + /* Lazy way to retrieve sorted array from 0 to the number of dev fields */ + out_indices = + parse_output_fields(NULL, + (const NMMetaAbstractInfo *const *) metagen_device_detail_general, + FALSE, + NULL, + NULL); + + row = g_new0(NmcOutputField, G_N_ELEMENTS(metagen_device_detail_general)); + for (i = 0; i < G_N_ELEMENTS(metagen_device_detail_general); i++) + row[i].info = (const NMMetaAbstractInfo *) &metagen_device_detail_general[i]; + + print_required_fields(&nmc->nmc_config, + &nmc->pager_data, + NMC_OF_FLAG_MAIN_HEADER_ONLY, + out_indices, + header_name, + 0, + row); + } + + /* Loop through the required sections and print them. */ + for (k = 0; k < sections_array->len; k++) { + int section_idx = g_array_index(sections_array, int, k); + char *section_fld = (char *) g_ptr_array_index(fields_in_section, k); + + if (NM_IN_SET(nmc->nmc_config.print_output, NMC_PRINT_NORMAL, NMC_PRINT_PRETTY) + && !nmc->nmc_config.multiline_output && was_output) + g_print("\n"); /* Print empty line between groups in tabular mode */ + + was_output = FALSE; + + state = nm_device_get_state(device); + + if (nmc_fields_dev_show_sections[section_idx]->nested == metagen_device_detail_general) { + gs_free char *f = section_fld ? g_strdup_printf("GENERAL.%s", section_fld) : NULL; + + nmc_print(&nmc->nmc_config, + (gpointer[]){device, NULL}, + NULL, + NULL, + NMC_META_GENERIC_GROUP("GENERAL", metagen_device_detail_general, N_("NAME")), + f, + NULL); + was_output = TRUE; + continue; + } + + if (nmc_fields_dev_show_sections[section_idx]->nested + == metagen_device_detail_capabilities) { + gs_free char *f = section_fld ? g_strdup_printf("CAPABILITIES.%s", section_fld) : NULL; + + nmc_print(&nmc->nmc_config, + (gpointer[]){device, NULL}, + NULL, + NULL, + NMC_META_GENERIC_GROUP("CAPABILITIES", + metagen_device_detail_capabilities, + N_("NAME")), + f, + NULL); + was_output = TRUE; + continue; + } + + if (nmc_fields_dev_show_sections[section_idx]->nested + == metagen_device_detail_interface_flags) { + gs_free char *f = + section_fld ? g_strdup_printf("INTERFACE-FLAGS.%s", section_fld) : NULL; + + nmc_print(&nmc->nmc_config, + (gpointer[]){device, NULL}, + NULL, + NULL, + NMC_META_GENERIC_GROUP("INTERFACE-FLAGS", + metagen_device_detail_interface_flags, + N_("NAME")), + f, + NULL); + was_output = TRUE; + continue; + } + + if (nmc_fields_dev_show_sections[section_idx]->nested + == metagen_device_detail_wifi_properties) { + if (NM_IS_DEVICE_WIFI(device)) { + gs_free char *f = + section_fld ? g_strdup_printf("WIFI-PROPERTIES.%s", section_fld) : NULL; + + nmc_print(&nmc->nmc_config, + (gpointer[]){device, NULL}, + NULL, + NULL, + NMC_META_GENERIC_GROUP("WIFI-PROPERTIES", + metagen_device_detail_wifi_properties, + N_("NAME")), + f, + NULL); + was_output = TRUE; + } + continue; + } + + /* Wireless specific information */ + if ((NM_IS_DEVICE_WIFI(device))) { + NMAccessPoint *active_ap = NULL; + const char * active_bssid = NULL; + + /* section AP */ + if (!g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[4]->name)) { + NMC_OUTPUT_DATA_DEFINE_SCOPED(out); + + if (state == NM_DEVICE_STATE_ACTIVATED) { + active_ap = nm_device_wifi_get_active_access_point(NM_DEVICE_WIFI(device)); + active_bssid = active_ap ? nm_access_point_get_bssid(active_ap) : NULL; + } + + tmpl = (const NMMetaAbstractInfo *const *) nmc_fields_dev_wifi_list; + out_indices = + parse_output_fields(section_fld ?: NMC_FIELDS_DEV_WIFI_LIST_FOR_DEV_LIST, + tmpl, + FALSE, + NULL, + NULL); + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_FIELD_NAMES); + g_ptr_array_add(out.output_data, arr); + + { + gs_unref_ptrarray GPtrArray *aps = NULL; + APInfo info = { + .nmc = nmc, + .index = 1, + .output_flags = NMC_OF_FLAG_SECTION_PREFIX, + .active_bssid = active_bssid, + .device = nm_device_get_iface(device), + .output_data = out.output_data, + }; + + aps = sort_access_points( + nm_device_wifi_get_access_points(NM_DEVICE_WIFI(device))); + g_ptr_array_foreach(aps, fill_output_access_point, &info); + } + + print_data_prepare_width(out.output_data); + print_data(&nmc->nmc_config, &nmc->pager_data, out_indices, NULL, 0, &out); + was_output = TRUE; + } + } + + if (nmc_fields_dev_show_sections[section_idx]->nested + == metagen_device_detail_wired_properties) { + if ((NM_IS_DEVICE_ETHERNET(device))) { + gs_free char *f = + section_fld ? g_strdup_printf("WIRED-PROPERTIES.%s", section_fld) : NULL; + + nmc_print(&nmc->nmc_config, + (gpointer[]){device, NULL}, + NULL, + NULL, + NMC_META_GENERIC_GROUP("WIRED-PROPERTIES", + metagen_device_detail_wired_properties, + N_("NAME")), + f, + NULL); + was_output = TRUE; + } + continue; + } + + /* IP configuration info */ + cfg4 = nm_device_get_ip4_config(device); + cfg6 = nm_device_get_ip6_config(device); + dhcp4 = nm_device_get_dhcp4_config(device); + dhcp6 = nm_device_get_dhcp6_config(device); + + /* IP4 */ + if (cfg4 + && !g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[8]->name)) + was_output = print_ip_config(cfg4, AF_INET, &nmc->nmc_config, section_fld); + + /* DHCP4 */ + if (dhcp4 + && !g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[9]->name)) + was_output = print_dhcp_config(dhcp4, AF_INET, &nmc->nmc_config, section_fld); + + /* IP6 */ + if (cfg6 + && !g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[10]->name)) + was_output = print_ip_config(cfg6, AF_INET6, &nmc->nmc_config, section_fld); + + /* DHCP6 */ + if (dhcp6 + && !g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[11]->name)) + was_output = print_dhcp_config(dhcp6, AF_INET6, &nmc->nmc_config, section_fld); + + /* Bond specific information */ + if (NM_IS_DEVICE_BOND(device)) { + if (!g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[12]->name)) + was_output = print_bond_bridge_info(device, + nmc, + nmc_fields_dev_show_sections[12]->name, + section_fld); + } + + /* Team specific information */ + if (NM_IS_DEVICE_TEAM(device)) { + if (!g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[13]->name)) + was_output = print_team_info(device, + nmc, + nmc_fields_dev_show_sections[13]->name, + section_fld); + } + + /* Bridge specific information */ + if (NM_IS_DEVICE_BRIDGE(device)) { + if (!g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[14]->name)) + was_output = print_bond_bridge_info(device, + nmc, + nmc_fields_dev_show_sections[14]->name, + section_fld); + } + + /* VLAN-specific information */ + if ((NM_IS_DEVICE_VLAN(device))) { + if (!g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[15]->name)) { + char *vlan_id_str = + g_strdup_printf("%u", nm_device_vlan_get_vlan_id(NM_DEVICE_VLAN(device))); + NMDevice *parent = nm_device_vlan_get_parent(NM_DEVICE_VLAN(device)); + NMC_OUTPUT_DATA_DEFINE_SCOPED(out); + + tmpl = (const NMMetaAbstractInfo *const *) nmc_fields_dev_show_vlan_prop; + out_indices = parse_output_fields(section_fld, tmpl, FALSE, NULL, NULL); + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_FIELD_NAMES); + g_ptr_array_add(out.output_data, arr); + + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_SECTION_PREFIX); + set_val_strc(arr, 0, nmc_fields_dev_show_sections[15]->name); /* "VLAN" */ + set_val_strc(arr, 1, parent ? nm_device_get_iface(parent) : NULL); + set_val_str(arr, 2, vlan_id_str); + g_ptr_array_add(out.output_data, arr); + + print_data_prepare_width(out.output_data); + print_data(&nmc->nmc_config, &nmc->pager_data, out_indices, NULL, 0, &out); + + was_output = TRUE; + } + } + + if (NM_IS_DEVICE_BT(device)) { + if (!g_ascii_strcasecmp(nmc_fields_dev_show_sections[section_idx]->name, + nmc_fields_dev_show_sections[16]->name)) { + NMC_OUTPUT_DATA_DEFINE_SCOPED(out); + + tmpl = (const NMMetaAbstractInfo *const *) nmc_fields_dev_show_bluetooth; + out_indices = parse_output_fields(section_fld, tmpl, FALSE, NULL, NULL); + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_FIELD_NAMES); + g_ptr_array_add(out.output_data, arr); + + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_SECTION_PREFIX); + set_val_strc(arr, 0, nmc_fields_dev_show_sections[16]->name); /* "BLUETOOTH" */ + set_val_str( + arr, + 1, + bluetooth_caps_to_string(nm_device_bt_get_capabilities(NM_DEVICE_BT(device)))); + g_ptr_array_add(out.output_data, arr); + + print_data_prepare_width(out.output_data); + print_data(&nmc->nmc_config, &nmc->pager_data, out_indices, NULL, 0, &out); + was_output = TRUE; + } + } + + if (nmc_fields_dev_show_sections[section_idx]->nested + == metagen_device_detail_connections) { + gs_free char *f = section_fld ? g_strdup_printf("CONNECTIONS.%s", section_fld) : NULL; + + nmc_print(&nmc->nmc_config, + (gpointer[]){device, NULL}, + NULL, + NULL, + NMC_META_GENERIC_GROUP("CONNECTIONS", + metagen_device_detail_connections, + N_("NAME")), + f, + NULL); + was_output = TRUE; + continue; + } + } + + if (sections_array) + g_array_free(sections_array, TRUE); + if (fields_in_section) + g_ptr_array_free(fields_in_section, TRUE); + + return TRUE; +} + +NMMetaColor +nmc_device_state_to_color(NMDevice *device) +{ + NMDeviceState state; + NMActiveConnection *ac; + + if (!device) + return NM_META_COLOR_DEVICE_UNKNOWN; + + ac = nm_device_get_active_connection(device); + if (ac + && NM_FLAGS_HAS(nm_active_connection_get_state_flags(ac), + NM_ACTIVATION_STATE_FLAG_EXTERNAL)) + return NM_META_COLOR_CONNECTION_EXTERNAL; + + state = nm_device_get_state(device); + if (state <= NM_DEVICE_STATE_UNAVAILABLE) + return NM_META_COLOR_DEVICE_UNAVAILABLE; + else if (state == NM_DEVICE_STATE_DISCONNECTED) + return NM_META_COLOR_DEVICE_DISCONNECTED; + else if (state >= NM_DEVICE_STATE_PREPARE && state <= NM_DEVICE_STATE_SECONDARIES) + return NM_META_COLOR_DEVICE_ACTIVATING; + else if (state == NM_DEVICE_STATE_ACTIVATED) + return NM_META_COLOR_DEVICE_ACTIVATED; + + return NM_META_COLOR_DEVICE_UNKNOWN; +} + +static void +do_devices_status(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + GError *error = NULL; + gs_free NMDevice **devices = NULL; + const char * fields_str = NULL; + + next_arg(nmc, &argc, &argv, NULL); + + if (nmc->complete) + return; + + if (argc) { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) + fields_str = "DEVICE,TYPE,STATE,CONNECTION"; + else if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "all") == 0) { + /* pass */ + } else + fields_str = nmc->required_fields; + + devices = nmc_get_devices_sorted(nmc->client); + + if (!nmc_print(&nmc->nmc_config, + (gpointer *) devices, + NULL, + N_("Status of devices"), + (const NMMetaAbstractInfo *const *) metagen_device_status, + fields_str, + &error)) { + g_string_printf(nmc->return_text, _("Error: 'device status': %s"), error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } +} + +static void +do_device_show(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gs_free_error GError *error = NULL; + + next_arg(nmc, &argc, &argv, NULL); + if (!nmc->mode_specified) + nmc->nmc_config_mutable.multiline_output = + TRUE; /* multiline mode is default for 'device show' */ + + if (argc) { + NMDevice *device; + + device = get_device(nmc, &argc, &argv, &error); + if (!device) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + + if (argc) { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (nmc->complete) + return; + + show_device_info(device, nmc); + } else { + NMDevice **devices = nmc_get_devices_sorted(nmc->client); + int i; + + /* nmc_do_cmd() should not call this with argc=0. */ + nm_assert(!nmc->complete); + + /* Show details for all devices */ + for (i = 0; devices[i]; i++) { + if (!show_device_info(devices[i], nmc)) + break; + if (devices[i + 1]) + g_print("\n"); /* Empty line */ + } + + g_free(devices); + } +} + +static gboolean +timeout_cb(gpointer user_data) +{ + /* Time expired -> exit nmcli */ + + NmCli *nmc = (NmCli *) user_data; + + g_string_printf(nmc->return_text, _("Error: Timeout %d sec expired."), nmc->timeout); + nmc->return_value = NMC_RESULT_ERROR_TIMEOUT_EXPIRED; + quit(); + return FALSE; +} + +static gboolean +progress_cb(gpointer user_data) +{ + NMDevice *device = (NMDevice *) user_data; + + nmc_terminal_show_progress(device ? gettext(nmc_device_state_to_string_with_external(device)) + : ""); + + return TRUE; +} + +typedef struct { + NmCli * nmc; + NMDevice * device; + NMActiveConnection *active; + char * specific_object; + bool hotspot : 1; + bool create : 1; +} AddAndActivateInfo; + +static AddAndActivateInfo * +add_and_activate_info_new(NmCli * nmc, + NMDevice * device, + gboolean hotspot, + gboolean create, + const char *specific_object) +{ + AddAndActivateInfo *info; + + info = g_slice_new(AddAndActivateInfo); + *info = (AddAndActivateInfo){ + .nmc = nmc, + .device = g_object_ref(device), + .hotspot = hotspot, + .create = create, + .specific_object = g_strdup(specific_object), + }; + return info; +} + +static void +add_and_activate_info_free(AddAndActivateInfo *info) +{ + g_object_unref(info->device); + g_clear_object(&info->active); + g_free(info->specific_object); + nm_g_slice_free(info); +} + +NM_AUTO_DEFINE_FCN0(AddAndActivateInfo *, + _nm_auto_free_add_and_activate_info, + add_and_activate_info_free); +#define nm_auto_free_add_and_activate_info nm_auto(_nm_auto_free_add_and_activate_info) + +static void +connected_state_cb(AddAndActivateInfo *info) +{ + NMDeviceState state; + NMDeviceStateReason reason; + NMActiveConnectionState ac_state; + + state = nm_device_get_state(info->device); + ac_state = nm_active_connection_get_state(info->active); + + if (ac_state == NM_ACTIVE_CONNECTION_STATE_ACTIVATING) + return; + + if (state == NM_DEVICE_STATE_ACTIVATED) { + nmc_terminal_erase_line(); + g_print(_("Device '%s' successfully activated with '%s'.\n"), + nm_device_get_iface(info->device), + nm_active_connection_get_uuid(info->active)); + + if (info->hotspot) + g_print( + _("Hint: \"nmcli dev wifi show-password\" shows the Wi-Fi name and password.\n")); + } else if (state <= NM_DEVICE_STATE_DISCONNECTED || state >= NM_DEVICE_STATE_DEACTIVATING) { + reason = nm_device_get_state_reason(info->device); + g_print(_("Error: Connection activation failed: (%d) %s.\n"), + reason, + gettext(nmc_device_reason_to_string(reason))); + } else { + return; + } + + g_signal_handlers_disconnect_by_func(info->active, G_CALLBACK(connected_state_cb), info); + g_signal_handlers_disconnect_by_func(info->device, G_CALLBACK(connected_state_cb), info); + add_and_activate_info_free(info); + + quit(); +} + +static void +add_and_activate_cb(GObject *client, GAsyncResult *result, gpointer user_data) +{ + nm_auto_free_add_and_activate_info AddAndActivateInfo *info = user_data; + NmCli * nmc = info->nmc; + gs_unref_object NMActiveConnection *active = NULL; + gs_free_error GError *error = NULL; + + if (info->create) + active = nm_client_add_and_activate_connection_finish(NM_CLIENT(client), result, &error); + else + active = nm_client_activate_connection_finish(NM_CLIENT(client), result, &error); + + if (error) { + if (info->hotspot) { + g_string_printf(nmc->return_text, + _("Error: Failed to setup a Wi-Fi hotspot: %s"), + error->message); + } else if (info->create) { + g_string_printf(nmc->return_text, + _("Error: Failed to add/activate new connection: %s"), + error->message); + } else { + g_string_printf(nmc->return_text, + _("Error: Failed to activate connection: %s"), + error->message); + } + nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION; + quit(); + return; + } + + if (nmc->nowait_flag) { + quit(); + return; + } + + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + progress_id = g_timeout_add(120, progress_cb, info->device); + + info->active = g_steal_pointer(&active); + g_signal_connect_swapped(info->device, "notify::state", G_CALLBACK(connected_state_cb), info); + g_signal_connect_swapped(info->active, "notify::state", G_CALLBACK(connected_state_cb), info); + connected_state_cb(g_steal_pointer(&info)); + + g_timeout_add_seconds(nmc->timeout, timeout_cb, nmc); /* Exit if timeout expires */ +} + +static void +create_connect_connection_for_device(AddAndActivateInfo *info) +{ + NMConnection * connection; + NMSettingConnection *s_con; + + /* Create new connection and tie it to the device */ + connection = nm_simple_connection_new(); + s_con = (NMSettingConnection *) nm_setting_connection_new(); + nm_connection_add_setting(connection, NM_SETTING(s_con)); + g_object_set(s_con, NM_SETTING_CONNECTION_ID, nm_device_get_iface(info->device), NULL); + + nm_client_add_and_activate_connection_async(info->nmc->client, + connection, + info->device, + NULL, + NULL, + add_and_activate_cb, + info); +} + +static void +connect_device_cb(GObject *client, GAsyncResult *result, gpointer user_data) +{ + nm_auto_free_add_and_activate_info AddAndActivateInfo *info = user_data; + NmCli * nmc = info->nmc; + gs_unref_object NMActiveConnection *active = NULL; + GError * error = NULL; + + active = nm_client_activate_connection_finish(NM_CLIENT(client), result, &error); + + if (error) { + /* If no connection existed for the device, create one and activate it */ + if (g_error_matches(error, NM_MANAGER_ERROR, NM_MANAGER_ERROR_UNKNOWN_CONNECTION)) { + info->create = TRUE; + create_connect_connection_for_device(g_steal_pointer(&info)); + return; + } + + g_string_printf(nmc->return_text, _("Error: Device activation failed: %s"), error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION; + quit(); + return; + } + + nm_assert(NM_IS_ACTIVE_CONNECTION(active)); + + if (nmc->nowait_flag) { + quit(); + return; + } + + if (nmc->secret_agent) { + NMRemoteConnection *connection = nm_active_connection_get_connection(active); + + nm_secret_agent_simple_enable(nmc->secret_agent, + nm_connection_get_path(NM_CONNECTION(connection))); + } + + info->active = g_steal_pointer(&active); + g_signal_connect_swapped(info->device, "notify::state", G_CALLBACK(connected_state_cb), info); + g_signal_connect_swapped(info->active, "notify::state", G_CALLBACK(connected_state_cb), info); + connected_state_cb(g_steal_pointer(&info)); + + /* Start timer not to loop forever if "notify::state" signal is not issued */ + g_timeout_add_seconds(nmc->timeout, timeout_cb, nmc); +} + +static void +do_device_connect(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice * device = NULL; + AddAndActivateInfo *info; + gs_free_error GError *error = NULL; + + /* Set default timeout for connect operation. */ + if (nmc->timeout == -1) + nmc->timeout = 90; + + next_arg(nmc, &argc, &argv, NULL); + device = get_device(nmc, &argc, &argv, &error); + if (!device) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + + if (*argv) { + g_string_printf(nmc->return_text, _("Error: extra argument not allowed: '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (nmc->complete) + return; + + /* + * Use nowait_flag instead of should_wait, because exiting has to be postponed + * till connect_device_cb() is called, giving NM time to check our permissions. + */ + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + /* Create secret agent */ + nmc->secret_agent = nm_secret_agent_simple_new("nmcli-connect"); + if (nmc->secret_agent) { + g_signal_connect(nmc->secret_agent, + NM_SECRET_AGENT_SIMPLE_REQUEST_SECRETS, + G_CALLBACK(nmc_secrets_requested), + nmc); + } + + info = add_and_activate_info_new(nmc, device, FALSE, FALSE, NULL); + + nm_client_activate_connection_async(nmc->client, + NULL, /* let NM find a connection automatically */ + device, + NULL, + NULL, + connect_device_cb, + info); + + /* Start progress indication */ + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + progress_id = g_timeout_add(120, progress_cb, device); +} + +typedef struct { + NmCli * nmc; + GSList * queue; + guint timeout_id; + gboolean cmd_disconnect; + GCancellable *cancellable; +} DeviceCbInfo; + +static void device_cb_info_finish(DeviceCbInfo *info, NMDevice *device); + +static gboolean +device_op_timeout_cb(gpointer user_data) +{ + DeviceCbInfo *info = user_data; + + timeout_cb(info->nmc); + device_cb_info_finish(info, NULL); + return G_SOURCE_REMOVE; +} + +static void +device_removed_cb(NMClient *client, NMDevice *device, DeviceCbInfo *info) +{ + /* Success: device has been removed. + * It can also happen when disconnecting a software device. + */ + if (!g_slist_find(info->queue, device)) + return; + + if (info->cmd_disconnect) + g_print(_("Device '%s' successfully disconnected.\n"), nm_device_get_iface(device)); + else + g_print(_("Device '%s' successfully removed.\n"), nm_device_get_iface(device)); + device_cb_info_finish(info, device); +} + +static void +disconnect_state_cb(NMDevice *device, GParamSpec *pspec, DeviceCbInfo *info) +{ + if (!g_slist_find(info->queue, device)) + return; + + if (nm_device_get_state(device) <= NM_DEVICE_STATE_DISCONNECTED) { + g_print(_("Device '%s' successfully disconnected.\n"), nm_device_get_iface(device)); + device_cb_info_finish(info, device); + } +} + +static void +destroy_queue_element(gpointer data) +{ + g_signal_handlers_disconnect_matched(data, + G_SIGNAL_MATCH_FUNC, + 0, + 0, + 0, + disconnect_state_cb, + NULL); + g_object_unref(data); +} + +static void +device_cb_info_finish(DeviceCbInfo *info, NMDevice *device) +{ + if (device) { + GSList *elem = g_slist_find(info->queue, device); + if (!elem) + return; + info->queue = g_slist_delete_link(info->queue, elem); + destroy_queue_element(device); + } else { + g_slist_free_full(info->queue, destroy_queue_element); + info->queue = NULL; + } + + if (info->queue) + return; + + if (info->timeout_id) + g_source_remove(info->timeout_id); + + g_signal_handlers_disconnect_by_func(info->nmc->client, device_removed_cb, info); + nm_clear_g_cancellable(&info->cancellable); + + g_slice_free(DeviceCbInfo, info); + quit(); +} + +static void +reapply_device_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NMDevice * device = NM_DEVICE(object); + DeviceCbInfo *info = (DeviceCbInfo *) user_data; + NmCli * nmc = info->nmc; + GError * error = NULL; + + if (!nm_device_reapply_finish(device, result, &error)) { + g_string_printf(nmc->return_text, + _("Error: Reapplying connection to device '%s' (%s) failed: %s"), + nm_device_get_iface(device), + nm_object_get_path(NM_OBJECT(device)), + error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_DEV_DISCONNECT; + device_cb_info_finish(info, device); + } else { + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + nmc_terminal_erase_line(); + g_print(_("Connection successfully reapplied to device '%s'.\n"), + nm_device_get_iface(device)); + device_cb_info_finish(info, device); + } +} + +static void +do_device_reapply(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice * device; + DeviceCbInfo *info = NULL; + gs_free_error GError *error = NULL; + + /* Set default timeout for reapply operation. */ + if (nmc->timeout == -1) + nmc->timeout = 10; + + next_arg(nmc, &argc, &argv, NULL); + device = get_device(nmc, &argc, &argv, &error); + if (!device) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + + if (argc) { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (nmc->complete) + return; + + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + info = g_slice_new0(DeviceCbInfo); + info->nmc = nmc; + info->queue = g_slist_prepend(info->queue, g_object_ref(device)); + + /* Now reapply the connection to the device */ + nm_device_reapply_async(device, NULL, 0, 0, NULL, reapply_device_cb, info); +} + +typedef struct { + NmCli *nmc; + int argc; + char **argv; +} ModifyInfo; + +static void +modify_info_free(ModifyInfo *info) +{ + g_strfreev(info->argv); + nm_g_slice_free(info); +} + +NM_AUTO_DEFINE_FCN_VOID0(ModifyInfo *, _auto_free_modify_info, modify_info_free); + +static void +modify_reapply_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NMDevice * device = NM_DEVICE(object); + nm_auto(_auto_free_modify_info) ModifyInfo *info = user_data; + NmCli * nmc = info->nmc; + GError * error = NULL; + + if (!nm_device_reapply_finish(device, result, &error)) { + g_string_printf(nmc->return_text, + _("Error: Reapplying connection to device '%s' (%s) failed: %s"), + nm_device_get_iface(device), + nm_object_get_path(NM_OBJECT(device)), + error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_DEV_DISCONNECT; + } else { + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + nmc_terminal_erase_line(); + g_print(_("Connection successfully reapplied to device '%s'.\n"), + nm_device_get_iface(device)); + } + + quit(); +} + +static void +modify_get_applied_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NMDevice * device = NM_DEVICE(object); + nm_auto(_auto_free_modify_info) ModifyInfo *info = user_data; + NmCli * nmc = info->nmc; + gs_free_error GError *error = NULL; + NMConnection * connection; + guint64 version_id; + int argc; + const char *const * argv; + + connection = nm_device_get_applied_connection_finish(device, result, &version_id, &error); + if (!connection) { + g_string_printf(nmc->return_text, + _("Error: Reading applied connection from device '%s' (%s) failed: %s"), + nm_device_get_iface(device), + nm_object_get_path(NM_OBJECT(device)), + error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + quit(); + return; + } + + argc = info->argc; + argv = (const char *const *) info->argv; + + if (!nmc_process_connection_properties(info->nmc, connection, &argc, &argv, TRUE, &error)) { + g_string_assign(nmc->return_text, error->message); + nmc->return_value = error->code; + quit(); + return; + } + + if (nmc->complete) { + quit(); + return; + } + + nm_device_reapply_async(device, + connection, + version_id, + 0, + NULL, + modify_reapply_cb, + g_steal_pointer(&info)); +} + +static void +do_device_modify(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice * device = NULL; + ModifyInfo * info; + gs_free_error GError *error = NULL; + + next_arg(nmc, &argc, &argv, NULL); + device = get_device(nmc, &argc, &argv, &error); + if (!device) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + + if (nmc->timeout == -1) + nmc->timeout = 10; + + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + info = g_slice_new(ModifyInfo); + *info = (ModifyInfo){ + .nmc = nmc, + .argc = argc, + .argv = nm_utils_strv_dup(argv, argc, TRUE), + }; + + nm_device_get_applied_connection_async(device, 0, NULL, modify_get_applied_cb, info); +} + +static void +disconnect_device_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NMDevice * device = NM_DEVICE(object); + DeviceCbInfo *info = (DeviceCbInfo *) user_data; + NmCli * nmc; + NMDeviceState state; + GError * error = NULL; + + if (!nm_device_disconnect_finish(device, result, &error)) { + if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + return; + nmc = info->nmc; + g_string_printf(nmc->return_text, _("Error: not all devices disconnected.")); + g_printerr(_("Error: Device '%s' (%s) disconnecting failed: %s\n"), + nm_device_get_iface(device), + nm_object_get_path(NM_OBJECT(device)), + error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_DEV_DISCONNECT; + device_cb_info_finish(info, device); + } else { + nmc = info->nmc; + state = nm_device_get_state(device); + if (nmc->nowait_flag || state <= NM_DEVICE_STATE_DISCONNECTED) { + /* Don't want to wait or device already disconnected */ + if (state <= NM_DEVICE_STATE_DISCONNECTED) { + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) + nmc_terminal_erase_line(); + g_print(_("Device '%s' successfully disconnected.\n"), nm_device_get_iface(device)); + } + device_cb_info_finish(info, device); + } + } +} + +static void +do_devices_disconnect(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice * device; + DeviceCbInfo *info = NULL; + GSList * queue, *iter; + + /* Set default timeout for disconnect operation. */ + if (nmc->timeout == -1) + nmc->timeout = 10; + + next_arg(nmc, &argc, &argv, NULL); + queue = get_device_list(nmc, argc, argv); + if (!queue) + return; + if (nmc->complete) + goto out; + queue = g_slist_reverse(queue); + + info = g_slice_new0(DeviceCbInfo); + info->nmc = nmc; + info->cmd_disconnect = TRUE; + info->cancellable = g_cancellable_new(); + if (nmc->timeout > 0) + info->timeout_id = g_timeout_add_seconds(nmc->timeout, device_op_timeout_cb, info); + + g_signal_connect(nmc->client, NM_CLIENT_DEVICE_REMOVED, G_CALLBACK(device_removed_cb), info); + + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + for (iter = queue; iter; iter = g_slist_next(iter)) { + device = iter->data; + + info->queue = g_slist_prepend(info->queue, g_object_ref(device)); + g_signal_connect(device, "notify::" NM_DEVICE_STATE, G_CALLBACK(disconnect_state_cb), info); + + /* Now disconnect the device */ + nm_device_disconnect_async(device, info->cancellable, disconnect_device_cb, info); + } + +out: + g_slist_free(queue); +} + +static void +delete_device_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NMDevice * device = NM_DEVICE(object); + DeviceCbInfo *info = (DeviceCbInfo *) user_data; + NmCli * nmc = info->nmc; + GError * error = NULL; + + if (!nm_device_delete_finish(device, result, &error)) { + g_string_printf(nmc->return_text, _("Error: not all devices deleted.")); + g_printerr(_("Error: Device '%s' (%s) deletion failed: %s\n"), + nm_device_get_iface(device), + nm_object_get_path(NM_OBJECT(device)), + error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + device_cb_info_finish(info, device); + } else { + g_print(_("Device '%s' successfully removed.\n"), nm_device_get_iface(device)); + device_cb_info_finish(info, device); + } +} + +static void +do_devices_delete(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice * device; + DeviceCbInfo *info = NULL; + GSList * queue, *iter; + + /* Set default timeout for delete operation. */ + if (nmc->timeout == -1) + nmc->timeout = 10; + + next_arg(nmc, &argc, &argv, NULL); + queue = get_device_list(nmc, argc, argv); + if (!queue) + return; + if (nmc->complete) + goto out; + queue = g_slist_reverse(queue); + + info = g_slice_new0(DeviceCbInfo); + info->nmc = nmc; + if (nmc->timeout > 0) + info->timeout_id = g_timeout_add_seconds(nmc->timeout, device_op_timeout_cb, info); + + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + for (iter = queue; iter; iter = g_slist_next(iter)) { + device = iter->data; + + info->queue = g_slist_prepend(info->queue, g_object_ref(device)); + + /* Now delete the device */ + nm_device_delete_async(device, NULL, delete_device_cb, info); + } + +out: + g_slist_free(queue); +} + +static void +do_device_set(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ +#define DEV_SET_AUTOCONNECT 0 +#define DEV_SET_MANAGED 1 + NMDevice *device = NULL; + int i; + struct { + int idx; + gboolean value; + } values[2] = { + [DEV_SET_AUTOCONNECT] = {-1}, + [DEV_SET_MANAGED] = {-1}, + }; + gs_free_error GError *error = NULL; + + next_arg(nmc, &argc, &argv, NULL); + if (argc >= 1 && g_strcmp0(*argv, "ifname") == 0) + next_arg(nmc, &argc, &argv, NULL); + + device = get_device(nmc, &argc, &argv, &error); + if (!device) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + + if (!argc) { + g_string_printf(nmc->return_text, _("Error: No property specified.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + i = 0; + do { + gboolean flag; + + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "managed", "autoconnect"); + + if (matches(*argv, "managed")) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, + _("Error: '%s' argument is missing."), + *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + if (argc == 1 && nmc->complete) + nmc_complete_bool(*argv); + if (!nmc_string_to_bool(*argv, &flag, &error)) { + g_string_printf(nmc->return_text, _("Error: 'managed': %s."), error->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + values[DEV_SET_MANAGED].idx = ++i; + values[DEV_SET_MANAGED].value = flag; + } else if (matches(*argv, "autoconnect")) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, + _("Error: '%s' argument is missing."), + *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + if (argc == 1 && nmc->complete) + nmc_complete_bool(*argv); + if (!nmc_string_to_bool(*argv, &flag, &error)) { + g_string_printf(nmc->return_text, _("Error: 'autoconnect': %s."), error->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + values[DEV_SET_AUTOCONNECT].idx = ++i; + values[DEV_SET_AUTOCONNECT].value = flag; + } else { + g_string_printf(nmc->return_text, _("Error: property '%s' is not known."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + } while (next_arg(nmc, &argc, &argv, NULL) == 0); + + if (nmc->complete) + return; + + /* when multiple properties are specified, set them in the order as they + * are specified on the command line. */ + if (values[DEV_SET_AUTOCONNECT].idx >= 0 && values[DEV_SET_MANAGED].idx >= 0 + && values[DEV_SET_MANAGED].idx < values[DEV_SET_AUTOCONNECT].idx) { + nm_device_set_managed(device, values[DEV_SET_MANAGED].value); + values[DEV_SET_MANAGED].idx = -1; + } + if (values[DEV_SET_AUTOCONNECT].idx >= 0) + nm_device_set_autoconnect(device, values[DEV_SET_AUTOCONNECT].value); + if (values[DEV_SET_MANAGED].idx >= 0) + nm_device_set_managed(device, values[DEV_SET_MANAGED].value); +} + +static void +device_state(NMDevice *device, GParamSpec *pspec, NmCli *nmc) +{ + gs_free char *str = NULL; + NMMetaColor color; + + color = nmc_device_state_to_color(device); + str = nmc_colorize(&nmc->nmc_config, + color, + "%s: %s\n", + nm_device_get_iface(device), + gettext(nmc_device_state_to_string_with_external(device))); + + g_print("%s", str); +} + +static void +device_ac(NMDevice *device, GParamSpec *pspec, NmCli *nmc) +{ + NMActiveConnection *ac = nm_device_get_active_connection(device); + const char * id = ac ? nm_active_connection_get_id(ac) : NULL; + + if (!id) + return; + + g_print(_("%s: using connection '%s'\n"), nm_device_get_iface(device), id); +} + +static void +device_watch(NmCli *nmc, NMDevice *device) +{ + nmc->should_wait++; + g_signal_connect(device, "notify::" NM_DEVICE_STATE, G_CALLBACK(device_state), nmc); + g_signal_connect(device, "notify::" NM_DEVICE_ACTIVE_CONNECTION, G_CALLBACK(device_ac), nmc); +} + +static void +device_unwatch(NmCli *nmc, NMDevice *device) +{ + g_signal_handlers_disconnect_by_func(device, device_state, nmc); + if (g_signal_handlers_disconnect_by_func(device, device_ac, nmc)) + nmc->should_wait--; + + /* Terminate if all the watched devices disappeared. */ + if (!nmc->should_wait) + quit(); +} + +static void +device_added(NMClient *client, NMDevice *device, NmCli *nmc) +{ + g_print(_("%s: device created\n"), nm_device_get_iface(device)); + device_watch(nmc, NM_DEVICE(device)); +} + +static void +device_removed(NMClient *client, NMDevice *device, NmCli *nmc) +{ + g_print(_("%s: device removed\n"), nm_device_get_iface(device)); + device_unwatch(nmc, device); +} + +static void +do_devices_monitor(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + if (nmc->complete) + return; + + next_arg(nmc, &argc, &argv, NULL); + if (argc == 0) { + /* No devices specified. Monitor all. */ + const GPtrArray *devices = nm_client_get_devices(nmc->client); + int i; + + for (i = 0; i < devices->len; i++) + device_watch(nmc, g_ptr_array_index(devices, i)); + + /* We'll watch the device additions too, never exit. */ + nmc->should_wait++; + g_signal_connect(nmc->client, NM_CLIENT_DEVICE_ADDED, G_CALLBACK(device_added), nmc); + } else { + GSList *queue = get_device_list(nmc, argc, argv); + GSList *iter; + + /* Monitor the specified devices. */ + for (iter = queue; iter; iter = g_slist_next(iter)) + device_watch(nmc, NM_DEVICE(iter->data)); + g_slist_free(queue); + } + + g_signal_connect(nmc->client, NM_CLIENT_DEVICE_REMOVED, G_CALLBACK(device_removed), nmc); +} + +/* + * Find a Wi-Fi device with 'iface' in 'devices' array. If 'iface' is NULL, + * the first Wi-Fi device is returned. 'idx' parameter is updated to the point + * where the function finished so that the function can be called repeatedly + * to get next matching device. + * Returns: found device or NULL + */ +static NMDevice * +find_wifi_device_by_iface(NMDevice **devices, const char *iface, int *idx) +{ + int i; + + for (i = idx ? *idx : 0; devices[i]; i++) { + const char *dev_iface = nm_device_get_iface(devices[i]); + + if (!NM_IS_DEVICE_WIFI(devices[i])) + continue; + + if (iface) { + /* If a iface was specified then use it. */ + if (g_strcmp0(dev_iface, iface) == 0) + break; + } else { + /* Else return the first Wi-Fi device. */ + break; + } + } + + if (idx) + *idx = i + 1; + return devices[i]; +} + +/* + * Find AP on 'device' according to 'bssid' and 'ssid' parameters. + * Returns: found AP or NULL + */ +static NMAccessPoint * +find_ap_on_device(NMDevice *device, const char *bssid, const char *ssid, gboolean complete) +{ + const GPtrArray *aps; + NMAccessPoint * ap = NULL; + int i; + + g_return_val_if_fail(NM_IS_DEVICE_WIFI(device), NULL); + + aps = nm_device_wifi_get_access_points(NM_DEVICE_WIFI(device)); + for (i = 0; i < aps->len; i++) { + NMAccessPoint *candidate_ap = g_ptr_array_index(aps, i); + + if (bssid) { + const char *candidate_bssid = nm_access_point_get_bssid(candidate_ap); + + if (!candidate_bssid) + continue; + + /* Compare BSSIDs */ + if (complete) { + if (g_str_has_prefix(candidate_bssid, bssid)) + g_print("%s\n", candidate_bssid); + } else if (strcmp(bssid, candidate_bssid) != 0) + continue; + } + + if (ssid) { + /* Parameter is SSID */ + GBytes *candidate_ssid; + char * ssid_tmp; + + candidate_ssid = nm_access_point_get_ssid(candidate_ap); + if (!candidate_ssid) + continue; + + ssid_tmp = nm_utils_ssid_to_utf8(g_bytes_get_data(candidate_ssid, NULL), + g_bytes_get_size(candidate_ssid)); + + /* Compare SSIDs */ + if (complete) { + if (g_str_has_prefix(ssid_tmp, ssid)) + g_print("%s\n", ssid_tmp); + } else if (strcmp(ssid, ssid_tmp) != 0) { + g_free(ssid_tmp); + continue; + } + g_free(ssid_tmp); + } + + if (complete) + continue; + + ap = candidate_ap; + break; + } + + return ap; +} + +static void +show_access_point_info(NMDeviceWifi *wifi, NmCli *nmc, NmcOutputData *out) +{ + NMAccessPoint * active_ap = NULL; + const char * active_bssid = NULL; + NmcOutputField *arr; + + if (nm_device_get_state(NM_DEVICE(wifi)) == NM_DEVICE_STATE_ACTIVATED) { + active_ap = nm_device_wifi_get_active_access_point(wifi); + active_bssid = active_ap ? nm_access_point_get_bssid(active_ap) : NULL; + } + + arr = nmc_dup_fields_array((const NMMetaAbstractInfo *const *) nmc_fields_dev_wifi_list, + NMC_OF_FLAG_MAIN_HEADER_ADD | NMC_OF_FLAG_FIELD_NAMES); + g_ptr_array_add(out->output_data, arr); + + { + gs_unref_ptrarray GPtrArray *aps = NULL; + APInfo info = { + .nmc = nmc, + .index = 1, + .output_flags = 0, + .active_bssid = active_bssid, + .device = nm_device_get_iface(NM_DEVICE(wifi)), + .output_data = out->output_data, + }; + + aps = sort_access_points(nm_device_wifi_get_access_points(wifi)); + g_ptr_array_foreach(aps, fill_output_access_point, &info); + } + + print_data_prepare_width(out->output_data); +} + +static void +wifi_print_aps(NMDeviceWifi * wifi, + NmCli * nmc, + GArray * _out_indices, + const NMMetaAbstractInfo *const *tmpl, + const char * bssid_user, + gboolean * bssid_found) +{ + NMAccessPoint * ap = NULL; + const GPtrArray *aps; + APInfo * info; + guint i; + NmcOutputField * arr; + const char * base_hdr = _("Wi-Fi scan list"); + NMC_OUTPUT_DATA_DEFINE_SCOPED(out); + gs_free char * header_name = NULL; + static gboolean empty_line = FALSE; + + if (empty_line) + g_print("\n"); /* Empty line between devices' APs */ + + /* Main header name */ + header_name = construct_header_name(base_hdr, nm_device_get_iface(NM_DEVICE(wifi))); + + out_indices = g_array_ref(_out_indices); + + if (bssid_user) { + /* Specific AP requested - list only that */ + aps = nm_device_wifi_get_access_points(wifi); + for (i = 0; i < aps->len; i++) { + NMAccessPoint *candidate_ap = g_ptr_array_index(aps, i); + + if (nm_utils_hwaddr_matches(bssid_user, + -1, + nm_access_point_get_bssid(candidate_ap), + -1)) + ap = candidate_ap; + } + if (ap) { + /* Add headers (field names) */ + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_MAIN_HEADER_ADD | NMC_OF_FLAG_FIELD_NAMES); + g_ptr_array_add(out.output_data, arr); + + info = g_malloc0(sizeof(APInfo)); + info->nmc = nmc; + info->index = 1; + info->output_flags = 0; + info->active_bssid = NULL; + info->device = nm_device_get_iface(NM_DEVICE(wifi)); + info->output_data = out.output_data; + + fill_output_access_point(ap, info); + + print_data_prepare_width(out.output_data); + print_data(&nmc->nmc_config, &nmc->pager_data, out_indices, header_name, 0, &out); + g_free(info); + + *bssid_found = TRUE; + empty_line = TRUE; + } + } else { + show_access_point_info(wifi, nmc, &out); + print_data(&nmc->nmc_config, &nmc->pager_data, out_indices, header_name, 0, &out); + empty_line = TRUE; + } +} + +static gint64 +_device_wifi_get_last_scan(NMDeviceWifi *wifi) +{ + gint64 timestamp; + + timestamp = nm_device_wifi_get_last_scan(wifi); + if (timestamp == -1) + return G_MININT64; + return timestamp; +} + +typedef struct { + NmCli * nmc; + NMDevice ** devices; + const NMMetaAbstractInfo *const *tmpl; + char * bssid_user; + GArray * out_indices; + gint64 rescan_cutoff_msec; + guint pending; +} ScanInfo; + +typedef struct { + ScanInfo * scan_info; + NMDeviceWifi *wifi; + gulong last_scan_id; + guint timeout_id; + GCancellable *scan_cancellable; +} WifiListData; + +static void +wifi_list_finish(WifiListData *wifi_list_data, gboolean force_finished) +{ + ScanInfo *scan_info = wifi_list_data->scan_info; + NmCli * nmc = scan_info->nmc; + gboolean bssid_found = FALSE; + guint i; + + if (!force_finished + && scan_info->rescan_cutoff_msec > _device_wifi_get_last_scan(wifi_list_data->wifi)) { + /* wait longer... */ + return; + } + + nm_clear_g_signal_handler(wifi_list_data->wifi, &wifi_list_data->last_scan_id); + nm_clear_g_source(&wifi_list_data->timeout_id); + nm_clear_g_cancellable(&wifi_list_data->scan_cancellable); + nm_g_slice_free(wifi_list_data); + + if (--scan_info->pending > 0) + return; + + for (i = 0; scan_info->devices[i]; i++) { + wifi_print_aps(NM_DEVICE_WIFI(scan_info->devices[i]), + nmc, + scan_info->out_indices, + scan_info->tmpl, + scan_info->bssid_user, + &bssid_found); + } + + if (scan_info->bssid_user && !bssid_found) { + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + g_string_printf(nmc->return_text, + _("Error: Access point with bssid '%s' not found."), + scan_info->bssid_user); + } + + for (i = 0; scan_info->devices[i]; i++) + g_object_unref(scan_info->devices[i]); + g_free(scan_info->devices); + g_array_unref(scan_info->out_indices); + g_free(scan_info->bssid_user); + nm_g_slice_free(scan_info); + + nmc->should_wait--; + g_main_loop_quit(loop); +} + +static void +wifi_last_scan_updated(GObject *gobject, GParamSpec *pspec, gpointer user_data) +{ + wifi_list_finish(user_data, FALSE); +} + +static void wifi_list_rescan_cb(GObject *source_object, GAsyncResult *res, gpointer user_data); + +static void +wifi_list_rescan_retry_cb(gpointer user_data, GCancellable *cancellable) +{ + WifiListData *wifi_list_data; + + if (g_cancellable_is_cancelled(cancellable)) + return; + + wifi_list_data = user_data; + nm_device_wifi_request_scan_async(wifi_list_data->wifi, + wifi_list_data->scan_cancellable, + wifi_list_rescan_cb, + wifi_list_data); +} + +static void +wifi_list_rescan_cb(GObject *source_object, GAsyncResult *res, gpointer user_data) +{ + NMDeviceWifi *wifi = NM_DEVICE_WIFI(source_object); + gs_free_error GError *error = NULL; + WifiListData * wifi_list_data; + gboolean force_finished; + gboolean done; + + nm_device_wifi_request_scan_finish(wifi, res, &error); + if (nm_utils_error_is_cancelled(error)) + return; + + wifi_list_data = user_data; + + if (g_error_matches(error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_NOT_ALLOWED)) { + if (nm_device_get_state(NM_DEVICE(wifi)) < NM_DEVICE_STATE_DISCONNECTED) { + /* the device is either unmanaged or unavailable. + * + * If it's unmanaged, we don't expect any scan result and are done. + * If it's unavailable, that usually means that we wait for wpa_supplicant + * to start. In that case, also quit (without scan results). */ + force_finished = TRUE; + done = TRUE; + } else { + /* This likely means that scanning is already in progress. There's + * a good chance we'll get updated results soon; wait for them. + * + * But also, NetworkManager ratelimits (and rejects requests). That + * means, possibly we were just ratelimited, so waiting will not lead + * to a new scan result. Instead, repeatedly ask new scans... */ + nm_utils_invoke_on_timeout(1000, + wifi_list_data->scan_cancellable, + wifi_list_rescan_retry_cb, + wifi_list_data); + force_finished = FALSE; + done = FALSE; + } + } else if (error) { + force_finished = TRUE; + done = TRUE; + } else { + force_finished = FALSE; + done = TRUE; + } + + if (done) + g_clear_object(&wifi_list_data->scan_cancellable); + wifi_list_finish(wifi_list_data, force_finished); +} + +static gboolean +wifi_list_scan_timeout(gpointer user_data) +{ + WifiListData *wifi_list_data = user_data; + + wifi_list_data->timeout_id = 0; + wifi_list_finish(user_data, TRUE); + return G_SOURCE_REMOVE; +} + +static void +complete_aps(NMDevice ** devices, + const char *ifname, + const char *bssid_prefix, + const char *ssid_prefix) +{ + int devices_idx = 0; + NMDevice *device; + + while ((device = find_wifi_device_by_iface(devices, ifname, &devices_idx))) + find_ap_on_device(device, bssid_prefix, ssid_prefix, TRUE); +} + +void +nmc_complete_bssid(NMClient *client, const char *ifname, const char *bssid_prefix) +{ + gs_free NMDevice **devices = NULL; + + devices = nmc_get_devices_sorted(client); + complete_aps(devices, ifname, bssid_prefix, NULL); +} + +static void +do_device_wifi_list(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + GError * error = NULL; + NMDevice * device = NULL; + const char *ifname = NULL; + const char *bssid_user = NULL; + const char *rescan = NULL; + gs_free NMDevice ** devices = NULL; + const char * fields_str = NULL; + const NMMetaAbstractInfo *const *tmpl; + gs_unref_array GArray *out_indices = NULL; + int option; + gint64 rescan_cutoff_msec; + ScanInfo * scan_info = NULL; + gboolean ifname_handled; + NMDevice * ifname_handled_candidate; + guint i, j; + + devices = nmc_get_devices_sorted(nmc->client); + + while ((option = next_arg(nmc, &argc, &argv, "ifname", "hwaddr", "bssid", "--rescan", NULL)) + > 0) { + switch (option) { + case 1: /* ifname */ + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + ifname = *argv; + if (argc == 1 && nmc->complete) + complete_device(devices, ifname, TRUE); + break; + case 2: /* hwaddr is deprecated and will be removed later */ + case 3: /* bssid */ + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + bssid_user = *argv; + if (argc == 1 && nmc->complete) + complete_aps(devices, NULL, bssid_user, NULL); + break; + case 4: /* --rescan */ + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + rescan = *argv; + if (argc == 1 && nmc->complete) + nmc_complete_strings(rescan, "auto", "no", "yes"); + break; + default: + nm_assert_not_reached(); + break; + } + } + + if (nmc->complete) + return; + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) + fields_str = NMC_FIELDS_DEV_WIFI_LIST_COMMON; + else if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "all") == 0) { + /* pass */ + } else + fields_str = nmc->required_fields; + + tmpl = (const NMMetaAbstractInfo *const *) nmc_fields_dev_wifi_list; + out_indices = parse_output_fields(fields_str, tmpl, FALSE, NULL, &error); + + if (error) { + g_string_printf(nmc->return_text, _("Error: 'device wifi': %s"), error->message); + g_error_free(error); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (argc) { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (NM_IN_STRSET(rescan, NULL, "auto")) + rescan_cutoff_msec = nm_utils_get_timestamp_msec() - (30 * NM_UTILS_MSEC_PER_SEC); + else if (nm_streq(rescan, "no")) + rescan_cutoff_msec = G_MININT64; + else if (nm_streq(rescan, "yes")) + rescan_cutoff_msec = nm_utils_get_timestamp_msec(); + else { + g_string_printf(nmc->return_text, + _("Error: invalid rescan argument: '%s' not among [auto, no, yes]"), + rescan); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + ifname_handled = (ifname == NULL); + ifname_handled_candidate = NULL; + + j = 0; + for (i = 0; devices[i]; i++) { + const char *dev_iface; + + device = devices[i]; + dev_iface = nm_device_get_iface(device); + + if (ifname) { + if (!nm_streq0(ifname, dev_iface)) + continue; + if (!NM_IS_DEVICE_WIFI(device)) { + if (nm_device_get_device_type(device) == NM_DEVICE_TYPE_GENERIC + && nm_streq0(nm_device_get_type_description(device), "wifi")) + ifname_handled_candidate = device; + else if (!ifname_handled_candidate) + ifname_handled_candidate = device; + continue; + } + ifname_handled = TRUE; + } else { + if (!NM_IS_DEVICE_WIFI(device)) + continue; + } + + devices[j++] = device; + } + devices[j] = NULL; + + if (!ifname_handled) { + if (!ifname_handled_candidate) { + g_string_printf(nmc->return_text, _("Error: Device '%s' not found."), ifname); + } else if (nm_device_get_device_type(ifname_handled_candidate) == NM_DEVICE_TYPE_GENERIC + && nm_streq0(nm_device_get_type_description(ifname_handled_candidate), "wifi")) { + g_string_printf(nmc->return_text, + _("Error: Device '%s' was not recognized as a Wi-Fi device, check " + "NetworkManager Wi-Fi plugin."), + ifname); + } else { + g_string_printf(nmc->return_text, + _("Error: Device '%s' is not a Wi-Fi device."), + ifname); + } + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + return; + } + + if (!devices[0]) { + if (bssid_user) { + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + g_string_printf(nmc->return_text, + _("Error: Access point with bssid '%s' not found."), + bssid_user); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + } + return; + } + + scan_info = g_slice_new(ScanInfo); + *scan_info = (ScanInfo){ + .out_indices = g_array_ref(out_indices), + .tmpl = tmpl, + .bssid_user = g_strdup(bssid_user), + .nmc = nmc, + .rescan_cutoff_msec = rescan_cutoff_msec, + }; + + for (i = 0; devices[i]; i++) + g_object_ref(devices[i]); + + for (i = 0; devices[i]; i++) { + NMDeviceWifi *wifi = NM_DEVICE_WIFI(devices[i]); + WifiListData *wifi_list_data; + int timeout_msec; + + if (rescan_cutoff_msec <= _device_wifi_get_last_scan(wifi)) + timeout_msec = 0; + else + timeout_msec = 15000; + + wifi_list_data = g_slice_new(WifiListData); + *wifi_list_data = (WifiListData){ + .wifi = wifi, + .scan_info = scan_info, + .timeout_id = g_timeout_add(timeout_msec, wifi_list_scan_timeout, wifi_list_data), + }; + + scan_info->pending++; + + if (timeout_msec > 0) { + wifi_list_data->last_scan_id = g_signal_connect(wifi, + "notify::" NM_DEVICE_WIFI_LAST_SCAN, + G_CALLBACK(wifi_last_scan_updated), + wifi_list_data), + wifi_list_data->scan_cancellable = g_cancellable_new(), + nm_device_wifi_request_scan_async(wifi, + wifi_list_data->scan_cancellable, + wifi_list_rescan_cb, + wifi_list_data); + } + } + + scan_info->devices = g_steal_pointer(&devices); + + nmc->should_wait++; +} + +static void +activate_update2_cb(GObject *source_object, GAsyncResult *res, gpointer user_data) +{ + NMRemoteConnection *remote_con = NM_REMOTE_CONNECTION(source_object); + AddAndActivateInfo *info = user_data; + NmCli * nmc = info->nmc; + gs_unref_variant GVariant *ret = NULL; + GError * error = NULL; + + ret = nm_remote_connection_update2_finish(remote_con, res, &error); + + if (!ret) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + g_error_free(error); + quit(); + add_and_activate_info_free(info); + return; + } + + nm_client_activate_connection_async(nmc->client, + NM_CONNECTION(remote_con), + info->device, + info->specific_object, + NULL, + add_and_activate_cb, + info); +} + +static void +save_and_activate_connection(NmCli * nmc, + NMDevice * device, + NMConnection *connection, + gboolean hotspot, + const char * specific_object) +{ + AddAndActivateInfo *info; + + info = add_and_activate_info_new(nmc, + device, + hotspot, + !NM_IS_REMOTE_CONNECTION(connection), + specific_object); + + if (NM_IS_REMOTE_CONNECTION(connection)) { + nm_remote_connection_update2(NM_REMOTE_CONNECTION(connection), + nm_connection_to_dbus(connection, NM_CONNECTION_SERIALIZE_ALL), + NM_SETTINGS_UPDATE2_FLAG_BLOCK_AUTOCONNECT, + NULL, + NULL, + activate_update2_cb, + info); + } else { + nm_client_add_and_activate_connection_async(nmc->client, + connection, + info->device, + info->specific_object, + NULL, + add_and_activate_cb, + info); + } +} + +static void +do_device_wifi_connect(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice * device = NULL; + NMAccessPoint * ap = NULL; + NM80211ApFlags ap_flags; + NM80211ApSecurityFlags ap_wpa_flags; + NM80211ApSecurityFlags ap_rsn_flags; + gs_unref_object NMConnection *connection = NULL; + NMSettingConnection * s_con; + NMSettingWireless * s_wifi; + const char * param_user = NULL; + const char * ifname = NULL; + const char * bssid = NULL; + const char * password = NULL; + const char * con_name = NULL; + gboolean private = FALSE; + gboolean hidden = FALSE; + gboolean wep_passphrase = FALSE; + GByteArray *bssid1_arr = NULL; + GByteArray *bssid2_arr = NULL; + gs_free NMDevice **devices = NULL; + int devices_idx; + char * ssid_ask = NULL; + char * passwd_ask = NULL; + const GPtrArray * avail_cons; + gboolean name_match = FALSE; + int i; + + /* Set default timeout waiting for operation completion. */ + if (nmc->timeout == -1) + nmc->timeout = 90; + + devices = nmc_get_devices_sorted(nmc->client); + + next_arg(nmc, &argc, &argv, NULL); + /* Get the first compulsory argument (SSID or BSSID) */ + if (argc > 0) { + param_user = *argv; + bssid1_arr = nm_utils_hwaddr_atoba(param_user, ETH_ALEN); + + if (argc == 1 && nmc->complete) + complete_aps(devices, NULL, param_user, param_user); + + next_arg(nmc, &argc, &argv, NULL); + } else { + /* nmc_do_cmd() should not call this with argc=0. */ + nm_assert(!nmc->complete); + + if (nmc->ask) { + ssid_ask = nmc_readline(&nmc->nmc_config, _("SSID or BSSID: ")); + param_user = ssid_ask ?: ""; + bssid1_arr = nm_utils_hwaddr_atoba(param_user, ETH_ALEN); + } + if (!ssid_ask) { + g_string_printf(nmc->return_text, _("Error: SSID or BSSID are missing.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + } + + /* Get the rest of the parameters */ + while (argc > 0) { + if (argc == 1 && nmc->complete) { + nmc_complete_strings(*argv, + "ifname", + "bssid", + "password", + "wep-key-type", + "name", + "private", + "hidden"); + } + + if (strcmp(*argv, "ifname") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + ifname = *argv; + if (argc == 1 && nmc->complete) + complete_device(devices, ifname, TRUE); + } else if (strcmp(*argv, "bssid") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + bssid = *argv; + if (argc == 1 && nmc->complete) + complete_aps(devices, NULL, bssid, NULL); + bssid2_arr = nm_utils_hwaddr_atoba(bssid, ETH_ALEN); + if (!bssid2_arr) { + g_string_printf(nmc->return_text, + _("Error: bssid argument value '%s' is not a valid BSSID."), + bssid); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + } else if (strcmp(*argv, "password") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + password = *argv; + } else if (strcmp(*argv, "wep-key-type") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "key", "phrase"); + if (strcmp(*argv, "key") == 0) + wep_passphrase = FALSE; + else if (strcmp(*argv, "phrase") == 0) + wep_passphrase = TRUE; + else { + g_string_printf( + nmc->return_text, + _("Error: wep-key-type argument value '%s' is invalid, use 'key' or 'phrase'."), + *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + } else if (strcmp(*argv, "name") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + con_name = *argv; + } else if (strcmp(*argv, "private") == 0) { + GError *err_tmp = NULL; + + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + if (argc == 1 && nmc->complete) + nmc_complete_bool(*argv); + if (!nmc_string_to_bool(*argv, &private, &err_tmp)) { + g_string_printf(nmc->return_text, + _("Error: %s: %s."), + *(argv - 1), + err_tmp->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + g_clear_error(&err_tmp); + goto finish; + } + } else if (strcmp(*argv, "hidden") == 0) { + GError *err_tmp = NULL; + + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + if (argc == 1 && nmc->complete) + nmc_complete_bool(*argv); + if (!nmc_string_to_bool(*argv, &hidden, &err_tmp)) { + g_string_printf(nmc->return_text, + _("Error: %s: %s."), + *(argv - 1), + err_tmp->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + g_clear_error(&err_tmp); + goto finish; + } + } else if (!nmc->complete) { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + + next_arg(nmc, &argc, &argv, NULL); + } + + if (nmc->complete) + goto finish; + + /* Verify SSID/BSSID parameters */ + if (bssid1_arr && bssid2_arr && memcmp(bssid1_arr->data, bssid2_arr->data, ETH_ALEN)) { + g_string_printf(nmc->return_text, + _("Error: BSSID to connect to (%s) differs from bssid argument (%s)."), + param_user, + bssid); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + if (!bssid1_arr && strlen(param_user) > 32) { + g_string_printf(nmc->return_text, + _("Error: Parameter '%s' is neither SSID nor BSSID."), + param_user); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + goto finish; + } + + /* Find a device to activate the connection on */ + devices_idx = 0; + device = find_wifi_device_by_iface(devices, ifname, &devices_idx); + + if (!device) { + if (ifname) + g_string_printf(nmc->return_text, + _("Error: Device '%s' is not a Wi-Fi device."), + ifname); + else + g_string_printf(nmc->return_text, _("Error: No Wi-Fi device found.")); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + goto finish; + } + + /* For hidden SSID first scan it so that NM learns about the AP */ + if (hidden) { + GVariantBuilder builder, array_builder; + GVariant * options; + GError * scan_err = NULL; + + g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); + g_variant_builder_init(&array_builder, G_VARIANT_TYPE("aay")); + g_variant_builder_add(&array_builder, + "@ay", + nm_g_variant_new_ay((const guint8 *) param_user, strlen(param_user))); + g_variant_builder_add(&builder, "{sv}", "ssids", g_variant_builder_end(&array_builder)); + options = g_variant_builder_end(&builder); + + nm_device_wifi_request_scan_options(NM_DEVICE_WIFI(device), options, NULL, &scan_err); + if (scan_err) { + g_string_printf(nmc->return_text, + _("Error: Failed to scan hidden SSID: %s."), + scan_err->message); + g_clear_error(&scan_err); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + goto finish; + } + } + + /* Find an AP to connect to */ + ap = find_ap_on_device(device, + bssid1_arr ? param_user : bssid, + bssid1_arr ? NULL : param_user, + FALSE); + if (!ap && !ifname) { + NMDevice *dev; + + /* AP not found, ifname was not specified, so try finding the AP on another device. */ + while ((dev = find_wifi_device_by_iface(devices, NULL, &devices_idx)) != NULL) { + ap = find_ap_on_device(dev, + bssid1_arr ? param_user : bssid, + bssid1_arr ? NULL : param_user, + FALSE); + if (ap) { + device = dev; + break; + } + } + } + + if (!ap) { + if (!bssid1_arr) + g_string_printf(nmc->return_text, + _("Error: No network with SSID '%s' found."), + param_user); + else + g_string_printf(nmc->return_text, + _("Error: No access point with BSSID '%s' found."), + param_user); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + goto finish; + } + + avail_cons = nm_device_get_available_connections(device); + for (i = 0; i < avail_cons->len; i++) { + NMConnection *avail_con = g_ptr_array_index(avail_cons, i); + const char * id = nm_connection_get_id(NM_CONNECTION(avail_con)); + + if (con_name) { + if (!id || strcmp(id, con_name)) + continue; + + name_match = TRUE; + } + + if (nm_access_point_connection_valid(ap, NM_CONNECTION(avail_con))) { + /* ap has been checked against bssid1, bssid2 and the ssid + * and now avail_con has been checked against ap. + */ + connection = g_object_ref(avail_con); + break; + } + } + + if (name_match && !connection) { + g_string_printf(nmc->return_text, + _("Error: Connection '%s' exists but properties don't match."), + con_name); + nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND; + goto finish; + } + + if (!connection) { + /* If there are some connection data from user, create a connection and + * fill them into proper settings. */ + if (con_name || private || bssid2_arr || hidden) + connection = nm_simple_connection_new(); + + if (con_name || private) { + s_con = (NMSettingConnection *) nm_setting_connection_new(); + nm_connection_add_setting(connection, NM_SETTING(s_con)); + + /* Set user provided connection name */ + if (con_name) + g_object_set(s_con, NM_SETTING_CONNECTION_ID, con_name, NULL); + + /* Connection will only be visible to this user when 'private' is specified */ + if (private) + nm_setting_connection_add_permission(s_con, + NM_SETTINGS_CONNECTION_PERMISSION_USER, + g_get_user_name() ?: "", + NULL); + } + if (bssid2_arr || hidden) { + s_wifi = (NMSettingWireless *) nm_setting_wireless_new(); + nm_connection_add_setting(connection, NM_SETTING(s_wifi)); + + /* 'bssid' parameter is used to restrict the connection only to the BSSID */ + if (bssid2_arr) + g_object_set(s_wifi, NM_SETTING_WIRELESS_BSSID, bssid2_arr, NULL); + + /* 'hidden' parameter is used to indicate that SSID is not broadcasted */ + if (hidden) { + GBytes *ssid = g_bytes_new(param_user, strlen(param_user)); + + g_object_set(s_wifi, + NM_SETTING_WIRELESS_SSID, + ssid, + NM_SETTING_WIRELESS_HIDDEN, + hidden, + NULL); + g_bytes_unref(ssid); + + /* Warn when the provided AP identifier looks like BSSID instead of SSID */ + if (bssid1_arr) + g_printerr(_("Warning: '%s' should be SSID for hidden APs; but it looks like a " + "BSSID.\n"), + param_user); + } + } + } + + /* handle password */ + ap_flags = nm_access_point_get_flags(ap); + ap_wpa_flags = nm_access_point_get_wpa_flags(ap); + ap_rsn_flags = nm_access_point_get_rsn_flags(ap); + + /* Set password for WEP or WPA-PSK. */ + if ((ap_flags & NM_802_11_AP_FLAGS_PRIVACY) + || (ap_wpa_flags != NM_802_11_AP_SEC_NONE + && !NM_FLAGS_ANY(ap_wpa_flags, + NM_802_11_AP_SEC_KEY_MGMT_OWE | NM_802_11_AP_SEC_KEY_MGMT_OWE_TM)) + || (ap_rsn_flags != NM_802_11_AP_SEC_NONE + && !NM_FLAGS_ANY(ap_rsn_flags, + NM_802_11_AP_SEC_KEY_MGMT_OWE | NM_802_11_AP_SEC_KEY_MGMT_OWE_TM))) { + const char * con_password = NULL; + NMSettingWirelessSecurity *s_wsec = NULL; + + if (connection) { + s_wsec = nm_connection_get_setting_wireless_security(connection); + if (s_wsec) { + if (ap_wpa_flags == NM_802_11_AP_SEC_NONE + && ap_rsn_flags == NM_802_11_AP_SEC_NONE) { + /* WEP */ + con_password = nm_setting_wireless_security_get_wep_key(s_wsec, 0); + } else if ((ap_wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) + || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) + || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_SAE)) { + /* WPA PSK */ + con_password = nm_setting_wireless_security_get_psk(s_wsec); + } + } + } + + /* Ask for missing password when one is expected and '--ask' is used */ + if (!password && !con_password && nmc->ask) { + password = passwd_ask = + nmc_readline_echo(&nmc->nmc_config, nmc->nmc_config.show_secrets, _("Password: ")); + } + + if (password) { + if (!connection) + connection = nm_simple_connection_new(); + if (!s_wsec) { + s_wsec = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new(); + nm_connection_add_setting(connection, NM_SETTING(s_wsec)); + } + + if (ap_wpa_flags == NM_802_11_AP_SEC_NONE && ap_rsn_flags == NM_802_11_AP_SEC_NONE) { + /* WEP */ + nm_setting_wireless_security_set_wep_key(s_wsec, 0, password); + g_object_set(G_OBJECT(s_wsec), + NM_SETTING_WIRELESS_SECURITY_WEP_KEY_TYPE, + wep_passphrase ? NM_WEP_KEY_TYPE_PASSPHRASE : NM_WEP_KEY_TYPE_KEY, + NULL); + } else if ((ap_wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) + || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) + || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_SAE)) { + /* WPA PSK */ + g_object_set(s_wsec, NM_SETTING_WIRELESS_SECURITY_PSK, password, NULL); + } + } + } + // FIXME: Creating WPA-Enterprise connections is not supported yet. + // We are not able to determine and fill all the parameters for + // 802.1X authentication automatically without user providing + // the data. Adding nmcli options for the 8021x setting would + // clutter the command. However, that could be solved later by + // implementing add/edit connections support for nmcli. + + /* nowait_flag indicates user input. should_wait says whether quit in start(). + * We have to delay exit after add_and_activate_cb() is called, even if + * the user doesn't want to wait, in order to give NM time to check our + * permissions. */ + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + save_and_activate_connection(nmc, device, connection, FALSE, nm_object_get_path(NM_OBJECT(ap))); + +finish: + if (bssid1_arr) + g_byte_array_free(bssid1_arr, TRUE); + if (bssid2_arr) + g_byte_array_free(bssid2_arr, TRUE); + g_free(ssid_ask); + nm_free_secret(passwd_ask); +} + +static GBytes * +generate_ssid_for_hotspot(void) +{ + GBytes *ssid_bytes; + char * ssid = NULL; + + ssid = g_strdup_printf("Hotspot-%s", g_get_host_name()); + if (strlen(ssid) > 32) + ssid[32] = '\0'; + ssid_bytes = g_bytes_new(ssid, strlen(ssid)); + g_free(ssid); + + return ssid_bytes; +} + +#define WPA_PASSKEY_SIZE 8 +static void +generate_wpa_key(char *key, size_t len) +{ + guint i; + + g_return_if_fail(key); + g_return_if_fail(len > WPA_PASSKEY_SIZE); + + /* generate a 8-chars ASCII WPA key */ + for (i = 0; i < WPA_PASSKEY_SIZE; i++) { + int c; + c = g_random_int_range(33, 126); + /* too many non alphanumeric characters are hard to remember for humans */ + while (!g_ascii_isalnum(c)) + c = g_random_int_range(33, 126); + + key[i] = (char) c; + } + key[WPA_PASSKEY_SIZE] = '\0'; +} + +static void +generate_wep_key(char *key, size_t len) +{ + int i; + const char *hexdigits = "0123456789abcdef"; + + g_return_if_fail(key); + g_return_if_fail(len > 10); + + /* generate a 10-digit hex WEP key */ + for (i = 0; i < 10; i++) { + int digit; + digit = g_random_int_range(0, 16); + key[i] = hexdigits[digit]; + } + key[10] = '\0'; +} + +static gboolean +set_wireless_security_for_hotspot(NMSettingWirelessSecurity *s_wsec, + const char * wifi_mode, + NMDeviceWifiCapabilities caps, + const char * password, + gboolean show_password, + GError ** error) +{ + char generated_key[11]; + const char *key; + const char *key_mgmt; + + if (g_strcmp0(wifi_mode, NM_SETTING_WIRELESS_MODE_AP) == 0) { + if (caps & NM_WIFI_DEVICE_CAP_RSN) { + nm_setting_wireless_security_add_proto(s_wsec, "rsn"); + nm_setting_wireless_security_add_pairwise(s_wsec, "ccmp"); + nm_setting_wireless_security_add_group(s_wsec, "ccmp"); + key_mgmt = "wpa-psk"; + } else if (caps & NM_WIFI_DEVICE_CAP_WPA) { + nm_setting_wireless_security_add_proto(s_wsec, "wpa"); + nm_setting_wireless_security_add_pairwise(s_wsec, "tkip"); + nm_setting_wireless_security_add_group(s_wsec, "tkip"); + key_mgmt = "wpa-psk"; + } else + key_mgmt = "none"; + } else + key_mgmt = "none"; + + if (g_strcmp0(key_mgmt, "wpa-psk") == 0) { + /* use WPA */ + if (password) { + if (!nm_utils_wpa_psk_valid(password)) { + g_set_error(error, NMCLI_ERROR, 0, _("'%s' is not valid WPA PSK"), password); + return FALSE; + } + key = password; + } else { + generate_wpa_key(generated_key, sizeof(generated_key)); + key = generated_key; + } + g_object_set(s_wsec, + NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, + key_mgmt, + NM_SETTING_WIRELESS_SECURITY_PSK, + key, + NULL); + } else { + /* use WEP */ + if (password) { + if (!nm_utils_wep_key_valid(password, NM_WEP_KEY_TYPE_KEY)) { + g_set_error(error, + NMCLI_ERROR, + 0, + _("'%s' is not valid WEP key (it should be 5 or 13 ASCII chars)"), + password); + return FALSE; + } + key = password; + } else { + generate_wep_key(generated_key, sizeof(generated_key)); + key = generated_key; + } + g_object_set(s_wsec, + NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, + key_mgmt, + NM_SETTING_WIRELESS_SECURITY_WEP_KEY0, + key, + NM_SETTING_WIRELESS_SECURITY_WEP_KEY_TYPE, + NM_WEP_KEY_TYPE_KEY, + NULL); + } + if (show_password) + g_print(_("Hotspot password: %s\n"), key); + + return TRUE; +} + +static NMConnection * +find_hotspot_conn(NMDevice * device, + const GPtrArray *connections, + const char * con_name, + GBytes * ssid_bytes, + const char * wifi_mode, + const char * band, + gint64 channel_int) +{ + NMConnection * connection; + NMSettingWireless *s_wifi; + int i; + + for (i = 0; i < connections->len; i++) { + connection = NM_CONNECTION(connections->pdata[i]); + + s_wifi = nm_connection_get_setting_wireless(connection); + if (!s_wifi) + continue; + + if (channel_int != -1 && nm_setting_wireless_get_channel(s_wifi) != channel_int) + continue; + + if (g_strcmp0(nm_setting_wireless_get_mode(s_wifi), wifi_mode) != 0) + continue; + + if (band && g_strcmp0(nm_setting_wireless_get_band(s_wifi), band) != 0) + continue; + + if (ssid_bytes && !g_bytes_equal(nm_setting_wireless_get_ssid(s_wifi), ssid_bytes)) + continue; + + if (!nm_device_connection_compatible(device, connection, NULL)) + continue; + + return g_object_ref(connection); + } + + return NULL; +} + +static NMConnection * +create_hotspot_conn(const GPtrArray *connections, + const char * con_name, + GBytes * ssid_bytes, + const char * wifi_mode, + const char * band, + gint64 channel_int) +{ + char * default_name = NULL; + NMConnection * connection; + NMSettingConnection * s_con; + NMSettingWireless * s_wifi; + NMSettingWirelessSecurity *s_wsec; + NMSettingIPConfig * s_ip4, *s_ip6; + NMSettingProxy * s_proxy; + + connection = nm_simple_connection_new(); + s_con = (NMSettingConnection *) nm_setting_connection_new(); + nm_connection_add_setting(connection, NM_SETTING(s_con)); + if (!con_name) + con_name = default_name = nmc_unique_connection_name(connections, "Hotspot"); + g_object_set(s_con, + NM_SETTING_CONNECTION_ID, + con_name, + NM_SETTING_CONNECTION_AUTOCONNECT, + FALSE, + NULL); + g_free(default_name); + + s_wifi = (NMSettingWireless *) nm_setting_wireless_new(); + nm_connection_add_setting(connection, NM_SETTING(s_wifi)); + + g_object_set(s_wifi, + NM_SETTING_WIRELESS_MODE, + wifi_mode, + NM_SETTING_WIRELESS_SSID, + ssid_bytes, + NULL); + + if (channel_int != -1) { + g_object_set(s_wifi, + NM_SETTING_WIRELESS_CHANNEL, + (guint32) channel_int, + NM_SETTING_WIRELESS_BAND, + band, + NULL); + } + + s_wsec = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new(); + nm_connection_add_setting(connection, NM_SETTING(s_wsec)); + + s_ip4 = (NMSettingIPConfig *) nm_setting_ip4_config_new(); + nm_connection_add_setting(connection, NM_SETTING(s_ip4)); + g_object_set(s_ip4, NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP4_CONFIG_METHOD_SHARED, NULL); + + s_ip6 = (NMSettingIPConfig *) nm_setting_ip6_config_new(); + nm_connection_add_setting(connection, NM_SETTING(s_ip6)); + g_object_set(s_ip6, NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP6_CONFIG_METHOD_IGNORE, NULL); + + s_proxy = (NMSettingProxy *) nm_setting_proxy_new(); + nm_connection_add_setting(connection, NM_SETTING(s_proxy)); + g_object_set(s_proxy, NM_SETTING_PROXY_METHOD, (int) NM_SETTING_PROXY_METHOD_NONE, NULL); + + return connection; +} + +static void +do_device_wifi_hotspot(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + const char * ifname = NULL; + const char * con_name = NULL; + gs_unref_bytes GBytes *ssid_bytes = NULL; + const char * wifi_mode; + const char * band = NULL; + const char * channel = NULL; + gint64 channel_int = -1; + const char * password = NULL; + gboolean show_password = FALSE; + NMDevice * device = NULL; + gs_free NMDevice ** devices = NULL; + NMDeviceWifiCapabilities caps; + gs_unref_object NMConnection *connection = NULL; + const GPtrArray * connections; + NMSettingWirelessSecurity * s_wsec; + GError * error = NULL; + + /* Set default timeout waiting for operation completion. */ + if (nmc->timeout == -1) + nmc->timeout = 60; + + devices = nmc_get_devices_sorted(nmc->client); + + next_arg(nmc, &argc, &argv, NULL); + while (argc > 0) { + if (argc == 1 && nmc->complete) { + nmc_complete_strings(*argv, + "ifname", + "con-name", + "ssid", + "band", + "channel", + "password"); + } + + if (strcmp(*argv, "ifname") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + ifname = *argv; + if (argc == 1 && nmc->complete) + complete_device(devices, ifname, TRUE); + } else if (strcmp(*argv, "con-name") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + con_name = *argv; + } else if (strcmp(*argv, "ssid") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + if (strlen(*argv) > 32) { + g_string_printf(nmc->return_text, _("Error: ssid is too long.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + ssid_bytes = g_bytes_new(*argv, strlen(*argv)); + } else if (strcmp(*argv, "band") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + band = *argv; + if (argc == 1 && nmc->complete) + nmc_complete_strings(band, "a", "bg"); + if (strcmp(band, "a") && strcmp(band, "bg")) { + g_string_printf(nmc->return_text, + _("Error: band argument value '%s' is invalid; use 'a' or 'bg'."), + band); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + } else if (strcmp(*argv, "channel") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + channel = *argv; + } else if (strcmp(*argv, "password") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + password = *argv; + /* --show-password is deprecated in favour of global --show-secrets option */ + /* Keep it here for backwards compatibility */ + } else if (nmc_arg_is_option(*argv, "show-password")) { + show_password = TRUE; + } else { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + next_arg(nmc, &argc, &argv, NULL); + } + show_password = nmc->nmc_config.show_secrets || show_password; + + if (nmc->complete) + return; + + /* Verify band and channel parameters */ + if (!channel) { + if (g_strcmp0(band, "bg") == 0) + channel = "1"; + if (g_strcmp0(band, "a") == 0) + channel = "7"; + } + if (channel) { + unsigned long int value; + + if (!band) { + g_string_printf(nmc->return_text, _("Error: channel requires band too.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + if (!nmc_string_to_uint(channel, TRUE, 1, 5825, &value) + || !nm_utils_wifi_is_channel_valid(value, band)) { + g_string_printf(nmc->return_text, + _("Error: channel '%s' not valid for band '%s'."), + channel, + band); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + channel_int = value; + } + + /* Find Wi-Fi device. When no ifname is provided, the first Wi-Fi is used. */ + device = find_wifi_device_by_iface(devices, ifname, NULL); + if (!device) { + if (ifname) + g_string_printf(nmc->return_text, + _("Error: Device '%s' is not a Wi-Fi device."), + ifname); + else + g_string_printf(nmc->return_text, _("Error: No Wi-Fi device found.")); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } + + /* Check device supported mode */ + caps = nm_device_wifi_get_capabilities(NM_DEVICE_WIFI(device)); + if (caps & NM_WIFI_DEVICE_CAP_AP) + wifi_mode = NM_SETTING_WIRELESS_MODE_AP; + else if (caps & NM_WIFI_DEVICE_CAP_ADHOC) + wifi_mode = NM_SETTING_WIRELESS_MODE_ADHOC; + else { + g_string_printf(nmc->return_text, + _("Error: Device '%s' supports neither AP nor Ad-Hoc mode."), + nm_device_get_iface(device)); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } + + connections = nm_client_get_connections(nmc->client); + connection = + find_hotspot_conn(device, connections, con_name, ssid_bytes, wifi_mode, band, channel_int); + if (!connection) { + /* Create a connection with appropriate parameters */ + if (!ssid_bytes) + ssid_bytes = generate_ssid_for_hotspot(); + connection = + create_hotspot_conn(connections, con_name, ssid_bytes, wifi_mode, band, channel_int); + } + + if (password || !NM_IS_REMOTE_CONNECTION(connection)) { + s_wsec = nm_connection_get_setting_wireless_security(connection); + g_return_if_fail(s_wsec); + + if (!set_wireless_security_for_hotspot(s_wsec, + wifi_mode, + caps, + password, + show_password, + &error)) { + g_string_printf(nmc->return_text, _("Error: Invalid 'password': %s."), error->message); + g_clear_error(&error); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } + } + + /* Activate the connection now */ + nmc->nowait_flag = (nmc->timeout == 0); + nmc->should_wait++; + + save_and_activate_connection(nmc, device, connection, TRUE, NULL); +} + +static void +request_rescan_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NmCli * nmc = (NmCli *) user_data; + GError *error = NULL; + + nm_device_wifi_request_scan_finish(NM_DEVICE_WIFI(object), result, &error); + if (error) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + g_error_free(error); + } + quit(); +} + +static void +do_device_wifi_rescan(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice * device; + const char * ifname = NULL; + gs_unref_ptrarray GPtrArray *ssids = NULL; + gs_free NMDevice **devices = NULL; + GVariantBuilder builder, array_builder; + GVariant * options; + int i; + + ssids = g_ptr_array_new(); + devices = nmc_get_devices_sorted(nmc->client); + + next_arg(nmc, &argc, &argv, NULL); + /* Get the parameters */ + while (argc > 0) { + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "ifname", "ssid"); + + if (strcmp(*argv, "ifname") == 0) { + if (ifname) { + g_string_printf(nmc->return_text, _("Error: '%s' cannot repeat."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + ifname = *argv; + if (argc == 1 && nmc->complete) + complete_device(devices, ifname, TRUE); + } else if (strcmp(*argv, "ssid") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + g_ptr_array_add(ssids, (gpointer) *argv); + } else if (!nmc->complete) { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + next_arg(nmc, &argc, &argv, NULL); + } + + if (nmc->complete) + return; + + /* Find Wi-Fi device to scan on. When no ifname is provided, the first Wi-Fi is used. */ + device = find_wifi_device_by_iface(devices, ifname, NULL); + + if (!device) { + if (ifname) + g_string_printf(nmc->return_text, + _("Error: Device '%s' is not a Wi-Fi device."), + ifname); + else + g_string_printf(nmc->return_text, _("Error: No Wi-Fi device found.")); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } + + if (ssids->len) { + g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); + g_variant_builder_init(&array_builder, G_VARIANT_TYPE("aay")); + + for (i = 0; i < ssids->len; i++) { + const char *ssid = g_ptr_array_index(ssids, i); + + g_variant_builder_add(&array_builder, + "@ay", + nm_g_variant_new_ay((const guint8 *) ssid, strlen(ssid))); + } + + g_variant_builder_add(&builder, "{sv}", "ssids", g_variant_builder_end(&array_builder)); + options = g_variant_builder_end(&builder); + + nm_device_wifi_request_scan_options_async(NM_DEVICE_WIFI(device), + options, + NULL, + request_rescan_cb, + nmc); + } else + nm_device_wifi_request_scan_async(NM_DEVICE_WIFI(device), NULL, request_rescan_cb, nmc); + + nmc->should_wait++; +} + +static void +string_append_mecard(GString *string, const char *tag, const char *text) +{ + const char *p; + bool is_hex = TRUE; + int start; + + if (!text) + return; + + g_string_append(string, tag); + start = string->len; + + for (p = text; *p; p++) { + if (!g_ascii_isxdigit(*p)) + is_hex = FALSE; + if (strchr("\\\":;,", *p)) + g_string_append_c(string, '\\'); + g_string_append_c(string, *p); + } + + if (is_hex) { + g_string_insert_c(string, start, '\"'); + g_string_append_c(string, '\"'); + } + g_string_append_c(string, ';'); +} + +static void +print_wifi_connection(const NmcConfig *nmc_config, NMConnection *connection) +{ + NMSettingWireless * s_wireless; + NMSettingWirelessSecurity *s_wsec; + const char * key_mgmt = NULL; + const char * psk = NULL; + const char * type = NULL; + GBytes * ssid_bytes; + gs_free char * ssid = NULL; + nm_auto_free_gstring GString *string = NULL; + + s_wireless = nm_connection_get_setting_wireless(connection); + g_return_if_fail(s_wireless); + + ssid_bytes = nm_setting_wireless_get_ssid(s_wireless); + g_return_if_fail(ssid_bytes); + ssid = nm_utils_ssid_to_utf8(g_bytes_get_data(ssid_bytes, NULL), g_bytes_get_size(ssid_bytes)); + g_return_if_fail(ssid); + g_print("SSID: %s\n", ssid); + + string = g_string_sized_new(64); + g_string_append(string, "WIFI:"); + + s_wsec = nm_connection_get_setting_wireless_security(connection); + if (s_wsec) { + key_mgmt = nm_setting_wireless_security_get_key_mgmt(s_wsec); + psk = nm_setting_wireless_security_get_psk(s_wsec); + } + + if (key_mgmt == NULL) { + type = "nopass"; + g_print("%s: %s\n", _("Security"), _("None")); + } else if (strcmp(key_mgmt, "none") == 0 || strcmp(key_mgmt, "ieee8021x") == 0) { + type = "WEP"; + g_print("%s: WEP\n", _("Security")); + } else if (strcmp(key_mgmt, "wpa-none") == 0 || strcmp(key_mgmt, "wpa-psk") == 0 + || strcmp(key_mgmt, "sae") == 0) { + type = "WPA"; + g_print("%s: WPA\n", _("Security")); + } else if (strcmp(key_mgmt, "owe") == 0) { + type = "nopass"; + g_print("%s: OWE\n", _("Security")); + } + + if (psk) + g_print("%s: %s\n", _("Password"), psk); + + string_append_mecard(string, "T:", type); + string_append_mecard(string, "S:", ssid); + string_append_mecard(string, "P:", psk); + + if (nm_setting_wireless_get_hidden(s_wireless)) + g_string_append(string, "H:true;"); + + g_string_append_c(string, ';'); + if (nmc_config->use_colors) + nmc_print_qrcode(string->str); + + g_print("\n"); +} + +static gboolean +wifi_show_device(const NmcConfig *nmc_config, NMDevice *device, GError **error) +{ + NMActiveConnection *active_conn; + gs_unref_object NMConnection *connection = NULL; + gs_unref_variant GVariant *secrets = NULL; + + if (!NM_IS_DEVICE_WIFI(device)) { + g_set_error(error, + NMCLI_ERROR, + 0, + _("Error: Device '%s' is not a Wi-Fi device."), + nm_device_get_iface(device)); + return FALSE; + } + + connection = nm_device_get_applied_connection(device, 0, NULL, NULL, error); + if (!connection) + return FALSE; + + active_conn = nm_device_get_active_connection(device); + if (!active_conn) { + g_set_error(error, + NMCLI_ERROR, + 0, + _("no active connection on device '%s'"), + nm_device_get_iface(device)); + return FALSE; + } + + secrets = nm_remote_connection_get_secrets(nm_active_connection_get_connection(active_conn), + NM_SETTING_WIRELESS_SECURITY_SETTING_NAME, + NULL, + NULL); + if (secrets + && !nm_connection_update_secrets(connection, + NM_SETTING_WIRELESS_SECURITY_SETTING_NAME, + secrets, + error)) { + return FALSE; + } + + print_wifi_connection(nmc_config, connection); + + return TRUE; +} + +static void +do_device_wifi_show_password(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + const char *ifname = NULL; + gs_free NMDevice **devices = NULL; + gs_free_error GError *error = NULL; + gboolean found = FALSE; + int i; + + devices = nmc_get_devices_sorted(nmc->client); + + next_arg(nmc, &argc, &argv, NULL); + while (argc > 0) { + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "ifname"); + + if (strcmp(*argv, "ifname") == 0) { + if (ifname) { + g_string_printf(nmc->return_text, _("Error: '%s' cannot repeat."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + ifname = *argv; + if (argc == 1 && nmc->complete) + complete_device(devices, ifname, TRUE); + } else if (!nmc->complete) { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + next_arg(nmc, &argc, &argv, NULL); + } + + if (nmc->complete) + return; + + for (i = 0; devices[i]; i++) { + if (ifname && g_strcmp0(nm_device_get_iface(devices[i]), ifname) != 0) + continue; + + if (wifi_show_device(&nmc->nmc_config, devices[i], &error)) { + found = TRUE; + } else { + if (ifname) { + g_string_printf(nmc->return_text, _("%s"), error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } + g_clear_error(&error); + } + + if (ifname) + break; + } + + if (!found) { + g_string_printf(nmc->return_text, _("Error: No Wi-Fi device found.")); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + return; + } +} + +static NMCCommand device_wifi_cmds[] = { + {"list", do_device_wifi_list, NULL, TRUE, TRUE}, + {"connect", do_device_wifi_connect, NULL, TRUE, TRUE}, + {"hotspot", do_device_wifi_hotspot, NULL, TRUE, TRUE}, + {"rescan", do_device_wifi_rescan, NULL, TRUE, TRUE}, + {"show-password", do_device_wifi_show_password, NULL, TRUE, TRUE}, + {NULL, do_device_wifi_list, NULL, TRUE, TRUE}, +}; + +static void +do_device_wifi(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + nmc_do_cmd(nmc, device_wifi_cmds, *argv, argc, argv); +} + +static int +show_device_lldp_list(NMDevice *device, NmCli *nmc, const char *fields_str, int *counter) +{ + const NMMetaAbstractInfo *const *tmpl; + NmcOutputField * arr; + GPtrArray * neighbors; + const char * str; + int i; + NMC_OUTPUT_DATA_DEFINE_SCOPED(out); + gs_free char *header_name = NULL; + + neighbors = nm_device_get_lldp_neighbors(device); + + if (!neighbors || !neighbors->len) + return 0; + + tmpl = (const NMMetaAbstractInfo *const *) nmc_fields_dev_lldp_list; + + /* Main header name */ + header_name = construct_header_name(_("Device LLDP neighbors"), nm_device_get_iface(device)); + out_indices = parse_output_fields(fields_str, + (const NMMetaAbstractInfo *const *) nmc_fields_dev_lldp_list, + FALSE, + NULL, + NULL); + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_MAIN_HEADER_ADD | NMC_OF_FLAG_FIELD_NAMES); + g_ptr_array_add(out.output_data, arr); + + for (i = 0; i < neighbors->len; i++) { + NMLldpNeighbor *neighbor = neighbors->pdata[i]; + guint value; + + arr = nmc_dup_fields_array(tmpl, NMC_OF_FLAG_SECTION_PREFIX); + set_val_str(arr, 0, g_strdup_printf("NEIGHBOR[%d]", (*counter)++)); + + set_val_strc(arr, 1, nm_device_get_iface(device)); + + if (nm_lldp_neighbor_get_attr_string_value(neighbor, NM_LLDP_ATTR_CHASSIS_ID, &str)) + set_val_strc(arr, 2, str); + + if (nm_lldp_neighbor_get_attr_string_value(neighbor, NM_LLDP_ATTR_PORT_ID, &str)) + set_val_strc(arr, 3, str); + + if (nm_lldp_neighbor_get_attr_string_value(neighbor, NM_LLDP_ATTR_PORT_DESCRIPTION, &str)) + set_val_strc(arr, 4, str); + + if (nm_lldp_neighbor_get_attr_string_value(neighbor, NM_LLDP_ATTR_SYSTEM_NAME, &str)) + set_val_strc(arr, 5, str); + + if (nm_lldp_neighbor_get_attr_string_value(neighbor, NM_LLDP_ATTR_SYSTEM_DESCRIPTION, &str)) + set_val_strc(arr, 6, str); + + if (nm_lldp_neighbor_get_attr_uint_value(neighbor, + NM_LLDP_ATTR_SYSTEM_CAPABILITIES, + &value)) { + gs_free char *tmp = NULL; + + set_val_str( + arr, + 7, + g_strdup_printf("%u (%s)", value, (tmp = nmc_parse_lldp_capabilities(value)))); + } + + if (nm_lldp_neighbor_get_attr_uint_value(neighbor, NM_LLDP_ATTR_IEEE_802_1_PVID, &value)) + set_val_str(arr, 8, nm_strdup_int(value)); + + if (nm_lldp_neighbor_get_attr_uint_value(neighbor, NM_LLDP_ATTR_IEEE_802_1_PPVID, &value)) + set_val_str(arr, 9, nm_strdup_int(value)); + + if (nm_lldp_neighbor_get_attr_uint_value(neighbor, + NM_LLDP_ATTR_IEEE_802_1_PPVID_FLAGS, + &value)) + set_val_str(arr, 10, nm_strdup_int(value)); + + if (nm_lldp_neighbor_get_attr_uint_value(neighbor, NM_LLDP_ATTR_IEEE_802_1_VID, &value)) + set_val_str(arr, 11, nm_strdup_int(value)); + + if (nm_lldp_neighbor_get_attr_string_value(neighbor, + NM_LLDP_ATTR_IEEE_802_1_VLAN_NAME, + &str)) + set_val_strc(arr, 12, str); + + if (nm_lldp_neighbor_get_attr_string_value(neighbor, NM_LLDP_ATTR_DESTINATION, &str)) + set_val_strc(arr, 13, str); + + if (nm_lldp_neighbor_get_attr_uint_value(neighbor, NM_LLDP_ATTR_CHASSIS_ID_TYPE, &value)) + set_val_str(arr, 14, nm_strdup_int(value)); + + if (nm_lldp_neighbor_get_attr_uint_value(neighbor, NM_LLDP_ATTR_PORT_ID_TYPE, &value)) + set_val_str(arr, 15, nm_strdup_int(value)); + + g_ptr_array_add(out.output_data, arr); + } + + print_data_prepare_width(out.output_data); + print_data(&nmc->nmc_config, &nmc->pager_data, out_indices, header_name, 0, &out); + + return neighbors->len; +} + +static void +do_device_lldp_list(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice * device = NULL; + gs_free_error GError *error = NULL; + const char * fields_str = NULL; + int counter = 0; + gs_unref_array GArray *out_indices = NULL; + + next_arg(nmc, &argc, &argv, NULL); + while (argc > 0) { + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "ifname"); + + if (strcmp(*argv, "ifname") == 0) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, _("Error: %s argument is missing."), *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + device = get_device(nmc, &argc, &argv, &error); + if (!device) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = error->code; + return; + } + } else { + g_string_printf(nmc->return_text, _("Error: invalid extra argument '%s'."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + next_arg(nmc, &argc, &argv, NULL); + } + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) + fields_str = NMC_FIELDS_DEV_LLDP_LIST_COMMON; + else if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "all") == 0) { + /* pass */ + } else + fields_str = nmc->required_fields; + + out_indices = parse_output_fields(fields_str, + (const NMMetaAbstractInfo *const *) nmc_fields_dev_lldp_list, + FALSE, + NULL, + &error); + + if (error) { + g_string_printf(nmc->return_text, _("Error: 'device lldp list': %s"), error->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + if (nmc->complete) + return; + + if (device) { + show_device_lldp_list(device, nmc, fields_str, &counter); + } else { + gs_free NMDevice **devices = nmc_get_devices_sorted(nmc->client); + guint i; + + for (i = 0; devices[i]; i++) + show_device_lldp_list(devices[i], nmc, fields_str, &counter); + } +} + +static NMCCommand device_lldp_cmds[] = { + {"list", do_device_lldp_list, NULL, TRUE, TRUE}, + {NULL, do_device_lldp_list, NULL, TRUE, TRUE}, +}; + +static void +do_device_lldp(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + if (!nmc->mode_specified) + nmc->nmc_config_mutable.multiline_output = + TRUE; /* multiline mode is default for 'device lldp' */ + + next_arg(nmc, &argc, &argv, NULL); + nmc_do_cmd(nmc, device_lldp_cmds, *argv, argc, argv); +} + +static gboolean +is_single_word(const char *line) +{ + size_t n1, n2, n3; + + n1 = strspn(line, " \t"); + n2 = strcspn(line + n1, " \t\0") + n1; + n3 = strspn(line + n2, " \t"); + + if (n3 == 0) + return TRUE; + else + return FALSE; +} + +static char ** +nmcli_device_tab_completion(const char *text, int start, int end) +{ + char ** match_array = NULL; + rl_compentry_func_t *generator_func = NULL; + + /* Disable readline's default filename completion */ + rl_attempted_completion_over = 1; + + if (g_strcmp0(rl_prompt, PROMPT_INTERFACE) == 0) { + /* Disable appending space after completion */ + rl_completion_append_character = '\0'; + + if (!is_single_word(rl_line_buffer)) + return NULL; + + generator_func = nmc_rl_gen_func_ifnames; + } else if (g_strcmp0(rl_prompt, PROMPT_INTERFACES) == 0) { + generator_func = nmc_rl_gen_func_ifnames; + } + + if (generator_func) + match_array = rl_completion_matches(text, generator_func); + + return match_array; +} + +void +nmc_command_func_device(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + static const NMCCommand cmds[] = { + {"status", do_devices_status, usage_device_status, TRUE, TRUE}, + {"show", do_device_show, usage_device_show, TRUE, TRUE}, + {"connect", do_device_connect, usage_device_connect, TRUE, TRUE}, + {"reapply", do_device_reapply, usage_device_reapply, TRUE, TRUE}, + {"disconnect", do_devices_disconnect, usage_device_disconnect, TRUE, TRUE}, + {"delete", do_devices_delete, usage_device_delete, TRUE, TRUE}, + {"set", do_device_set, usage_device_set, TRUE, TRUE}, + {"monitor", do_devices_monitor, usage_device_monitor, TRUE, TRUE}, + {"wifi", do_device_wifi, usage_device_wifi, FALSE, FALSE}, + {"lldp", do_device_lldp, usage_device_lldp, FALSE, FALSE}, + {"modify", do_device_modify, usage_device_modify, TRUE, TRUE}, + {NULL, do_devices_status, usage, TRUE, TRUE}, + }; + + next_arg(nmc, &argc, &argv, NULL); + + nmc_start_polkit_agent_start_try(nmc); + + rl_attempted_completion_function = (rl_completion_func_t *) nmcli_device_tab_completion; + + nmc_do_cmd(nmc, cmds, *argv, argc, argv); +} + +void +monitor_devices(NmCli *nmc) +{ + do_devices_monitor(NULL, nmc, 0, NULL); +} diff --git a/src/nmcli/devices.h b/src/nmcli/devices.h new file mode 100644 index 00000000..6214ea03 --- /dev/null +++ b/src/nmcli/devices.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#ifndef NMC_DEVICES_H +#define NMC_DEVICES_H + +#include "nmcli.h" + +void nmc_complete_device(NMClient *client, const char *prefix, gboolean wifi_only); + +void nmc_complete_bssid(NMClient *client, const char *ifname, const char *bssid_prefix); + +void monitor_devices(NmCli *nmc); + +NMDevice **nmc_get_devices_sorted(NMClient *client); + +NMMetaColor nmc_device_state_to_color(NMDevice *device); + +extern const NmcMetaGenericInfo *const metagen_device_status[]; +extern const NmcMetaGenericInfo *const metagen_device_detail_general[]; +extern const NmcMetaGenericInfo *const metagen_device_detail_connections[]; +extern const NmcMetaGenericInfo *const metagen_device_detail_capabilities[]; +extern const NmcMetaGenericInfo *const metagen_device_detail_wired_properties[]; +extern const NmcMetaGenericInfo *const metagen_device_detail_wifi_properties[]; +extern const NmcMetaGenericInfo *const metagen_device_detail_wimax_properties[]; +extern const NmcMetaGenericInfo *const nmc_fields_dev_wifi_list[]; +extern const NmcMetaGenericInfo *const nmc_fields_dev_wimax_list[]; +extern const NmcMetaGenericInfo *const nmc_fields_dev_show_master_prop[]; +extern const NmcMetaGenericInfo *const nmc_fields_dev_show_team_prop[]; +extern const NmcMetaGenericInfo *const nmc_fields_dev_show_vlan_prop[]; +extern const NmcMetaGenericInfo *const nmc_fields_dev_show_bluetooth[]; +extern const NmcMetaGenericInfo *const nmc_fields_dev_show_sections[]; +extern const NmcMetaGenericInfo *const nmc_fields_dev_lldp_list[]; + +#endif /* NMC_DEVICES_H */ diff --git a/src/nmcli/general.c b/src/nmcli/general.c new file mode 100644 index 00000000..225d3d8a --- /dev/null +++ b/src/nmcli/general.c @@ -0,0 +1,1618 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include <stdlib.h> + +#include "libnm-core-aux-intern/nm-common-macros.h" + +#include "libnm-glib-aux/nm-dbus-aux.h" +#include "libnmc-base/nm-client-utils.h" + +#include "polkit-agent.h" +#include "utils.h" +#include "common.h" +#include "common.h" +#include "devices.h" +#include "connections.h" + +/*****************************************************************************/ + +static void permission_changed(GObject *gobject, GParamSpec *pspec, NmCli *nmc); + +/*****************************************************************************/ + +static NM_UTILS_LOOKUP_STR_DEFINE(nm_state_to_string, + NMState, + NM_UTILS_LOOKUP_DEFAULT(N_("unknown")), + NM_UTILS_LOOKUP_ITEM(NM_STATE_ASLEEP, N_("asleep")), + NM_UTILS_LOOKUP_ITEM(NM_STATE_CONNECTING, N_("connecting")), + NM_UTILS_LOOKUP_ITEM(NM_STATE_CONNECTED_LOCAL, + N_("connected (local only)")), + NM_UTILS_LOOKUP_ITEM(NM_STATE_CONNECTED_SITE, + N_("connected (site only)")), + NM_UTILS_LOOKUP_ITEM(NM_STATE_CONNECTED_GLOBAL, N_("connected")), + NM_UTILS_LOOKUP_ITEM(NM_STATE_DISCONNECTING, N_("disconnecting")), + NM_UTILS_LOOKUP_ITEM(NM_STATE_DISCONNECTED, N_("disconnected")), + NM_UTILS_LOOKUP_ITEM_IGNORE(NM_STATE_UNKNOWN), ); + +static NMMetaColor +state_to_color(NMState state) +{ + switch (state) { + case NM_STATE_CONNECTING: + return NM_META_COLOR_STATE_CONNECTING; + case NM_STATE_CONNECTED_LOCAL: + return NM_META_COLOR_STATE_CONNECTED_LOCAL; + case NM_STATE_CONNECTED_SITE: + return NM_META_COLOR_STATE_CONNECTED_SITE; + case NM_STATE_CONNECTED_GLOBAL: + return NM_META_COLOR_STATE_CONNECTED_GLOBAL; + case NM_STATE_DISCONNECTING: + return NM_META_COLOR_STATE_DISCONNECTING; + case NM_STATE_ASLEEP: + return NM_META_COLOR_STATE_ASLEEP; + case NM_STATE_DISCONNECTED: + return NM_META_COLOR_STATE_DISCONNECTED; + default: + return NM_META_COLOR_STATE_UNKNOWN; + } +} + +static NMMetaColor +connectivity_to_color(NMConnectivityState connectivity) +{ + switch (connectivity) { + case NM_CONNECTIVITY_NONE: + return NM_META_COLOR_CONNECTIVITY_NONE; + case NM_CONNECTIVITY_PORTAL: + return NM_META_COLOR_CONNECTIVITY_PORTAL; + case NM_CONNECTIVITY_LIMITED: + return NM_META_COLOR_CONNECTIVITY_LIMITED; + case NM_CONNECTIVITY_FULL: + return NM_META_COLOR_CONNECTIVITY_FULL; + default: + return NM_META_COLOR_CONNECTIVITY_UNKNOWN; + } +} + +static const char * +permission_to_string(NMClientPermission perm) +{ + return nm_auth_permission_to_string(perm) ?: _("unknown"); +} + +static NM_UTILS_LOOKUP_STR_DEFINE( + permission_result_to_string, + NMClientPermissionResult, + NM_UTILS_LOOKUP_DEFAULT(N_("unknown")), + NM_UTILS_LOOKUP_ITEM(NM_CLIENT_PERMISSION_RESULT_YES, N_("yes")), + NM_UTILS_LOOKUP_ITEM(NM_CLIENT_PERMISSION_RESULT_NO, N_("no")), + NM_UTILS_LOOKUP_ITEM(NM_CLIENT_PERMISSION_RESULT_AUTH, N_("auth")), + NM_UTILS_LOOKUP_ITEM_IGNORE(NM_CLIENT_PERMISSION_RESULT_UNKNOWN), ); + +static NM_UTILS_LOOKUP_DEFINE( + permission_result_to_color, + NMClientPermissionResult, + NMMetaColor, + NM_UTILS_LOOKUP_DEFAULT(NM_META_COLOR_PERMISSION_UNKNOWN), + NM_UTILS_LOOKUP_ITEM(NM_CLIENT_PERMISSION_RESULT_YES, NM_META_COLOR_PERMISSION_YES), + NM_UTILS_LOOKUP_ITEM(NM_CLIENT_PERMISSION_RESULT_NO, NM_META_COLOR_PERMISSION_NO), + NM_UTILS_LOOKUP_ITEM(NM_CLIENT_PERMISSION_RESULT_AUTH, NM_META_COLOR_PERMISSION_AUTH), + NM_UTILS_LOOKUP_ITEM_IGNORE(NM_CLIENT_PERMISSION_RESULT_UNKNOWN), ); + +/*****************************************************************************/ + +static const NmcMetaGenericInfo *const metagen_general_status[]; + +static gconstpointer _metagen_general_status_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NmCli * nmc = target; + const char * value; + gboolean v_bool; + NMState state; + NMConnectivityState connectivity; + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_RUNNING: + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + value = N_("running"); + goto translate_and_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_VERSION: + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + value = nm_client_get_version(nmc->client); + goto clone_and_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_STATE: + state = nm_client_get_state(nmc->client); + NMC_HANDLE_COLOR(state_to_color(state)); + value = nm_state_to_string(state); + goto translate_and_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_STARTUP: + v_bool = nm_client_get_startup(nmc->client); + NMC_HANDLE_COLOR(v_bool ? NM_META_COLOR_MANAGER_STARTING : NM_META_COLOR_MANAGER_RUNNING); + value = v_bool ? N_("starting") : N_("started"); + goto translate_and_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_CONNECTIVITY: + connectivity = nm_client_get_connectivity(nmc->client); + NMC_HANDLE_COLOR(connectivity_to_color(connectivity)); + value = nm_connectivity_to_string(connectivity); + goto translate_and_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_NETWORKING: + v_bool = nm_client_networking_get_enabled(nmc->client); + goto enabled_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIFI_HW: + v_bool = nm_client_wireless_hardware_get_enabled(nmc->client); + goto enabled_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIFI: + v_bool = nm_client_wireless_get_enabled(nmc->client); + goto enabled_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WWAN_HW: + v_bool = nm_client_wwan_hardware_get_enabled(nmc->client); + goto enabled_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WWAN: + v_bool = nm_client_wwan_get_enabled(nmc->client); + goto enabled_out; + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIMAX_HW: + case NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIMAX: + /* deprecated fields. Don't return anything. */ + return NULL; + default: + break; + } + + g_return_val_if_reached(NULL); + +enabled_out: + NMC_HANDLE_COLOR(v_bool ? NM_META_COLOR_ENABLED : NM_META_COLOR_DISABLED); + value = v_bool ? N_("enabled") : N_("disabled"); + goto translate_and_out; + +clone_and_out: + return (*out_to_free = g_strdup(value)); + +translate_and_out: + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) + return _(value); + return value; +} + +static const NmcMetaGenericInfo + *const metagen_general_status[_NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_NUM + 1] = { +#define _METAGEN_GENERAL_STATUS(type, name) \ + [type] = NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_general_status_get_fcn) + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_RUNNING, "RUNNING"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_VERSION, "VERSION"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_STATE, "STATE"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_STARTUP, "STARTUP"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_CONNECTIVITY, "CONNECTIVITY"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_NETWORKING, "NETWORKING"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIFI_HW, "WIFI-HW"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIFI, "WIFI"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WWAN_HW, "WWAN-HW"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WWAN, "WWAN"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIMAX_HW, "WIMAX-HW"), + _METAGEN_GENERAL_STATUS(NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIMAX, "WIMAX"), +}; +#define NMC_FIELDS_NM_STATUS_ALL \ + "RUNNING,VERSION,STATE,STARTUP,CONNECTIVITY,NETWORKING,WIFI-HW,WIFI,WWAN-HW,WWAN" +#define NMC_FIELDS_NM_STATUS_SWITCH "NETWORKING,WIFI-HW,WIFI,WWAN-HW,WWAN" +#define NMC_FIELDS_NM_STATUS_RADIO "WIFI-HW,WIFI,WWAN-HW,WWAN" +#define NMC_FIELDS_NM_STATUS_COMMON "STATE,CONNECTIVITY,WIFI-HW,WIFI,WWAN-HW,WWAN" +#define NMC_FIELDS_NM_NETWORKING "NETWORKING" +#define NMC_FIELDS_NM_WIFI "WIFI" +#define NMC_FIELDS_NM_WWAN "WWAN" +#define NMC_FIELDS_NM_WIMAX "WIMAX" +#define NMC_FIELDS_NM_CONNECTIVITY "CONNECTIVITY" + +/*****************************************************************************/ + +static gconstpointer _metagen_general_permissions_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NMClientPermission perm = GPOINTER_TO_UINT(target); + NmCli * nmc = environment_user_data; + NMClientPermissionResult perm_result; + const char * s; + + switch (info->info_type) { + case NMC_GENERIC_INFO_TYPE_GENERAL_PERMISSIONS_PERMISSION: + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + return permission_to_string(perm); + case NMC_GENERIC_INFO_TYPE_GENERAL_PERMISSIONS_VALUE: + perm_result = nm_client_get_permission_result(nmc->client, perm); + NMC_HANDLE_COLOR(permission_result_to_color(perm_result)); + s = permission_result_to_string(perm_result); + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) + return _(s); + return s; + default: + break; + } + + g_return_val_if_reached(NULL); +} + +static const NmcMetaGenericInfo + *const metagen_general_permissions[_NMC_GENERIC_INFO_TYPE_GENERAL_PERMISSIONS_NUM + 1] = { +#define _METAGEN_GENERAL_PERMISSIONS(type, name) \ + [type] = \ + NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_general_permissions_get_fcn) + _METAGEN_GENERAL_PERMISSIONS(NMC_GENERIC_INFO_TYPE_GENERAL_PERMISSIONS_PERMISSION, + "PERMISSION"), + _METAGEN_GENERAL_PERMISSIONS(NMC_GENERIC_INFO_TYPE_GENERAL_PERMISSIONS_VALUE, "VALUE"), +}; + +/*****************************************************************************/ + +typedef struct { + bool initialized; + char **level; + char **domains; +} GetGeneralLoggingData; + +static gconstpointer _metagen_general_logging_get_fcn(NMC_META_GENERIC_INFO_GET_FCN_ARGS) +{ + NmCli * nmc = environment_user_data; + GetGeneralLoggingData *d = target; + + nm_assert(info->info_type < _NMC_GENERIC_INFO_TYPE_GENERAL_LOGGING_NUM); + + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + + if (!d->initialized) { + d->initialized = TRUE; + if (!nm_client_get_logging(nmc->client, d->level, d->domains, NULL)) + return NULL; + } + + if (info->info_type == NMC_GENERIC_INFO_TYPE_GENERAL_LOGGING_LEVEL) + return *d->level; + else + return *d->domains; +} + +static const NmcMetaGenericInfo + *const metagen_general_logging[_NMC_GENERIC_INFO_TYPE_GENERAL_LOGGING_NUM + 1] = { +#define _METAGEN_GENERAL_LOGGING(type, name) \ + [type] = NMC_META_GENERIC(name, .info_type = type, .get_fcn = _metagen_general_logging_get_fcn) + _METAGEN_GENERAL_LOGGING(NMC_GENERIC_INFO_TYPE_GENERAL_LOGGING_LEVEL, "LEVEL"), + _METAGEN_GENERAL_LOGGING(NMC_GENERIC_INFO_TYPE_GENERAL_LOGGING_DOMAINS, "DOMAINS"), +}; + +/*****************************************************************************/ + +static void +usage_general(void) +{ + g_printerr(_("Usage: nmcli general { COMMAND | help }\n\n" + "COMMAND := { status | hostname | permissions | logging }\n\n" + " status\n\n" + " hostname [<hostname>]\n\n" + " permissions\n\n" + " logging [level <log level>] [domains <log domains>]\n\n")); +} + +static void +usage_general_status(void) +{ + g_printerr( + _("Usage: nmcli general status { help }\n" + "\n" + "Show overall status of NetworkManager.\n" + "'status' is the default action, which means 'nmcli gen' calls 'nmcli gen status'\n\n")); +} + +static void +usage_general_hostname(void) +{ + g_printerr( + _("Usage: nmcli general hostname { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [<hostname>]\n" + "\n" + "Get or change persistent system hostname.\n" + "With no arguments, this prints currently configured hostname. When you pass\n" + "a hostname, NetworkManager will set it as the new persistent system hostname.\n\n")); +} + +static void +usage_general_permissions(void) +{ + g_printerr(_("Usage: nmcli general permissions { help }\n" + "\n" + "Show caller permissions for authenticated operations.\n\n")); +} + +static void +usage_general_reload(void) +{ + g_printerr(_("Usage: nmcli general reload { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [<flag>[,<flag>...]]\n" + "\n" + "Reload NetworkManager's configuration and perform certain updates, like\n" + "flushing caches or rewriting external state to disk. This is similar to\n" + "sending SIGHUP to NetworkManager but it allows for more fine-grained\n" + "control over what to reload through the flags argument. It also allows\n" + "non-root access via PolicyKit and contrary to signals it is synchronous.\n" + "\n" + "Available flags are:\n" + "\n" + " 'conf' Reload the NetworkManager.conf configuration from\n" + " disk. Note that this does not include connections, which\n" + " can be reloaded through 'nmcli connection reload' instead.\n" + "\n" + " 'dns-rc' Update DNS configuration, which usually involves writing\n" + " /etc/resolv.conf anew. This is equivalent to sending the\n" + " SIGUSR1 signal to the NetworkManager process.\n" + "\n" + " 'dns-full' Restart the DNS plugin. This is for example useful when\n" + " using dnsmasq plugin, which uses additional configuration\n" + " in /etc/NetworkManager/dnsmasq.d. If you edit those files,\n" + " you can restart the DNS plugin. This action shortly\n" + " interrupts name resolution.\n" + "\n" + "With no flags, everything that is supported is reloaded, which is\n" + "identical to sending a SIGHUP.\n")); +} + +static void +usage_general_logging(void) +{ + g_printerr(_("Usage: nmcli general logging { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [level <log level>] [domains <log domains>]\n" + "\n" + "Get or change NetworkManager logging level and domains.\n" + "Without any argument current logging level and domains are shown. In order to\n" + "change logging state, provide level and/or domain. Please refer to the man page\n" + "for the list of possible logging domains.\n\n")); +} + +static void +usage_networking(void) +{ + g_printerr(_("Usage: nmcli networking { COMMAND | help }\n\n" + "COMMAND := { [ on | off | connectivity ] }\n\n" + " on\n\n" + " off\n\n" + " connectivity [check]\n\n")); +} + +static void +usage_networking_on(void) +{ + g_printerr(_("Usage: nmcli networking on { help }\n" + "\n" + "Switch networking on.\n\n")); +} + +static void +usage_networking_off(void) +{ + g_printerr(_("Usage: nmcli networking off { help }\n" + "\n" + "Switch networking off.\n\n")); +} + +static void +usage_networking_connectivity(void) +{ + g_printerr( + _("Usage: nmcli networking connectivity { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [check]\n" + "\n" + "Get network connectivity state.\n" + "The optional 'check' argument makes NetworkManager re-check the connectivity.\n\n")); +} + +static void +usage_radio(void) +{ + g_printerr(_("Usage: nmcli radio { COMMAND | help }\n\n" + "COMMAND := { all | wifi | wwan }\n\n" + " all | wifi | wwan [ on | off ]\n\n")); +} + +static void +usage_radio_all(void) +{ + g_printerr(_("Usage: nmcli radio all { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [on | off]\n" + "\n" + "Get status of all radio switches, or turn them on/off.\n\n")); +} + +static void +usage_radio_wifi(void) +{ + g_printerr(_("Usage: nmcli radio wifi { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [on | off]\n" + "\n" + "Get status of Wi-Fi radio switch, or turn it on/off.\n\n")); +} + +static void +usage_radio_wwan(void) +{ + g_printerr(_("Usage: nmcli radio wwan { ARGUMENTS | help }\n" + "\n" + "ARGUMENTS := [on | off]\n" + "\n" + "Get status of mobile broadband radio switch, or turn it on/off.\n\n")); +} + +static void +usage_monitor(void) +{ + g_printerr(_("Usage: nmcli monitor\n" + "\n" + "Monitor NetworkManager changes.\n" + "Prints a line whenever a change occurs in NetworkManager\n\n")); +} + +static void +quit(void) +{ + g_main_loop_quit(loop); +} + +static gboolean +show_nm_status(NmCli *nmc, const char *pretty_header_name, const char *print_flds) +{ + gs_free_error GError *error = NULL; + const char * fields_str; + const char * fields_all = print_flds ?: NMC_FIELDS_NM_STATUS_ALL; + const char * fields_common = print_flds ?: NMC_FIELDS_NM_STATUS_COMMON; + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) + fields_str = fields_common; + else if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "all") == 0) + fields_str = fields_all; + else + fields_str = nmc->required_fields; + + if (!nmc_print(&nmc->nmc_config, + (gpointer[]){nmc, NULL}, + NULL, + pretty_header_name ?: N_("NetworkManager status"), + (const NMMetaAbstractInfo *const *) metagen_general_status, + fields_str, + &error)) { + g_string_printf(nmc->return_text, + _("Error: only these fields are allowed: %s"), + fields_all); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + return TRUE; +} + +static void +do_general_status(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) + return; + + show_nm_status(nmc, NULL, NULL); +} + +static gboolean +timeout_cb(gpointer user_data) +{ + NmCli *nmc = (NmCli *) user_data; + + g_signal_handlers_disconnect_by_func(nmc->client, G_CALLBACK(permission_changed), nmc); + + g_string_printf(nmc->return_text, _("Error: Timeout %d sec expired."), nmc->timeout); + nmc->return_value = NMC_RESULT_ERROR_TIMEOUT_EXPIRED; + quit(); + return FALSE; +} + +static void +print_permissions(void *user_data) +{ + NmCli * nmc = user_data; + gs_free_error GError *error = NULL; + const char * fields_str = NULL; + gpointer permissions[G_N_ELEMENTS(nm_auth_permission_sorted) + 1]; + gboolean is_running; + int i; + + is_running = nm_client_get_nm_running(nmc->client); + + if (is_running && nm_client_get_permissions_state(nmc->client) != NM_TERNARY_TRUE) { + /* wait longer. Permissions are not up to date. */ + return; + } + + g_signal_handlers_disconnect_by_func(nmc->client, G_CALLBACK(permission_changed), nmc); + + if (!is_running) { + /* NetworkManager quit while we were waiting. */ + g_string_printf(nmc->return_text, _("NetworkManager is not running.")); + nmc->return_value = NMC_RESULT_ERROR_NM_NOT_RUNNING; + quit(); + return; + } + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) { + /* pass */ + } else if (g_ascii_strcasecmp(nmc->required_fields, "all") == 0) { + /* pass */ + } else + fields_str = nmc->required_fields; + + for (i = 0; i < (int) G_N_ELEMENTS(nm_auth_permission_sorted); i++) + permissions[i] = GINT_TO_POINTER(nm_auth_permission_sorted[i]); + permissions[i] = NULL; + + nm_cli_spawn_pager(&nmc->nmc_config, &nmc->pager_data); + + if (!nmc_print(&nmc->nmc_config, + permissions, + NULL, + _("NetworkManager permissions"), + (const NMMetaAbstractInfo *const *) metagen_general_permissions, + fields_str, + &error)) { + g_string_printf(nmc->return_text, _("Error: 'general permissions': %s"), error->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + } + + quit(); +} + +static void +permission_changed(GObject *gobject, GParamSpec *pspec, NmCli *nmc) +{ + if (NM_IN_STRSET(pspec->name, NM_CLIENT_NM_RUNNING, NM_CLIENT_PERMISSIONS_STATE)) + print_permissions(nmc); +} + +static gboolean +show_nm_permissions(NmCli *nmc) +{ + NMClientInstanceFlags instance_flags; + + instance_flags = nm_client_get_instance_flags(nmc->client); + instance_flags &= ~NM_CLIENT_INSTANCE_FLAGS_NO_AUTO_FETCH_PERMISSIONS; + + g_object_set(nmc->client, NM_CLIENT_INSTANCE_FLAGS, (guint) instance_flags, NULL); + + g_signal_connect(nmc->client, "notify", G_CALLBACK(permission_changed), nmc); + + if (nmc->timeout == -1) + nmc->timeout = 10; + g_timeout_add_seconds(nmc->timeout, timeout_cb, nmc); + + nmc->should_wait++; + + print_permissions(nmc); + + return TRUE; +} + +static void +reload_cb(GObject *source, GAsyncResult *result, gpointer user_data) +{ + NmCli * nmc = user_data; + gs_free_error GError *error = NULL; + gs_unref_variant GVariant *ret = NULL; + + ret = nm_dbus_call_finish(result, &error); + if (error) { + g_string_printf(nmc->return_text, + _("Error: failed to reload: %s"), + nmc_error_get_simple_message(error)); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } + + quit(); +} + +static void +do_general_reload(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gs_free const char **values = NULL; + gs_free char * err_token = NULL; + gs_free char * joined = NULL; + int flags = 0; + + next_arg(nmc, &argc, &argv, NULL); + + if (nmc->complete) { + if (argc == 0) + return; + + if (argc == 1) { + values = nm_utils_enum_get_values(nm_manager_reload_flags_get_type(), + NM_MANAGER_RELOAD_FLAG_CONF, + NM_MANAGER_RELOAD_FLAG_ALL); + nmc_complete_strv(*argv, -1, values); + } + return; + } + + if (argc > 0) { + if (!nm_utils_enum_from_str(nm_manager_reload_flags_get_type(), + *argv, + &flags, + &err_token)) { + values = nm_utils_enum_get_values(nm_manager_reload_flags_get_type(), + NM_MANAGER_RELOAD_FLAG_CONF, + NM_MANAGER_RELOAD_FLAG_ALL); + joined = g_strjoinv(",", (char **) values); + g_string_printf(nmc->return_text, + _("Error: invalid reload flag '%s'. Allowed flags are: %s"), + err_token, + joined); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + argc--; + argv++; + } + + if (argc > 0) { + g_string_printf(nmc->return_text, _("Error: extra argument '%s'"), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + + nmc->should_wait++; + nm_dbus_call(G_BUS_TYPE_SYSTEM, + NM_DBUS_SERVICE, + NM_DBUS_PATH, + NM_DBUS_INTERFACE, + "Reload", + g_variant_new("(u)", flags), + G_VARIANT_TYPE("()"), + NULL, + (nmc->timeout == -1 ? 90 : nmc->timeout) * 1000, + reload_cb, + nmc); +} + +static void +do_general_permissions(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) + return; + + show_nm_permissions(nmc); +} + +static void +show_general_logging(NmCli *nmc) +{ + gs_free char *level_cache = NULL; + gs_free char *domains_cache = NULL; + gs_free_error GError *error = NULL; + const char * fields_str = NULL; + GetGeneralLoggingData d = { + .level = &level_cache, + .domains = &domains_cache, + }; + + if (!nmc->required_fields || g_ascii_strcasecmp(nmc->required_fields, "common") == 0) { + /* pass */ + } else if (g_ascii_strcasecmp(nmc->required_fields, "all") == 0) { + /* pass */ + } else + fields_str = nmc->required_fields; + + if (!nmc_print(&nmc->nmc_config, + (gpointer const[]){&d, NULL}, + NULL, + _("NetworkManager logging"), + (const NMMetaAbstractInfo *const *) metagen_general_logging, + fields_str, + &error)) { + g_string_printf(nmc->return_text, _("Error: 'general logging': %s"), error->message); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + } +} + +static void +nmc_complete_strings_nocase(const char *prefix, ...) +{ + va_list args; + const char *candidate; + int len; + + len = strlen(prefix); + + va_start(args, prefix); + while ((candidate = va_arg(args, const char *))) { + if (strncasecmp(prefix, candidate, len) == 0) + g_print("%s\n", candidate); + } + va_end(args); +} + +static void +_set_logging_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NmCli * nmc = user_data; + gs_unref_variant GVariant *res = NULL; + gs_free_error GError *error = NULL; + + res = nm_client_dbus_call_finish(NM_CLIENT(object), result, &error); + if (!res) { + g_dbus_error_strip_remote_error(error); + g_string_printf(nmc->return_text, + _("Error: failed to set logging: %s"), + nmc_error_get_simple_message(error)); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } + quit(); +} + +static void +do_general_logging(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + if (argc == 0) { + if (nmc->complete) + return; + + show_general_logging(nmc); + } else { + /* arguments provided -> set logging level and domains */ + const char *level = NULL; + const char *domains = NULL; + + do { + if (argc == 1 && nmc->complete) + nmc_complete_strings(*argv, "level", "domains"); + + if (matches(*argv, "level")) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, + _("Error: '%s' argument is missing."), + *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + if (argc == 1 && nmc->complete) { + nmc_complete_strings_nocase(*argv, + "TRACE", + "DEBUG", + "INFO", + "WARN", + "ERR", + "OFF", + "KEEP", + NULL); + } + level = *argv; + } else if (matches(*argv, "domains")) { + argc--; + argv++; + if (!argc) { + g_string_printf(nmc->return_text, + _("Error: '%s' argument is missing."), + *(argv - 1)); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + if (argc == 1 && nmc->complete) { + nmc_complete_strings_nocase(*argv, + "PLATFORM", + "RFKILL", + "ETHER", + "WIFI", + "BT", + "MB", + "DHCP4", + "DHCP6", + "PPP", + "WIFI_SCAN", + "IP4", + "IP6", + "AUTOIP4", + "DNS", + "VPN", + "SHARING", + "SUPPLICANT", + "AGENTS", + "SETTINGS", + "SUSPEND", + "CORE", + "DEVICE", + "OLPC", + "INFINIBAND", + "FIREWALL", + "ADSL", + "BOND", + "VLAN", + "BRIDGE", + "DBUS_PROPS", + "TEAM", + "CONCHECK", + "DCB", + "DISPATCH", + "AUDIT", + "SYSTEMD", + "VPN_PLUGIN", + "PROXY", + "TC", + NULL); + } + domains = *argv; + } else { + g_string_printf(nmc->return_text, _("Error: property '%s' is not known."), *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return; + } + } while (next_arg(nmc, &argc, &argv, NULL) == 0); + + if (nmc->complete) + return; + + nmc->should_wait++; + nm_client_dbus_call(nmc->client, + NM_DBUS_PATH, + NM_DBUS_INTERFACE, + "SetLogging", + g_variant_new("(ss)", level ?: "", domains ?: ""), + G_VARIANT_TYPE("()"), + -1, + NULL, + _set_logging_cb, + nmc); + } +} + +static void +save_hostname_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NmCli * nmc = user_data; + gs_free_error GError *error = NULL; + + nm_client_save_hostname_finish(NM_CLIENT(object), result, &error); + if (error) { + g_string_printf(nmc->return_text, _("Error: failed to set hostname: %s"), error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } + + quit(); +} + +static void +do_general_hostname(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + const char *hostname; + + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) + return; + + if (argc == 0) { + /* no arguments -> get hostname */ + gs_free char *s = NULL; + + g_object_get(nmc->client, NM_CLIENT_HOSTNAME, &s, NULL); + if (s) + g_print("%s\n", s); + return; + } + + hostname = *argv; + if (next_arg(nmc, &argc, &argv, NULL) == 0) + g_print("Warning: ignoring extra garbage after '%s' hostname\n", hostname); + + nmc->should_wait++; + nm_client_save_hostname_async(nmc->client, hostname, NULL, save_hostname_cb, nmc); +} + +void +nmc_command_func_general(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + static const NMCCommand cmds[] = { + {"status", do_general_status, usage_general_status, TRUE, TRUE}, + {"hostname", do_general_hostname, usage_general_hostname, TRUE, TRUE}, + {"permissions", do_general_permissions, usage_general_permissions, TRUE, TRUE}, + {"logging", do_general_logging, usage_general_logging, TRUE, TRUE}, + {"reload", do_general_reload, usage_general_reload, FALSE, FALSE}, + {NULL, do_general_status, usage_general, TRUE, TRUE}, + }; + + next_arg(nmc, &argc, &argv, NULL); + + nmc_start_polkit_agent_start_try(nmc); + + nmc_do_cmd(nmc, cmds, *argv, argc, argv); +} + +static gboolean +nmc_switch_show(NmCli *nmc, const char *switch_name, const char *header) +{ + g_return_val_if_fail(nmc != NULL, FALSE); + g_return_val_if_fail(switch_name != NULL, FALSE); + + if (nmc->required_fields && g_ascii_strcasecmp(nmc->required_fields, switch_name) != 0) { + g_string_printf(nmc->return_text, + _("Error: '--fields' value '%s' is not valid here (allowed field: %s)"), + nmc->required_fields, + switch_name); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + if (nmc->nmc_config.print_output == NMC_PRINT_NORMAL) + nmc->nmc_config_mutable.print_output = NMC_PRINT_TERSE; + + if (!nmc->required_fields) + nmc->required_fields = g_strdup(switch_name); + return show_nm_status(nmc, header, NULL); +} + +static gboolean +nmc_switch_parse_on_off(NmCli *nmc, const char *arg1, const char *arg2, gboolean *res) +{ + g_return_val_if_fail(nmc != NULL, FALSE); + g_return_val_if_fail(arg1 && arg2, FALSE); + g_return_val_if_fail(res != NULL, FALSE); + + if (!strcmp(arg2, "on")) + *res = TRUE; + else if (!strcmp(arg2, "off")) + *res = FALSE; + else { + g_string_printf(nmc->return_text, + _("Error: invalid '%s' argument: '%s' (use on/off)."), + arg1, + arg2); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + + return TRUE; +} + +static void +_do_networking_on_off_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NmCli * nmc = user_data; + gs_unref_variant GVariant *ret = NULL; + gs_free_error GError *error = NULL; + + ret = nm_client_dbus_call_finish(NM_CLIENT(object), result, &error); + if (!ret) { + if (g_error_matches(error, + NM_MANAGER_ERROR, + NM_MANAGER_ERROR_ALREADY_ENABLED_OR_DISABLED)) { + /* This is fine. Be quiet about it. */ + } else { + g_dbus_error_strip_remote_error(error); + g_string_printf(nmc->return_text, + _("Error: failed to set networking: %s"), + nmc_error_get_simple_message(error)); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } + } + quit(); +} + +static void +do_networking_on_off(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gboolean enable = nm_streq(cmd->cmd, "on"); + + next_arg(nmc, &argc, &argv, NULL); + + if (nmc->complete) + return; + + nmc_start_polkit_agent_start_try(nmc); + + nmc->should_wait++; + nm_client_dbus_call(nmc->client, + NM_DBUS_PATH, + NM_DBUS_INTERFACE, + "Enable", + g_variant_new("(b)", enable), + G_VARIANT_TYPE("()"), + -1, + NULL, + _do_networking_on_off_cb, + nmc); +} + +static void +do_networking_connectivity(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) { + if (argc == 1) + nmc_complete_strings(*argv, "check"); + return; + } + + if (!argc) { + /* no arguments -> get current state */ + nmc_switch_show(nmc, NMC_FIELDS_NM_CONNECTIVITY, N_("Connectivity")); + } else if (matches(*argv, "check")) { + gs_free_error GError *error = NULL; + + /* Register polkit agent */ + nmc_start_polkit_agent_start_try(nmc); + + nm_client_check_connectivity(nmc->client, NULL, &error); + if (error) { + g_string_printf(nmc->return_text, _("Error: %s."), error->message); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } else + nmc_switch_show(nmc, NMC_FIELDS_NM_CONNECTIVITY, N_("Connectivity")); + } else { + usage_networking(); + g_string_printf(nmc->return_text, + _("Error: 'networking' command '%s' is not valid."), + *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + } +} + +static void +do_networking_show(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + if (nmc->complete) + return; + + nmc_switch_show(nmc, NMC_FIELDS_NM_NETWORKING, N_("Networking")); +} + +void +nmc_command_func_networking(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + static const NMCCommand cmds[] = { + {"on", do_networking_on_off, usage_networking_on, TRUE, TRUE}, + {"off", do_networking_on_off, usage_networking_off, TRUE, TRUE}, + {"connectivity", do_networking_connectivity, usage_networking_connectivity, TRUE, TRUE}, + {NULL, do_networking_show, usage_networking, TRUE, TRUE}, + }; + + next_arg(nmc, &argc, &argv, NULL); + nmc_do_cmd(nmc, cmds, *argv, argc, argv); +} + +static void +do_radio_all(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gboolean enable_flag; + + next_arg(nmc, &argc, &argv, NULL); + if (argc == 0) { + if (nmc->complete) + return; + + /* no argument, show all radio switches */ + show_nm_status(nmc, N_("Radio switches"), NMC_FIELDS_NM_STATUS_RADIO); + } else { + if (nmc->complete) { + if (argc == 1) + nmc_complete_bool(*argv); + return; + } + + if (!nmc_switch_parse_on_off(nmc, *(argv - 1), *argv, &enable_flag)) + return; + + nm_client_wireless_set_enabled(nmc->client, enable_flag); + nm_client_wimax_set_enabled(nmc->client, enable_flag); + nm_client_wwan_set_enabled(nmc->client, enable_flag); + } +} + +static void +_do_radio_wifi_cb(GObject *object, GAsyncResult *result, gpointer user_data) +{ + NmCli * nmc = user_data; + gs_free_error GError *error = NULL; + + if (!nm_client_dbus_set_property_finish(NM_CLIENT(object), result, &error)) { + g_dbus_error_strip_remote_error(error); + g_string_printf(nmc->return_text, + _("Error: failed to set Wi-Fi radio: %s"), + nmc_error_get_simple_message(error)); + nmc->return_value = NMC_RESULT_ERROR_UNKNOWN; + } + quit(); +} + +static void +do_radio_wifi(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gboolean enable_flag; + + next_arg(nmc, &argc, &argv, NULL); + if (argc == 0) { + if (nmc->complete) + return; + + /* no argument, show current Wi-Fi state */ + nmc_switch_show(nmc, NMC_FIELDS_NM_WIFI, N_("Wi-Fi radio switch")); + } else { + if (nmc->complete) { + if (argc == 1) + nmc_complete_bool(*argv); + return; + } + if (!nmc_switch_parse_on_off(nmc, *(argv - 1), *argv, &enable_flag)) + return; + + nmc_start_polkit_agent_start_try(nmc); + + nmc->should_wait++; + nm_client_dbus_set_property(nmc->client, + NM_DBUS_PATH, + NM_DBUS_INTERFACE, + "WirelessEnabled", + g_variant_new_boolean(enable_flag), + -1, + NULL, + _do_radio_wifi_cb, + nmc); + } +} + +static void +do_radio_wwan(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + gboolean enable_flag; + + next_arg(nmc, &argc, &argv, NULL); + if (argc == 0) { + if (nmc->complete) + return; + + /* no argument, show current WWAN (mobile broadband) state */ + nmc_switch_show(nmc, NMC_FIELDS_NM_WWAN, N_("WWAN radio switch")); + } else { + if (nmc->complete) { + if (argc == 1) + nmc_complete_bool(*argv); + return; + } + if (!nmc_switch_parse_on_off(nmc, *(argv - 1), *argv, &enable_flag)) + return; + + nm_client_wwan_set_enabled(nmc->client, enable_flag); + } +} + +void +nmc_command_func_radio(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + static const NMCCommand cmds[] = { + {"all", do_radio_all, usage_radio_all, TRUE, TRUE}, + {"wifi", do_radio_wifi, usage_radio_wifi, TRUE, TRUE}, + {"wwan", do_radio_wwan, usage_radio_wwan, TRUE, TRUE}, + {NULL, do_radio_all, usage_radio, TRUE, TRUE}, + }; + + next_arg(nmc, &argc, &argv, NULL); + + nmc_start_polkit_agent_start_try(nmc); + + nmc_do_cmd(nmc, cmds, *argv, argc, argv); +} + +static void +networkmanager_running(NMClient *client, GParamSpec *param, NmCli *nmc) +{ + gboolean running; + char * str; + + running = nm_client_get_nm_running(client); + str = nmc_colorize(&nmc->nmc_config, + running ? NM_META_COLOR_MANAGER_RUNNING : NM_META_COLOR_MANAGER_STOPPED, + running ? _("NetworkManager has started") : _("NetworkManager has stopped")); + g_print("%s\n", str); + g_free(str); +} + +static void +client_hostname(NMClient *client, GParamSpec *param, NmCli *nmc) +{ + const char *hostname; + + g_object_get(client, NM_CLIENT_HOSTNAME, &hostname, NULL); + g_print(_("Hostname set to '%s'\n"), hostname); +} + +static void +client_primary_connection(NMClient *client, GParamSpec *param, NmCli *nmc) +{ + NMActiveConnection *primary; + const char * id; + + primary = nm_client_get_primary_connection(client); + if (primary) { + id = nm_active_connection_get_id(primary); + if (!id) + id = nm_active_connection_get_uuid(primary); + + g_print(_("'%s' is now the primary connection\n"), id); + } else { + g_print(_("There's no primary connection\n")); + } +} + +static void +client_connectivity(NMClient *client, GParamSpec *param, NmCli *nmc) +{ + NMConnectivityState connectivity; + char * str; + + g_object_get(client, NM_CLIENT_CONNECTIVITY, &connectivity, NULL); + str = nmc_colorize(&nmc->nmc_config, + connectivity_to_color(connectivity), + _("Connectivity is now '%s'\n"), + gettext(nm_connectivity_to_string(connectivity))); + g_print("%s", str); + g_free(str); +} + +static void +client_state(NMClient *client, GParamSpec *param, NmCli *nmc) +{ + NMState state; + char * str; + + g_object_get(client, NM_CLIENT_STATE, &state, NULL); + str = nmc_colorize(&nmc->nmc_config, + state_to_color(state), + _("Networkmanager is now in the '%s' state\n"), + gettext(nm_state_to_string(state))); + g_print("%s", str); + g_free(str); +} + +static void +device_overview(NmCli *nmc, NMDevice *device) +{ + GString * outbuf = g_string_sized_new(80); + char * tmp; + const GPtrArray *activatable; + + activatable = nm_device_get_available_connections(device); + + g_string_append_printf(outbuf, "%s", nm_device_get_type_description(device)); + + if (nm_device_get_state(device) == NM_DEVICE_STATE_DISCONNECTED) { + if (activatable) { + if (activatable->len == 1) + g_print("\t%d %s\n", activatable->len, _("connection available")); + else if (activatable->len > 1) + g_print("\t%d %s\n", activatable->len, _("connections available")); + } + } + + if (nm_device_get_driver(device) && strcmp(nm_device_get_driver(device), "") + && strcmp(nm_device_get_driver(device), nm_device_get_type_description(device))) { + g_string_append_printf(outbuf, " (%s)", nm_device_get_driver(device)); + } + + g_string_append_printf(outbuf, ", "); + + if (nm_device_get_hw_address(device) && strcmp(nm_device_get_hw_address(device), "")) { + g_string_append_printf(outbuf, "%s, ", nm_device_get_hw_address(device)); + } + + if (!nm_device_get_autoconnect(device)) + g_string_append_printf(outbuf, "%s, ", _("autoconnect")); + if (nm_device_get_firmware_missing(device)) { + tmp = + nmc_colorize(&nmc->nmc_config, NM_META_COLOR_DEVICE_FIRMWARE_MISSING, _("fw missing")); + g_string_append_printf(outbuf, "%s, ", tmp); + g_free(tmp); + } + if (nm_device_get_nm_plugin_missing(device)) { + tmp = nmc_colorize(&nmc->nmc_config, + NM_META_COLOR_DEVICE_PLUGIN_MISSING, + _("plugin missing")); + g_string_append_printf(outbuf, "%s, ", tmp); + g_free(tmp); + } + + switch (nm_device_get_device_type(device)) { + case NM_DEVICE_TYPE_WIFI: + case NM_DEVICE_TYPE_OLPC_MESH: + case NM_DEVICE_TYPE_WIFI_P2P: + if (!nm_client_wireless_get_enabled(nmc->client)) { + tmp = nmc_colorize(&nmc->nmc_config, NM_META_COLOR_DEVICE_DISABLED, _("sw disabled")); + g_string_append_printf(outbuf, "%s, ", tmp); + g_free(tmp); + } + if (!nm_client_wireless_hardware_get_enabled(nmc->client)) { + tmp = nmc_colorize(&nmc->nmc_config, NM_META_COLOR_DEVICE_DISABLED, _("hw disabled")); + g_string_append_printf(outbuf, "%s, ", tmp); + g_free(tmp); + } + break; + case NM_DEVICE_TYPE_MODEM: + if (nm_device_modem_get_current_capabilities(NM_DEVICE_MODEM(device)) + & (NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS | NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO)) { + if (!nm_client_wwan_get_enabled(nmc->client)) { + tmp = + nmc_colorize(&nmc->nmc_config, NM_META_COLOR_DEVICE_DISABLED, _("sw disabled")); + g_string_append_printf(outbuf, "%s, ", tmp); + g_free(tmp); + } + if (!nm_client_wwan_hardware_get_enabled(nmc->client)) { + tmp = + nmc_colorize(&nmc->nmc_config, NM_META_COLOR_DEVICE_DISABLED, _("hw disabled")); + g_string_append_printf(outbuf, "%s, ", tmp); + g_free(tmp); + } + } + break; + default: + break; + } + + if (nm_device_is_software(device)) + g_string_append_printf(outbuf, "%s, ", _("sw")); + else + g_string_append_printf(outbuf, "%s, ", _("hw")); + + if (!NM_IN_STRSET(nm_device_get_ip_iface(device), NULL, nm_device_get_iface(device))) + g_string_append_printf(outbuf, "%s %s, ", _("iface"), nm_device_get_ip_iface(device)); + + if (nm_device_get_physical_port_id(device)) + g_string_append_printf(outbuf, + "%s %s, ", + _("port"), + nm_device_get_physical_port_id(device)); + + if (nm_device_get_mtu(device)) + g_string_append_printf(outbuf, "%s %d, ", _("mtu"), nm_device_get_mtu(device)); + + if (outbuf->len >= 2) { + g_string_truncate(outbuf, outbuf->len - 2); + g_print("\t%s\n", outbuf->str); + } + + g_string_free(outbuf, TRUE); +} + +static void +ac_overview(NmCli *nmc, NMActiveConnection *ac) +{ + GString * outbuf = g_string_sized_new(80); + NMIPConfig *ip; + + if (nm_active_connection_get_master(ac)) { + g_string_append_printf(outbuf, + "%s %s, ", + _("master"), + nm_device_get_iface(nm_active_connection_get_master(ac))); + } + if (nm_active_connection_get_vpn(ac)) + g_string_append_printf(outbuf, "%s, ", _("VPN")); + if (nm_active_connection_get_default(ac)) + g_string_append_printf(outbuf, "%s, ", _("ip4 default")); + if (nm_active_connection_get_default6(ac)) + g_string_append_printf(outbuf, "%s, ", _("ip6 default")); + if (outbuf->len >= 2) { + g_string_truncate(outbuf, outbuf->len - 2); + g_print("\t%s\n", outbuf->str); + } + + ip = nm_active_connection_get_ip4_config(ac); + if (ip) { + const GPtrArray *p; + int i; + + p = nm_ip_config_get_addresses(ip); + for (i = 0; i < p->len; i++) { + NMIPAddress *a = p->pdata[i]; + g_print("\tinet4 %s/%d\n", nm_ip_address_get_address(a), nm_ip_address_get_prefix(a)); + } + + p = nm_ip_config_get_routes(ip); + for (i = 0; i < p->len; i++) { + NMIPRoute *a = p->pdata[i]; + g_print("\troute4 %s/%d\n", nm_ip_route_get_dest(a), nm_ip_route_get_prefix(a)); + } + } + + ip = nm_active_connection_get_ip6_config(ac); + if (ip) { + const GPtrArray *p; + int i; + + p = nm_ip_config_get_addresses(ip); + for (i = 0; i < p->len; i++) { + NMIPAddress *a = p->pdata[i]; + g_print("\tinet6 %s/%d\n", nm_ip_address_get_address(a), nm_ip_address_get_prefix(a)); + } + + p = nm_ip_config_get_routes(ip); + for (i = 0; i < p->len; i++) { + NMIPRoute *a = p->pdata[i]; + g_print("\troute6 %s/%d\n", nm_ip_route_get_dest(a), nm_ip_route_get_prefix(a)); + } + } + + g_string_free(outbuf, TRUE); +} + +void +nmc_command_func_overview(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + NMDevice ** devices; + const GPtrArray * p; + NMActiveConnection *ac; + NMMetaColor color; + NMDnsEntry * dns; + char * tmp; + int i; + + next_arg(nmc, &argc, &argv, NULL); + + /* Register polkit agent */ + nmc_start_polkit_agent_start_try(nmc); + + nm_cli_spawn_pager(&nmc->nmc_config, &nmc->pager_data); + + /* The VPN connections don't have devices (yet?). */ + p = nm_client_get_active_connections(nmc->client); + for (i = 0; i < p->len; i++) { + ac = p->pdata[i]; + + if (!nm_active_connection_get_vpn(ac)) + continue; + + color = nmc_active_connection_state_to_color(ac); + tmp = nmc_colorize(&nmc->nmc_config, + color, + _("%s VPN connection"), + nm_active_connection_get_id(ac)); + g_print("%s\n", tmp); + g_free(tmp); + + ac_overview(nmc, ac); + g_print("\n"); + } + + devices = nmc_get_devices_sorted(nmc->client); + for (i = 0; devices[i]; i++) { + NMDevice *device = devices[i]; + + ac = nm_device_get_active_connection(device); + + color = nmc_device_state_to_color(device); + if (ac) { + /* TRANSLATORS: prints header line for activated device in plain `nmcli` overview output as + * "<interface-name>: <device-state> to <connection-id>" */ + tmp = nmc_colorize(&nmc->nmc_config, + color, + C_("nmcli-overview", "%s: %s to %s"), + nm_device_get_iface(device), + gettext(nmc_device_state_to_string_with_external(device)), + nm_active_connection_get_id(ac)); + } else { + /* TRANSLATORS: prints header line for not active device in plain `nmcli` overview output as + * "<interface-name>: <device-state>" */ + tmp = nmc_colorize(&nmc->nmc_config, + color, + C_("nmcli-overview", "%s: %s"), + nm_device_get_iface(device), + gettext(nmc_device_state_to_string_with_external(device))); + } + g_print("%s\n", tmp); + g_free(tmp); + + if (nm_device_get_description(device) && strcmp(nm_device_get_description(device), "")) + g_print("\t\"%s\"\n", nm_device_get_description(device)); + + device_overview(nmc, device); + if (ac) + ac_overview(nmc, ac); + g_print("\n"); + } + g_free(devices); + + p = nm_client_get_dns_configuration(nmc->client); + for (i = 0; p && i < p->len; i++) { + const char *const *strv; + + dns = p->pdata[i]; + strv = nm_dns_entry_get_nameservers(dns); + if (!strv || !strv[0]) { + /* Invalid entry */ + continue; + } + + if (i == 0) + g_print("DNS configuration:\n"); + + tmp = g_strjoinv(" ", (char **) strv); + g_print("\tservers: %s\n", tmp); + g_free(tmp); + + strv = nm_dns_entry_get_domains(dns); + if (strv && strv[0]) { + tmp = g_strjoinv(" ", (char **) strv); + g_print("\tdomains: %s\n", tmp); + g_free(tmp); + } + + if (nm_dns_entry_get_interface(dns)) + g_print("\tinterface: %s\n", nm_dns_entry_get_interface(dns)); + + if (nm_dns_entry_get_vpn(dns)) + g_print("\ttype: vpn\n"); + g_print("\n"); + } + + g_print(_("Use \"nmcli device show\" to get complete information about known devices and\n" + "\"nmcli connection show\" to get an overview on active connection profiles.\n" + "\n" + "Consult nmcli(1) and nmcli-examples(7) manual pages for complete usage details.\n")); +} + +void +nmc_command_func_monitor(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv) +{ + next_arg(nmc, &argc, &argv, NULL); + + if (nmc->complete) + return; + + if (argc > 0) { + if (!nmc_arg_is_help(*argv)) { + g_string_printf(nmc->return_text, + _("Error: 'monitor' command '%s' is not valid."), + *argv); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + } + + usage_monitor(); + return; + } + + if (!nm_client_get_nm_running(nmc->client)) { + char *str; + + str = nmc_colorize(&nmc->nmc_config, + NM_META_COLOR_MANAGER_STOPPED, + _("Networkmanager is not running (waiting for it)\n")); + g_print("%s", str); + g_free(str); + } + + g_signal_connect(nmc->client, + "notify::" NM_CLIENT_NM_RUNNING, + G_CALLBACK(networkmanager_running), + nmc); + g_signal_connect(nmc->client, "notify::" NM_CLIENT_HOSTNAME, G_CALLBACK(client_hostname), nmc); + g_signal_connect(nmc->client, + "notify::" NM_CLIENT_PRIMARY_CONNECTION, + G_CALLBACK(client_primary_connection), + nmc); + g_signal_connect(nmc->client, + "notify::" NM_CLIENT_CONNECTIVITY, + G_CALLBACK(client_connectivity), + nmc); + g_signal_connect(nmc->client, "notify::" NM_CLIENT_STATE, G_CALLBACK(client_state), nmc); + + nmc->should_wait++; + + monitor_devices(nmc); + monitor_connections(nmc); +} diff --git a/src/nmcli/generate-docs-nm-settings-nmcli.c b/src/nmcli/generate-docs-nm-settings-nmcli.c new file mode 100644 index 00000000..cd1bb670 --- /dev/null +++ b/src/nmcli/generate-docs-nm-settings-nmcli.c @@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include "libnmc-setting/nm-meta-setting-desc.h" + +#define INDENT 4 + +static char * +_xml_escape_attribute(const char *value) +{ + gs_free char *s = NULL; + + s = g_markup_escape_text(value, -1); + return g_strdup_printf("\"%s\"", s); +} + +static const char * +_indent_level(guint num_spaces) +{ + static const char spaces[] = " "; + + nm_assert(num_spaces < G_N_ELEMENTS(spaces)); + return &spaces[G_N_ELEMENTS(spaces) - num_spaces - 1]; +} + +int +main(int argc, char *argv[]) +{ + int i_sett_infos; + int i_property; + + g_print("<nm-setting-docs>\n"); + for (i_sett_infos = 0; i_sett_infos < G_N_ELEMENTS(nm_meta_setting_infos_editor); + i_sett_infos++) { + const NMMetaSettingInfoEditor *sett_info = &nm_meta_setting_infos_editor[i_sett_infos]; + gs_free char * tmp_s1 = NULL; + gs_free char * tmp_s2 = NULL; + + g_print("%s<setting", _indent_level(INDENT)); + g_print(" name=%s", tmp_s1 = _xml_escape_attribute(sett_info->general->setting_name)); + if (sett_info->alias) + g_print("\n%salias=%s", + _indent_level(INDENT + 9), + tmp_s2 = _xml_escape_attribute(sett_info->alias)); + g_print(" >\n"); + + for (i_property = 0; i_property < sett_info->properties_num; i_property++) { + const NMMetaPropertyInfo *prop_info = sett_info->properties[i_property]; + gs_free char * tmp2 = NULL; + gs_free char * tmp3 = NULL; + gs_free char * tmp4 = NULL; + + g_print("%s<property", _indent_level(2 * INDENT)); + g_print(" name=%s", tmp2 = _xml_escape_attribute(prop_info->property_name)); + if (prop_info->property_alias) + g_print("\n%salias=%s", + _indent_level(2 * INDENT + 10), + tmp3 = _xml_escape_attribute(prop_info->property_alias)); + if (prop_info->describe_doc) + g_print("\n%sdescription=%s", + _indent_level(2 * INDENT + 10), + tmp4 = _xml_escape_attribute(prop_info->describe_doc)); + g_print(" />\n"); + } + + g_print("%s</setting>\n", _indent_level(INDENT)); + } + g_print("</nm-setting-docs>\n"); + return 0; +} diff --git a/src/nmcli/generate-docs-nm-settings-nmcli.xml b/src/nmcli/generate-docs-nm-settings-nmcli.xml new file mode 100644 index 00000000..ca5225ba --- /dev/null +++ b/src/nmcli/generate-docs-nm-settings-nmcli.xml @@ -0,0 +1,1143 @@ +<nm-setting-docs> + <setting name="6lowpan" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID from which this 6LowPAN interface should be created." /> + </setting> + <setting name="802-11-olpc-mesh" + alias="olpc-mesh" > + <property name="ssid" + alias="ssid" + description="SSID of the mesh network to join." /> + <property name="channel" + alias="channel" + description="Channel on which the mesh network to join is located." /> + <property name="dhcp-anycast-address" + alias="dhcp-anycast" + description="Anycast DHCP MAC address used when requesting an IP address via DHCP. The specific anycast address used determines which DHCP server class answers the request. This is currently only implemented by dhclient DHCP plugin." /> + </setting> + <setting name="802-11-wireless" + alias="wifi" > + <property name="ssid" + alias="ssid" + description="SSID of the Wi-Fi network. Must be specified." /> + <property name="mode" + alias="mode" + description="Wi-Fi network mode; one of "infrastructure", "mesh", "adhoc" or "ap". If blank, infrastructure is assumed." /> + <property name="band" + description="802.11 frequency band of the network. One of "a" for 5GHz 802.11a or "bg" for 2.4GHz 802.11. This will lock associations to the Wi-Fi network to the specific band, i.e. if "a" is specified, the device will not associate with the same network in the 2.4GHz band even if the network's settings are compatible. This setting depends on specific driver capability and may not work with all drivers." /> + <property name="channel" + description="Wireless channel to use for the Wi-Fi connection. The device will only join (or create for Ad-Hoc networks) a Wi-Fi network on the specified channel. Because channel numbers overlap between bands, this property also requires the "band" property to be set." /> + <property name="bssid" + description="If specified, directs the device to only associate with the given access point. This capability is highly driver dependent and not supported by all devices. Note: this property does not control the BSSID used when creating an Ad-Hoc network and is unlikely to in the future." /> + <property name="rate" + description="If non-zero, directs the device to only use the specified bitrate for communication with the access point. Units are in Kb/s, ie 5500 = 5.5 Mbit/s. This property is highly driver dependent and not all devices support setting a static bitrate." /> + <property name="tx-power" + description="If non-zero, directs the device to use the specified transmit power. Units are dBm. This property is highly driver dependent and not all devices support setting a static transmit power." /> + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the Wi-Fi device whose permanent MAC address matches. This property does not change the MAC address of the device (i.e. MAC spoofing)." /> + <property name="cloned-mac-address" + alias="cloned-mac" + description="If specified, request that the device use this MAC address instead. This is known as MAC cloning or spoofing. Beside explicitly specifying a MAC address, the special values "preserve", "permanent", "random" and "stable" are supported. "preserve" means not to touch the MAC address on activation. "permanent" means to use the permanent hardware address of the device. "random" creates a random MAC address on each connect. "stable" creates a hashed MAC address based on connection.stable-id and a machine dependent key. If unspecified, the value can be overwritten via global defaults, see manual of NetworkManager.conf. If still unspecified, it defaults to "preserve" (older versions of NetworkManager may use a different default value). On D-Bus, this field is expressed as "assigned-mac-address" or the deprecated "cloned-mac-address"." /> + <property name="generate-mac-address-mask" + description="With "cloned-mac-address" setting "random" or "stable", by default all bits of the MAC address are scrambled and a locally-administered, unicast MAC address is created. This property allows to specify that certain bits are fixed. Note that the least significant bit of the first MAC address will always be unset to create a unicast MAC address. If the property is NULL, it is eligible to be overwritten by a default connection setting. If the value is still NULL or an empty string, the default is to create a locally-administered, unicast MAC address. If the value contains one MAC address, this address is used as mask. The set bits of the mask are to be filled with the current MAC address of the device, while the unset bits are subject to randomization. Setting "FE:FF:FF:00:00:00" means to preserve the OUI of the current MAC address and only randomize the lower 3 bytes using the "random" or "stable" algorithm. If the value contains one additional MAC address after the mask, this address is used instead of the current MAC address to fill the bits that shall not be randomized. For example, a value of "FE:FF:FF:00:00:00 68:F7:28:00:00:00" will set the OUI of the MAC address to 68:F7:28, while the lower bits are randomized. A value of "02:00:00:00:00:00 00:00:00:00:00:00" will create a fully scrambled globally-administered, burned-in MAC address. If the value contains more than one additional MAC addresses, one of them is chosen randomly. For example, "02:00:00:00:00:00 00:00:00:00:00:00 02:00:00:00:00:00" will create a fully scrambled MAC address, randomly locally or globally administered." /> + <property name="mac-address-blacklist" + description="A list of permanent MAC addresses of Wi-Fi devices to which this connection should never apply. Each MAC address should be given in the standard hex-digits-and-colons notation (eg "00:11:22:33:44:55")." /> + <property name="mac-address-randomization" + description="One of NM_SETTING_MAC_RANDOMIZATION_DEFAULT (0) (never randomize unless the user has set a global default to randomize and the supplicant supports randomization), NM_SETTING_MAC_RANDOMIZATION_NEVER (1) (never randomize the MAC address), or NM_SETTING_MAC_RANDOMIZATION_ALWAYS (2) (always randomize the MAC address). This property is deprecated for 'cloned-mac-address'. Deprecated: 1" /> + <property name="mtu" + alias="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple Ethernet frames." /> + <property name="seen-bssids" + description="A list of BSSIDs (each BSSID formatted as a MAC address like "00:11:22:33:44:55") that have been detected as part of the Wi-Fi network. NetworkManager internally tracks previously seen BSSIDs. The property is only meant for reading and reflects the BSSID list of NetworkManager. The changes you make to this property will not be preserved." /> + <property name="hidden" + description="If TRUE, indicates that the network is a non-broadcasting network that hides its SSID. This works both in infrastructure and AP mode. In infrastructure mode, various workarounds are used for a more reliable discovery of hidden networks, such as probe-scanning the SSID. However, these workarounds expose inherent insecurities with hidden SSID networks, and thus hidden SSID networks should be used with caution. In AP mode, the created network does not broadcast its SSID. Note that marking the network as hidden may be a privacy issue for you (in infrastructure mode) or client stations (in AP mode), as the explicit probe-scans are distinctly recognizable on the air." /> + <property name="powersave" + description="One of NM_SETTING_WIRELESS_POWERSAVE_DISABLE (2) (disable Wi-Fi power saving), NM_SETTING_WIRELESS_POWERSAVE_ENABLE (3) (enable Wi-Fi power saving), NM_SETTING_WIRELESS_POWERSAVE_IGNORE (1) (don't touch currently configure setting) or NM_SETTING_WIRELESS_POWERSAVE_DEFAULT (0) (use the globally configured value). All other values are reserved." /> + <property name="wake-on-wlan" + description="The NMSettingWirelessWakeOnWLan options to enable. Not all devices support all options. May be any combination of NM_SETTING_WIRELESS_WAKE_ON_WLAN_ANY (0x2), NM_SETTING_WIRELESS_WAKE_ON_WLAN_DISCONNECT (0x4), NM_SETTING_WIRELESS_WAKE_ON_WLAN_MAGIC (0x8), NM_SETTING_WIRELESS_WAKE_ON_WLAN_GTK_REKEY_FAILURE (0x10), NM_SETTING_WIRELESS_WAKE_ON_WLAN_EAP_IDENTITY_REQUEST (0x20), NM_SETTING_WIRELESS_WAKE_ON_WLAN_4WAY_HANDSHAKE (0x40), NM_SETTING_WIRELESS_WAKE_ON_WLAN_RFKILL_RELEASE (0x80), NM_SETTING_WIRELESS_WAKE_ON_WLAN_TCP (0x100) or the special values NM_SETTING_WIRELESS_WAKE_ON_WLAN_DEFAULT (0x1) (to use global settings) and NM_SETTING_WIRELESS_WAKE_ON_WLAN_IGNORE (0x8000) (to disable management of Wake-on-LAN in NetworkManager)." /> + <property name="ap-isolation" + description="Configures AP isolation, which prevents communication between wireless devices connected to this AP. This property can be set to a value different from NM_TERNARY_DEFAULT (-1) only when the interface is configured in AP mode. If set to NM_TERNARY_TRUE (1), devices are not able to communicate with each other. This increases security because it protects devices against attacks from other clients in the network. At the same time, it prevents devices to access resources on the same wireless networks as file shares, printers, etc. If set to NM_TERNARY_FALSE (0), devices can talk to each other. When set to NM_TERNARY_DEFAULT (-1), the global default is used; in case the global default is unspecified it is assumed to be NM_TERNARY_FALSE (0)." /> + </setting> + <setting name="802-11-wireless-security" + alias="wifi-sec" > + <property name="key-mgmt" + description="Key management used for the connection. One of "none" (WEP or no password protection), "ieee8021x" (Dynamic WEP), "owe" (Opportunistic Wireless Encryption), "wpa-psk" (WPA2 + WPA3 personal), "sae" (WPA3 personal only), "wpa-eap" (WPA2 + WPA3 enterprise) or "wpa-eap-suite-b-192" (WPA3 enterprise only). This property must be set for any Wi-Fi connection that uses security." /> + <property name="wep-tx-keyidx" + description="When static WEP is used (ie, key-mgmt = "none") and a non-default WEP key index is used by the AP, put that WEP key index here. Valid values are 0 (default key) through 3. Note that some consumer access points (like the Linksys WRT54G) number the keys 1 - 4." /> + <property name="auth-alg" + description="When WEP is used (ie, key-mgmt = "none" or "ieee8021x") indicate the 802.11 authentication algorithm required by the AP here. One of "open" for Open System, "shared" for Shared Key, or "leap" for Cisco LEAP. When using Cisco LEAP (ie, key-mgmt = "ieee8021x" and auth-alg = "leap") the "leap-username" and "leap-password" properties must be specified." /> + <property name="proto" + description="List of strings specifying the allowed WPA protocol versions to use. Each element may be one "wpa" (allow WPA) or "rsn" (allow WPA2/RSN). If not specified, both WPA and RSN connections are allowed." /> + <property name="pairwise" + description="A list of pairwise encryption algorithms which prevents connections to Wi-Fi networks that do not utilize one of the algorithms in the list. For maximum compatibility leave this property empty. Each list element may be one of "tkip" or "ccmp"." /> + <property name="group" + description="A list of group/broadcast encryption algorithms which prevents connections to Wi-Fi networks that do not utilize one of the algorithms in the list. For maximum compatibility leave this property empty. Each list element may be one of "wep40", "wep104", "tkip", or "ccmp"." /> + <property name="pmf" + description="Indicates whether Protected Management Frames (802.11w) must be enabled for the connection. One of NM_SETTING_WIRELESS_SECURITY_PMF_DEFAULT (0) (use global default value), NM_SETTING_WIRELESS_SECURITY_PMF_DISABLE (1) (disable PMF), NM_SETTING_WIRELESS_SECURITY_PMF_OPTIONAL (2) (enable PMF if the supplicant and the access point support it) or NM_SETTING_WIRELESS_SECURITY_PMF_REQUIRED (3) (enable PMF and fail if not supported). When set to NM_SETTING_WIRELESS_SECURITY_PMF_DEFAULT (0) and no global default is set, PMF will be optionally enabled." /> + <property name="leap-username" + description="The login username for legacy LEAP connections (ie, key-mgmt = "ieee8021x" and auth-alg = "leap")." /> + <property name="wep-key0" + description="Index 0 WEP key. This is the WEP key used in most networks. See the "wep-key-type" property for a description of how this key is interpreted." /> + <property name="wep-key1" + description="Index 1 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted." /> + <property name="wep-key2" + description="Index 2 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted." /> + <property name="wep-key3" + description="Index 3 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted." /> + <property name="wep-key-flags" + description="Flags indicating how to handle the "wep-key0", "wep-key1", "wep-key2", and "wep-key3" properties." /> + <property name="wep-key-type" + description="Controls the interpretation of WEP keys. Allowed values are NM_WEP_KEY_TYPE_KEY (1), in which case the key is either a 10- or 26-character hexadecimal string, or a 5- or 13-character ASCII password; or NM_WEP_KEY_TYPE_PASSPHRASE (2), in which case the passphrase is provided as a string and will be hashed using the de-facto MD5 method to derive the actual WEP key." /> + <property name="psk" + description="Pre-Shared-Key for WPA networks. For WPA-PSK, it's either an ASCII passphrase of 8 to 63 characters that is (as specified in the 802.11i standard) hashed to derive the actual key, or the key in form of 64 hexadecimal character. The WPA3-Personal networks use a passphrase of any length for SAE authentication." /> + <property name="psk-flags" + description="Flags indicating how to handle the "psk" property." /> + <property name="leap-password" + description="The login password for legacy LEAP connections (ie, key-mgmt = "ieee8021x" and auth-alg = "leap")." /> + <property name="leap-password-flags" + description="Flags indicating how to handle the "leap-password" property." /> + <property name="wps-method" + description="Flags indicating which mode of WPS is to be used if any. There's little point in changing the default setting as NetworkManager will automatically determine whether it's feasible to start WPS enrollment from the Access Point capabilities. WPS can be disabled by setting this property to a value of 1." /> + <property name="fils" + description="Indicates whether Fast Initial Link Setup (802.11ai) must be enabled for the connection. One of NM_SETTING_WIRELESS_SECURITY_FILS_DEFAULT (0) (use global default value), NM_SETTING_WIRELESS_SECURITY_FILS_DISABLE (1) (disable FILS), NM_SETTING_WIRELESS_SECURITY_FILS_OPTIONAL (2) (enable FILS if the supplicant and the access point support it) or NM_SETTING_WIRELESS_SECURITY_FILS_REQUIRED (3) (enable FILS and fail if not supported). When set to NM_SETTING_WIRELESS_SECURITY_FILS_DEFAULT (0) and no global default is set, FILS will be optionally enabled." /> + </setting> + <setting name="802-1x" > + <property name="optional" + description="Whether the 802.1X authentication is optional. If TRUE, the activation will continue even after a timeout or an authentication failure. Setting the property to TRUE is currently allowed only for Ethernet connections. If set to FALSE, the activation can continue only after a successful authentication." /> + <property name="eap" + description="The allowed EAP method to be used when authenticating to the network with 802.1x. Valid methods are: "leap", "md5", "tls", "peap", "ttls", "pwd", and "fast". Each method requires different configuration using the properties of this setting; refer to wpa_supplicant documentation for the allowed combinations." /> + <property name="identity" + description="Identity string for EAP authentication methods. Often the user's user or login name." /> + <property name="anonymous-identity" + description="Anonymous identity string for EAP authentication methods. Used as the unencrypted identity with EAP types that support different tunneled identity like EAP-TTLS." /> + <property name="pac-file" + description="UTF-8 encoded file path containing PAC for EAP-FAST." /> + <property name="ca-cert" + description="Contains the CA certificate if used by the EAP method specified in the "eap" property. Certificate data is specified using a "scheme"; three are currently supported: blob, path and pkcs#11 URL. When using the blob scheme this property should be set to the certificate's DER encoded data. When using the path scheme, this property should be set to the full UTF-8 encoded path of the certificate, prefixed with the string "file://" and ending with a terminating NUL byte. This property can be unset even if the EAP method supports CA certificates, but this allows man-in-the-middle attacks and is NOT recommended. Note that enabling NMSetting8021x:system-ca-certs will override this setting to use the built-in path, if the built-in path is not a directory." /> + <property name="ca-cert-password" + description="The password used to access the CA certificate stored in "ca-cert" property. Only makes sense if the certificate is stored on a PKCS#11 token that requires a login." /> + <property name="ca-cert-password-flags" + description="Flags indicating how to handle the "ca-cert-password" property." /> + <property name="ca-path" + description="UTF-8 encoded path to a directory containing PEM or DER formatted certificates to be added to the verification chain in addition to the certificate specified in the "ca-cert" property. If NMSetting8021x:system-ca-certs is enabled and the built-in CA path is an existing directory, then this setting is ignored." /> + <property name="subject-match" + description="Substring to be matched against the subject of the certificate presented by the authentication server. When unset, no verification of the authentication server certificate's subject is performed. This property provides little security, if any, and its use is deprecated in favor of NMSetting8021x:domain-suffix-match." /> + <property name="altsubject-matches" + description="List of strings to be matched against the altSubjectName of the certificate presented by the authentication server. If the list is empty, no verification of the server certificate's altSubjectName is performed." /> + <property name="domain-suffix-match" + description="Constraint for server domain name. If set, this FQDN is used as a suffix match requirement for dNSName element(s) of the certificate presented by the authentication server. If a matching dNSName is found, this constraint is met. If no dNSName values are present, this constraint is matched against SubjectName CN using same suffix match comparison. Since version 1.24, multiple valid FQDNs can be passed as a ";" delimited list." /> + <property name="domain-match" + description="Constraint for server domain name. If set, this list of FQDNs is used as a match requirement for dNSName element(s) of the certificate presented by the authentication server. If a matching dNSName is found, this constraint is met. If no dNSName values are present, this constraint is matched against SubjectName CN using the same comparison. Multiple valid FQDNs can be passed as a ";" delimited list." /> + <property name="client-cert" + description="Contains the client certificate if used by the EAP method specified in the "eap" property. Certificate data is specified using a "scheme"; two are currently supported: blob and path. When using the blob scheme (which is backwards compatible with NM 0.7.x) this property should be set to the certificate's DER encoded data. When using the path scheme, this property should be set to the full UTF-8 encoded path of the certificate, prefixed with the string "file://" and ending with a terminating NUL byte." /> + <property name="client-cert-password" + description="The password used to access the client certificate stored in "client-cert" property. Only makes sense if the certificate is stored on a PKCS#11 token that requires a login." /> + <property name="client-cert-password-flags" + description="Flags indicating how to handle the "client-cert-password" property." /> + <property name="phase1-peapver" + description="Forces which PEAP version is used when PEAP is set as the EAP method in the "eap" property. When unset, the version reported by the server will be used. Sometimes when using older RADIUS servers, it is necessary to force the client to use a particular PEAP version. To do so, this property may be set to "0" or "1" to force that specific PEAP version." /> + <property name="phase1-peaplabel" + description="Forces use of the new PEAP label during key derivation. Some RADIUS servers may require forcing the new PEAP label to interoperate with PEAPv1. Set to "1" to force use of the new PEAP label. See the wpa_supplicant documentation for more details." /> + <property name="phase1-fast-provisioning" + description="Enables or disables in-line provisioning of EAP-FAST credentials when FAST is specified as the EAP method in the "eap" property. Recognized values are "0" (disabled), "1" (allow unauthenticated provisioning), "2" (allow authenticated provisioning), and "3" (allow both authenticated and unauthenticated provisioning). See the wpa_supplicant documentation for more details." /> + <property name="phase1-auth-flags" + description="Specifies authentication flags to use in "phase 1" outer authentication using NMSetting8021xAuthFlags options. The individual TLS versions can be explicitly disabled. If a certain TLS disable flag is not set, it is up to the supplicant to allow or forbid it. The TLS options map to tls_disable_tlsv1_x settings. See the wpa_supplicant documentation for more details." /> + <property name="phase2-auth" + description="Specifies the allowed "phase 2" inner authentication method when an EAP method that uses an inner TLS tunnel is specified in the "eap" property. For TTLS this property selects one of the supported non-EAP inner methods: "pap", "chap", "mschap", "mschapv2" while "phase2-autheap" selects an EAP inner method. For PEAP this selects an inner EAP method, one of: "gtc", "otp", "md5" and "tls". Each "phase 2" inner method requires specific parameters for successful authentication; see the wpa_supplicant documentation for more details. Both "phase2-auth" and "phase2-autheap" cannot be specified." /> + <property name="phase2-autheap" + description="Specifies the allowed "phase 2" inner EAP-based authentication method when TTLS is specified in the "eap" property. Recognized EAP-based "phase 2" methods are "md5", "mschapv2", "otp", "gtc", and "tls". Each "phase 2" inner method requires specific parameters for successful authentication; see the wpa_supplicant documentation for more details." /> + <property name="phase2-ca-cert" + description="Contains the "phase 2" CA certificate if used by the EAP method specified in the "phase2-auth" or "phase2-autheap" properties. Certificate data is specified using a "scheme"; three are currently supported: blob, path and pkcs#11 URL. When using the blob scheme this property should be set to the certificate's DER encoded data. When using the path scheme, this property should be set to the full UTF-8 encoded path of the certificate, prefixed with the string "file://" and ending with a terminating NUL byte. This property can be unset even if the EAP method supports CA certificates, but this allows man-in-the-middle attacks and is NOT recommended. Note that enabling NMSetting8021x:system-ca-certs will override this setting to use the built-in path, if the built-in path is not a directory." /> + <property name="phase2-ca-cert-password" + description="The password used to access the "phase2" CA certificate stored in "phase2-ca-cert" property. Only makes sense if the certificate is stored on a PKCS#11 token that requires a login." /> + <property name="phase2-ca-cert-password-flags" + description="Flags indicating how to handle the "phase2-ca-cert-password" property." /> + <property name="phase2-ca-path" + description="UTF-8 encoded path to a directory containing PEM or DER formatted certificates to be added to the verification chain in addition to the certificate specified in the "phase2-ca-cert" property. If NMSetting8021x:system-ca-certs is enabled and the built-in CA path is an existing directory, then this setting is ignored." /> + <property name="phase2-subject-match" + description="Substring to be matched against the subject of the certificate presented by the authentication server during the inner "phase 2" authentication. When unset, no verification of the authentication server certificate's subject is performed. This property provides little security, if any, and its use is deprecated in favor of NMSetting8021x:phase2-domain-suffix-match." /> + <property name="phase2-altsubject-matches" + description="List of strings to be matched against the altSubjectName of the certificate presented by the authentication server during the inner "phase 2" authentication. If the list is empty, no verification of the server certificate's altSubjectName is performed." /> + <property name="phase2-domain-suffix-match" + description="Constraint for server domain name. If set, this FQDN is used as a suffix match requirement for dNSName element(s) of the certificate presented by the authentication server during the inner "phase 2" authentication. If a matching dNSName is found, this constraint is met. If no dNSName values are present, this constraint is matched against SubjectName CN using same suffix match comparison. Since version 1.24, multiple valid FQDNs can be passed as a ";" delimited list." /> + <property name="phase2-domain-match" + description="Constraint for server domain name. If set, this list of FQDNs is used as a match requirement for dNSName element(s) of the certificate presented by the authentication server during the inner "phase 2" authentication. If a matching dNSName is found, this constraint is met. If no dNSName values are present, this constraint is matched against SubjectName CN using the same comparison. Multiple valid FQDNs can be passed as a ";" delimited list." /> + <property name="phase2-client-cert" + description="Contains the "phase 2" client certificate if used by the EAP method specified in the "phase2-auth" or "phase2-autheap" properties. Certificate data is specified using a "scheme"; two are currently supported: blob and path. When using the blob scheme (which is backwards compatible with NM 0.7.x) this property should be set to the certificate's DER encoded data. When using the path scheme, this property should be set to the full UTF-8 encoded path of the certificate, prefixed with the string "file://" and ending with a terminating NUL byte. This property can be unset even if the EAP method supports CA certificates, but this allows man-in-the-middle attacks and is NOT recommended." /> + <property name="phase2-client-cert-password" + description="The password used to access the "phase2" client certificate stored in "phase2-client-cert" property. Only makes sense if the certificate is stored on a PKCS#11 token that requires a login." /> + <property name="phase2-client-cert-password-flags" + description="Flags indicating how to handle the "phase2-client-cert-password" property." /> + <property name="password" + description="UTF-8 encoded password used for EAP authentication methods. If both the "password" property and the "password-raw" property are specified, "password" is preferred." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + <property name="password-raw" + description="Password used for EAP authentication methods, given as a byte array to allow passwords in other encodings than UTF-8 to be used. If both the "password" property and the "password-raw" property are specified, "password" is preferred." /> + <property name="password-raw-flags" + description="Flags indicating how to handle the "password-raw" property." /> + <property name="private-key" + description="Contains the private key when the "eap" property is set to "tls". Key data is specified using a "scheme"; two are currently supported: blob and path. When using the blob scheme and private keys, this property should be set to the key's encrypted PEM encoded data. When using private keys with the path scheme, this property should be set to the full UTF-8 encoded path of the key, prefixed with the string "file://" and ending with a terminating NUL byte. When using PKCS#12 format private keys and the blob scheme, this property should be set to the PKCS#12 data and the "private-key-password" property must be set to password used to decrypt the PKCS#12 certificate and key. When using PKCS#12 files and the path scheme, this property should be set to the full UTF-8 encoded path of the key, prefixed with the string "file://" and ending with a terminating NUL byte, and as with the blob scheme the "private-key-password" property must be set to the password used to decode the PKCS#12 private key and certificate. WARNING: "private-key" is not a "secret" property, and thus unencrypted private key data using the BLOB scheme may be readable by unprivileged users. Private keys should always be encrypted with a private key password to prevent unauthorized access to unencrypted private key data." /> + <property name="private-key-password" + description="The password used to decrypt the private key specified in the "private-key" property when the private key either uses the path scheme, or if the private key is a PKCS#12 format key." /> + <property name="private-key-password-flags" + description="Flags indicating how to handle the "private-key-password" property." /> + <property name="phase2-private-key" + description="Contains the "phase 2" inner private key when the "phase2-auth" or "phase2-autheap" property is set to "tls". Key data is specified using a "scheme"; two are currently supported: blob and path. When using the blob scheme and private keys, this property should be set to the key's encrypted PEM encoded data. When using private keys with the path scheme, this property should be set to the full UTF-8 encoded path of the key, prefixed with the string "file://" and ending with a terminating NUL byte. When using PKCS#12 format private keys and the blob scheme, this property should be set to the PKCS#12 data and the "phase2-private-key-password" property must be set to password used to decrypt the PKCS#12 certificate and key. When using PKCS#12 files and the path scheme, this property should be set to the full UTF-8 encoded path of the key, prefixed with the string "file://" and ending with a terminating NUL byte, and as with the blob scheme the "phase2-private-key-password" property must be set to the password used to decode the PKCS#12 private key and certificate." /> + <property name="phase2-private-key-password" + description="The password used to decrypt the "phase 2" private key specified in the "phase2-private-key" property when the private key either uses the path scheme, or is a PKCS#12 format key." /> + <property name="phase2-private-key-password-flags" + description="Flags indicating how to handle the "phase2-private-key-password" property." /> + <property name="pin" + description="PIN used for EAP authentication methods." /> + <property name="pin-flags" + description="Flags indicating how to handle the "pin" property." /> + <property name="system-ca-certs" + description="When TRUE, overrides the "ca-path" and "phase2-ca-path" properties using the system CA directory specified at configure time with the --system-ca-path switch. The certificates in this directory are added to the verification chain in addition to any certificates specified by the "ca-cert" and "phase2-ca-cert" properties. If the path provided with --system-ca-path is rather a file name (bundle of trusted CA certificates), it overrides "ca-cert" and "phase2-ca-cert" properties instead (sets ca_cert/ca_cert2 options for wpa_supplicant)." /> + <property name="auth-timeout" + description="A timeout for the authentication. Zero means the global default; if the global default is not set, the authentication timeout is 25 seconds." /> + </setting> + <setting name="802-3-ethernet" + alias="ethernet" > + <property name="port" + description="Specific port type to use if the device supports multiple attachment methods. One of "tp" (Twisted Pair), "aui" (Attachment Unit Interface), "bnc" (Thin Ethernet) or "mii" (Media Independent Interface). If the device supports only one port type, this setting is ignored." /> + <property name="speed" + description="When a value greater than 0 is set, configures the device to use the specified speed. If "auto-negotiate" is "yes" the specified speed will be the only one advertised during link negotiation: this works only for BASE-T 802.3 specifications and is useful for enforcing gigabit speeds, as in this case link negotiation is mandatory. If the value is unset (0, the default), the link configuration will be either skipped (if "auto-negotiate" is "no", the default) or will be auto-negotiated (if "auto-negotiate" is "yes") and the local device will advertise all the supported speeds. In Mbit/s, ie 100 == 100Mbit/s. Must be set together with the "duplex" property when non-zero. Before specifying a speed value be sure your device supports it." /> + <property name="duplex" + description="When a value is set, either "half" or "full", configures the device to use the specified duplex mode. If "auto-negotiate" is "yes" the specified duplex mode will be the only one advertised during link negotiation: this works only for BASE-T 802.3 specifications and is useful for enforcing gigabits modes, as in these cases link negotiation is mandatory. If the value is unset (the default), the link configuration will be either skipped (if "auto-negotiate" is "no", the default) or will be auto-negotiated (if "auto-negotiate" is "yes") and the local device will advertise all the supported duplex modes. Must be set together with the "speed" property if specified. Before specifying a duplex mode be sure your device supports it." /> + <property name="auto-negotiate" + description="When TRUE, enforce auto-negotiation of speed and duplex mode. If "speed" and "duplex" properties are both specified, only that single mode will be advertised and accepted during the link auto-negotiation process: this works only for BASE-T 802.3 specifications and is useful for enforcing gigabits modes, as in these cases link negotiation is mandatory. When FALSE, "speed" and "duplex" properties should be both set or link configuration will be skipped." /> + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the Ethernet device whose permanent MAC address matches. This property does not change the MAC address of the device (i.e. MAC spoofing)." /> + <property name="cloned-mac-address" + alias="cloned-mac" + description="If specified, request that the device use this MAC address instead. This is known as MAC cloning or spoofing. Beside explicitly specifying a MAC address, the special values "preserve", "permanent", "random" and "stable" are supported. "preserve" means not to touch the MAC address on activation. "permanent" means to use the permanent hardware address if the device has one (otherwise this is treated as "preserve"). "random" creates a random MAC address on each connect. "stable" creates a hashed MAC address based on connection.stable-id and a machine dependent key. If unspecified, the value can be overwritten via global defaults, see manual of NetworkManager.conf. If still unspecified, it defaults to "preserve" (older versions of NetworkManager may use a different default value). On D-Bus, this field is expressed as "assigned-mac-address" or the deprecated "cloned-mac-address"." /> + <property name="generate-mac-address-mask" + description="With "cloned-mac-address" setting "random" or "stable", by default all bits of the MAC address are scrambled and a locally-administered, unicast MAC address is created. This property allows to specify that certain bits are fixed. Note that the least significant bit of the first MAC address will always be unset to create a unicast MAC address. If the property is NULL, it is eligible to be overwritten by a default connection setting. If the value is still NULL or an empty string, the default is to create a locally-administered, unicast MAC address. If the value contains one MAC address, this address is used as mask. The set bits of the mask are to be filled with the current MAC address of the device, while the unset bits are subject to randomization. Setting "FE:FF:FF:00:00:00" means to preserve the OUI of the current MAC address and only randomize the lower 3 bytes using the "random" or "stable" algorithm. If the value contains one additional MAC address after the mask, this address is used instead of the current MAC address to fill the bits that shall not be randomized. For example, a value of "FE:FF:FF:00:00:00 68:F7:28:00:00:00" will set the OUI of the MAC address to 68:F7:28, while the lower bits are randomized. A value of "02:00:00:00:00:00 00:00:00:00:00:00" will create a fully scrambled globally-administered, burned-in MAC address. If the value contains more than one additional MAC addresses, one of them is chosen randomly. For example, "02:00:00:00:00:00 00:00:00:00:00:00 02:00:00:00:00:00" will create a fully scrambled MAC address, randomly locally or globally administered." /> + <property name="mac-address-blacklist" + description="If specified, this connection will never apply to the Ethernet device whose permanent MAC address matches an address in the list. Each MAC address is in the standard hex-digits-and-colons notation (00:11:22:33:44:55)." /> + <property name="mtu" + alias="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple Ethernet frames." /> + <property name="s390-subchannels" + description="Identifies specific subchannels that this network device uses for communication with z/VM or s390 host. Like the "mac-address" property for non-z/VM devices, this property can be used to ensure this connection only applies to the network device that uses these subchannels. The list should contain exactly 3 strings, and each string may only be composed of hexadecimal characters and the period (.) character." /> + <property name="s390-nettype" + description="s390 network device type; one of "qeth", "lcs", or "ctc", representing the different types of virtual network devices available on s390 systems." /> + <property name="s390-options" + description="Dictionary of key/value pairs of s390-specific device options. Both keys and values must be strings. Allowed keys include "portno", "layer2", "portname", "protocol", among others. Key names must contain only alphanumeric characters (ie, [a-zA-Z0-9])." /> + <property name="wake-on-lan" + description="The NMSettingWiredWakeOnLan options to enable. Not all devices support all options. May be any combination of NM_SETTING_WIRED_WAKE_ON_LAN_PHY (0x2), NM_SETTING_WIRED_WAKE_ON_LAN_UNICAST (0x4), NM_SETTING_WIRED_WAKE_ON_LAN_MULTICAST (0x8), NM_SETTING_WIRED_WAKE_ON_LAN_BROADCAST (0x10), NM_SETTING_WIRED_WAKE_ON_LAN_ARP (0x20), NM_SETTING_WIRED_WAKE_ON_LAN_MAGIC (0x40) or the special values NM_SETTING_WIRED_WAKE_ON_LAN_DEFAULT (0x1) (to use global settings) and NM_SETTING_WIRED_WAKE_ON_LAN_IGNORE (0x8000) (to disable management of Wake-on-LAN in NetworkManager)." /> + <property name="wake-on-lan-password" + description="If specified, the password used with magic-packet-based Wake-on-LAN, represented as an Ethernet MAC address. If NULL, no password will be required." /> + <property name="accept-all-mac-addresses" + description="When TRUE, setup the interface to accept packets for all MAC addresses. This is enabling the kernel interface flag IFF_PROMISC. When FALSE, the interface will only accept the packets with the interface destination mac address or broadcast." /> + </setting> + <setting name="adsl" > + <property name="username" + alias="username" + description="Username used to authenticate with the ADSL service." /> + <property name="password" + alias="password" + description="Password used to authenticate with the ADSL service." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + <property name="protocol" + alias="protocol" + description="ADSL connection protocol. Can be "pppoa", "pppoe" or "ipoatm"." /> + <property name="encapsulation" + alias="encapsulation" + description="Encapsulation of ADSL connection. Can be "vcmux" or "llc"." /> + <property name="vpi" + description="VPI of ADSL connection" /> + <property name="vci" + description="VCI of ADSL connection" /> + </setting> + <setting name="bluetooth" > + <property name="bdaddr" + alias="addr" + description="The Bluetooth address of the device." /> + <property name="type" + alias="bt-type" + description="Either "dun" for Dial-Up Networking connections or "panu" for Personal Area Networking connections to devices supporting the NAP profile." /> + </setting> + <setting name="bond" > + <property name="options" + description="Dictionary of key/value pairs of bonding options. Both keys and values must be strings. Option names must contain only alphanumeric characters (ie, [a-zA-Z0-9])." /> + </setting> + <setting name="bridge" > + <property name="mac-address" + alias="mac" + description="If specified, the MAC address of bridge. When creating a new bridge, this MAC address will be set. If this field is left unspecified, the "ethernet.cloned-mac-address" is referred instead to generate the initial MAC address. Note that setting "ethernet.cloned-mac-address" anyway overwrites the MAC address of the bridge later while activating the bridge. Hence, this property is deprecated. Deprecated: 1" /> + <property name="stp" + alias="stp" + description="Controls whether Spanning Tree Protocol (STP) is enabled for this bridge." /> + <property name="priority" + alias="priority" + description="Sets the Spanning Tree Protocol (STP) priority for this bridge. Lower values are "better"; the lowest priority bridge will be elected the root bridge." /> + <property name="forward-delay" + alias="forward-delay" + description="The Spanning Tree Protocol (STP) forwarding delay, in seconds." /> + <property name="hello-time" + alias="hello-time" + description="The Spanning Tree Protocol (STP) hello time, in seconds." /> + <property name="max-age" + alias="max-age" + description="The Spanning Tree Protocol (STP) maximum message age, in seconds." /> + <property name="ageing-time" + alias="ageing-time" + description="The Ethernet MAC address aging time, in seconds." /> + <property name="group-address" + description="If specified, The MAC address of the multicast group this bridge uses for STP. The address must be a link-local address in standard Ethernet MAC address format, ie an address of the form 01:80:C2:00:00:0X, with X in [0, 4..F]. If not specified the default value is 01:80:C2:00:00:00." /> + <property name="group-forward-mask" + alias="group-forward-mask" + description="A mask of group addresses to forward. Usually, group addresses in the range from 01:80:C2:00:00:00 to 01:80:C2:00:00:0F are not forwarded according to standards. This property is a mask of 16 bits, each corresponding to a group address in that range that must be forwarded. The mask can't have bits 0, 1 or 2 set because they are used for STP, MAC pause frames and LACP." /> + <property name="multicast-hash-max" + description="Set maximum size of multicast hash table (value must be a power of 2)." /> + <property name="multicast-last-member-count" + description="Set the number of queries the bridge will send before stopping forwarding a multicast group after a "leave" message has been received." /> + <property name="multicast-last-member-interval" + description="Set interval (in deciseconds) between queries to find remaining members of a group, after a "leave" message is received." /> + <property name="multicast-membership-interval" + description="Set delay (in deciseconds) after which the bridge will leave a group, if no membership reports for this group are received." /> + <property name="multicast-querier" + description="Enable or disable sending of multicast queries by the bridge. If not specified the option is disabled." /> + <property name="multicast-querier-interval" + description="If no queries are seen after this delay (in deciseconds) has passed, the bridge will start to send its own queries." /> + <property name="multicast-query-interval" + description="Interval (in deciseconds) between queries sent by the bridge after the end of the startup phase." /> + <property name="multicast-query-response-interval" + description="Set the Max Response Time/Max Response Delay (in deciseconds) for IGMP/MLD queries sent by the bridge." /> + <property name="multicast-query-use-ifaddr" + description="If enabled the bridge's own IP address is used as the source address for IGMP queries otherwise the default of 0.0.0.0 is used." /> + <property name="multicast-snooping" + alias="multicast-snooping" + description="Controls whether IGMP snooping is enabled for this bridge. Note that if snooping was automatically disabled due to hash collisions, the system may refuse to enable the feature until the collisions are resolved." /> + <property name="multicast-startup-query-count" + description="Set the number of IGMP queries to send during startup phase." /> + <property name="multicast-startup-query-interval" + description="Sets the time (in deciseconds) between queries sent out at startup to determine membership information." /> + <property name="multicast-router" + description="Sets bridge's multicast router. Multicast-snooping must be enabled for this option to work. Supported values are: 'auto', 'disabled', 'enabled' to which kernel assigns the numbers 1, 0, and 2, respectively. If not specified the default value is 'auto' (1)." /> + <property name="vlan-filtering" + description="Control whether VLAN filtering is enabled on the bridge." /> + <property name="vlan-default-pvid" + description="The default PVID for the ports of the bridge, that is the VLAN id assigned to incoming untagged frames." /> + <property name="vlan-stats-enabled" + description="Controls whether per-VLAN stats accounting is enabled." /> + <property name="vlan-protocol" + description="If specified, the protocol used for VLAN filtering. Supported values are: '802.1Q', '802.1ad'. If not specified the default value is '802.1Q'." /> + <property name="vlans" + description="Array of bridge VLAN objects. In addition to the VLANs specified here, the bridge will also have the default-pvid VLAN configured by the bridge.vlan-default-pvid property. In nmcli the VLAN list can be specified with the following syntax: $vid [pvid] [untagged] [, $vid [pvid] [untagged]]... where $vid is either a single id between 1 and 4094 or a range, represented as a couple of ids separated by a dash." /> + </setting> + <setting name="bridge-port" > + <property name="priority" + alias="priority" + description="The Spanning Tree Protocol (STP) priority of this bridge port." /> + <property name="path-cost" + alias="path-cost" + description="The Spanning Tree Protocol (STP) port cost for destinations via this port." /> + <property name="hairpin-mode" + alias="hairpin" + description="Enables or disables "hairpin mode" for the port, which allows frames to be sent back out through the port the frame was received on." /> + <property name="vlans" + description="Array of bridge VLAN objects. In addition to the VLANs specified here, the port will also have the default-pvid VLAN configured on the bridge by the bridge.vlan-default-pvid property. In nmcli the VLAN list can be specified with the following syntax: $vid [pvid] [untagged] [, $vid [pvid] [untagged]]... where $vid is either a single id between 1 and 4094 or a range, represented as a couple of ids separated by a dash." /> + </setting> + <setting name="cdma" > + <property name="number" + description="The number to dial to establish the connection to the CDMA-based mobile broadband network, if any. If not specified, the default number (#777) is used when required." /> + <property name="username" + alias="user" + description="The username used to authenticate with the network, if required. Many providers do not require a username, or accept any username. But if a username is required, it is specified here." /> + <property name="password" + alias="password" + description="The password used to authenticate with the network, if required. Many providers do not require a password, or accept any password. But if a password is required, it is specified here." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + <property name="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple frames." /> + </setting> + <setting name="connection" > + <property name="id" + alias="con-name" + description="A human readable unique identifier for the connection, like "Work Wi-Fi" or "T-Mobile 3G"." /> + <property name="uuid" + description="A universally unique identifier for the connection, for example generated with libuuid. It should be assigned when the connection is created, and never changed as long as the connection still applies to the same network. For example, it should not be changed when the "id" property or NMSettingIP4Config changes, but might need to be re-created when the Wi-Fi SSID, mobile broadband network provider, or "type" property changes. The UUID must be in the format "2815492f-7e56-435e-b2e9-246bd7cdc664" (ie, contains only hexadecimal characters and "-")." /> + <property name="stable-id" + description="This represents the identity of the connection used for various purposes. It allows to configure multiple profiles to share the identity. Also, the stable-id can contain placeholders that are substituted dynamically and deterministically depending on the context. The stable-id is used for generating IPv6 stable private addresses with ipv6.addr-gen-mode=stable-privacy. It is also used to seed the generated cloned MAC address for ethernet.cloned-mac-address=stable and wifi.cloned-mac-address=stable. It is also used as DHCP client identifier with ipv4.dhcp-client-id=stable and to derive the DHCP DUID with ipv6.dhcp-duid=stable-[llt,ll,uuid]. Note that depending on the context where it is used, other parameters are also seeded into the generation algorithm. For example, a per-host key is commonly also included, so that different systems end up generating different IDs. Or with ipv6.addr-gen-mode=stable-privacy, also the device's name is included, so that different interfaces yield different addresses. The per-host key is the identity of your machine and stored in /var/lib/NetworkManager/secret-key. The '$' character is treated special to perform dynamic substitutions at runtime. Currently, supported are "${CONNECTION}", "${DEVICE}", "${MAC}", "${BOOT}", "${RANDOM}". These effectively create unique IDs per-connection, per-device, per-boot, or every time. Note that "${DEVICE}" corresponds to the interface name of the device and "${MAC}" is the permanent MAC address of the device. Any unrecognized patterns following '$' are treated verbatim, however are reserved for future use. You are thus advised to avoid '$' or escape it as "$$". For example, set it to "${CONNECTION}-${BOOT}-${DEVICE}" to create a unique id for this connection that changes with every reboot and differs depending on the interface where the profile activates. If the value is unset, a global connection default is consulted. If the value is still unset, the default is similar to "${CONNECTION}" and uses a unique, fixed ID for the connection." /> + <property name="type" + alias="type" + description="Base type of the connection. For hardware-dependent connections, should contain the setting name of the hardware-type specific setting (ie, "802-3-ethernet" or "802-11-wireless" or "bluetooth", etc), and for non-hardware dependent connections like VPN or otherwise, should contain the setting name of that setting type (ie, "vpn" or "bridge", etc)." /> + <property name="interface-name" + alias="ifname" + description="The name of the network interface this connection is bound to. If not set, then the connection can be attached to any interface of the appropriate type (subject to restrictions imposed by other settings). For software devices this specifies the name of the created device. For connection types where interface names cannot easily be made persistent (e.g. mobile broadband or USB Ethernet), this property should not be used. Setting this property restricts the interfaces a connection can be used with, and if interface names change or are reordered the connection may be applied to the wrong interface." /> + <property name="autoconnect" + alias="autoconnect" + description="Whether or not the connection should be automatically connected by NetworkManager when the resources for the connection are available. TRUE to automatically activate the connection, FALSE to require manual intervention to activate the connection. Note that autoconnect is not implemented for VPN profiles. See "secondaries" as an alternative to automatically connect VPN profiles." /> + <property name="autoconnect-priority" + description="The autoconnect priority. If the connection is set to autoconnect, connections with higher priority will be preferred. Defaults to 0. The higher number means higher priority." /> + <property name="autoconnect-retries" + description="The number of times a connection should be tried when autoactivating before giving up. Zero means forever, -1 means the global default (4 times if not overridden). Setting this to 1 means to try activation only once before blocking autoconnect. Note that after a timeout, NetworkManager will try to autoconnect again." /> + <property name="multi-connect" + description="Specifies whether the profile can be active multiple times at a particular moment. The value is of type NMConnectionMultiConnect." /> + <property name="auth-retries" + description="The number of retries for the authentication. Zero means to try indefinitely; -1 means to use a global default. If the global default is not set, the authentication retries for 3 times before failing the connection. Currently, this only applies to 802-1x authentication." /> + <property name="timestamp" + description="The time, in seconds since the Unix Epoch, that the connection was last _successfully_ fully activated. NetworkManager updates the connection timestamp periodically when the connection is active to ensure that an active connection has the latest timestamp. The property is only meant for reading (changes to this property will not be preserved)." /> + <property name="read-only" + description="FALSE if the connection can be modified using the provided settings service's D-Bus interface with the right privileges, or TRUE if the connection is read-only and cannot be modified." /> + <property name="permissions" + description="An array of strings defining what access a given user has to this connection. If this is NULL or empty, all users are allowed to access this connection; otherwise users are allowed if and only if they are in this list. When this is not empty, the connection can be active only when one of the specified users is logged into an active session. Each entry is of the form "[type]:[id]:[reserved]"; for example, "user:dcbw:blah". At this time only the "user" [type] is allowed. Any other values are ignored and reserved for future use. [id] is the username that this permission refers to, which may not contain the ":" character. Any [reserved] information present must be ignored and is reserved for future use. All of [type], [id], and [reserved] must be valid UTF-8." /> + <property name="zone" + description="The trust level of a the connection. Free form case-insensitive string (for example "Home", "Work", "Public"). NULL or unspecified zone means the connection will be placed in the default zone as defined by the firewall. When updating this property on a currently activated connection, the change takes effect immediately." /> + <property name="master" + alias="master" + description="Interface name of the master device or UUID of the master connection." /> + <property name="slave-type" + alias="slave-type" + description="Setting name of the device type of this slave's master connection (eg, "bond"), or NULL if this connection is not a slave." /> + <property name="autoconnect-slaves" + description="Whether or not slaves of this connection should be automatically brought up when NetworkManager activates this connection. This only has a real effect for master connections. The properties "autoconnect", "autoconnect-priority" and "autoconnect-retries" are unrelated to this setting. The permitted values are: 0: leave slave connections untouched, 1: activate all the slave connections with this connection, -1: default. If -1 (default) is set, global connection.autoconnect-slaves is read to determine the real value. If it is default as well, this fallbacks to 0." /> + <property name="secondaries" + description="List of connection UUIDs that should be activated when the base connection itself is activated. Currently, only VPN connections are supported." /> + <property name="gateway-ping-timeout" + description="If greater than zero, delay success of IP addressing until either the timeout is reached, or an IP gateway replies to a ping." /> + <property name="metered" + description="Whether the connection is metered. When updating this property on a currently activated connection, the change takes effect immediately." /> + <property name="lldp" + description="Whether LLDP is enabled for the connection." /> + <property name="mdns" + description="Whether mDNS is enabled for the connection. The permitted values are: "yes" (2) register hostname and resolving for the connection, "no" (0) disable mDNS for the interface, "resolve" (1) do not register hostname but allow resolving of mDNS host names and "default" (-1) to allow lookup of a global default in NetworkManager.conf. If unspecified, "default" ultimately depends on the DNS plugin (which for systemd-resolved currently means "no"). This feature requires a plugin which supports mDNS. Otherwise, the setting has no effect. One such plugin is dns-systemd-resolved." /> + <property name="llmnr" + description="Whether Link-Local Multicast Name Resolution (LLMNR) is enabled for the connection. LLMNR is a protocol based on the Domain Name System (DNS) packet format that allows both IPv4 and IPv6 hosts to perform name resolution for hosts on the same local link. The permitted values are: "yes" (2) register hostname and resolving for the connection, "no" (0) disable LLMNR for the interface, "resolve" (1) do not register hostname but allow resolving of LLMNR host names If unspecified, "default" ultimately depends on the DNS plugin (which for systemd-resolved currently means "yes"). This feature requires a plugin which supports LLMNR. Otherwise, the setting has no effect. One such plugin is dns-systemd-resolved." /> + <property name="mud-url" + description="If configured, set to a Manufacturer Usage Description (MUD) URL that points to manufacturer-recommended network policies for IoT devices. It is transmitted as a DHCPv4 or DHCPv6 option. The value must be a valid URL starting with "https://". The special value "none" is allowed to indicate that no MUD URL is used. If the per-profile value is unspecified (the default), a global connection default gets consulted. If still unspecified, the ultimate default is "none"." /> + <property name="wait-device-timeout" + description="Timeout in milliseconds to wait for device at startup. During boot, devices may take a while to be detected by the driver. This property will cause to delay NetworkManager-wait-online.service and nm-online to give the device a chance to appear. This works by waiting for the given timeout until a compatible device for the profile is available and managed. The value 0 means no wait time. The default value is -1, which currently has the same meaning as no wait time." /> + </setting> + <setting name="dcb" > + <property name="app-fcoe-flags" + description="Specifies the NMSettingDcbFlags for the DCB FCoE application. Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="app-fcoe-priority" + description="The highest User Priority (0 - 7) which FCoE frames should use, or -1 for default priority. Only used when the "app-fcoe-flags" property includes the NM_SETTING_DCB_FLAG_ENABLE (0x1) flag." /> + <property name="app-fcoe-mode" + description="The FCoE controller mode; either "fabric" (default) or "vn2vn"." /> + <property name="app-iscsi-flags" + description="Specifies the NMSettingDcbFlags for the DCB iSCSI application. Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="app-iscsi-priority" + description="The highest User Priority (0 - 7) which iSCSI frames should use, or -1 for default priority. Only used when the "app-iscsi-flags" property includes the NM_SETTING_DCB_FLAG_ENABLE (0x1) flag." /> + <property name="app-fip-flags" + description="Specifies the NMSettingDcbFlags for the DCB FIP application. Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="app-fip-priority" + description="The highest User Priority (0 - 7) which FIP frames should use, or -1 for default priority. Only used when the "app-fip-flags" property includes the NM_SETTING_DCB_FLAG_ENABLE (0x1) flag." /> + <property name="priority-flow-control-flags" + description="Specifies the NMSettingDcbFlags for DCB Priority Flow Control (PFC). Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="priority-flow-control" + description="An array of 8 boolean values, where the array index corresponds to the User Priority (0 - 7) and the value indicates whether or not the corresponding priority should transmit priority pause." /> + <property name="priority-group-flags" + description="Specifies the NMSettingDcbFlags for DCB Priority Groups. Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="priority-group-id" + description="An array of 8 uint values, where the array index corresponds to the User Priority (0 - 7) and the value indicates the Priority Group ID. Allowed Priority Group ID values are 0 - 7 or 15 for the unrestricted group." /> + <property name="priority-group-bandwidth" + description="An array of 8 uint values, where the array index corresponds to the Priority Group ID (0 - 7) and the value indicates the percentage of link bandwidth allocated to that group. Allowed values are 0 - 100, and the sum of all values must total 100 percents." /> + <property name="priority-bandwidth" + description="An array of 8 uint values, where the array index corresponds to the User Priority (0 - 7) and the value indicates the percentage of bandwidth of the priority's assigned group that the priority may use. The sum of all percentages for priorities which belong to the same group must total 100 percents." /> + <property name="priority-strict-bandwidth" + description="An array of 8 boolean values, where the array index corresponds to the User Priority (0 - 7) and the value indicates whether or not the priority may use all of the bandwidth allocated to its assigned group." /> + <property name="priority-traffic-class" + description="An array of 8 uint values, where the array index corresponds to the User Priority (0 - 7) and the value indicates the traffic class (0 - 7) to which the priority is mapped." /> + </setting> + <setting name="dummy" > + </setting> + <setting name="ethtool" > + <property name="feature-esp-hw-offload" /> + <property name="feature-esp-tx-csum-hw-offload" /> + <property name="feature-fcoe-mtu" /> + <property name="feature-gro" /> + <property name="feature-gso" /> + <property name="feature-highdma" /> + <property name="feature-hw-tc-offload" /> + <property name="feature-l2-fwd-offload" /> + <property name="feature-loopback" /> + <property name="feature-lro" /> + <property name="feature-macsec-hw-offload" /> + <property name="feature-ntuple" /> + <property name="feature-rx" /> + <property name="feature-rxhash" /> + <property name="feature-rxvlan" /> + <property name="feature-rx-all" /> + <property name="feature-rx-fcs" /> + <property name="feature-rx-gro-hw" /> + <property name="feature-rx-gro-list" /> + <property name="feature-rx-udp-gro-forwarding" /> + <property name="feature-rx-udp_tunnel-port-offload" /> + <property name="feature-rx-vlan-filter" /> + <property name="feature-rx-vlan-stag-filter" /> + <property name="feature-rx-vlan-stag-hw-parse" /> + <property name="feature-sg" /> + <property name="feature-tls-hw-record" /> + <property name="feature-tls-hw-rx-offload" /> + <property name="feature-tls-hw-tx-offload" /> + <property name="feature-tso" /> + <property name="feature-tx" /> + <property name="feature-txvlan" /> + <property name="feature-tx-checksum-fcoe-crc" /> + <property name="feature-tx-checksum-ipv4" /> + <property name="feature-tx-checksum-ipv6" /> + <property name="feature-tx-checksum-ip-generic" /> + <property name="feature-tx-checksum-sctp" /> + <property name="feature-tx-esp-segmentation" /> + <property name="feature-tx-fcoe-segmentation" /> + <property name="feature-tx-gre-csum-segmentation" /> + <property name="feature-tx-gre-segmentation" /> + <property name="feature-tx-gso-list" /> + <property name="feature-tx-gso-partial" /> + <property name="feature-tx-gso-robust" /> + <property name="feature-tx-ipxip4-segmentation" /> + <property name="feature-tx-ipxip6-segmentation" /> + <property name="feature-tx-nocache-copy" /> + <property name="feature-tx-scatter-gather" /> + <property name="feature-tx-scatter-gather-fraglist" /> + <property name="feature-tx-sctp-segmentation" /> + <property name="feature-tx-tcp6-segmentation" /> + <property name="feature-tx-tcp-ecn-segmentation" /> + <property name="feature-tx-tcp-mangleid-segmentation" /> + <property name="feature-tx-tcp-segmentation" /> + <property name="feature-tx-tunnel-remcsum-segmentation" /> + <property name="feature-tx-udp-segmentation" /> + <property name="feature-tx-udp_tnl-csum-segmentation" /> + <property name="feature-tx-udp_tnl-segmentation" /> + <property name="feature-tx-vlan-stag-hw-insert" /> + <property name="coalesce-adaptive-rx" /> + <property name="coalesce-adaptive-tx" /> + <property name="coalesce-pkt-rate-high" /> + <property name="coalesce-pkt-rate-low" /> + <property name="coalesce-rx-frames" /> + <property name="coalesce-rx-frames-irq" /> + <property name="coalesce-rx-frames-high" /> + <property name="coalesce-rx-frames-low" /> + <property name="coalesce-rx-usecs" /> + <property name="coalesce-rx-usecs-irq" /> + <property name="coalesce-rx-usecs-high" /> + <property name="coalesce-rx-usecs-low" /> + <property name="coalesce-sample-interval" /> + <property name="coalesce-stats-block-usecs" /> + <property name="coalesce-tx-frames" /> + <property name="coalesce-tx-frames-irq" /> + <property name="coalesce-tx-frames-high" /> + <property name="coalesce-tx-frames-low" /> + <property name="coalesce-tx-usecs" /> + <property name="coalesce-tx-usecs-irq" /> + <property name="coalesce-tx-usecs-high" /> + <property name="coalesce-tx-usecs-low" /> + <property name="pause-autoneg" + description="Whether to automatically negotiate on pause frame of flow control mechanism defined by IEEE 802.3x standard." /> + <property name="pause-rx" + description="Whether RX pause should be enabled. Only valid when automatic negotiation is disabled" /> + <property name="pause-tx" + description="Whether TX pause should be enabled. Only valid when automatic negotiation is disabled" /> + <property name="ring-rx" /> + <property name="ring-rx-jumbo" /> + <property name="ring-rx-mini" /> + <property name="ring-tx" /> + </setting> + <setting name="generic" > + </setting> + <setting name="gsm" > + <property name="auto-config" + description="When TRUE, the settings such as APN, username, or password will default to values that match the network the modem will register to in the Mobile Broadband Provider database." /> + <property name="number" + description="Legacy setting that used to help establishing PPP data sessions for GSM-based modems. Deprecated: 1" /> + <property name="username" + alias="user" + description="The username used to authenticate with the network, if required. Many providers do not require a username, or accept any username. But if a username is required, it is specified here." /> + <property name="password" + alias="password" + description="The password used to authenticate with the network, if required. Many providers do not require a password, or accept any password. But if a password is required, it is specified here." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + <property name="apn" + alias="apn" + description="The GPRS Access Point Name specifying the APN used when establishing a data session with the GSM-based network. The APN often determines how the user will be billed for their network usage and whether the user has access to the Internet or just a provider-specific walled-garden, so it is important to use the correct APN for the user's mobile broadband plan. The APN may only be composed of the characters a-z, 0-9, ., and - per GSM 03.60 Section 14.9." /> + <property name="network-id" + description="The Network ID (GSM LAI format, ie MCC-MNC) to force specific network registration. If the Network ID is specified, NetworkManager will attempt to force the device to register only on the specified network. This can be used to ensure that the device does not roam when direct roaming control of the device is not otherwise possible." /> + <property name="pin" + description="If the SIM is locked with a PIN it must be unlocked before any other operations are requested. Specify the PIN here to allow operation of the device." /> + <property name="pin-flags" + description="Flags indicating how to handle the "pin" property." /> + <property name="home-only" + description="When TRUE, only connections to the home network will be allowed. Connections to roaming networks will not be made." /> + <property name="device-id" + description="The device unique identifier (as given by the WWAN management service) which this connection applies to. If given, the connection will only apply to the specified device." /> + <property name="sim-id" + description="The SIM card unique identifier (as given by the WWAN management service) which this connection applies to. If given, the connection will apply to any device also allowed by "device-id" which contains a SIM card matching the given identifier." /> + <property name="sim-operator-id" + description="A MCC/MNC string like "310260" or "21601" identifying the specific mobile network operator which this connection applies to. If given, the connection will apply to any device also allowed by "device-id" and "sim-id" which contains a SIM card provisioned by the given operator." /> + <property name="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple frames." /> + </setting> + <setting name="hostname" > + <property name="priority" + description="The relative priority of this connection to determine the system hostname. A lower numerical value is better (higher priority). A connection with higher priority is considered before connections with lower priority. If the value is zero, it can be overridden by a global value from NetworkManager configuration. If the property doesn't have a value in the global configuration, the value is assumed to be 100. Negative values have the special effect of excluding other connections with a greater numerical priority value; so in presence of at least one negative priority, only connections with the lowest priority value will be used to determine the hostname." /> + <property name="from-dhcp" + description="Whether the system hostname can be determined from DHCP on this connection. When set to NM_TERNARY_DEFAULT (-1), the value from global configuration is used. If the property doesn't have a value in the global configuration, NetworkManager assumes the value to be NM_TERNARY_TRUE (1)." /> + <property name="from-dns-lookup" + description="Whether the system hostname can be determined from reverse DNS lookup of addresses on this device. When set to NM_TERNARY_DEFAULT (-1), the value from global configuration is used. If the property doesn't have a value in the global configuration, NetworkManager assumes the value to be NM_TERNARY_TRUE (1)." /> + <property name="only-from-default" + description="If set to NM_TERNARY_TRUE (1), NetworkManager attempts to get the hostname via DHCPv4/DHCPv6 or reverse DNS lookup on this device only when the device has the default route for the given address family (IPv4/IPv6). If set to NM_TERNARY_FALSE (0), the hostname can be set from this device even if it doesn't have the default route. When set to NM_TERNARY_DEFAULT (-1), the value from global configuration is used. If the property doesn't have a value in the global configuration, NetworkManager assumes the value to be NM_TERNARY_FALSE (0)." /> + </setting> + <setting name="infiniband" > + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the IPoIB device whose permanent MAC address matches. This property does not change the MAC address of the device (i.e. MAC spoofing)." /> + <property name="mtu" + alias="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple frames." /> + <property name="transport-mode" + alias="transport-mode" + description="The IP-over-InfiniBand transport mode. Either "datagram" or "connected"." /> + <property name="p-key" + alias="p-key" + description="The InfiniBand P_Key to use for this device. A value of -1 means to use the default P_Key (aka "the P_Key at index 0"). Otherwise, it is a 16-bit unsigned integer, whose high bit is set if it is a "full membership" P_Key." /> + <property name="parent" + alias="parent" + description="The interface name of the parent device of this device. Normally NULL, but if the "p_key" property is set, then you must specify the base device by setting either this property or "mac-address"." /> + </setting> + <setting name="ip-tunnel" > + <property name="mode" + alias="mode" + description="The tunneling mode, for example NM_IP_TUNNEL_MODE_IPIP (1) or NM_IP_TUNNEL_MODE_GRE (2)." /> + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID the new device will be bound to so that tunneled packets will only be routed via that interface." /> + <property name="local" + alias="local" + description="The local endpoint of the tunnel; the value can be empty, otherwise it must contain an IPv4 or IPv6 address." /> + <property name="remote" + alias="remote" + description="The remote endpoint of the tunnel; the value must contain an IPv4 or IPv6 address." /> + <property name="ttl" + description="The TTL to assign to tunneled packets. 0 is a special value meaning that packets inherit the TTL value." /> + <property name="tos" + description="The type of service (IPv4) or traffic class (IPv6) field to be set on tunneled packets." /> + <property name="path-mtu-discovery" + description="Whether to enable Path MTU Discovery on this tunnel." /> + <property name="input-key" + description="The key used for tunnel input packets; the property is valid only for certain tunnel modes (GRE, IP6GRE). If empty, no key is used." /> + <property name="output-key" + description="The key used for tunnel output packets; the property is valid only for certain tunnel modes (GRE, IP6GRE). If empty, no key is used." /> + <property name="encapsulation-limit" + description="How many additional levels of encapsulation are permitted to be prepended to packets. This property applies only to IPv6 tunnels." /> + <property name="flow-label" + description="The flow label to assign to tunnel packets. This property applies only to IPv6 tunnels." /> + <property name="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple fragments." /> + <property name="flags" + description="Tunnel flags. Currently, the following values are supported: NM_IP_TUNNEL_FLAG_IP6_IGN_ENCAP_LIMIT (0x1), NM_IP_TUNNEL_FLAG_IP6_USE_ORIG_TCLASS (0x2), NM_IP_TUNNEL_FLAG_IP6_USE_ORIG_FLOWLABEL (0x4), NM_IP_TUNNEL_FLAG_IP6_MIP6_DEV (0x8), NM_IP_TUNNEL_FLAG_IP6_RCV_DSCP_COPY (0x10), NM_IP_TUNNEL_FLAG_IP6_USE_ORIG_FWMARK (0x20). They are valid only for IPv6 tunnels." /> + </setting> + <setting name="ipv4" > + <property name="method" + description="IP configuration method. NMSettingIP4Config and NMSettingIP6Config both support "disabled", "auto", "manual", and "link-local". See the subclass-specific documentation for other values. In general, for the "auto" method, properties such as "dns" and "routes" specify information that is added on to the information returned from automatic configuration. The "ignore-auto-routes" and "ignore-auto-dns" properties modify this behavior. For methods that imply no upstream network, such as "shared" or "link-local", these properties must be empty. For IPv4 method "shared", the IP subnet can be configured by adding one manual IPv4 address or otherwise 10.42.x.0/24 is chosen. Note that the shared method must be configured on the interface which shares the internet to a subnet, not on the uplink which is shared." /> + <property name="dns" + description="Array of IP addresses of DNS servers." /> + <property name="dns-search" + description="Array of DNS search domains. Domains starting with a tilde ('~') are considered 'routing' domains and are used only to decide the interface over which a query must be forwarded; they are not used to complete unqualified host names. When using a DNS plugin that supports Conditional Forwarding or Split DNS, then the search domains specify which name servers to query. This makes the behavior different from running with plain /etc/resolv.conf. For more information see also the dns-priority setting." /> + <property name="dns-options" + description="Array of DNS options as described in man 5 resolv.conf. NULL means that the options are unset and left at the default. In this case NetworkManager will use default options. This is distinct from an empty list of properties. The currently supported options are "attempts", "debug", "edns0", "inet6", "ip6-bytestring", "ip6-dotint", "ndots", "no-check-names", "no-ip6-dotint", "no-reload", "no-tld-query", "rotate", "single-request", "single-request-reopen", "timeout", "trust-ad", "use-vc". The "trust-ad" setting is only honored if the profile contributes name servers to resolv.conf, and if all contributing profiles have "trust-ad" enabled. When using a caching DNS plugin (dnsmasq or systemd-resolved in NetworkManager.conf) then "edns0" and "trust-ad" are automatically added." /> + <property name="dns-priority" + description="DNS servers priority. The relative priority for DNS servers specified by this setting. A lower numerical value is better (higher priority). Negative values have the special effect of excluding other configurations with a greater numerical priority value; so in presence of at least one negative priority, only DNS servers from connections with the lowest priority value will be used. To avoid all DNS leaks, set the priority of the profile that should be used to the most negative value of all active connections profiles. Zero selects a globally configured default value. If the latter is missing or zero too, it defaults to 50 for VPNs (including WireGuard) and 100 for other connections. Note that the priority is to order DNS settings for multiple active connections. It does not disambiguate multiple DNS servers within the same connection profile. When multiple devices have configurations with the same priority, VPNs will be considered first, then devices with the best (lowest metric) default route and then all other devices. When using dns=default, servers with higher priority will be on top of resolv.conf. To prioritize a given server over another one within the same connection, just specify them in the desired order. Note that commonly the resolver tries name servers in /etc/resolv.conf in the order listed, proceeding with the next server in the list on failure. See for example the "rotate" option of the dns-options setting. If there are any negative DNS priorities, then only name servers from the devices with that lowest priority will be considered. When using a DNS resolver that supports Conditional Forwarding or Split DNS (with dns=dnsmasq or dns=systemd-resolved settings), each connection is used to query domains in its search list. The search domains determine which name servers to ask, and the DNS priority is used to prioritize name servers based on the domain. Queries for domains not present in any search list are routed through connections having the '~.' special wildcard domain, which is added automatically to connections with the default route (or can be added manually). When multiple connections specify the same domain, the one with the best priority (lowest numerical value) wins. If a sub domain is configured on another interface it will be accepted regardless the priority, unless parent domain on the other interface has a negative priority, which causes the sub domain to be shadowed. With Split DNS one can avoid undesired DNS leaks by properly configuring DNS priorities and the search domains, so that only name servers of the desired interface are configured." /> + <property name="addresses" + alias="ip4" + description="A list of IPv4 addresses and their prefix length. Multiple addresses can be separated by comma. For example "192.168.1.5/24, 10.1.0.5/24". The addresses are listed in decreasing priority, meaning the first address will be the primary address." /> + <property name="gateway" + alias="gw4" + description="The gateway associated with this configuration. This is only meaningful if "addresses" is also set. The gateway's main purpose is to control the next hop of the standard default route on the device. Hence, the gateway property conflicts with "never-default" and will be automatically dropped if the IP configuration is set to never-default. As an alternative to set the gateway, configure a static default route with /0 as prefix length." /> + <property name="routes" + description="A list of IPv4 destination addresses, prefix length, optional IPv4 next hop addresses, optional route metric, optional attribute. The valid syntax is: "ip[/prefix] [next-hop] [metric] [attribute=val]...[,ip[/prefix]...]". For example "192.0.2.0/24 10.1.1.1 77, 198.51.100.0/24"." /> + <property name="route-metric" + description="The default metric for routes that don't explicitly specify a metric. The default value -1 means that the metric is chosen automatically based on the device type. The metric applies to dynamic routes, manual (static) routes that don't have an explicit metric setting, address prefix routes, and the default route. Note that for IPv6, the kernel accepts zero (0) but coerces it to 1024 (user default). Hence, setting this property to zero effectively mean setting it to 1024. For IPv4, zero is a regular value for the metric." /> + <property name="route-table" + description="Enable policy routing (source routing) and set the routing table used when adding routes. This affects all routes, including device-routes, IPv4LL, DHCP, SLAAC, default-routes and static routes. But note that static routes can individually overwrite the setting by explicitly specifying a non-zero routing table. If the table setting is left at zero, it is eligible to be overwritten via global configuration. If the property is zero even after applying the global configuration value, policy routing is disabled for the address family of this connection. Policy routing disabled means that NetworkManager will add all routes to the main table (except static routes that explicitly configure a different table). Additionally, NetworkManager will not delete any extraneous routes from tables except the main table. This is to preserve backward compatibility for users who manage routing tables outside of NetworkManager." /> + <property name="routing-rules" /> + <property name="ignore-auto-routes" + description="When "method" is set to "auto" and this property to TRUE, automatically configured routes are ignored and only routes specified in the "routes" property, if any, are used." /> + <property name="ignore-auto-dns" + description="When "method" is set to "auto" and this property to TRUE, automatically configured name servers and search domains are ignored and only name servers and search domains specified in the "dns" and "dns-search" properties, if any, are used." /> + <property name="dhcp-client-id" + description="A string sent to the DHCP server to identify the local machine which the DHCP server may use to customize the DHCP lease and options. When the property is a hex string ('aa:bb:cc') it is interpreted as a binary client ID, in which case the first byte is assumed to be the 'type' field as per RFC 2132 section 9.14 and the remaining bytes may be an hardware address (e.g. '01:xx:xx:xx:xx:xx:xx' where 1 is the Ethernet ARP type and the rest is a MAC address). If the property is not a hex string it is considered as a non-hardware-address client ID and the 'type' field is set to 0. The special values "mac" and "perm-mac" are supported, which use the current or permanent MAC address of the device to generate a client identifier with type ethernet (01). Currently, these options only work for ethernet type of links. The special value "ipv6-duid" uses the DUID from "ipv6.dhcp-duid" property as an RFC4361-compliant client identifier. As IAID it uses "ipv4.dhcp-iaid" and falls back to "ipv6.dhcp-iaid" if unset. The special value "duid" generates a RFC4361-compliant client identifier based on "ipv4.dhcp-iaid" and uses a DUID generated by hashing /etc/machine-id. The special value "stable" is supported to generate a type 0 client identifier based on the stable-id (see connection.stable-id) and a per-host key. If you set the stable-id, you may want to include the "${DEVICE}" or "${MAC}" specifier to get a per-device key. If unset, a globally configured default is used. If still unset, the default depends on the DHCP plugin." /> + <property name="dhcp-iaid" + description="A string containing the "Identity Association Identifier" (IAID) used by the DHCP client. The property is a 32-bit decimal value or a special value among "mac", "perm-mac", "ifname" and "stable". When set to "mac" (or "perm-mac"), the last 4 bytes of the current (or permanent) MAC address are used as IAID. When set to "ifname", the IAID is computed by hashing the interface name. The special value "stable" can be used to generate an IAID based on the stable-id (see connection.stable-id), a per-host key and the interface name. When the property is unset, the value from global configuration is used; if no global default is set then the IAID is assumed to be "ifname". Note that at the moment this property is ignored for IPv6 by dhclient, which always derives the IAID from the MAC address." /> + <property name="dhcp-timeout" + description="A timeout for a DHCP transaction in seconds. If zero (the default), a globally configured default is used. If still unspecified, a device specific timeout is used (usually 45 seconds). Set to 2147483647 (MAXINT32) for infinity." /> + <property name="dhcp-send-hostname" + description="If TRUE, a hostname is sent to the DHCP server when acquiring a lease. Some DHCP servers use this hostname to update DNS databases, essentially providing a static hostname for the computer. If the "dhcp-hostname" property is NULL and this property is TRUE, the current persistent hostname of the computer is sent." /> + <property name="dhcp-hostname" + description="If the "dhcp-send-hostname" property is TRUE, then the specified name will be sent to the DHCP server when acquiring a lease. This property and "dhcp-fqdn" are mutually exclusive and cannot be set at the same time." /> + <property name="dhcp-fqdn" + description="If the "dhcp-send-hostname" property is TRUE, then the specified FQDN will be sent to the DHCP server when acquiring a lease. This property and "dhcp-hostname" are mutually exclusive and cannot be set at the same time." /> + <property name="dhcp-hostname-flags" + description="Flags for the DHCP hostname and FQDN. Currently, this property only includes flags to control the FQDN flags set in the DHCP FQDN option. Supported FQDN flags are NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1), NM_DHCP_HOSTNAME_FLAG_FQDN_ENCODED (0x2) and NM_DHCP_HOSTNAME_FLAG_FQDN_NO_UPDATE (0x4). When no FQDN flag is set and NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS (0x8) is set, the DHCP FQDN option will contain no flag. Otherwise, if no FQDN flag is set and NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS (0x8) is not set, the standard FQDN flags are set in the request: NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1), NM_DHCP_HOSTNAME_FLAG_FQDN_ENCODED (0x2) for IPv4 and NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1) for IPv6. When this property is set to the default value NM_DHCP_HOSTNAME_FLAG_NONE (0x0), a global default is looked up in NetworkManager configuration. If that value is unset or also NM_DHCP_HOSTNAME_FLAG_NONE (0x0), then the standard FQDN flags described above are sent in the DHCP requests." /> + <property name="never-default" + description="If TRUE, this connection will never be the default connection for this IP type, meaning it will never be assigned the default route by NetworkManager." /> + <property name="may-fail" + description="If TRUE, allow overall network configuration to proceed even if the configuration specified by this property times out. Note that at least one IP configuration must succeed or overall network configuration will still fail. For example, in IPv6-only networks, setting this property to TRUE on the NMSettingIP4Config allows the overall network configuration to succeed if IPv4 configuration fails but IPv6 configuration completes successfully." /> + <property name="required-timeout" + description="The minimum time interval in milliseconds for which dynamic IP configuration should be tried before the connection succeeds. This property is useful for example if both IPv4 and IPv6 are enabled and are allowed to fail. Normally the connection succeeds as soon as one of the two address families completes; by setting a required timeout for e.g. IPv4, one can ensure that even if IP6 succeeds earlier than IPv4, NetworkManager waits some time for IPv4 before the connection becomes active. Note that if "may-fail" is FALSE for the same address family, this property has no effect as NetworkManager needs to wait for the full DHCP timeout. A zero value means that no required timeout is present, -1 means the default value (either configuration ipvx.required-timeout override or zero)." /> + <property name="dad-timeout" + description="Timeout in milliseconds used to check for the presence of duplicate IP addresses on the network. If an address conflict is detected, the activation will fail. A zero value means that no duplicate address detection is performed, -1 means the default value (either configuration ipvx.dad-timeout override or zero). A value greater than zero is a timeout in milliseconds. The property is currently implemented only for IPv4." /> + <property name="dhcp-vendor-class-identifier" + description="The Vendor Class Identifier DHCP option (60). Special characters in the data string may be escaped using C-style escapes, nevertheless this property cannot contain nul bytes. If the per-profile value is unspecified (the default), a global connection default gets consulted. If still unspecified, the DHCP option is not sent to the server. Since 1.28" /> + <property name="dhcp-reject-servers" + description="Array of servers from which DHCP offers must be rejected. This property is useful to avoid getting a lease from misconfigured or rogue servers. For DHCPv4, each element must be an IPv4 address, optionally followed by a slash and a prefix length (e.g. "192.168.122.0/24"). This property is currently not implemented for DHCPv6." /> + </setting> + <setting name="ipv6" > + <property name="method" + description="IP configuration method. NMSettingIP4Config and NMSettingIP6Config both support "disabled", "auto", "manual", and "link-local". See the subclass-specific documentation for other values. In general, for the "auto" method, properties such as "dns" and "routes" specify information that is added on to the information returned from automatic configuration. The "ignore-auto-routes" and "ignore-auto-dns" properties modify this behavior. For methods that imply no upstream network, such as "shared" or "link-local", these properties must be empty. For IPv4 method "shared", the IP subnet can be configured by adding one manual IPv4 address or otherwise 10.42.x.0/24 is chosen. Note that the shared method must be configured on the interface which shares the internet to a subnet, not on the uplink which is shared." /> + <property name="dns" + description="Array of IP addresses of DNS servers." /> + <property name="dns-search" + description="Array of DNS search domains. Domains starting with a tilde ('~') are considered 'routing' domains and are used only to decide the interface over which a query must be forwarded; they are not used to complete unqualified host names. When using a DNS plugin that supports Conditional Forwarding or Split DNS, then the search domains specify which name servers to query. This makes the behavior different from running with plain /etc/resolv.conf. For more information see also the dns-priority setting." /> + <property name="dns-options" + description="Array of DNS options as described in man 5 resolv.conf. NULL means that the options are unset and left at the default. In this case NetworkManager will use default options. This is distinct from an empty list of properties. The currently supported options are "attempts", "debug", "edns0", "inet6", "ip6-bytestring", "ip6-dotint", "ndots", "no-check-names", "no-ip6-dotint", "no-reload", "no-tld-query", "rotate", "single-request", "single-request-reopen", "timeout", "trust-ad", "use-vc". The "trust-ad" setting is only honored if the profile contributes name servers to resolv.conf, and if all contributing profiles have "trust-ad" enabled. When using a caching DNS plugin (dnsmasq or systemd-resolved in NetworkManager.conf) then "edns0" and "trust-ad" are automatically added." /> + <property name="dns-priority" + description="DNS servers priority. The relative priority for DNS servers specified by this setting. A lower numerical value is better (higher priority). Negative values have the special effect of excluding other configurations with a greater numerical priority value; so in presence of at least one negative priority, only DNS servers from connections with the lowest priority value will be used. To avoid all DNS leaks, set the priority of the profile that should be used to the most negative value of all active connections profiles. Zero selects a globally configured default value. If the latter is missing or zero too, it defaults to 50 for VPNs (including WireGuard) and 100 for other connections. Note that the priority is to order DNS settings for multiple active connections. It does not disambiguate multiple DNS servers within the same connection profile. When multiple devices have configurations with the same priority, VPNs will be considered first, then devices with the best (lowest metric) default route and then all other devices. When using dns=default, servers with higher priority will be on top of resolv.conf. To prioritize a given server over another one within the same connection, just specify them in the desired order. Note that commonly the resolver tries name servers in /etc/resolv.conf in the order listed, proceeding with the next server in the list on failure. See for example the "rotate" option of the dns-options setting. If there are any negative DNS priorities, then only name servers from the devices with that lowest priority will be considered. When using a DNS resolver that supports Conditional Forwarding or Split DNS (with dns=dnsmasq or dns=systemd-resolved settings), each connection is used to query domains in its search list. The search domains determine which name servers to ask, and the DNS priority is used to prioritize name servers based on the domain. Queries for domains not present in any search list are routed through connections having the '~.' special wildcard domain, which is added automatically to connections with the default route (or can be added manually). When multiple connections specify the same domain, the one with the best priority (lowest numerical value) wins. If a sub domain is configured on another interface it will be accepted regardless the priority, unless parent domain on the other interface has a negative priority, which causes the sub domain to be shadowed. With Split DNS one can avoid undesired DNS leaks by properly configuring DNS priorities and the search domains, so that only name servers of the desired interface are configured." /> + <property name="addresses" + alias="ip6" + description="A list of IPv6 addresses and their prefix length. Multiple addresses can be separated by comma. For example "2001:db8:85a3::8a2e:370:7334/64, 2001:db8:85a3::5/64". The addresses are listed in increasing priority, meaning the last address will be the primary address." /> + <property name="gateway" + alias="gw6" + description="The gateway associated with this configuration. This is only meaningful if "addresses" is also set. The gateway's main purpose is to control the next hop of the standard default route on the device. Hence, the gateway property conflicts with "never-default" and will be automatically dropped if the IP configuration is set to never-default. As an alternative to set the gateway, configure a static default route with /0 as prefix length." /> + <property name="routes" + description="Array of IP routes." /> + <property name="route-metric" + description="The default metric for routes that don't explicitly specify a metric. The default value -1 means that the metric is chosen automatically based on the device type. The metric applies to dynamic routes, manual (static) routes that don't have an explicit metric setting, address prefix routes, and the default route. Note that for IPv6, the kernel accepts zero (0) but coerces it to 1024 (user default). Hence, setting this property to zero effectively mean setting it to 1024. For IPv4, zero is a regular value for the metric." /> + <property name="route-table" + description="Enable policy routing (source routing) and set the routing table used when adding routes. This affects all routes, including device-routes, IPv4LL, DHCP, SLAAC, default-routes and static routes. But note that static routes can individually overwrite the setting by explicitly specifying a non-zero routing table. If the table setting is left at zero, it is eligible to be overwritten via global configuration. If the property is zero even after applying the global configuration value, policy routing is disabled for the address family of this connection. Policy routing disabled means that NetworkManager will add all routes to the main table (except static routes that explicitly configure a different table). Additionally, NetworkManager will not delete any extraneous routes from tables except the main table. This is to preserve backward compatibility for users who manage routing tables outside of NetworkManager." /> + <property name="routing-rules" /> + <property name="ignore-auto-routes" + description="When "method" is set to "auto" and this property to TRUE, automatically configured routes are ignored and only routes specified in the "routes" property, if any, are used." /> + <property name="ignore-auto-dns" + description="When "method" is set to "auto" and this property to TRUE, automatically configured name servers and search domains are ignored and only name servers and search domains specified in the "dns" and "dns-search" properties, if any, are used." /> + <property name="never-default" + description="If TRUE, this connection will never be the default connection for this IP type, meaning it will never be assigned the default route by NetworkManager." /> + <property name="may-fail" + description="If TRUE, allow overall network configuration to proceed even if the configuration specified by this property times out. Note that at least one IP configuration must succeed or overall network configuration will still fail. For example, in IPv6-only networks, setting this property to TRUE on the NMSettingIP4Config allows the overall network configuration to succeed if IPv4 configuration fails but IPv6 configuration completes successfully." /> + <property name="required-timeout" + description="The minimum time interval in milliseconds for which dynamic IP configuration should be tried before the connection succeeds. This property is useful for example if both IPv4 and IPv6 are enabled and are allowed to fail. Normally the connection succeeds as soon as one of the two address families completes; by setting a required timeout for e.g. IPv4, one can ensure that even if IP6 succeeds earlier than IPv4, NetworkManager waits some time for IPv4 before the connection becomes active. Note that if "may-fail" is FALSE for the same address family, this property has no effect as NetworkManager needs to wait for the full DHCP timeout. A zero value means that no required timeout is present, -1 means the default value (either configuration ipvx.required-timeout override or zero)." /> + <property name="ip6-privacy" + description="Configure IPv6 Privacy Extensions for SLAAC, described in RFC4941. If enabled, it makes the kernel generate a temporary IPv6 address in addition to the public one generated from MAC address via modified EUI-64. This enhances privacy, but could cause problems in some applications, on the other hand. The permitted values are: -1: unknown, 0: disabled, 1: enabled (prefer public address), 2: enabled (prefer temporary addresses). Having a per-connection setting set to "-1" (unknown) means fallback to global configuration "ipv6.ip6-privacy". If also global configuration is unspecified or set to "-1", fallback to read "/proc/sys/net/ipv6/conf/default/use_tempaddr". Note that this setting is distinct from the Stable Privacy addresses that can be enabled with the "addr-gen-mode" property's "stable-privacy" setting as another way of avoiding host tracking with IPv6 addresses." /> + <property name="addr-gen-mode" + description="Configure method for creating the address for use with RFC4862 IPv6 Stateless Address Autoconfiguration. The permitted values are: NM_SETTING_IP6_CONFIG_ADDR_GEN_MODE_EUI64 (0) or NM_SETTING_IP6_CONFIG_ADDR_GEN_MODE_STABLE_PRIVACY (1). If the property is set to EUI64, the addresses will be generated using the interface tokens derived from hardware address. This makes the host part of the address to stay constant, making it possible to track host's presence when it changes networks. The address changes when the interface hardware is replaced. The value of stable-privacy enables use of cryptographically secure hash of a secret host-specific key along with the connection's stable-id and the network address as specified by RFC7217. This makes it impossible to use the address track host's presence, and makes the address stable when the network interface hardware is replaced. On D-Bus, the absence of an addr-gen-mode setting equals enabling stable-privacy. For keyfile plugin, the absence of the setting on disk means EUI64 so that the property doesn't change on upgrade from older versions. Note that this setting is distinct from the Privacy Extensions as configured by "ip6-privacy" property and it does not affect the temporary addresses configured with this option." /> + <property name="ra-timeout" + description="A timeout for waiting Router Advertisements in seconds. If zero (the default), a globally configured default is used. If still unspecified, the timeout depends on the sysctl settings of the device. Set to 2147483647 (MAXINT32) for infinity." /> + <property name="dhcp-duid" + description="A string containing the DHCPv6 Unique Identifier (DUID) used by the dhcp client to identify itself to DHCPv6 servers (RFC 3315). The DUID is carried in the Client Identifier option. If the property is a hex string ('aa:bb:cc') it is interpreted as a binary DUID and filled as an opaque value in the Client Identifier option. The special value "lease" will retrieve the DUID previously used from the lease file belonging to the connection. If no DUID is found and "dhclient" is the configured dhcp client, the DUID is searched in the system-wide dhclient lease file. If still no DUID is found, or another dhcp client is used, a global and permanent DUID-UUID (RFC 6355) will be generated based on the machine-id. The special values "llt" and "ll" will generate a DUID of type LLT or LL (see RFC 3315) based on the current MAC address of the device. In order to try providing a stable DUID-LLT, the time field will contain a constant timestamp that is used globally (for all profiles) and persisted to disk. The special values "stable-llt", "stable-ll" and "stable-uuid" will generate a DUID of the corresponding type, derived from the connection's stable-id and a per-host unique key. You may want to include the "${DEVICE}" or "${MAC}" specifier in the stable-id, in case this profile gets activated on multiple devices. So, the link-layer address of "stable-ll" and "stable-llt" will be a generated address derived from the stable id. The DUID-LLT time value in the "stable-llt" option will be picked among a static timespan of three years (the upper bound of the interval is the same constant timestamp used in "llt"). When the property is unset, the global value provided for "ipv6.dhcp-duid" is used. If no global value is provided, the default "lease" value is assumed." /> + <property name="dhcp-iaid" + description="A string containing the "Identity Association Identifier" (IAID) used by the DHCP client. The property is a 32-bit decimal value or a special value among "mac", "perm-mac", "ifname" and "stable". When set to "mac" (or "perm-mac"), the last 4 bytes of the current (or permanent) MAC address are used as IAID. When set to "ifname", the IAID is computed by hashing the interface name. The special value "stable" can be used to generate an IAID based on the stable-id (see connection.stable-id), a per-host key and the interface name. When the property is unset, the value from global configuration is used; if no global default is set then the IAID is assumed to be "ifname". Note that at the moment this property is ignored for IPv6 by dhclient, which always derives the IAID from the MAC address." /> + <property name="dhcp-timeout" + description="A timeout for a DHCP transaction in seconds. If zero (the default), a globally configured default is used. If still unspecified, a device specific timeout is used (usually 45 seconds). Set to 2147483647 (MAXINT32) for infinity." /> + <property name="dhcp-send-hostname" + description="If TRUE, a hostname is sent to the DHCP server when acquiring a lease. Some DHCP servers use this hostname to update DNS databases, essentially providing a static hostname for the computer. If the "dhcp-hostname" property is NULL and this property is TRUE, the current persistent hostname of the computer is sent." /> + <property name="dhcp-hostname" + description="If the "dhcp-send-hostname" property is TRUE, then the specified name will be sent to the DHCP server when acquiring a lease. This property and "dhcp-fqdn" are mutually exclusive and cannot be set at the same time." /> + <property name="dhcp-hostname-flags" + description="Flags for the DHCP hostname and FQDN. Currently, this property only includes flags to control the FQDN flags set in the DHCP FQDN option. Supported FQDN flags are NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1), NM_DHCP_HOSTNAME_FLAG_FQDN_ENCODED (0x2) and NM_DHCP_HOSTNAME_FLAG_FQDN_NO_UPDATE (0x4). When no FQDN flag is set and NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS (0x8) is set, the DHCP FQDN option will contain no flag. Otherwise, if no FQDN flag is set and NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS (0x8) is not set, the standard FQDN flags are set in the request: NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1), NM_DHCP_HOSTNAME_FLAG_FQDN_ENCODED (0x2) for IPv4 and NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1) for IPv6. When this property is set to the default value NM_DHCP_HOSTNAME_FLAG_NONE (0x0), a global default is looked up in NetworkManager configuration. If that value is unset or also NM_DHCP_HOSTNAME_FLAG_NONE (0x0), then the standard FQDN flags described above are sent in the DHCP requests." /> + <property name="token" + description="Configure the token for draft-chown-6man-tokenised-ipv6-identifiers-02 IPv6 tokenized interface identifiers. Useful with eui64 addr-gen-mode." /> + </setting> + <setting name="macsec" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID from which this MACSEC interface should be created. If this property is not specified, the connection must contain an "802-3-ethernet" setting with a "mac-address" property." /> + <property name="mode" + alias="mode" + description="Specifies how the CAK (Connectivity Association Key) for MKA (MACsec Key Agreement) is obtained." /> + <property name="encrypt" + alias="encrypt" + description="Whether the transmitted traffic must be encrypted." /> + <property name="mka-cak" + alias="cak" + description="The pre-shared CAK (Connectivity Association Key) for MACsec Key Agreement." /> + <property name="mka-cak-flags" + description="Flags indicating how to handle the "mka-cak" property." /> + <property name="mka-ckn" + alias="ckn" + description="The pre-shared CKN (Connectivity-association Key Name) for MACsec Key Agreement." /> + <property name="port" + alias="port" + description="The port component of the SCI (Secure Channel Identifier), between 1 and 65534." /> + <property name="validation" + description="Specifies the validation mode for incoming frames." /> + <property name="send-sci" + description="Specifies whether the SCI (Secure Channel Identifier) is included in every packet." /> + </setting> + <setting name="macvlan" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID from which this MAC-VLAN interface should be created. If this property is not specified, the connection must contain an "802-3-ethernet" setting with a "mac-address" property." /> + <property name="mode" + alias="mode" + description="The macvlan mode, which specifies the communication mechanism between multiple macvlans on the same lower device." /> + <property name="promiscuous" + description="Whether the interface should be put in promiscuous mode." /> + <property name="tap" + alias="tap" + description="Whether the interface should be a MACVTAP." /> + </setting> + <setting name="match" > + <property name="interface-name" + description="A list of interface names to match. Each element is a shell wildcard pattern. An element can be prefixed with a pipe symbol (|) or an ampersand (&). The former means that the element is optional and the latter means that it is mandatory. If there are any optional elements, than the match evaluates to true if at least one of the optional element matches (logical OR). If there are any mandatory elements, then they all must match (logical AND). By default, an element is optional. This means that an element "foo" behaves the same as "|foo". An element can also be inverted with exclamation mark (!) between the pipe symbol (or the ampersand) and before the pattern. Note that "!foo" is a shortcut for the mandatory match "&!foo". Finally, a backslash can be used at the beginning of the element (after the optional special characters) to escape the start of the pattern. For example, "&\!a" is an mandatory match for literally "!a"." /> + <property name="kernel-command-line" + description="A list of kernel command line arguments to match. This may be used to check whether a specific kernel command line option is set (or unset, if prefixed with the exclamation mark). The argument must either be a single word, or an assignment (i.e. two words, joined by "="). In the former case the kernel command line is searched for the word appearing as is, or as left hand side of an assignment. In the latter case, the exact assignment is looked for with right and left hand side matching. Wildcard patterns are not supported. See NMSettingMatch:interface-name for how special characters '|', '&', '!' and '\' are used for optional and mandatory matches and inverting the match." /> + <property name="driver" + description="A list of driver names to match. Each element is a shell wildcard pattern. See NMSettingMatch:interface-name for how special characters '|', '&', '!' and '\' are used for optional and mandatory matches and inverting the pattern." /> + <property name="path" + description="A list of paths to match against the ID_PATH udev property of devices. ID_PATH represents the topological persistent path of a device. It typically contains a subsystem string (pci, usb, platform, etc.) and a subsystem-specific identifier. For PCI devices the path has the form "pci-$domain:$bus:$device.$function", where each variable is an hexadecimal value; for example "pci-0000:0a:00.0". The path of a device can be obtained with "udevadm info /sys/class/net/$dev | grep ID_PATH=" or by looking at the "path" property exported by NetworkManager ("nmcli -f general.path device show $dev"). Each element of the list is a shell wildcard pattern. See NMSettingMatch:interface-name for how special characters '|', '&', '!' and '\' are used for optional and mandatory matches and inverting the pattern." /> + </setting> + <setting name="ovs-bridge" > + <property name="fail-mode" + description="The bridge failure mode. One of "secure", "standalone" or empty." /> + <property name="mcast-snooping-enable" + description="Enable or disable multicast snooping." /> + <property name="rstp-enable" + description="Enable or disable RSTP." /> + <property name="stp-enable" + description="Enable or disable STP." /> + <property name="datapath-type" + description="The data path type. One of "system", "netdev" or empty." /> + </setting> + <setting name="ovs-dpdk" > + <property name="devargs" + description="Open vSwitch DPDK device arguments." /> + </setting> + <setting name="ovs-external-ids" > + </setting> + <setting name="ovs-interface" > + <property name="type" + description="The interface type. Either "internal", "system", "patch", "dpdk", or empty." /> + </setting> + <setting name="ovs-patch" > + <property name="peer" + description="Specifies the name of the interface for the other side of the patch. The patch on the other side must also set this interface as peer." /> + </setting> + <setting name="ovs-port" > + <property name="vlan-mode" + description="The VLAN mode. One of "access", "native-tagged", "native-untagged", "trunk" or unset." /> + <property name="tag" + description="The VLAN tag in the range 0-4095." /> + <property name="lacp" + description="LACP mode. One of "active", "off", or "passive"." /> + <property name="bond-mode" + description="Bonding mode. One of "active-backup", "balance-slb", or "balance-tcp"." /> + <property name="bond-updelay" + description="The time port must be active before it starts forwarding traffic." /> + <property name="bond-downdelay" + description="The time port must be inactive in order to be considered down." /> + </setting> + <setting name="ppp" > + <property name="noauth" + description="If TRUE, do not require the other side (usually the PPP server) to authenticate itself to the client. If FALSE, require authentication from the remote side. In almost all cases, this should be TRUE." /> + <property name="refuse-eap" + description="If TRUE, the EAP authentication method will not be used." /> + <property name="refuse-pap" + description="If TRUE, the PAP authentication method will not be used." /> + <property name="refuse-chap" + description="If TRUE, the CHAP authentication method will not be used." /> + <property name="refuse-mschap" + description="If TRUE, the MSCHAP authentication method will not be used." /> + <property name="refuse-mschapv2" + description="If TRUE, the MSCHAPv2 authentication method will not be used." /> + <property name="nobsdcomp" + description="If TRUE, BSD compression will not be requested." /> + <property name="nodeflate" + description="If TRUE, "deflate" compression will not be requested." /> + <property name="no-vj-comp" + description="If TRUE, Van Jacobsen TCP header compression will not be requested." /> + <property name="require-mppe" + description="If TRUE, MPPE (Microsoft Point-to-Point Encryption) will be required for the PPP session. If either 64-bit or 128-bit MPPE is not available the session will fail. Note that MPPE is not used on mobile broadband connections." /> + <property name="require-mppe-128" + description="If TRUE, 128-bit MPPE (Microsoft Point-to-Point Encryption) will be required for the PPP session, and the "require-mppe" property must also be set to TRUE. If 128-bit MPPE is not available the session will fail." /> + <property name="mppe-stateful" + description="If TRUE, stateful MPPE is used. See pppd documentation for more information on stateful MPPE." /> + <property name="crtscts" + description="If TRUE, specify that pppd should set the serial port to use hardware flow control with RTS and CTS signals. This value should normally be set to FALSE." /> + <property name="baud" + description="If non-zero, instruct pppd to set the serial port to the specified baudrate. This value should normally be left as 0 to automatically choose the speed." /> + <property name="mru" + description="If non-zero, instruct pppd to request that the peer send packets no larger than the specified size. If non-zero, the MRU should be between 128 and 16384." /> + <property name="mtu" + description="If non-zero, instruct pppd to send packets no larger than the specified size." /> + <property name="lcp-echo-failure" + description="If non-zero, instruct pppd to presume the connection to the peer has failed if the specified number of LCP echo-requests go unanswered by the peer. The "lcp-echo-interval" property must also be set to a non-zero value if this property is used." /> + <property name="lcp-echo-interval" + description="If non-zero, instruct pppd to send an LCP echo-request frame to the peer every n seconds (where n is the specified value). Note that some PPP peers will respond to echo requests and some will not, and it is not possible to autodetect this." /> + </setting> + <setting name="pppoe" > + <property name="parent" + alias="parent" + description="If given, specifies the parent interface name on which this PPPoE connection should be created. If this property is not specified, the connection is activated on the interface specified in "interface-name" of NMSettingConnection." /> + <property name="service" + alias="service" + description="If specified, instruct PPPoE to only initiate sessions with access concentrators that provide the specified service. For most providers, this should be left blank. It is only required if there are multiple access concentrators or a specific service is known to be required." /> + <property name="username" + alias="username" + description="Username used to authenticate with the PPPoE service." /> + <property name="password" + alias="password" + description="Password used to authenticate with the PPPoE service." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + </setting> + <setting name="proxy" > + <property name="method" + alias="method" + description="Method for proxy configuration, Default is NM_SETTING_PROXY_METHOD_NONE (0)" /> + <property name="browser-only" + alias="browser-only" + description="Whether the proxy configuration is for browser only." /> + <property name="pac-url" + alias="pac-url" + description="PAC URL for obtaining PAC file." /> + <property name="pac-script" + alias="pac-script" + description="PAC script for the connection." /> + </setting> + <setting name="serial" > + <property name="baud" + description="Speed to use for communication over the serial port. Note that this value usually has no effect for mobile broadband modems as they generally ignore speed settings and use the highest available speed." /> + <property name="bits" + description="Byte-width of the serial communication. The 8 in "8n1" for example." /> + <property name="parity" + description="Parity setting of the serial port." /> + <property name="stopbits" + description="Number of stop bits for communication on the serial port. Either 1 or 2. The 1 in "8n1" for example." /> + <property name="send-delay" + description="Time to delay between each byte sent to the modem, in microseconds." /> + </setting> + <setting name="sriov" > + <property name="total-vfs" + description="The total number of virtual functions to create. Note that when the sriov setting is present NetworkManager enforces the number of virtual functions on the interface (also when it is zero) during activation and resets it upon deactivation. To prevent any changes to SR-IOV parameters don't add a sriov setting to the connection." /> + <property name="vfs" + description="Array of virtual function descriptors. Each VF descriptor is a dictionary mapping attribute names to GVariant values. The 'index' entry is mandatory for each VF. When represented as string a VF is in the form: "INDEX [ATTR=VALUE[ ATTR=VALUE]...]". for example: "2 mac=00:11:22:33:44:55 spoof-check=true". Multiple VFs can be specified using a comma as separator. Currently, the following attributes are supported: mac, spoof-check, trust, min-tx-rate, max-tx-rate, vlans. The "vlans" attribute is represented as a semicolon-separated list of VLAN descriptors, where each descriptor has the form "ID[.PRIORITY[.PROTO]]". PROTO can be either 'q' for 802.1Q (the default) or 'ad' for 802.1ad." /> + <property name="autoprobe-drivers" + description="Whether to autoprobe virtual functions by a compatible driver. If set to NM_TERNARY_TRUE (1), the kernel will try to bind VFs to a compatible driver and if this succeeds a new network interface will be instantiated for each VF. If set to NM_TERNARY_FALSE (0), VFs will not be claimed and no network interfaces will be created for them. When set to NM_TERNARY_DEFAULT (-1), the global default is used; in case the global default is unspecified it is assumed to be NM_TERNARY_TRUE (1)." /> + </setting> + <setting name="tc" > + <property name="qdiscs" + description="Array of TC queueing disciplines. When the "tc" setting is present, qdiscs from this property are applied upon activation. If the property is empty, all qdiscs are removed and the device will only have the default qdisc assigned by kernel according to the "net.core.default_qdisc" sysctl. If the "tc" setting is not present, NetworkManager doesn't touch the qdiscs present on the interface." /> + <property name="tfilters" + description="Array of TC traffic filters. When the "tc" setting is present, filters from this property are applied upon activation. If the property is empty, NetworkManager removes all the filters. If the "tc" setting is not present, NetworkManager doesn't touch the filters present on the interface." /> + </setting> + <setting name="team" > + <property name="config" + alias="config" + description="The JSON configuration for the team network interface. The property should contain raw JSON configuration data suitable for teamd, because the value is passed directly to teamd. If not specified, the default configuration is used. See man teamd.conf for the format details." /> + <property name="notify-peers-count" + description="Corresponds to the teamd notify_peers.count." /> + <property name="notify-peers-interval" + description="Corresponds to the teamd notify_peers.interval." /> + <property name="mcast-rejoin-count" + description="Corresponds to the teamd mcast_rejoin.count." /> + <property name="mcast-rejoin-interval" + description="Corresponds to the teamd mcast_rejoin.interval." /> + <property name="runner" + description="Corresponds to the teamd runner.name. Permitted values are: "roundrobin", "broadcast", "activebackup", "loadbalance", "lacp", "random"." /> + <property name="runner-hwaddr-policy" + description="Corresponds to the teamd runner.hwaddr_policy." /> + <property name="runner-tx-hash" + description="Corresponds to the teamd runner.tx_hash." /> + <property name="runner-tx-balancer" + description="Corresponds to the teamd runner.tx_balancer.name." /> + <property name="runner-tx-balancer-interval" + description="Corresponds to the teamd runner.tx_balancer.interval." /> + <property name="runner-active" + description="Corresponds to the teamd runner.active." /> + <property name="runner-fast-rate" + description="Corresponds to the teamd runner.fast_rate." /> + <property name="runner-sys-prio" + description="Corresponds to the teamd runner.sys_prio." /> + <property name="runner-min-ports" + description="Corresponds to the teamd runner.min_ports." /> + <property name="runner-agg-select-policy" + description="Corresponds to the teamd runner.agg_select_policy." /> + <property name="link-watchers" + description="Link watchers configuration for the connection: each link watcher is defined by a dictionary, whose keys depend upon the selected link watcher. Available link watchers are 'ethtool', 'nsna_ping' and 'arp_ping' and it is specified in the dictionary with the key 'name'. Available keys are: ethtool: 'delay-up', 'delay-down', 'init-wait'; nsna_ping: 'init-wait', 'interval', 'missed-max', 'target-host'; arp_ping: all the ones in nsna_ping and 'source-host', 'validate-active', 'validate-inactive', 'send-always'. See teamd.conf man for more details." /> + </setting> + <setting name="team-port" > + <property name="config" + alias="config" + description="The JSON configuration for the team port. The property should contain raw JSON configuration data suitable for teamd, because the value is passed directly to teamd. If not specified, the default configuration is used. See man teamd.conf for the format details." /> + <property name="queue-id" + description="Corresponds to the teamd ports.PORTIFNAME.queue_id. When set to -1 means the parameter is skipped from the json config." /> + <property name="prio" + description="Corresponds to the teamd ports.PORTIFNAME.prio." /> + <property name="sticky" + description="Corresponds to the teamd ports.PORTIFNAME.sticky." /> + <property name="lacp-prio" + description="Corresponds to the teamd ports.PORTIFNAME.lacp_prio." /> + <property name="lacp-key" + description="Corresponds to the teamd ports.PORTIFNAME.lacp_key." /> + <property name="link-watchers" + description="Link watchers configuration for the connection: each link watcher is defined by a dictionary, whose keys depend upon the selected link watcher. Available link watchers are 'ethtool', 'nsna_ping' and 'arp_ping' and it is specified in the dictionary with the key 'name'. Available keys are: ethtool: 'delay-up', 'delay-down', 'init-wait'; nsna_ping: 'init-wait', 'interval', 'missed-max', 'target-host'; arp_ping: all the ones in nsna_ping and 'source-host', 'validate-active', 'validate-inactive', 'send-always'. See teamd.conf man for more details." /> + </setting> + <setting name="tun" > + <property name="mode" + alias="mode" + description="The operating mode of the virtual device. Allowed values are NM_SETTING_TUN_MODE_TUN (1) to create a layer 3 device and NM_SETTING_TUN_MODE_TAP (2) to create an Ethernet-like layer 2 one." /> + <property name="owner" + alias="owner" + description="The user ID which will own the device. If set to NULL everyone will be able to use the device." /> + <property name="group" + alias="group" + description="The group ID which will own the device. If set to NULL everyone will be able to use the device." /> + <property name="pi" + alias="pi" + description="If TRUE the interface will prepend a 4 byte header describing the physical interface to the packets." /> + <property name="vnet-hdr" + alias="vnet-hdr" + description="If TRUE the IFF_VNET_HDR the tunnel packets will include a virtio network header." /> + <property name="multi-queue" + alias="multi-queue" + description="If the property is set to TRUE, the interface will support multiple file descriptors (queues) to parallelize packet sending or receiving. Otherwise, the interface will only support a single queue." /> + </setting> + <setting name="user" > + </setting> + <setting name="veth" > + <property name="peer" + alias="peer" + description="This property specifies the peer interface name of the veth. This property is mandatory." /> + </setting> + <setting name="vlan" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID from which this VLAN interface should be created. If this property is not specified, the connection must contain an "802-3-ethernet" setting with a "mac-address" property." /> + <property name="id" + alias="id" + description="The VLAN identifier that the interface created by this connection should be assigned. The valid range is from 0 to 4094, without the reserved id 4095." /> + <property name="flags" + alias="flags" + description="One or more flags which control the behavior and features of the VLAN interface. Flags include NM_VLAN_FLAG_REORDER_HEADERS (0x1) (reordering of output packet headers), NM_VLAN_FLAG_GVRP (0x2) (use of the GVRP protocol), and NM_VLAN_FLAG_LOOSE_BINDING (0x4) (loose binding of the interface to its master device's operating state). NM_VLAN_FLAG_MVRP (0x8) (use of the MVRP protocol). The default value of this property is NM_VLAN_FLAG_REORDER_HEADERS, but it used to be 0. To preserve backward compatibility, the default-value in the D-Bus API continues to be 0 and a missing property on D-Bus is still considered as 0." /> + <property name="ingress-priority-map" + alias="ingress" + description="For incoming packets, a list of mappings from 802.1p priorities to Linux SKB priorities. The mapping is given in the format "from:to" where both "from" and "to" are unsigned integers, ie "7:3"." /> + <property name="egress-priority-map" + alias="egress" + description="For outgoing packets, a list of mappings from Linux SKB priorities to 802.1p priorities. The mapping is given in the format "from:to" where both "from" and "to" are unsigned integers, ie "7:3"." /> + </setting> + <setting name="vpn" > + <property name="service-type" + alias="vpn-type" + description="D-Bus service name of the VPN plugin that this setting uses to connect to its network. i.e. org.freedesktop.NetworkManager.vpnc for the vpnc plugin." /> + <property name="user-name" + alias="user" + description="If the VPN connection requires a user name for authentication, that name should be provided here. If the connection is available to more than one user, and the VPN requires each user to supply a different name, then leave this property empty. If this property is empty, NetworkManager will automatically supply the username of the user which requested the VPN connection." /> + <property name="data" + description="Dictionary of key/value pairs of VPN plugin specific data. Both keys and values must be strings." /> + <property name="secrets" + description="Dictionary of key/value pairs of VPN plugin specific secrets like passwords or private keys. Both keys and values must be strings." /> + <property name="persistent" + description="If the VPN service supports persistence, and this property is TRUE, the VPN will attempt to stay connected across link changes and outages, until explicitly disconnected." /> + <property name="timeout" + description="Timeout for the VPN service to establish the connection. Some services may take quite a long time to connect. Value of 0 means a default timeout, which is 60 seconds (unless overridden by vpn.timeout in configuration file). Values greater than zero mean timeout in seconds." /> + </setting> + <setting name="vrf" > + <property name="table" + alias="table" + description="The routing table for this VRF." /> + </setting> + <setting name="vxlan" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID." /> + <property name="id" + alias="id" + description="Specifies the VXLAN Network Identifier (or VXLAN Segment Identifier) to use." /> + <property name="local" + alias="local" + description="If given, specifies the source IP address to use in outgoing packets." /> + <property name="remote" + alias="remote" + description="Specifies the unicast destination IP address to use in outgoing packets when the destination link layer address is not known in the VXLAN device forwarding database, or the multicast IP address to join." /> + <property name="source-port-min" + alias="source-port-min" + description="Specifies the minimum UDP source port to communicate to the remote VXLAN tunnel endpoint." /> + <property name="source-port-max" + alias="source-port-max" + description="Specifies the maximum UDP source port to communicate to the remote VXLAN tunnel endpoint." /> + <property name="destination-port" + alias="destination-port" + description="Specifies the UDP destination port to communicate to the remote VXLAN tunnel endpoint." /> + <property name="tos" + description="Specifies the TOS value to use in outgoing packets." /> + <property name="ttl" + description="Specifies the time-to-live value to use in outgoing packets." /> + <property name="ageing" + description="Specifies the lifetime in seconds of FDB entries learnt by the kernel." /> + <property name="limit" + description="Specifies the maximum number of FDB entries. A value of zero means that the kernel will store unlimited entries." /> + <property name="learning" + description="Specifies whether unknown source link layer addresses and IP addresses are entered into the VXLAN device forwarding database." /> + <property name="proxy" + description="Specifies whether ARP proxy is turned on." /> + <property name="rsc" + description="Specifies whether route short circuit is turned on." /> + <property name="l2-miss" + description="Specifies whether netlink LL ADDR miss notifications are generated." /> + <property name="l3-miss" + description="Specifies whether netlink IP ADDR miss notifications are generated." /> + </setting> + <setting name="wifi-p2p" > + <property name="peer" + alias="peer" + description="The P2P device that should be connected to. Currently, this is the only way to create or join a group." /> + <property name="wps-method" + description="Flags indicating which mode of WPS is to be used. There's little point in changing the default setting as NetworkManager will automatically determine the best method to use." /> + <property name="wfd-ies" + description="The Wi-Fi Display (WFD) Information Elements (IEs) to set. Wi-Fi Display requires a protocol specific information element to be set in certain Wi-Fi frames. These can be specified here for the purpose of establishing a connection. This setting is only useful when implementing a Wi-Fi Display client." /> + </setting> + <setting name="wimax" > + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the WiMAX device whose MAC address matches. This property does not change the MAC address of the device (known as MAC spoofing). Deprecated: 1" /> + <property name="network-name" + alias="nsp" + description="Network Service Provider (NSP) name of the WiMAX network this connection should use. Deprecated: 1" /> + </setting> + <setting name="wireguard" > + <property name="private-key" + description="The 256 bit private-key in base64 encoding." /> + <property name="private-key-flags" + description="Flags indicating how to handle the "private-key" property." /> + <property name="listen-port" + description="The listen-port. If listen-port is not specified, the port will be chosen randomly when the interface comes up." /> + <property name="fwmark" + description="The use of fwmark is optional and is by default off. Setting it to 0 disables it. Otherwise, it is a 32-bit fwmark for outgoing packets. Note that "ip4-auto-default-route" or "ip6-auto-default-route" enabled, implies to automatically choose a fwmark." /> + <property name="peer-routes" + description="Whether to automatically add routes for the AllowedIPs ranges of the peers. If TRUE (the default), NetworkManager will automatically add routes in the routing tables according to ipv4.route-table and ipv6.route-table. Usually you want this automatism enabled. If FALSE, no such routes are added automatically. In this case, the user may want to configure static routes in ipv4.routes and ipv6.routes, respectively. Note that if the peer's AllowedIPs is "0.0.0.0/0" or "::/0" and the profile's ipv4.never-default or ipv6.never-default setting is enabled, the peer route for this peer won't be added automatically." /> + <property name="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple fragments. If zero a default MTU is used. Note that contrary to wg-quick's MTU setting, this does not take into account the current routes at the time of activation." /> + <property name="ip4-auto-default-route" + description="Whether to enable special handling of the IPv4 default route. If enabled, the IPv4 default route from wireguard.peer-routes will be placed to a dedicated routing-table and two policy routing rules will be added. The fwmark number is also used as routing-table for the default-route, and if fwmark is zero, an unused fwmark/table is chosen automatically. This corresponds to what wg-quick does with Table=auto and what WireGuard calls "Improved Rule-based Routing". Note that for this automatism to work, you usually don't want to set ipv4.gateway, because that will result in a conflicting default route. Leaving this at the default will enable this option automatically if ipv4.never-default is not set and there are any peers that use a default-route as allowed-ips." /> + <property name="ip6-auto-default-route" + description="Like ip4-auto-default-route, but for the IPv6 default route." /> + </setting> + <setting name="wpan" > + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the IEEE 802.15.4 (WPAN) MAC layer device whose permanent MAC address matches." /> + <property name="short-address" + alias="short-addr" + description="Short IEEE 802.15.4 address to be used within a restricted environment." /> + <property name="pan-id" + alias="pan-id" + description="IEEE 802.15.4 Personal Area Network (PAN) identifier." /> + <property name="page" + alias="page" + description="IEEE 802.15.4 channel page. A positive integer or -1, meaning "do not set, use whatever the device is already set to"." /> + <property name="channel" + alias="channel" + description="IEEE 802.15.4 channel. A positive integer or -1, meaning "do not set, use whatever the device is already set to"." /> + </setting> +</nm-setting-docs> diff --git a/src/nmcli/generate-docs-nm-settings-nmcli.xml.in b/src/nmcli/generate-docs-nm-settings-nmcli.xml.in new file mode 100644 index 00000000..ca5225ba --- /dev/null +++ b/src/nmcli/generate-docs-nm-settings-nmcli.xml.in @@ -0,0 +1,1143 @@ +<nm-setting-docs> + <setting name="6lowpan" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID from which this 6LowPAN interface should be created." /> + </setting> + <setting name="802-11-olpc-mesh" + alias="olpc-mesh" > + <property name="ssid" + alias="ssid" + description="SSID of the mesh network to join." /> + <property name="channel" + alias="channel" + description="Channel on which the mesh network to join is located." /> + <property name="dhcp-anycast-address" + alias="dhcp-anycast" + description="Anycast DHCP MAC address used when requesting an IP address via DHCP. The specific anycast address used determines which DHCP server class answers the request. This is currently only implemented by dhclient DHCP plugin." /> + </setting> + <setting name="802-11-wireless" + alias="wifi" > + <property name="ssid" + alias="ssid" + description="SSID of the Wi-Fi network. Must be specified." /> + <property name="mode" + alias="mode" + description="Wi-Fi network mode; one of "infrastructure", "mesh", "adhoc" or "ap". If blank, infrastructure is assumed." /> + <property name="band" + description="802.11 frequency band of the network. One of "a" for 5GHz 802.11a or "bg" for 2.4GHz 802.11. This will lock associations to the Wi-Fi network to the specific band, i.e. if "a" is specified, the device will not associate with the same network in the 2.4GHz band even if the network's settings are compatible. This setting depends on specific driver capability and may not work with all drivers." /> + <property name="channel" + description="Wireless channel to use for the Wi-Fi connection. The device will only join (or create for Ad-Hoc networks) a Wi-Fi network on the specified channel. Because channel numbers overlap between bands, this property also requires the "band" property to be set." /> + <property name="bssid" + description="If specified, directs the device to only associate with the given access point. This capability is highly driver dependent and not supported by all devices. Note: this property does not control the BSSID used when creating an Ad-Hoc network and is unlikely to in the future." /> + <property name="rate" + description="If non-zero, directs the device to only use the specified bitrate for communication with the access point. Units are in Kb/s, ie 5500 = 5.5 Mbit/s. This property is highly driver dependent and not all devices support setting a static bitrate." /> + <property name="tx-power" + description="If non-zero, directs the device to use the specified transmit power. Units are dBm. This property is highly driver dependent and not all devices support setting a static transmit power." /> + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the Wi-Fi device whose permanent MAC address matches. This property does not change the MAC address of the device (i.e. MAC spoofing)." /> + <property name="cloned-mac-address" + alias="cloned-mac" + description="If specified, request that the device use this MAC address instead. This is known as MAC cloning or spoofing. Beside explicitly specifying a MAC address, the special values "preserve", "permanent", "random" and "stable" are supported. "preserve" means not to touch the MAC address on activation. "permanent" means to use the permanent hardware address of the device. "random" creates a random MAC address on each connect. "stable" creates a hashed MAC address based on connection.stable-id and a machine dependent key. If unspecified, the value can be overwritten via global defaults, see manual of NetworkManager.conf. If still unspecified, it defaults to "preserve" (older versions of NetworkManager may use a different default value). On D-Bus, this field is expressed as "assigned-mac-address" or the deprecated "cloned-mac-address"." /> + <property name="generate-mac-address-mask" + description="With "cloned-mac-address" setting "random" or "stable", by default all bits of the MAC address are scrambled and a locally-administered, unicast MAC address is created. This property allows to specify that certain bits are fixed. Note that the least significant bit of the first MAC address will always be unset to create a unicast MAC address. If the property is NULL, it is eligible to be overwritten by a default connection setting. If the value is still NULL or an empty string, the default is to create a locally-administered, unicast MAC address. If the value contains one MAC address, this address is used as mask. The set bits of the mask are to be filled with the current MAC address of the device, while the unset bits are subject to randomization. Setting "FE:FF:FF:00:00:00" means to preserve the OUI of the current MAC address and only randomize the lower 3 bytes using the "random" or "stable" algorithm. If the value contains one additional MAC address after the mask, this address is used instead of the current MAC address to fill the bits that shall not be randomized. For example, a value of "FE:FF:FF:00:00:00 68:F7:28:00:00:00" will set the OUI of the MAC address to 68:F7:28, while the lower bits are randomized. A value of "02:00:00:00:00:00 00:00:00:00:00:00" will create a fully scrambled globally-administered, burned-in MAC address. If the value contains more than one additional MAC addresses, one of them is chosen randomly. For example, "02:00:00:00:00:00 00:00:00:00:00:00 02:00:00:00:00:00" will create a fully scrambled MAC address, randomly locally or globally administered." /> + <property name="mac-address-blacklist" + description="A list of permanent MAC addresses of Wi-Fi devices to which this connection should never apply. Each MAC address should be given in the standard hex-digits-and-colons notation (eg "00:11:22:33:44:55")." /> + <property name="mac-address-randomization" + description="One of NM_SETTING_MAC_RANDOMIZATION_DEFAULT (0) (never randomize unless the user has set a global default to randomize and the supplicant supports randomization), NM_SETTING_MAC_RANDOMIZATION_NEVER (1) (never randomize the MAC address), or NM_SETTING_MAC_RANDOMIZATION_ALWAYS (2) (always randomize the MAC address). This property is deprecated for 'cloned-mac-address'. Deprecated: 1" /> + <property name="mtu" + alias="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple Ethernet frames." /> + <property name="seen-bssids" + description="A list of BSSIDs (each BSSID formatted as a MAC address like "00:11:22:33:44:55") that have been detected as part of the Wi-Fi network. NetworkManager internally tracks previously seen BSSIDs. The property is only meant for reading and reflects the BSSID list of NetworkManager. The changes you make to this property will not be preserved." /> + <property name="hidden" + description="If TRUE, indicates that the network is a non-broadcasting network that hides its SSID. This works both in infrastructure and AP mode. In infrastructure mode, various workarounds are used for a more reliable discovery of hidden networks, such as probe-scanning the SSID. However, these workarounds expose inherent insecurities with hidden SSID networks, and thus hidden SSID networks should be used with caution. In AP mode, the created network does not broadcast its SSID. Note that marking the network as hidden may be a privacy issue for you (in infrastructure mode) or client stations (in AP mode), as the explicit probe-scans are distinctly recognizable on the air." /> + <property name="powersave" + description="One of NM_SETTING_WIRELESS_POWERSAVE_DISABLE (2) (disable Wi-Fi power saving), NM_SETTING_WIRELESS_POWERSAVE_ENABLE (3) (enable Wi-Fi power saving), NM_SETTING_WIRELESS_POWERSAVE_IGNORE (1) (don't touch currently configure setting) or NM_SETTING_WIRELESS_POWERSAVE_DEFAULT (0) (use the globally configured value). All other values are reserved." /> + <property name="wake-on-wlan" + description="The NMSettingWirelessWakeOnWLan options to enable. Not all devices support all options. May be any combination of NM_SETTING_WIRELESS_WAKE_ON_WLAN_ANY (0x2), NM_SETTING_WIRELESS_WAKE_ON_WLAN_DISCONNECT (0x4), NM_SETTING_WIRELESS_WAKE_ON_WLAN_MAGIC (0x8), NM_SETTING_WIRELESS_WAKE_ON_WLAN_GTK_REKEY_FAILURE (0x10), NM_SETTING_WIRELESS_WAKE_ON_WLAN_EAP_IDENTITY_REQUEST (0x20), NM_SETTING_WIRELESS_WAKE_ON_WLAN_4WAY_HANDSHAKE (0x40), NM_SETTING_WIRELESS_WAKE_ON_WLAN_RFKILL_RELEASE (0x80), NM_SETTING_WIRELESS_WAKE_ON_WLAN_TCP (0x100) or the special values NM_SETTING_WIRELESS_WAKE_ON_WLAN_DEFAULT (0x1) (to use global settings) and NM_SETTING_WIRELESS_WAKE_ON_WLAN_IGNORE (0x8000) (to disable management of Wake-on-LAN in NetworkManager)." /> + <property name="ap-isolation" + description="Configures AP isolation, which prevents communication between wireless devices connected to this AP. This property can be set to a value different from NM_TERNARY_DEFAULT (-1) only when the interface is configured in AP mode. If set to NM_TERNARY_TRUE (1), devices are not able to communicate with each other. This increases security because it protects devices against attacks from other clients in the network. At the same time, it prevents devices to access resources on the same wireless networks as file shares, printers, etc. If set to NM_TERNARY_FALSE (0), devices can talk to each other. When set to NM_TERNARY_DEFAULT (-1), the global default is used; in case the global default is unspecified it is assumed to be NM_TERNARY_FALSE (0)." /> + </setting> + <setting name="802-11-wireless-security" + alias="wifi-sec" > + <property name="key-mgmt" + description="Key management used for the connection. One of "none" (WEP or no password protection), "ieee8021x" (Dynamic WEP), "owe" (Opportunistic Wireless Encryption), "wpa-psk" (WPA2 + WPA3 personal), "sae" (WPA3 personal only), "wpa-eap" (WPA2 + WPA3 enterprise) or "wpa-eap-suite-b-192" (WPA3 enterprise only). This property must be set for any Wi-Fi connection that uses security." /> + <property name="wep-tx-keyidx" + description="When static WEP is used (ie, key-mgmt = "none") and a non-default WEP key index is used by the AP, put that WEP key index here. Valid values are 0 (default key) through 3. Note that some consumer access points (like the Linksys WRT54G) number the keys 1 - 4." /> + <property name="auth-alg" + description="When WEP is used (ie, key-mgmt = "none" or "ieee8021x") indicate the 802.11 authentication algorithm required by the AP here. One of "open" for Open System, "shared" for Shared Key, or "leap" for Cisco LEAP. When using Cisco LEAP (ie, key-mgmt = "ieee8021x" and auth-alg = "leap") the "leap-username" and "leap-password" properties must be specified." /> + <property name="proto" + description="List of strings specifying the allowed WPA protocol versions to use. Each element may be one "wpa" (allow WPA) or "rsn" (allow WPA2/RSN). If not specified, both WPA and RSN connections are allowed." /> + <property name="pairwise" + description="A list of pairwise encryption algorithms which prevents connections to Wi-Fi networks that do not utilize one of the algorithms in the list. For maximum compatibility leave this property empty. Each list element may be one of "tkip" or "ccmp"." /> + <property name="group" + description="A list of group/broadcast encryption algorithms which prevents connections to Wi-Fi networks that do not utilize one of the algorithms in the list. For maximum compatibility leave this property empty. Each list element may be one of "wep40", "wep104", "tkip", or "ccmp"." /> + <property name="pmf" + description="Indicates whether Protected Management Frames (802.11w) must be enabled for the connection. One of NM_SETTING_WIRELESS_SECURITY_PMF_DEFAULT (0) (use global default value), NM_SETTING_WIRELESS_SECURITY_PMF_DISABLE (1) (disable PMF), NM_SETTING_WIRELESS_SECURITY_PMF_OPTIONAL (2) (enable PMF if the supplicant and the access point support it) or NM_SETTING_WIRELESS_SECURITY_PMF_REQUIRED (3) (enable PMF and fail if not supported). When set to NM_SETTING_WIRELESS_SECURITY_PMF_DEFAULT (0) and no global default is set, PMF will be optionally enabled." /> + <property name="leap-username" + description="The login username for legacy LEAP connections (ie, key-mgmt = "ieee8021x" and auth-alg = "leap")." /> + <property name="wep-key0" + description="Index 0 WEP key. This is the WEP key used in most networks. See the "wep-key-type" property for a description of how this key is interpreted." /> + <property name="wep-key1" + description="Index 1 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted." /> + <property name="wep-key2" + description="Index 2 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted." /> + <property name="wep-key3" + description="Index 3 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted." /> + <property name="wep-key-flags" + description="Flags indicating how to handle the "wep-key0", "wep-key1", "wep-key2", and "wep-key3" properties." /> + <property name="wep-key-type" + description="Controls the interpretation of WEP keys. Allowed values are NM_WEP_KEY_TYPE_KEY (1), in which case the key is either a 10- or 26-character hexadecimal string, or a 5- or 13-character ASCII password; or NM_WEP_KEY_TYPE_PASSPHRASE (2), in which case the passphrase is provided as a string and will be hashed using the de-facto MD5 method to derive the actual WEP key." /> + <property name="psk" + description="Pre-Shared-Key for WPA networks. For WPA-PSK, it's either an ASCII passphrase of 8 to 63 characters that is (as specified in the 802.11i standard) hashed to derive the actual key, or the key in form of 64 hexadecimal character. The WPA3-Personal networks use a passphrase of any length for SAE authentication." /> + <property name="psk-flags" + description="Flags indicating how to handle the "psk" property." /> + <property name="leap-password" + description="The login password for legacy LEAP connections (ie, key-mgmt = "ieee8021x" and auth-alg = "leap")." /> + <property name="leap-password-flags" + description="Flags indicating how to handle the "leap-password" property." /> + <property name="wps-method" + description="Flags indicating which mode of WPS is to be used if any. There's little point in changing the default setting as NetworkManager will automatically determine whether it's feasible to start WPS enrollment from the Access Point capabilities. WPS can be disabled by setting this property to a value of 1." /> + <property name="fils" + description="Indicates whether Fast Initial Link Setup (802.11ai) must be enabled for the connection. One of NM_SETTING_WIRELESS_SECURITY_FILS_DEFAULT (0) (use global default value), NM_SETTING_WIRELESS_SECURITY_FILS_DISABLE (1) (disable FILS), NM_SETTING_WIRELESS_SECURITY_FILS_OPTIONAL (2) (enable FILS if the supplicant and the access point support it) or NM_SETTING_WIRELESS_SECURITY_FILS_REQUIRED (3) (enable FILS and fail if not supported). When set to NM_SETTING_WIRELESS_SECURITY_FILS_DEFAULT (0) and no global default is set, FILS will be optionally enabled." /> + </setting> + <setting name="802-1x" > + <property name="optional" + description="Whether the 802.1X authentication is optional. If TRUE, the activation will continue even after a timeout or an authentication failure. Setting the property to TRUE is currently allowed only for Ethernet connections. If set to FALSE, the activation can continue only after a successful authentication." /> + <property name="eap" + description="The allowed EAP method to be used when authenticating to the network with 802.1x. Valid methods are: "leap", "md5", "tls", "peap", "ttls", "pwd", and "fast". Each method requires different configuration using the properties of this setting; refer to wpa_supplicant documentation for the allowed combinations." /> + <property name="identity" + description="Identity string for EAP authentication methods. Often the user's user or login name." /> + <property name="anonymous-identity" + description="Anonymous identity string for EAP authentication methods. Used as the unencrypted identity with EAP types that support different tunneled identity like EAP-TTLS." /> + <property name="pac-file" + description="UTF-8 encoded file path containing PAC for EAP-FAST." /> + <property name="ca-cert" + description="Contains the CA certificate if used by the EAP method specified in the "eap" property. Certificate data is specified using a "scheme"; three are currently supported: blob, path and pkcs#11 URL. When using the blob scheme this property should be set to the certificate's DER encoded data. When using the path scheme, this property should be set to the full UTF-8 encoded path of the certificate, prefixed with the string "file://" and ending with a terminating NUL byte. This property can be unset even if the EAP method supports CA certificates, but this allows man-in-the-middle attacks and is NOT recommended. Note that enabling NMSetting8021x:system-ca-certs will override this setting to use the built-in path, if the built-in path is not a directory." /> + <property name="ca-cert-password" + description="The password used to access the CA certificate stored in "ca-cert" property. Only makes sense if the certificate is stored on a PKCS#11 token that requires a login." /> + <property name="ca-cert-password-flags" + description="Flags indicating how to handle the "ca-cert-password" property." /> + <property name="ca-path" + description="UTF-8 encoded path to a directory containing PEM or DER formatted certificates to be added to the verification chain in addition to the certificate specified in the "ca-cert" property. If NMSetting8021x:system-ca-certs is enabled and the built-in CA path is an existing directory, then this setting is ignored." /> + <property name="subject-match" + description="Substring to be matched against the subject of the certificate presented by the authentication server. When unset, no verification of the authentication server certificate's subject is performed. This property provides little security, if any, and its use is deprecated in favor of NMSetting8021x:domain-suffix-match." /> + <property name="altsubject-matches" + description="List of strings to be matched against the altSubjectName of the certificate presented by the authentication server. If the list is empty, no verification of the server certificate's altSubjectName is performed." /> + <property name="domain-suffix-match" + description="Constraint for server domain name. If set, this FQDN is used as a suffix match requirement for dNSName element(s) of the certificate presented by the authentication server. If a matching dNSName is found, this constraint is met. If no dNSName values are present, this constraint is matched against SubjectName CN using same suffix match comparison. Since version 1.24, multiple valid FQDNs can be passed as a ";" delimited list." /> + <property name="domain-match" + description="Constraint for server domain name. If set, this list of FQDNs is used as a match requirement for dNSName element(s) of the certificate presented by the authentication server. If a matching dNSName is found, this constraint is met. If no dNSName values are present, this constraint is matched against SubjectName CN using the same comparison. Multiple valid FQDNs can be passed as a ";" delimited list." /> + <property name="client-cert" + description="Contains the client certificate if used by the EAP method specified in the "eap" property. Certificate data is specified using a "scheme"; two are currently supported: blob and path. When using the blob scheme (which is backwards compatible with NM 0.7.x) this property should be set to the certificate's DER encoded data. When using the path scheme, this property should be set to the full UTF-8 encoded path of the certificate, prefixed with the string "file://" and ending with a terminating NUL byte." /> + <property name="client-cert-password" + description="The password used to access the client certificate stored in "client-cert" property. Only makes sense if the certificate is stored on a PKCS#11 token that requires a login." /> + <property name="client-cert-password-flags" + description="Flags indicating how to handle the "client-cert-password" property." /> + <property name="phase1-peapver" + description="Forces which PEAP version is used when PEAP is set as the EAP method in the "eap" property. When unset, the version reported by the server will be used. Sometimes when using older RADIUS servers, it is necessary to force the client to use a particular PEAP version. To do so, this property may be set to "0" or "1" to force that specific PEAP version." /> + <property name="phase1-peaplabel" + description="Forces use of the new PEAP label during key derivation. Some RADIUS servers may require forcing the new PEAP label to interoperate with PEAPv1. Set to "1" to force use of the new PEAP label. See the wpa_supplicant documentation for more details." /> + <property name="phase1-fast-provisioning" + description="Enables or disables in-line provisioning of EAP-FAST credentials when FAST is specified as the EAP method in the "eap" property. Recognized values are "0" (disabled), "1" (allow unauthenticated provisioning), "2" (allow authenticated provisioning), and "3" (allow both authenticated and unauthenticated provisioning). See the wpa_supplicant documentation for more details." /> + <property name="phase1-auth-flags" + description="Specifies authentication flags to use in "phase 1" outer authentication using NMSetting8021xAuthFlags options. The individual TLS versions can be explicitly disabled. If a certain TLS disable flag is not set, it is up to the supplicant to allow or forbid it. The TLS options map to tls_disable_tlsv1_x settings. See the wpa_supplicant documentation for more details." /> + <property name="phase2-auth" + description="Specifies the allowed "phase 2" inner authentication method when an EAP method that uses an inner TLS tunnel is specified in the "eap" property. For TTLS this property selects one of the supported non-EAP inner methods: "pap", "chap", "mschap", "mschapv2" while "phase2-autheap" selects an EAP inner method. For PEAP this selects an inner EAP method, one of: "gtc", "otp", "md5" and "tls". Each "phase 2" inner method requires specific parameters for successful authentication; see the wpa_supplicant documentation for more details. Both "phase2-auth" and "phase2-autheap" cannot be specified." /> + <property name="phase2-autheap" + description="Specifies the allowed "phase 2" inner EAP-based authentication method when TTLS is specified in the "eap" property. Recognized EAP-based "phase 2" methods are "md5", "mschapv2", "otp", "gtc", and "tls". Each "phase 2" inner method requires specific parameters for successful authentication; see the wpa_supplicant documentation for more details." /> + <property name="phase2-ca-cert" + description="Contains the "phase 2" CA certificate if used by the EAP method specified in the "phase2-auth" or "phase2-autheap" properties. Certificate data is specified using a "scheme"; three are currently supported: blob, path and pkcs#11 URL. When using the blob scheme this property should be set to the certificate's DER encoded data. When using the path scheme, this property should be set to the full UTF-8 encoded path of the certificate, prefixed with the string "file://" and ending with a terminating NUL byte. This property can be unset even if the EAP method supports CA certificates, but this allows man-in-the-middle attacks and is NOT recommended. Note that enabling NMSetting8021x:system-ca-certs will override this setting to use the built-in path, if the built-in path is not a directory." /> + <property name="phase2-ca-cert-password" + description="The password used to access the "phase2" CA certificate stored in "phase2-ca-cert" property. Only makes sense if the certificate is stored on a PKCS#11 token that requires a login." /> + <property name="phase2-ca-cert-password-flags" + description="Flags indicating how to handle the "phase2-ca-cert-password" property." /> + <property name="phase2-ca-path" + description="UTF-8 encoded path to a directory containing PEM or DER formatted certificates to be added to the verification chain in addition to the certificate specified in the "phase2-ca-cert" property. If NMSetting8021x:system-ca-certs is enabled and the built-in CA path is an existing directory, then this setting is ignored." /> + <property name="phase2-subject-match" + description="Substring to be matched against the subject of the certificate presented by the authentication server during the inner "phase 2" authentication. When unset, no verification of the authentication server certificate's subject is performed. This property provides little security, if any, and its use is deprecated in favor of NMSetting8021x:phase2-domain-suffix-match." /> + <property name="phase2-altsubject-matches" + description="List of strings to be matched against the altSubjectName of the certificate presented by the authentication server during the inner "phase 2" authentication. If the list is empty, no verification of the server certificate's altSubjectName is performed." /> + <property name="phase2-domain-suffix-match" + description="Constraint for server domain name. If set, this FQDN is used as a suffix match requirement for dNSName element(s) of the certificate presented by the authentication server during the inner "phase 2" authentication. If a matching dNSName is found, this constraint is met. If no dNSName values are present, this constraint is matched against SubjectName CN using same suffix match comparison. Since version 1.24, multiple valid FQDNs can be passed as a ";" delimited list." /> + <property name="phase2-domain-match" + description="Constraint for server domain name. If set, this list of FQDNs is used as a match requirement for dNSName element(s) of the certificate presented by the authentication server during the inner "phase 2" authentication. If a matching dNSName is found, this constraint is met. If no dNSName values are present, this constraint is matched against SubjectName CN using the same comparison. Multiple valid FQDNs can be passed as a ";" delimited list." /> + <property name="phase2-client-cert" + description="Contains the "phase 2" client certificate if used by the EAP method specified in the "phase2-auth" or "phase2-autheap" properties. Certificate data is specified using a "scheme"; two are currently supported: blob and path. When using the blob scheme (which is backwards compatible with NM 0.7.x) this property should be set to the certificate's DER encoded data. When using the path scheme, this property should be set to the full UTF-8 encoded path of the certificate, prefixed with the string "file://" and ending with a terminating NUL byte. This property can be unset even if the EAP method supports CA certificates, but this allows man-in-the-middle attacks and is NOT recommended." /> + <property name="phase2-client-cert-password" + description="The password used to access the "phase2" client certificate stored in "phase2-client-cert" property. Only makes sense if the certificate is stored on a PKCS#11 token that requires a login." /> + <property name="phase2-client-cert-password-flags" + description="Flags indicating how to handle the "phase2-client-cert-password" property." /> + <property name="password" + description="UTF-8 encoded password used for EAP authentication methods. If both the "password" property and the "password-raw" property are specified, "password" is preferred." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + <property name="password-raw" + description="Password used for EAP authentication methods, given as a byte array to allow passwords in other encodings than UTF-8 to be used. If both the "password" property and the "password-raw" property are specified, "password" is preferred." /> + <property name="password-raw-flags" + description="Flags indicating how to handle the "password-raw" property." /> + <property name="private-key" + description="Contains the private key when the "eap" property is set to "tls". Key data is specified using a "scheme"; two are currently supported: blob and path. When using the blob scheme and private keys, this property should be set to the key's encrypted PEM encoded data. When using private keys with the path scheme, this property should be set to the full UTF-8 encoded path of the key, prefixed with the string "file://" and ending with a terminating NUL byte. When using PKCS#12 format private keys and the blob scheme, this property should be set to the PKCS#12 data and the "private-key-password" property must be set to password used to decrypt the PKCS#12 certificate and key. When using PKCS#12 files and the path scheme, this property should be set to the full UTF-8 encoded path of the key, prefixed with the string "file://" and ending with a terminating NUL byte, and as with the blob scheme the "private-key-password" property must be set to the password used to decode the PKCS#12 private key and certificate. WARNING: "private-key" is not a "secret" property, and thus unencrypted private key data using the BLOB scheme may be readable by unprivileged users. Private keys should always be encrypted with a private key password to prevent unauthorized access to unencrypted private key data." /> + <property name="private-key-password" + description="The password used to decrypt the private key specified in the "private-key" property when the private key either uses the path scheme, or if the private key is a PKCS#12 format key." /> + <property name="private-key-password-flags" + description="Flags indicating how to handle the "private-key-password" property." /> + <property name="phase2-private-key" + description="Contains the "phase 2" inner private key when the "phase2-auth" or "phase2-autheap" property is set to "tls". Key data is specified using a "scheme"; two are currently supported: blob and path. When using the blob scheme and private keys, this property should be set to the key's encrypted PEM encoded data. When using private keys with the path scheme, this property should be set to the full UTF-8 encoded path of the key, prefixed with the string "file://" and ending with a terminating NUL byte. When using PKCS#12 format private keys and the blob scheme, this property should be set to the PKCS#12 data and the "phase2-private-key-password" property must be set to password used to decrypt the PKCS#12 certificate and key. When using PKCS#12 files and the path scheme, this property should be set to the full UTF-8 encoded path of the key, prefixed with the string "file://" and ending with a terminating NUL byte, and as with the blob scheme the "phase2-private-key-password" property must be set to the password used to decode the PKCS#12 private key and certificate." /> + <property name="phase2-private-key-password" + description="The password used to decrypt the "phase 2" private key specified in the "phase2-private-key" property when the private key either uses the path scheme, or is a PKCS#12 format key." /> + <property name="phase2-private-key-password-flags" + description="Flags indicating how to handle the "phase2-private-key-password" property." /> + <property name="pin" + description="PIN used for EAP authentication methods." /> + <property name="pin-flags" + description="Flags indicating how to handle the "pin" property." /> + <property name="system-ca-certs" + description="When TRUE, overrides the "ca-path" and "phase2-ca-path" properties using the system CA directory specified at configure time with the --system-ca-path switch. The certificates in this directory are added to the verification chain in addition to any certificates specified by the "ca-cert" and "phase2-ca-cert" properties. If the path provided with --system-ca-path is rather a file name (bundle of trusted CA certificates), it overrides "ca-cert" and "phase2-ca-cert" properties instead (sets ca_cert/ca_cert2 options for wpa_supplicant)." /> + <property name="auth-timeout" + description="A timeout for the authentication. Zero means the global default; if the global default is not set, the authentication timeout is 25 seconds." /> + </setting> + <setting name="802-3-ethernet" + alias="ethernet" > + <property name="port" + description="Specific port type to use if the device supports multiple attachment methods. One of "tp" (Twisted Pair), "aui" (Attachment Unit Interface), "bnc" (Thin Ethernet) or "mii" (Media Independent Interface). If the device supports only one port type, this setting is ignored." /> + <property name="speed" + description="When a value greater than 0 is set, configures the device to use the specified speed. If "auto-negotiate" is "yes" the specified speed will be the only one advertised during link negotiation: this works only for BASE-T 802.3 specifications and is useful for enforcing gigabit speeds, as in this case link negotiation is mandatory. If the value is unset (0, the default), the link configuration will be either skipped (if "auto-negotiate" is "no", the default) or will be auto-negotiated (if "auto-negotiate" is "yes") and the local device will advertise all the supported speeds. In Mbit/s, ie 100 == 100Mbit/s. Must be set together with the "duplex" property when non-zero. Before specifying a speed value be sure your device supports it." /> + <property name="duplex" + description="When a value is set, either "half" or "full", configures the device to use the specified duplex mode. If "auto-negotiate" is "yes" the specified duplex mode will be the only one advertised during link negotiation: this works only for BASE-T 802.3 specifications and is useful for enforcing gigabits modes, as in these cases link negotiation is mandatory. If the value is unset (the default), the link configuration will be either skipped (if "auto-negotiate" is "no", the default) or will be auto-negotiated (if "auto-negotiate" is "yes") and the local device will advertise all the supported duplex modes. Must be set together with the "speed" property if specified. Before specifying a duplex mode be sure your device supports it." /> + <property name="auto-negotiate" + description="When TRUE, enforce auto-negotiation of speed and duplex mode. If "speed" and "duplex" properties are both specified, only that single mode will be advertised and accepted during the link auto-negotiation process: this works only for BASE-T 802.3 specifications and is useful for enforcing gigabits modes, as in these cases link negotiation is mandatory. When FALSE, "speed" and "duplex" properties should be both set or link configuration will be skipped." /> + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the Ethernet device whose permanent MAC address matches. This property does not change the MAC address of the device (i.e. MAC spoofing)." /> + <property name="cloned-mac-address" + alias="cloned-mac" + description="If specified, request that the device use this MAC address instead. This is known as MAC cloning or spoofing. Beside explicitly specifying a MAC address, the special values "preserve", "permanent", "random" and "stable" are supported. "preserve" means not to touch the MAC address on activation. "permanent" means to use the permanent hardware address if the device has one (otherwise this is treated as "preserve"). "random" creates a random MAC address on each connect. "stable" creates a hashed MAC address based on connection.stable-id and a machine dependent key. If unspecified, the value can be overwritten via global defaults, see manual of NetworkManager.conf. If still unspecified, it defaults to "preserve" (older versions of NetworkManager may use a different default value). On D-Bus, this field is expressed as "assigned-mac-address" or the deprecated "cloned-mac-address"." /> + <property name="generate-mac-address-mask" + description="With "cloned-mac-address" setting "random" or "stable", by default all bits of the MAC address are scrambled and a locally-administered, unicast MAC address is created. This property allows to specify that certain bits are fixed. Note that the least significant bit of the first MAC address will always be unset to create a unicast MAC address. If the property is NULL, it is eligible to be overwritten by a default connection setting. If the value is still NULL or an empty string, the default is to create a locally-administered, unicast MAC address. If the value contains one MAC address, this address is used as mask. The set bits of the mask are to be filled with the current MAC address of the device, while the unset bits are subject to randomization. Setting "FE:FF:FF:00:00:00" means to preserve the OUI of the current MAC address and only randomize the lower 3 bytes using the "random" or "stable" algorithm. If the value contains one additional MAC address after the mask, this address is used instead of the current MAC address to fill the bits that shall not be randomized. For example, a value of "FE:FF:FF:00:00:00 68:F7:28:00:00:00" will set the OUI of the MAC address to 68:F7:28, while the lower bits are randomized. A value of "02:00:00:00:00:00 00:00:00:00:00:00" will create a fully scrambled globally-administered, burned-in MAC address. If the value contains more than one additional MAC addresses, one of them is chosen randomly. For example, "02:00:00:00:00:00 00:00:00:00:00:00 02:00:00:00:00:00" will create a fully scrambled MAC address, randomly locally or globally administered." /> + <property name="mac-address-blacklist" + description="If specified, this connection will never apply to the Ethernet device whose permanent MAC address matches an address in the list. Each MAC address is in the standard hex-digits-and-colons notation (00:11:22:33:44:55)." /> + <property name="mtu" + alias="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple Ethernet frames." /> + <property name="s390-subchannels" + description="Identifies specific subchannels that this network device uses for communication with z/VM or s390 host. Like the "mac-address" property for non-z/VM devices, this property can be used to ensure this connection only applies to the network device that uses these subchannels. The list should contain exactly 3 strings, and each string may only be composed of hexadecimal characters and the period (.) character." /> + <property name="s390-nettype" + description="s390 network device type; one of "qeth", "lcs", or "ctc", representing the different types of virtual network devices available on s390 systems." /> + <property name="s390-options" + description="Dictionary of key/value pairs of s390-specific device options. Both keys and values must be strings. Allowed keys include "portno", "layer2", "portname", "protocol", among others. Key names must contain only alphanumeric characters (ie, [a-zA-Z0-9])." /> + <property name="wake-on-lan" + description="The NMSettingWiredWakeOnLan options to enable. Not all devices support all options. May be any combination of NM_SETTING_WIRED_WAKE_ON_LAN_PHY (0x2), NM_SETTING_WIRED_WAKE_ON_LAN_UNICAST (0x4), NM_SETTING_WIRED_WAKE_ON_LAN_MULTICAST (0x8), NM_SETTING_WIRED_WAKE_ON_LAN_BROADCAST (0x10), NM_SETTING_WIRED_WAKE_ON_LAN_ARP (0x20), NM_SETTING_WIRED_WAKE_ON_LAN_MAGIC (0x40) or the special values NM_SETTING_WIRED_WAKE_ON_LAN_DEFAULT (0x1) (to use global settings) and NM_SETTING_WIRED_WAKE_ON_LAN_IGNORE (0x8000) (to disable management of Wake-on-LAN in NetworkManager)." /> + <property name="wake-on-lan-password" + description="If specified, the password used with magic-packet-based Wake-on-LAN, represented as an Ethernet MAC address. If NULL, no password will be required." /> + <property name="accept-all-mac-addresses" + description="When TRUE, setup the interface to accept packets for all MAC addresses. This is enabling the kernel interface flag IFF_PROMISC. When FALSE, the interface will only accept the packets with the interface destination mac address or broadcast." /> + </setting> + <setting name="adsl" > + <property name="username" + alias="username" + description="Username used to authenticate with the ADSL service." /> + <property name="password" + alias="password" + description="Password used to authenticate with the ADSL service." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + <property name="protocol" + alias="protocol" + description="ADSL connection protocol. Can be "pppoa", "pppoe" or "ipoatm"." /> + <property name="encapsulation" + alias="encapsulation" + description="Encapsulation of ADSL connection. Can be "vcmux" or "llc"." /> + <property name="vpi" + description="VPI of ADSL connection" /> + <property name="vci" + description="VCI of ADSL connection" /> + </setting> + <setting name="bluetooth" > + <property name="bdaddr" + alias="addr" + description="The Bluetooth address of the device." /> + <property name="type" + alias="bt-type" + description="Either "dun" for Dial-Up Networking connections or "panu" for Personal Area Networking connections to devices supporting the NAP profile." /> + </setting> + <setting name="bond" > + <property name="options" + description="Dictionary of key/value pairs of bonding options. Both keys and values must be strings. Option names must contain only alphanumeric characters (ie, [a-zA-Z0-9])." /> + </setting> + <setting name="bridge" > + <property name="mac-address" + alias="mac" + description="If specified, the MAC address of bridge. When creating a new bridge, this MAC address will be set. If this field is left unspecified, the "ethernet.cloned-mac-address" is referred instead to generate the initial MAC address. Note that setting "ethernet.cloned-mac-address" anyway overwrites the MAC address of the bridge later while activating the bridge. Hence, this property is deprecated. Deprecated: 1" /> + <property name="stp" + alias="stp" + description="Controls whether Spanning Tree Protocol (STP) is enabled for this bridge." /> + <property name="priority" + alias="priority" + description="Sets the Spanning Tree Protocol (STP) priority for this bridge. Lower values are "better"; the lowest priority bridge will be elected the root bridge." /> + <property name="forward-delay" + alias="forward-delay" + description="The Spanning Tree Protocol (STP) forwarding delay, in seconds." /> + <property name="hello-time" + alias="hello-time" + description="The Spanning Tree Protocol (STP) hello time, in seconds." /> + <property name="max-age" + alias="max-age" + description="The Spanning Tree Protocol (STP) maximum message age, in seconds." /> + <property name="ageing-time" + alias="ageing-time" + description="The Ethernet MAC address aging time, in seconds." /> + <property name="group-address" + description="If specified, The MAC address of the multicast group this bridge uses for STP. The address must be a link-local address in standard Ethernet MAC address format, ie an address of the form 01:80:C2:00:00:0X, with X in [0, 4..F]. If not specified the default value is 01:80:C2:00:00:00." /> + <property name="group-forward-mask" + alias="group-forward-mask" + description="A mask of group addresses to forward. Usually, group addresses in the range from 01:80:C2:00:00:00 to 01:80:C2:00:00:0F are not forwarded according to standards. This property is a mask of 16 bits, each corresponding to a group address in that range that must be forwarded. The mask can't have bits 0, 1 or 2 set because they are used for STP, MAC pause frames and LACP." /> + <property name="multicast-hash-max" + description="Set maximum size of multicast hash table (value must be a power of 2)." /> + <property name="multicast-last-member-count" + description="Set the number of queries the bridge will send before stopping forwarding a multicast group after a "leave" message has been received." /> + <property name="multicast-last-member-interval" + description="Set interval (in deciseconds) between queries to find remaining members of a group, after a "leave" message is received." /> + <property name="multicast-membership-interval" + description="Set delay (in deciseconds) after which the bridge will leave a group, if no membership reports for this group are received." /> + <property name="multicast-querier" + description="Enable or disable sending of multicast queries by the bridge. If not specified the option is disabled." /> + <property name="multicast-querier-interval" + description="If no queries are seen after this delay (in deciseconds) has passed, the bridge will start to send its own queries." /> + <property name="multicast-query-interval" + description="Interval (in deciseconds) between queries sent by the bridge after the end of the startup phase." /> + <property name="multicast-query-response-interval" + description="Set the Max Response Time/Max Response Delay (in deciseconds) for IGMP/MLD queries sent by the bridge." /> + <property name="multicast-query-use-ifaddr" + description="If enabled the bridge's own IP address is used as the source address for IGMP queries otherwise the default of 0.0.0.0 is used." /> + <property name="multicast-snooping" + alias="multicast-snooping" + description="Controls whether IGMP snooping is enabled for this bridge. Note that if snooping was automatically disabled due to hash collisions, the system may refuse to enable the feature until the collisions are resolved." /> + <property name="multicast-startup-query-count" + description="Set the number of IGMP queries to send during startup phase." /> + <property name="multicast-startup-query-interval" + description="Sets the time (in deciseconds) between queries sent out at startup to determine membership information." /> + <property name="multicast-router" + description="Sets bridge's multicast router. Multicast-snooping must be enabled for this option to work. Supported values are: 'auto', 'disabled', 'enabled' to which kernel assigns the numbers 1, 0, and 2, respectively. If not specified the default value is 'auto' (1)." /> + <property name="vlan-filtering" + description="Control whether VLAN filtering is enabled on the bridge." /> + <property name="vlan-default-pvid" + description="The default PVID for the ports of the bridge, that is the VLAN id assigned to incoming untagged frames." /> + <property name="vlan-stats-enabled" + description="Controls whether per-VLAN stats accounting is enabled." /> + <property name="vlan-protocol" + description="If specified, the protocol used for VLAN filtering. Supported values are: '802.1Q', '802.1ad'. If not specified the default value is '802.1Q'." /> + <property name="vlans" + description="Array of bridge VLAN objects. In addition to the VLANs specified here, the bridge will also have the default-pvid VLAN configured by the bridge.vlan-default-pvid property. In nmcli the VLAN list can be specified with the following syntax: $vid [pvid] [untagged] [, $vid [pvid] [untagged]]... where $vid is either a single id between 1 and 4094 or a range, represented as a couple of ids separated by a dash." /> + </setting> + <setting name="bridge-port" > + <property name="priority" + alias="priority" + description="The Spanning Tree Protocol (STP) priority of this bridge port." /> + <property name="path-cost" + alias="path-cost" + description="The Spanning Tree Protocol (STP) port cost for destinations via this port." /> + <property name="hairpin-mode" + alias="hairpin" + description="Enables or disables "hairpin mode" for the port, which allows frames to be sent back out through the port the frame was received on." /> + <property name="vlans" + description="Array of bridge VLAN objects. In addition to the VLANs specified here, the port will also have the default-pvid VLAN configured on the bridge by the bridge.vlan-default-pvid property. In nmcli the VLAN list can be specified with the following syntax: $vid [pvid] [untagged] [, $vid [pvid] [untagged]]... where $vid is either a single id between 1 and 4094 or a range, represented as a couple of ids separated by a dash." /> + </setting> + <setting name="cdma" > + <property name="number" + description="The number to dial to establish the connection to the CDMA-based mobile broadband network, if any. If not specified, the default number (#777) is used when required." /> + <property name="username" + alias="user" + description="The username used to authenticate with the network, if required. Many providers do not require a username, or accept any username. But if a username is required, it is specified here." /> + <property name="password" + alias="password" + description="The password used to authenticate with the network, if required. Many providers do not require a password, or accept any password. But if a password is required, it is specified here." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + <property name="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple frames." /> + </setting> + <setting name="connection" > + <property name="id" + alias="con-name" + description="A human readable unique identifier for the connection, like "Work Wi-Fi" or "T-Mobile 3G"." /> + <property name="uuid" + description="A universally unique identifier for the connection, for example generated with libuuid. It should be assigned when the connection is created, and never changed as long as the connection still applies to the same network. For example, it should not be changed when the "id" property or NMSettingIP4Config changes, but might need to be re-created when the Wi-Fi SSID, mobile broadband network provider, or "type" property changes. The UUID must be in the format "2815492f-7e56-435e-b2e9-246bd7cdc664" (ie, contains only hexadecimal characters and "-")." /> + <property name="stable-id" + description="This represents the identity of the connection used for various purposes. It allows to configure multiple profiles to share the identity. Also, the stable-id can contain placeholders that are substituted dynamically and deterministically depending on the context. The stable-id is used for generating IPv6 stable private addresses with ipv6.addr-gen-mode=stable-privacy. It is also used to seed the generated cloned MAC address for ethernet.cloned-mac-address=stable and wifi.cloned-mac-address=stable. It is also used as DHCP client identifier with ipv4.dhcp-client-id=stable and to derive the DHCP DUID with ipv6.dhcp-duid=stable-[llt,ll,uuid]. Note that depending on the context where it is used, other parameters are also seeded into the generation algorithm. For example, a per-host key is commonly also included, so that different systems end up generating different IDs. Or with ipv6.addr-gen-mode=stable-privacy, also the device's name is included, so that different interfaces yield different addresses. The per-host key is the identity of your machine and stored in /var/lib/NetworkManager/secret-key. The '$' character is treated special to perform dynamic substitutions at runtime. Currently, supported are "${CONNECTION}", "${DEVICE}", "${MAC}", "${BOOT}", "${RANDOM}". These effectively create unique IDs per-connection, per-device, per-boot, or every time. Note that "${DEVICE}" corresponds to the interface name of the device and "${MAC}" is the permanent MAC address of the device. Any unrecognized patterns following '$' are treated verbatim, however are reserved for future use. You are thus advised to avoid '$' or escape it as "$$". For example, set it to "${CONNECTION}-${BOOT}-${DEVICE}" to create a unique id for this connection that changes with every reboot and differs depending on the interface where the profile activates. If the value is unset, a global connection default is consulted. If the value is still unset, the default is similar to "${CONNECTION}" and uses a unique, fixed ID for the connection." /> + <property name="type" + alias="type" + description="Base type of the connection. For hardware-dependent connections, should contain the setting name of the hardware-type specific setting (ie, "802-3-ethernet" or "802-11-wireless" or "bluetooth", etc), and for non-hardware dependent connections like VPN or otherwise, should contain the setting name of that setting type (ie, "vpn" or "bridge", etc)." /> + <property name="interface-name" + alias="ifname" + description="The name of the network interface this connection is bound to. If not set, then the connection can be attached to any interface of the appropriate type (subject to restrictions imposed by other settings). For software devices this specifies the name of the created device. For connection types where interface names cannot easily be made persistent (e.g. mobile broadband or USB Ethernet), this property should not be used. Setting this property restricts the interfaces a connection can be used with, and if interface names change or are reordered the connection may be applied to the wrong interface." /> + <property name="autoconnect" + alias="autoconnect" + description="Whether or not the connection should be automatically connected by NetworkManager when the resources for the connection are available. TRUE to automatically activate the connection, FALSE to require manual intervention to activate the connection. Note that autoconnect is not implemented for VPN profiles. See "secondaries" as an alternative to automatically connect VPN profiles." /> + <property name="autoconnect-priority" + description="The autoconnect priority. If the connection is set to autoconnect, connections with higher priority will be preferred. Defaults to 0. The higher number means higher priority." /> + <property name="autoconnect-retries" + description="The number of times a connection should be tried when autoactivating before giving up. Zero means forever, -1 means the global default (4 times if not overridden). Setting this to 1 means to try activation only once before blocking autoconnect. Note that after a timeout, NetworkManager will try to autoconnect again." /> + <property name="multi-connect" + description="Specifies whether the profile can be active multiple times at a particular moment. The value is of type NMConnectionMultiConnect." /> + <property name="auth-retries" + description="The number of retries for the authentication. Zero means to try indefinitely; -1 means to use a global default. If the global default is not set, the authentication retries for 3 times before failing the connection. Currently, this only applies to 802-1x authentication." /> + <property name="timestamp" + description="The time, in seconds since the Unix Epoch, that the connection was last _successfully_ fully activated. NetworkManager updates the connection timestamp periodically when the connection is active to ensure that an active connection has the latest timestamp. The property is only meant for reading (changes to this property will not be preserved)." /> + <property name="read-only" + description="FALSE if the connection can be modified using the provided settings service's D-Bus interface with the right privileges, or TRUE if the connection is read-only and cannot be modified." /> + <property name="permissions" + description="An array of strings defining what access a given user has to this connection. If this is NULL or empty, all users are allowed to access this connection; otherwise users are allowed if and only if they are in this list. When this is not empty, the connection can be active only when one of the specified users is logged into an active session. Each entry is of the form "[type]:[id]:[reserved]"; for example, "user:dcbw:blah". At this time only the "user" [type] is allowed. Any other values are ignored and reserved for future use. [id] is the username that this permission refers to, which may not contain the ":" character. Any [reserved] information present must be ignored and is reserved for future use. All of [type], [id], and [reserved] must be valid UTF-8." /> + <property name="zone" + description="The trust level of a the connection. Free form case-insensitive string (for example "Home", "Work", "Public"). NULL or unspecified zone means the connection will be placed in the default zone as defined by the firewall. When updating this property on a currently activated connection, the change takes effect immediately." /> + <property name="master" + alias="master" + description="Interface name of the master device or UUID of the master connection." /> + <property name="slave-type" + alias="slave-type" + description="Setting name of the device type of this slave's master connection (eg, "bond"), or NULL if this connection is not a slave." /> + <property name="autoconnect-slaves" + description="Whether or not slaves of this connection should be automatically brought up when NetworkManager activates this connection. This only has a real effect for master connections. The properties "autoconnect", "autoconnect-priority" and "autoconnect-retries" are unrelated to this setting. The permitted values are: 0: leave slave connections untouched, 1: activate all the slave connections with this connection, -1: default. If -1 (default) is set, global connection.autoconnect-slaves is read to determine the real value. If it is default as well, this fallbacks to 0." /> + <property name="secondaries" + description="List of connection UUIDs that should be activated when the base connection itself is activated. Currently, only VPN connections are supported." /> + <property name="gateway-ping-timeout" + description="If greater than zero, delay success of IP addressing until either the timeout is reached, or an IP gateway replies to a ping." /> + <property name="metered" + description="Whether the connection is metered. When updating this property on a currently activated connection, the change takes effect immediately." /> + <property name="lldp" + description="Whether LLDP is enabled for the connection." /> + <property name="mdns" + description="Whether mDNS is enabled for the connection. The permitted values are: "yes" (2) register hostname and resolving for the connection, "no" (0) disable mDNS for the interface, "resolve" (1) do not register hostname but allow resolving of mDNS host names and "default" (-1) to allow lookup of a global default in NetworkManager.conf. If unspecified, "default" ultimately depends on the DNS plugin (which for systemd-resolved currently means "no"). This feature requires a plugin which supports mDNS. Otherwise, the setting has no effect. One such plugin is dns-systemd-resolved." /> + <property name="llmnr" + description="Whether Link-Local Multicast Name Resolution (LLMNR) is enabled for the connection. LLMNR is a protocol based on the Domain Name System (DNS) packet format that allows both IPv4 and IPv6 hosts to perform name resolution for hosts on the same local link. The permitted values are: "yes" (2) register hostname and resolving for the connection, "no" (0) disable LLMNR for the interface, "resolve" (1) do not register hostname but allow resolving of LLMNR host names If unspecified, "default" ultimately depends on the DNS plugin (which for systemd-resolved currently means "yes"). This feature requires a plugin which supports LLMNR. Otherwise, the setting has no effect. One such plugin is dns-systemd-resolved." /> + <property name="mud-url" + description="If configured, set to a Manufacturer Usage Description (MUD) URL that points to manufacturer-recommended network policies for IoT devices. It is transmitted as a DHCPv4 or DHCPv6 option. The value must be a valid URL starting with "https://". The special value "none" is allowed to indicate that no MUD URL is used. If the per-profile value is unspecified (the default), a global connection default gets consulted. If still unspecified, the ultimate default is "none"." /> + <property name="wait-device-timeout" + description="Timeout in milliseconds to wait for device at startup. During boot, devices may take a while to be detected by the driver. This property will cause to delay NetworkManager-wait-online.service and nm-online to give the device a chance to appear. This works by waiting for the given timeout until a compatible device for the profile is available and managed. The value 0 means no wait time. The default value is -1, which currently has the same meaning as no wait time." /> + </setting> + <setting name="dcb" > + <property name="app-fcoe-flags" + description="Specifies the NMSettingDcbFlags for the DCB FCoE application. Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="app-fcoe-priority" + description="The highest User Priority (0 - 7) which FCoE frames should use, or -1 for default priority. Only used when the "app-fcoe-flags" property includes the NM_SETTING_DCB_FLAG_ENABLE (0x1) flag." /> + <property name="app-fcoe-mode" + description="The FCoE controller mode; either "fabric" (default) or "vn2vn"." /> + <property name="app-iscsi-flags" + description="Specifies the NMSettingDcbFlags for the DCB iSCSI application. Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="app-iscsi-priority" + description="The highest User Priority (0 - 7) which iSCSI frames should use, or -1 for default priority. Only used when the "app-iscsi-flags" property includes the NM_SETTING_DCB_FLAG_ENABLE (0x1) flag." /> + <property name="app-fip-flags" + description="Specifies the NMSettingDcbFlags for the DCB FIP application. Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="app-fip-priority" + description="The highest User Priority (0 - 7) which FIP frames should use, or -1 for default priority. Only used when the "app-fip-flags" property includes the NM_SETTING_DCB_FLAG_ENABLE (0x1) flag." /> + <property name="priority-flow-control-flags" + description="Specifies the NMSettingDcbFlags for DCB Priority Flow Control (PFC). Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="priority-flow-control" + description="An array of 8 boolean values, where the array index corresponds to the User Priority (0 - 7) and the value indicates whether or not the corresponding priority should transmit priority pause." /> + <property name="priority-group-flags" + description="Specifies the NMSettingDcbFlags for DCB Priority Groups. Flags may be any combination of NM_SETTING_DCB_FLAG_ENABLE (0x1), NM_SETTING_DCB_FLAG_ADVERTISE (0x2), and NM_SETTING_DCB_FLAG_WILLING (0x4)." /> + <property name="priority-group-id" + description="An array of 8 uint values, where the array index corresponds to the User Priority (0 - 7) and the value indicates the Priority Group ID. Allowed Priority Group ID values are 0 - 7 or 15 for the unrestricted group." /> + <property name="priority-group-bandwidth" + description="An array of 8 uint values, where the array index corresponds to the Priority Group ID (0 - 7) and the value indicates the percentage of link bandwidth allocated to that group. Allowed values are 0 - 100, and the sum of all values must total 100 percents." /> + <property name="priority-bandwidth" + description="An array of 8 uint values, where the array index corresponds to the User Priority (0 - 7) and the value indicates the percentage of bandwidth of the priority's assigned group that the priority may use. The sum of all percentages for priorities which belong to the same group must total 100 percents." /> + <property name="priority-strict-bandwidth" + description="An array of 8 boolean values, where the array index corresponds to the User Priority (0 - 7) and the value indicates whether or not the priority may use all of the bandwidth allocated to its assigned group." /> + <property name="priority-traffic-class" + description="An array of 8 uint values, where the array index corresponds to the User Priority (0 - 7) and the value indicates the traffic class (0 - 7) to which the priority is mapped." /> + </setting> + <setting name="dummy" > + </setting> + <setting name="ethtool" > + <property name="feature-esp-hw-offload" /> + <property name="feature-esp-tx-csum-hw-offload" /> + <property name="feature-fcoe-mtu" /> + <property name="feature-gro" /> + <property name="feature-gso" /> + <property name="feature-highdma" /> + <property name="feature-hw-tc-offload" /> + <property name="feature-l2-fwd-offload" /> + <property name="feature-loopback" /> + <property name="feature-lro" /> + <property name="feature-macsec-hw-offload" /> + <property name="feature-ntuple" /> + <property name="feature-rx" /> + <property name="feature-rxhash" /> + <property name="feature-rxvlan" /> + <property name="feature-rx-all" /> + <property name="feature-rx-fcs" /> + <property name="feature-rx-gro-hw" /> + <property name="feature-rx-gro-list" /> + <property name="feature-rx-udp-gro-forwarding" /> + <property name="feature-rx-udp_tunnel-port-offload" /> + <property name="feature-rx-vlan-filter" /> + <property name="feature-rx-vlan-stag-filter" /> + <property name="feature-rx-vlan-stag-hw-parse" /> + <property name="feature-sg" /> + <property name="feature-tls-hw-record" /> + <property name="feature-tls-hw-rx-offload" /> + <property name="feature-tls-hw-tx-offload" /> + <property name="feature-tso" /> + <property name="feature-tx" /> + <property name="feature-txvlan" /> + <property name="feature-tx-checksum-fcoe-crc" /> + <property name="feature-tx-checksum-ipv4" /> + <property name="feature-tx-checksum-ipv6" /> + <property name="feature-tx-checksum-ip-generic" /> + <property name="feature-tx-checksum-sctp" /> + <property name="feature-tx-esp-segmentation" /> + <property name="feature-tx-fcoe-segmentation" /> + <property name="feature-tx-gre-csum-segmentation" /> + <property name="feature-tx-gre-segmentation" /> + <property name="feature-tx-gso-list" /> + <property name="feature-tx-gso-partial" /> + <property name="feature-tx-gso-robust" /> + <property name="feature-tx-ipxip4-segmentation" /> + <property name="feature-tx-ipxip6-segmentation" /> + <property name="feature-tx-nocache-copy" /> + <property name="feature-tx-scatter-gather" /> + <property name="feature-tx-scatter-gather-fraglist" /> + <property name="feature-tx-sctp-segmentation" /> + <property name="feature-tx-tcp6-segmentation" /> + <property name="feature-tx-tcp-ecn-segmentation" /> + <property name="feature-tx-tcp-mangleid-segmentation" /> + <property name="feature-tx-tcp-segmentation" /> + <property name="feature-tx-tunnel-remcsum-segmentation" /> + <property name="feature-tx-udp-segmentation" /> + <property name="feature-tx-udp_tnl-csum-segmentation" /> + <property name="feature-tx-udp_tnl-segmentation" /> + <property name="feature-tx-vlan-stag-hw-insert" /> + <property name="coalesce-adaptive-rx" /> + <property name="coalesce-adaptive-tx" /> + <property name="coalesce-pkt-rate-high" /> + <property name="coalesce-pkt-rate-low" /> + <property name="coalesce-rx-frames" /> + <property name="coalesce-rx-frames-irq" /> + <property name="coalesce-rx-frames-high" /> + <property name="coalesce-rx-frames-low" /> + <property name="coalesce-rx-usecs" /> + <property name="coalesce-rx-usecs-irq" /> + <property name="coalesce-rx-usecs-high" /> + <property name="coalesce-rx-usecs-low" /> + <property name="coalesce-sample-interval" /> + <property name="coalesce-stats-block-usecs" /> + <property name="coalesce-tx-frames" /> + <property name="coalesce-tx-frames-irq" /> + <property name="coalesce-tx-frames-high" /> + <property name="coalesce-tx-frames-low" /> + <property name="coalesce-tx-usecs" /> + <property name="coalesce-tx-usecs-irq" /> + <property name="coalesce-tx-usecs-high" /> + <property name="coalesce-tx-usecs-low" /> + <property name="pause-autoneg" + description="Whether to automatically negotiate on pause frame of flow control mechanism defined by IEEE 802.3x standard." /> + <property name="pause-rx" + description="Whether RX pause should be enabled. Only valid when automatic negotiation is disabled" /> + <property name="pause-tx" + description="Whether TX pause should be enabled. Only valid when automatic negotiation is disabled" /> + <property name="ring-rx" /> + <property name="ring-rx-jumbo" /> + <property name="ring-rx-mini" /> + <property name="ring-tx" /> + </setting> + <setting name="generic" > + </setting> + <setting name="gsm" > + <property name="auto-config" + description="When TRUE, the settings such as APN, username, or password will default to values that match the network the modem will register to in the Mobile Broadband Provider database." /> + <property name="number" + description="Legacy setting that used to help establishing PPP data sessions for GSM-based modems. Deprecated: 1" /> + <property name="username" + alias="user" + description="The username used to authenticate with the network, if required. Many providers do not require a username, or accept any username. But if a username is required, it is specified here." /> + <property name="password" + alias="password" + description="The password used to authenticate with the network, if required. Many providers do not require a password, or accept any password. But if a password is required, it is specified here." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + <property name="apn" + alias="apn" + description="The GPRS Access Point Name specifying the APN used when establishing a data session with the GSM-based network. The APN often determines how the user will be billed for their network usage and whether the user has access to the Internet or just a provider-specific walled-garden, so it is important to use the correct APN for the user's mobile broadband plan. The APN may only be composed of the characters a-z, 0-9, ., and - per GSM 03.60 Section 14.9." /> + <property name="network-id" + description="The Network ID (GSM LAI format, ie MCC-MNC) to force specific network registration. If the Network ID is specified, NetworkManager will attempt to force the device to register only on the specified network. This can be used to ensure that the device does not roam when direct roaming control of the device is not otherwise possible." /> + <property name="pin" + description="If the SIM is locked with a PIN it must be unlocked before any other operations are requested. Specify the PIN here to allow operation of the device." /> + <property name="pin-flags" + description="Flags indicating how to handle the "pin" property." /> + <property name="home-only" + description="When TRUE, only connections to the home network will be allowed. Connections to roaming networks will not be made." /> + <property name="device-id" + description="The device unique identifier (as given by the WWAN management service) which this connection applies to. If given, the connection will only apply to the specified device." /> + <property name="sim-id" + description="The SIM card unique identifier (as given by the WWAN management service) which this connection applies to. If given, the connection will apply to any device also allowed by "device-id" which contains a SIM card matching the given identifier." /> + <property name="sim-operator-id" + description="A MCC/MNC string like "310260" or "21601" identifying the specific mobile network operator which this connection applies to. If given, the connection will apply to any device also allowed by "device-id" and "sim-id" which contains a SIM card provisioned by the given operator." /> + <property name="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple frames." /> + </setting> + <setting name="hostname" > + <property name="priority" + description="The relative priority of this connection to determine the system hostname. A lower numerical value is better (higher priority). A connection with higher priority is considered before connections with lower priority. If the value is zero, it can be overridden by a global value from NetworkManager configuration. If the property doesn't have a value in the global configuration, the value is assumed to be 100. Negative values have the special effect of excluding other connections with a greater numerical priority value; so in presence of at least one negative priority, only connections with the lowest priority value will be used to determine the hostname." /> + <property name="from-dhcp" + description="Whether the system hostname can be determined from DHCP on this connection. When set to NM_TERNARY_DEFAULT (-1), the value from global configuration is used. If the property doesn't have a value in the global configuration, NetworkManager assumes the value to be NM_TERNARY_TRUE (1)." /> + <property name="from-dns-lookup" + description="Whether the system hostname can be determined from reverse DNS lookup of addresses on this device. When set to NM_TERNARY_DEFAULT (-1), the value from global configuration is used. If the property doesn't have a value in the global configuration, NetworkManager assumes the value to be NM_TERNARY_TRUE (1)." /> + <property name="only-from-default" + description="If set to NM_TERNARY_TRUE (1), NetworkManager attempts to get the hostname via DHCPv4/DHCPv6 or reverse DNS lookup on this device only when the device has the default route for the given address family (IPv4/IPv6). If set to NM_TERNARY_FALSE (0), the hostname can be set from this device even if it doesn't have the default route. When set to NM_TERNARY_DEFAULT (-1), the value from global configuration is used. If the property doesn't have a value in the global configuration, NetworkManager assumes the value to be NM_TERNARY_FALSE (0)." /> + </setting> + <setting name="infiniband" > + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the IPoIB device whose permanent MAC address matches. This property does not change the MAC address of the device (i.e. MAC spoofing)." /> + <property name="mtu" + alias="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple frames." /> + <property name="transport-mode" + alias="transport-mode" + description="The IP-over-InfiniBand transport mode. Either "datagram" or "connected"." /> + <property name="p-key" + alias="p-key" + description="The InfiniBand P_Key to use for this device. A value of -1 means to use the default P_Key (aka "the P_Key at index 0"). Otherwise, it is a 16-bit unsigned integer, whose high bit is set if it is a "full membership" P_Key." /> + <property name="parent" + alias="parent" + description="The interface name of the parent device of this device. Normally NULL, but if the "p_key" property is set, then you must specify the base device by setting either this property or "mac-address"." /> + </setting> + <setting name="ip-tunnel" > + <property name="mode" + alias="mode" + description="The tunneling mode, for example NM_IP_TUNNEL_MODE_IPIP (1) or NM_IP_TUNNEL_MODE_GRE (2)." /> + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID the new device will be bound to so that tunneled packets will only be routed via that interface." /> + <property name="local" + alias="local" + description="The local endpoint of the tunnel; the value can be empty, otherwise it must contain an IPv4 or IPv6 address." /> + <property name="remote" + alias="remote" + description="The remote endpoint of the tunnel; the value must contain an IPv4 or IPv6 address." /> + <property name="ttl" + description="The TTL to assign to tunneled packets. 0 is a special value meaning that packets inherit the TTL value." /> + <property name="tos" + description="The type of service (IPv4) or traffic class (IPv6) field to be set on tunneled packets." /> + <property name="path-mtu-discovery" + description="Whether to enable Path MTU Discovery on this tunnel." /> + <property name="input-key" + description="The key used for tunnel input packets; the property is valid only for certain tunnel modes (GRE, IP6GRE). If empty, no key is used." /> + <property name="output-key" + description="The key used for tunnel output packets; the property is valid only for certain tunnel modes (GRE, IP6GRE). If empty, no key is used." /> + <property name="encapsulation-limit" + description="How many additional levels of encapsulation are permitted to be prepended to packets. This property applies only to IPv6 tunnels." /> + <property name="flow-label" + description="The flow label to assign to tunnel packets. This property applies only to IPv6 tunnels." /> + <property name="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple fragments." /> + <property name="flags" + description="Tunnel flags. Currently, the following values are supported: NM_IP_TUNNEL_FLAG_IP6_IGN_ENCAP_LIMIT (0x1), NM_IP_TUNNEL_FLAG_IP6_USE_ORIG_TCLASS (0x2), NM_IP_TUNNEL_FLAG_IP6_USE_ORIG_FLOWLABEL (0x4), NM_IP_TUNNEL_FLAG_IP6_MIP6_DEV (0x8), NM_IP_TUNNEL_FLAG_IP6_RCV_DSCP_COPY (0x10), NM_IP_TUNNEL_FLAG_IP6_USE_ORIG_FWMARK (0x20). They are valid only for IPv6 tunnels." /> + </setting> + <setting name="ipv4" > + <property name="method" + description="IP configuration method. NMSettingIP4Config and NMSettingIP6Config both support "disabled", "auto", "manual", and "link-local". See the subclass-specific documentation for other values. In general, for the "auto" method, properties such as "dns" and "routes" specify information that is added on to the information returned from automatic configuration. The "ignore-auto-routes" and "ignore-auto-dns" properties modify this behavior. For methods that imply no upstream network, such as "shared" or "link-local", these properties must be empty. For IPv4 method "shared", the IP subnet can be configured by adding one manual IPv4 address or otherwise 10.42.x.0/24 is chosen. Note that the shared method must be configured on the interface which shares the internet to a subnet, not on the uplink which is shared." /> + <property name="dns" + description="Array of IP addresses of DNS servers." /> + <property name="dns-search" + description="Array of DNS search domains. Domains starting with a tilde ('~') are considered 'routing' domains and are used only to decide the interface over which a query must be forwarded; they are not used to complete unqualified host names. When using a DNS plugin that supports Conditional Forwarding or Split DNS, then the search domains specify which name servers to query. This makes the behavior different from running with plain /etc/resolv.conf. For more information see also the dns-priority setting." /> + <property name="dns-options" + description="Array of DNS options as described in man 5 resolv.conf. NULL means that the options are unset and left at the default. In this case NetworkManager will use default options. This is distinct from an empty list of properties. The currently supported options are "attempts", "debug", "edns0", "inet6", "ip6-bytestring", "ip6-dotint", "ndots", "no-check-names", "no-ip6-dotint", "no-reload", "no-tld-query", "rotate", "single-request", "single-request-reopen", "timeout", "trust-ad", "use-vc". The "trust-ad" setting is only honored if the profile contributes name servers to resolv.conf, and if all contributing profiles have "trust-ad" enabled. When using a caching DNS plugin (dnsmasq or systemd-resolved in NetworkManager.conf) then "edns0" and "trust-ad" are automatically added." /> + <property name="dns-priority" + description="DNS servers priority. The relative priority for DNS servers specified by this setting. A lower numerical value is better (higher priority). Negative values have the special effect of excluding other configurations with a greater numerical priority value; so in presence of at least one negative priority, only DNS servers from connections with the lowest priority value will be used. To avoid all DNS leaks, set the priority of the profile that should be used to the most negative value of all active connections profiles. Zero selects a globally configured default value. If the latter is missing or zero too, it defaults to 50 for VPNs (including WireGuard) and 100 for other connections. Note that the priority is to order DNS settings for multiple active connections. It does not disambiguate multiple DNS servers within the same connection profile. When multiple devices have configurations with the same priority, VPNs will be considered first, then devices with the best (lowest metric) default route and then all other devices. When using dns=default, servers with higher priority will be on top of resolv.conf. To prioritize a given server over another one within the same connection, just specify them in the desired order. Note that commonly the resolver tries name servers in /etc/resolv.conf in the order listed, proceeding with the next server in the list on failure. See for example the "rotate" option of the dns-options setting. If there are any negative DNS priorities, then only name servers from the devices with that lowest priority will be considered. When using a DNS resolver that supports Conditional Forwarding or Split DNS (with dns=dnsmasq or dns=systemd-resolved settings), each connection is used to query domains in its search list. The search domains determine which name servers to ask, and the DNS priority is used to prioritize name servers based on the domain. Queries for domains not present in any search list are routed through connections having the '~.' special wildcard domain, which is added automatically to connections with the default route (or can be added manually). When multiple connections specify the same domain, the one with the best priority (lowest numerical value) wins. If a sub domain is configured on another interface it will be accepted regardless the priority, unless parent domain on the other interface has a negative priority, which causes the sub domain to be shadowed. With Split DNS one can avoid undesired DNS leaks by properly configuring DNS priorities and the search domains, so that only name servers of the desired interface are configured." /> + <property name="addresses" + alias="ip4" + description="A list of IPv4 addresses and their prefix length. Multiple addresses can be separated by comma. For example "192.168.1.5/24, 10.1.0.5/24". The addresses are listed in decreasing priority, meaning the first address will be the primary address." /> + <property name="gateway" + alias="gw4" + description="The gateway associated with this configuration. This is only meaningful if "addresses" is also set. The gateway's main purpose is to control the next hop of the standard default route on the device. Hence, the gateway property conflicts with "never-default" and will be automatically dropped if the IP configuration is set to never-default. As an alternative to set the gateway, configure a static default route with /0 as prefix length." /> + <property name="routes" + description="A list of IPv4 destination addresses, prefix length, optional IPv4 next hop addresses, optional route metric, optional attribute. The valid syntax is: "ip[/prefix] [next-hop] [metric] [attribute=val]...[,ip[/prefix]...]". For example "192.0.2.0/24 10.1.1.1 77, 198.51.100.0/24"." /> + <property name="route-metric" + description="The default metric for routes that don't explicitly specify a metric. The default value -1 means that the metric is chosen automatically based on the device type. The metric applies to dynamic routes, manual (static) routes that don't have an explicit metric setting, address prefix routes, and the default route. Note that for IPv6, the kernel accepts zero (0) but coerces it to 1024 (user default). Hence, setting this property to zero effectively mean setting it to 1024. For IPv4, zero is a regular value for the metric." /> + <property name="route-table" + description="Enable policy routing (source routing) and set the routing table used when adding routes. This affects all routes, including device-routes, IPv4LL, DHCP, SLAAC, default-routes and static routes. But note that static routes can individually overwrite the setting by explicitly specifying a non-zero routing table. If the table setting is left at zero, it is eligible to be overwritten via global configuration. If the property is zero even after applying the global configuration value, policy routing is disabled for the address family of this connection. Policy routing disabled means that NetworkManager will add all routes to the main table (except static routes that explicitly configure a different table). Additionally, NetworkManager will not delete any extraneous routes from tables except the main table. This is to preserve backward compatibility for users who manage routing tables outside of NetworkManager." /> + <property name="routing-rules" /> + <property name="ignore-auto-routes" + description="When "method" is set to "auto" and this property to TRUE, automatically configured routes are ignored and only routes specified in the "routes" property, if any, are used." /> + <property name="ignore-auto-dns" + description="When "method" is set to "auto" and this property to TRUE, automatically configured name servers and search domains are ignored and only name servers and search domains specified in the "dns" and "dns-search" properties, if any, are used." /> + <property name="dhcp-client-id" + description="A string sent to the DHCP server to identify the local machine which the DHCP server may use to customize the DHCP lease and options. When the property is a hex string ('aa:bb:cc') it is interpreted as a binary client ID, in which case the first byte is assumed to be the 'type' field as per RFC 2132 section 9.14 and the remaining bytes may be an hardware address (e.g. '01:xx:xx:xx:xx:xx:xx' where 1 is the Ethernet ARP type and the rest is a MAC address). If the property is not a hex string it is considered as a non-hardware-address client ID and the 'type' field is set to 0. The special values "mac" and "perm-mac" are supported, which use the current or permanent MAC address of the device to generate a client identifier with type ethernet (01). Currently, these options only work for ethernet type of links. The special value "ipv6-duid" uses the DUID from "ipv6.dhcp-duid" property as an RFC4361-compliant client identifier. As IAID it uses "ipv4.dhcp-iaid" and falls back to "ipv6.dhcp-iaid" if unset. The special value "duid" generates a RFC4361-compliant client identifier based on "ipv4.dhcp-iaid" and uses a DUID generated by hashing /etc/machine-id. The special value "stable" is supported to generate a type 0 client identifier based on the stable-id (see connection.stable-id) and a per-host key. If you set the stable-id, you may want to include the "${DEVICE}" or "${MAC}" specifier to get a per-device key. If unset, a globally configured default is used. If still unset, the default depends on the DHCP plugin." /> + <property name="dhcp-iaid" + description="A string containing the "Identity Association Identifier" (IAID) used by the DHCP client. The property is a 32-bit decimal value or a special value among "mac", "perm-mac", "ifname" and "stable". When set to "mac" (or "perm-mac"), the last 4 bytes of the current (or permanent) MAC address are used as IAID. When set to "ifname", the IAID is computed by hashing the interface name. The special value "stable" can be used to generate an IAID based on the stable-id (see connection.stable-id), a per-host key and the interface name. When the property is unset, the value from global configuration is used; if no global default is set then the IAID is assumed to be "ifname". Note that at the moment this property is ignored for IPv6 by dhclient, which always derives the IAID from the MAC address." /> + <property name="dhcp-timeout" + description="A timeout for a DHCP transaction in seconds. If zero (the default), a globally configured default is used. If still unspecified, a device specific timeout is used (usually 45 seconds). Set to 2147483647 (MAXINT32) for infinity." /> + <property name="dhcp-send-hostname" + description="If TRUE, a hostname is sent to the DHCP server when acquiring a lease. Some DHCP servers use this hostname to update DNS databases, essentially providing a static hostname for the computer. If the "dhcp-hostname" property is NULL and this property is TRUE, the current persistent hostname of the computer is sent." /> + <property name="dhcp-hostname" + description="If the "dhcp-send-hostname" property is TRUE, then the specified name will be sent to the DHCP server when acquiring a lease. This property and "dhcp-fqdn" are mutually exclusive and cannot be set at the same time." /> + <property name="dhcp-fqdn" + description="If the "dhcp-send-hostname" property is TRUE, then the specified FQDN will be sent to the DHCP server when acquiring a lease. This property and "dhcp-hostname" are mutually exclusive and cannot be set at the same time." /> + <property name="dhcp-hostname-flags" + description="Flags for the DHCP hostname and FQDN. Currently, this property only includes flags to control the FQDN flags set in the DHCP FQDN option. Supported FQDN flags are NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1), NM_DHCP_HOSTNAME_FLAG_FQDN_ENCODED (0x2) and NM_DHCP_HOSTNAME_FLAG_FQDN_NO_UPDATE (0x4). When no FQDN flag is set and NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS (0x8) is set, the DHCP FQDN option will contain no flag. Otherwise, if no FQDN flag is set and NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS (0x8) is not set, the standard FQDN flags are set in the request: NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1), NM_DHCP_HOSTNAME_FLAG_FQDN_ENCODED (0x2) for IPv4 and NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1) for IPv6. When this property is set to the default value NM_DHCP_HOSTNAME_FLAG_NONE (0x0), a global default is looked up in NetworkManager configuration. If that value is unset or also NM_DHCP_HOSTNAME_FLAG_NONE (0x0), then the standard FQDN flags described above are sent in the DHCP requests." /> + <property name="never-default" + description="If TRUE, this connection will never be the default connection for this IP type, meaning it will never be assigned the default route by NetworkManager." /> + <property name="may-fail" + description="If TRUE, allow overall network configuration to proceed even if the configuration specified by this property times out. Note that at least one IP configuration must succeed or overall network configuration will still fail. For example, in IPv6-only networks, setting this property to TRUE on the NMSettingIP4Config allows the overall network configuration to succeed if IPv4 configuration fails but IPv6 configuration completes successfully." /> + <property name="required-timeout" + description="The minimum time interval in milliseconds for which dynamic IP configuration should be tried before the connection succeeds. This property is useful for example if both IPv4 and IPv6 are enabled and are allowed to fail. Normally the connection succeeds as soon as one of the two address families completes; by setting a required timeout for e.g. IPv4, one can ensure that even if IP6 succeeds earlier than IPv4, NetworkManager waits some time for IPv4 before the connection becomes active. Note that if "may-fail" is FALSE for the same address family, this property has no effect as NetworkManager needs to wait for the full DHCP timeout. A zero value means that no required timeout is present, -1 means the default value (either configuration ipvx.required-timeout override or zero)." /> + <property name="dad-timeout" + description="Timeout in milliseconds used to check for the presence of duplicate IP addresses on the network. If an address conflict is detected, the activation will fail. A zero value means that no duplicate address detection is performed, -1 means the default value (either configuration ipvx.dad-timeout override or zero). A value greater than zero is a timeout in milliseconds. The property is currently implemented only for IPv4." /> + <property name="dhcp-vendor-class-identifier" + description="The Vendor Class Identifier DHCP option (60). Special characters in the data string may be escaped using C-style escapes, nevertheless this property cannot contain nul bytes. If the per-profile value is unspecified (the default), a global connection default gets consulted. If still unspecified, the DHCP option is not sent to the server. Since 1.28" /> + <property name="dhcp-reject-servers" + description="Array of servers from which DHCP offers must be rejected. This property is useful to avoid getting a lease from misconfigured or rogue servers. For DHCPv4, each element must be an IPv4 address, optionally followed by a slash and a prefix length (e.g. "192.168.122.0/24"). This property is currently not implemented for DHCPv6." /> + </setting> + <setting name="ipv6" > + <property name="method" + description="IP configuration method. NMSettingIP4Config and NMSettingIP6Config both support "disabled", "auto", "manual", and "link-local". See the subclass-specific documentation for other values. In general, for the "auto" method, properties such as "dns" and "routes" specify information that is added on to the information returned from automatic configuration. The "ignore-auto-routes" and "ignore-auto-dns" properties modify this behavior. For methods that imply no upstream network, such as "shared" or "link-local", these properties must be empty. For IPv4 method "shared", the IP subnet can be configured by adding one manual IPv4 address or otherwise 10.42.x.0/24 is chosen. Note that the shared method must be configured on the interface which shares the internet to a subnet, not on the uplink which is shared." /> + <property name="dns" + description="Array of IP addresses of DNS servers." /> + <property name="dns-search" + description="Array of DNS search domains. Domains starting with a tilde ('~') are considered 'routing' domains and are used only to decide the interface over which a query must be forwarded; they are not used to complete unqualified host names. When using a DNS plugin that supports Conditional Forwarding or Split DNS, then the search domains specify which name servers to query. This makes the behavior different from running with plain /etc/resolv.conf. For more information see also the dns-priority setting." /> + <property name="dns-options" + description="Array of DNS options as described in man 5 resolv.conf. NULL means that the options are unset and left at the default. In this case NetworkManager will use default options. This is distinct from an empty list of properties. The currently supported options are "attempts", "debug", "edns0", "inet6", "ip6-bytestring", "ip6-dotint", "ndots", "no-check-names", "no-ip6-dotint", "no-reload", "no-tld-query", "rotate", "single-request", "single-request-reopen", "timeout", "trust-ad", "use-vc". The "trust-ad" setting is only honored if the profile contributes name servers to resolv.conf, and if all contributing profiles have "trust-ad" enabled. When using a caching DNS plugin (dnsmasq or systemd-resolved in NetworkManager.conf) then "edns0" and "trust-ad" are automatically added." /> + <property name="dns-priority" + description="DNS servers priority. The relative priority for DNS servers specified by this setting. A lower numerical value is better (higher priority). Negative values have the special effect of excluding other configurations with a greater numerical priority value; so in presence of at least one negative priority, only DNS servers from connections with the lowest priority value will be used. To avoid all DNS leaks, set the priority of the profile that should be used to the most negative value of all active connections profiles. Zero selects a globally configured default value. If the latter is missing or zero too, it defaults to 50 for VPNs (including WireGuard) and 100 for other connections. Note that the priority is to order DNS settings for multiple active connections. It does not disambiguate multiple DNS servers within the same connection profile. When multiple devices have configurations with the same priority, VPNs will be considered first, then devices with the best (lowest metric) default route and then all other devices. When using dns=default, servers with higher priority will be on top of resolv.conf. To prioritize a given server over another one within the same connection, just specify them in the desired order. Note that commonly the resolver tries name servers in /etc/resolv.conf in the order listed, proceeding with the next server in the list on failure. See for example the "rotate" option of the dns-options setting. If there are any negative DNS priorities, then only name servers from the devices with that lowest priority will be considered. When using a DNS resolver that supports Conditional Forwarding or Split DNS (with dns=dnsmasq or dns=systemd-resolved settings), each connection is used to query domains in its search list. The search domains determine which name servers to ask, and the DNS priority is used to prioritize name servers based on the domain. Queries for domains not present in any search list are routed through connections having the '~.' special wildcard domain, which is added automatically to connections with the default route (or can be added manually). When multiple connections specify the same domain, the one with the best priority (lowest numerical value) wins. If a sub domain is configured on another interface it will be accepted regardless the priority, unless parent domain on the other interface has a negative priority, which causes the sub domain to be shadowed. With Split DNS one can avoid undesired DNS leaks by properly configuring DNS priorities and the search domains, so that only name servers of the desired interface are configured." /> + <property name="addresses" + alias="ip6" + description="A list of IPv6 addresses and their prefix length. Multiple addresses can be separated by comma. For example "2001:db8:85a3::8a2e:370:7334/64, 2001:db8:85a3::5/64". The addresses are listed in increasing priority, meaning the last address will be the primary address." /> + <property name="gateway" + alias="gw6" + description="The gateway associated with this configuration. This is only meaningful if "addresses" is also set. The gateway's main purpose is to control the next hop of the standard default route on the device. Hence, the gateway property conflicts with "never-default" and will be automatically dropped if the IP configuration is set to never-default. As an alternative to set the gateway, configure a static default route with /0 as prefix length." /> + <property name="routes" + description="Array of IP routes." /> + <property name="route-metric" + description="The default metric for routes that don't explicitly specify a metric. The default value -1 means that the metric is chosen automatically based on the device type. The metric applies to dynamic routes, manual (static) routes that don't have an explicit metric setting, address prefix routes, and the default route. Note that for IPv6, the kernel accepts zero (0) but coerces it to 1024 (user default). Hence, setting this property to zero effectively mean setting it to 1024. For IPv4, zero is a regular value for the metric." /> + <property name="route-table" + description="Enable policy routing (source routing) and set the routing table used when adding routes. This affects all routes, including device-routes, IPv4LL, DHCP, SLAAC, default-routes and static routes. But note that static routes can individually overwrite the setting by explicitly specifying a non-zero routing table. If the table setting is left at zero, it is eligible to be overwritten via global configuration. If the property is zero even after applying the global configuration value, policy routing is disabled for the address family of this connection. Policy routing disabled means that NetworkManager will add all routes to the main table (except static routes that explicitly configure a different table). Additionally, NetworkManager will not delete any extraneous routes from tables except the main table. This is to preserve backward compatibility for users who manage routing tables outside of NetworkManager." /> + <property name="routing-rules" /> + <property name="ignore-auto-routes" + description="When "method" is set to "auto" and this property to TRUE, automatically configured routes are ignored and only routes specified in the "routes" property, if any, are used." /> + <property name="ignore-auto-dns" + description="When "method" is set to "auto" and this property to TRUE, automatically configured name servers and search domains are ignored and only name servers and search domains specified in the "dns" and "dns-search" properties, if any, are used." /> + <property name="never-default" + description="If TRUE, this connection will never be the default connection for this IP type, meaning it will never be assigned the default route by NetworkManager." /> + <property name="may-fail" + description="If TRUE, allow overall network configuration to proceed even if the configuration specified by this property times out. Note that at least one IP configuration must succeed or overall network configuration will still fail. For example, in IPv6-only networks, setting this property to TRUE on the NMSettingIP4Config allows the overall network configuration to succeed if IPv4 configuration fails but IPv6 configuration completes successfully." /> + <property name="required-timeout" + description="The minimum time interval in milliseconds for which dynamic IP configuration should be tried before the connection succeeds. This property is useful for example if both IPv4 and IPv6 are enabled and are allowed to fail. Normally the connection succeeds as soon as one of the two address families completes; by setting a required timeout for e.g. IPv4, one can ensure that even if IP6 succeeds earlier than IPv4, NetworkManager waits some time for IPv4 before the connection becomes active. Note that if "may-fail" is FALSE for the same address family, this property has no effect as NetworkManager needs to wait for the full DHCP timeout. A zero value means that no required timeout is present, -1 means the default value (either configuration ipvx.required-timeout override or zero)." /> + <property name="ip6-privacy" + description="Configure IPv6 Privacy Extensions for SLAAC, described in RFC4941. If enabled, it makes the kernel generate a temporary IPv6 address in addition to the public one generated from MAC address via modified EUI-64. This enhances privacy, but could cause problems in some applications, on the other hand. The permitted values are: -1: unknown, 0: disabled, 1: enabled (prefer public address), 2: enabled (prefer temporary addresses). Having a per-connection setting set to "-1" (unknown) means fallback to global configuration "ipv6.ip6-privacy". If also global configuration is unspecified or set to "-1", fallback to read "/proc/sys/net/ipv6/conf/default/use_tempaddr". Note that this setting is distinct from the Stable Privacy addresses that can be enabled with the "addr-gen-mode" property's "stable-privacy" setting as another way of avoiding host tracking with IPv6 addresses." /> + <property name="addr-gen-mode" + description="Configure method for creating the address for use with RFC4862 IPv6 Stateless Address Autoconfiguration. The permitted values are: NM_SETTING_IP6_CONFIG_ADDR_GEN_MODE_EUI64 (0) or NM_SETTING_IP6_CONFIG_ADDR_GEN_MODE_STABLE_PRIVACY (1). If the property is set to EUI64, the addresses will be generated using the interface tokens derived from hardware address. This makes the host part of the address to stay constant, making it possible to track host's presence when it changes networks. The address changes when the interface hardware is replaced. The value of stable-privacy enables use of cryptographically secure hash of a secret host-specific key along with the connection's stable-id and the network address as specified by RFC7217. This makes it impossible to use the address track host's presence, and makes the address stable when the network interface hardware is replaced. On D-Bus, the absence of an addr-gen-mode setting equals enabling stable-privacy. For keyfile plugin, the absence of the setting on disk means EUI64 so that the property doesn't change on upgrade from older versions. Note that this setting is distinct from the Privacy Extensions as configured by "ip6-privacy" property and it does not affect the temporary addresses configured with this option." /> + <property name="ra-timeout" + description="A timeout for waiting Router Advertisements in seconds. If zero (the default), a globally configured default is used. If still unspecified, the timeout depends on the sysctl settings of the device. Set to 2147483647 (MAXINT32) for infinity." /> + <property name="dhcp-duid" + description="A string containing the DHCPv6 Unique Identifier (DUID) used by the dhcp client to identify itself to DHCPv6 servers (RFC 3315). The DUID is carried in the Client Identifier option. If the property is a hex string ('aa:bb:cc') it is interpreted as a binary DUID and filled as an opaque value in the Client Identifier option. The special value "lease" will retrieve the DUID previously used from the lease file belonging to the connection. If no DUID is found and "dhclient" is the configured dhcp client, the DUID is searched in the system-wide dhclient lease file. If still no DUID is found, or another dhcp client is used, a global and permanent DUID-UUID (RFC 6355) will be generated based on the machine-id. The special values "llt" and "ll" will generate a DUID of type LLT or LL (see RFC 3315) based on the current MAC address of the device. In order to try providing a stable DUID-LLT, the time field will contain a constant timestamp that is used globally (for all profiles) and persisted to disk. The special values "stable-llt", "stable-ll" and "stable-uuid" will generate a DUID of the corresponding type, derived from the connection's stable-id and a per-host unique key. You may want to include the "${DEVICE}" or "${MAC}" specifier in the stable-id, in case this profile gets activated on multiple devices. So, the link-layer address of "stable-ll" and "stable-llt" will be a generated address derived from the stable id. The DUID-LLT time value in the "stable-llt" option will be picked among a static timespan of three years (the upper bound of the interval is the same constant timestamp used in "llt"). When the property is unset, the global value provided for "ipv6.dhcp-duid" is used. If no global value is provided, the default "lease" value is assumed." /> + <property name="dhcp-iaid" + description="A string containing the "Identity Association Identifier" (IAID) used by the DHCP client. The property is a 32-bit decimal value or a special value among "mac", "perm-mac", "ifname" and "stable". When set to "mac" (or "perm-mac"), the last 4 bytes of the current (or permanent) MAC address are used as IAID. When set to "ifname", the IAID is computed by hashing the interface name. The special value "stable" can be used to generate an IAID based on the stable-id (see connection.stable-id), a per-host key and the interface name. When the property is unset, the value from global configuration is used; if no global default is set then the IAID is assumed to be "ifname". Note that at the moment this property is ignored for IPv6 by dhclient, which always derives the IAID from the MAC address." /> + <property name="dhcp-timeout" + description="A timeout for a DHCP transaction in seconds. If zero (the default), a globally configured default is used. If still unspecified, a device specific timeout is used (usually 45 seconds). Set to 2147483647 (MAXINT32) for infinity." /> + <property name="dhcp-send-hostname" + description="If TRUE, a hostname is sent to the DHCP server when acquiring a lease. Some DHCP servers use this hostname to update DNS databases, essentially providing a static hostname for the computer. If the "dhcp-hostname" property is NULL and this property is TRUE, the current persistent hostname of the computer is sent." /> + <property name="dhcp-hostname" + description="If the "dhcp-send-hostname" property is TRUE, then the specified name will be sent to the DHCP server when acquiring a lease. This property and "dhcp-fqdn" are mutually exclusive and cannot be set at the same time." /> + <property name="dhcp-hostname-flags" + description="Flags for the DHCP hostname and FQDN. Currently, this property only includes flags to control the FQDN flags set in the DHCP FQDN option. Supported FQDN flags are NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1), NM_DHCP_HOSTNAME_FLAG_FQDN_ENCODED (0x2) and NM_DHCP_HOSTNAME_FLAG_FQDN_NO_UPDATE (0x4). When no FQDN flag is set and NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS (0x8) is set, the DHCP FQDN option will contain no flag. Otherwise, if no FQDN flag is set and NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS (0x8) is not set, the standard FQDN flags are set in the request: NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1), NM_DHCP_HOSTNAME_FLAG_FQDN_ENCODED (0x2) for IPv4 and NM_DHCP_HOSTNAME_FLAG_FQDN_SERV_UPDATE (0x1) for IPv6. When this property is set to the default value NM_DHCP_HOSTNAME_FLAG_NONE (0x0), a global default is looked up in NetworkManager configuration. If that value is unset or also NM_DHCP_HOSTNAME_FLAG_NONE (0x0), then the standard FQDN flags described above are sent in the DHCP requests." /> + <property name="token" + description="Configure the token for draft-chown-6man-tokenised-ipv6-identifiers-02 IPv6 tokenized interface identifiers. Useful with eui64 addr-gen-mode." /> + </setting> + <setting name="macsec" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID from which this MACSEC interface should be created. If this property is not specified, the connection must contain an "802-3-ethernet" setting with a "mac-address" property." /> + <property name="mode" + alias="mode" + description="Specifies how the CAK (Connectivity Association Key) for MKA (MACsec Key Agreement) is obtained." /> + <property name="encrypt" + alias="encrypt" + description="Whether the transmitted traffic must be encrypted." /> + <property name="mka-cak" + alias="cak" + description="The pre-shared CAK (Connectivity Association Key) for MACsec Key Agreement." /> + <property name="mka-cak-flags" + description="Flags indicating how to handle the "mka-cak" property." /> + <property name="mka-ckn" + alias="ckn" + description="The pre-shared CKN (Connectivity-association Key Name) for MACsec Key Agreement." /> + <property name="port" + alias="port" + description="The port component of the SCI (Secure Channel Identifier), between 1 and 65534." /> + <property name="validation" + description="Specifies the validation mode for incoming frames." /> + <property name="send-sci" + description="Specifies whether the SCI (Secure Channel Identifier) is included in every packet." /> + </setting> + <setting name="macvlan" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID from which this MAC-VLAN interface should be created. If this property is not specified, the connection must contain an "802-3-ethernet" setting with a "mac-address" property." /> + <property name="mode" + alias="mode" + description="The macvlan mode, which specifies the communication mechanism between multiple macvlans on the same lower device." /> + <property name="promiscuous" + description="Whether the interface should be put in promiscuous mode." /> + <property name="tap" + alias="tap" + description="Whether the interface should be a MACVTAP." /> + </setting> + <setting name="match" > + <property name="interface-name" + description="A list of interface names to match. Each element is a shell wildcard pattern. An element can be prefixed with a pipe symbol (|) or an ampersand (&). The former means that the element is optional and the latter means that it is mandatory. If there are any optional elements, than the match evaluates to true if at least one of the optional element matches (logical OR). If there are any mandatory elements, then they all must match (logical AND). By default, an element is optional. This means that an element "foo" behaves the same as "|foo". An element can also be inverted with exclamation mark (!) between the pipe symbol (or the ampersand) and before the pattern. Note that "!foo" is a shortcut for the mandatory match "&!foo". Finally, a backslash can be used at the beginning of the element (after the optional special characters) to escape the start of the pattern. For example, "&\!a" is an mandatory match for literally "!a"." /> + <property name="kernel-command-line" + description="A list of kernel command line arguments to match. This may be used to check whether a specific kernel command line option is set (or unset, if prefixed with the exclamation mark). The argument must either be a single word, or an assignment (i.e. two words, joined by "="). In the former case the kernel command line is searched for the word appearing as is, or as left hand side of an assignment. In the latter case, the exact assignment is looked for with right and left hand side matching. Wildcard patterns are not supported. See NMSettingMatch:interface-name for how special characters '|', '&', '!' and '\' are used for optional and mandatory matches and inverting the match." /> + <property name="driver" + description="A list of driver names to match. Each element is a shell wildcard pattern. See NMSettingMatch:interface-name for how special characters '|', '&', '!' and '\' are used for optional and mandatory matches and inverting the pattern." /> + <property name="path" + description="A list of paths to match against the ID_PATH udev property of devices. ID_PATH represents the topological persistent path of a device. It typically contains a subsystem string (pci, usb, platform, etc.) and a subsystem-specific identifier. For PCI devices the path has the form "pci-$domain:$bus:$device.$function", where each variable is an hexadecimal value; for example "pci-0000:0a:00.0". The path of a device can be obtained with "udevadm info /sys/class/net/$dev | grep ID_PATH=" or by looking at the "path" property exported by NetworkManager ("nmcli -f general.path device show $dev"). Each element of the list is a shell wildcard pattern. See NMSettingMatch:interface-name for how special characters '|', '&', '!' and '\' are used for optional and mandatory matches and inverting the pattern." /> + </setting> + <setting name="ovs-bridge" > + <property name="fail-mode" + description="The bridge failure mode. One of "secure", "standalone" or empty." /> + <property name="mcast-snooping-enable" + description="Enable or disable multicast snooping." /> + <property name="rstp-enable" + description="Enable or disable RSTP." /> + <property name="stp-enable" + description="Enable or disable STP." /> + <property name="datapath-type" + description="The data path type. One of "system", "netdev" or empty." /> + </setting> + <setting name="ovs-dpdk" > + <property name="devargs" + description="Open vSwitch DPDK device arguments." /> + </setting> + <setting name="ovs-external-ids" > + </setting> + <setting name="ovs-interface" > + <property name="type" + description="The interface type. Either "internal", "system", "patch", "dpdk", or empty." /> + </setting> + <setting name="ovs-patch" > + <property name="peer" + description="Specifies the name of the interface for the other side of the patch. The patch on the other side must also set this interface as peer." /> + </setting> + <setting name="ovs-port" > + <property name="vlan-mode" + description="The VLAN mode. One of "access", "native-tagged", "native-untagged", "trunk" or unset." /> + <property name="tag" + description="The VLAN tag in the range 0-4095." /> + <property name="lacp" + description="LACP mode. One of "active", "off", or "passive"." /> + <property name="bond-mode" + description="Bonding mode. One of "active-backup", "balance-slb", or "balance-tcp"." /> + <property name="bond-updelay" + description="The time port must be active before it starts forwarding traffic." /> + <property name="bond-downdelay" + description="The time port must be inactive in order to be considered down." /> + </setting> + <setting name="ppp" > + <property name="noauth" + description="If TRUE, do not require the other side (usually the PPP server) to authenticate itself to the client. If FALSE, require authentication from the remote side. In almost all cases, this should be TRUE." /> + <property name="refuse-eap" + description="If TRUE, the EAP authentication method will not be used." /> + <property name="refuse-pap" + description="If TRUE, the PAP authentication method will not be used." /> + <property name="refuse-chap" + description="If TRUE, the CHAP authentication method will not be used." /> + <property name="refuse-mschap" + description="If TRUE, the MSCHAP authentication method will not be used." /> + <property name="refuse-mschapv2" + description="If TRUE, the MSCHAPv2 authentication method will not be used." /> + <property name="nobsdcomp" + description="If TRUE, BSD compression will not be requested." /> + <property name="nodeflate" + description="If TRUE, "deflate" compression will not be requested." /> + <property name="no-vj-comp" + description="If TRUE, Van Jacobsen TCP header compression will not be requested." /> + <property name="require-mppe" + description="If TRUE, MPPE (Microsoft Point-to-Point Encryption) will be required for the PPP session. If either 64-bit or 128-bit MPPE is not available the session will fail. Note that MPPE is not used on mobile broadband connections." /> + <property name="require-mppe-128" + description="If TRUE, 128-bit MPPE (Microsoft Point-to-Point Encryption) will be required for the PPP session, and the "require-mppe" property must also be set to TRUE. If 128-bit MPPE is not available the session will fail." /> + <property name="mppe-stateful" + description="If TRUE, stateful MPPE is used. See pppd documentation for more information on stateful MPPE." /> + <property name="crtscts" + description="If TRUE, specify that pppd should set the serial port to use hardware flow control with RTS and CTS signals. This value should normally be set to FALSE." /> + <property name="baud" + description="If non-zero, instruct pppd to set the serial port to the specified baudrate. This value should normally be left as 0 to automatically choose the speed." /> + <property name="mru" + description="If non-zero, instruct pppd to request that the peer send packets no larger than the specified size. If non-zero, the MRU should be between 128 and 16384." /> + <property name="mtu" + description="If non-zero, instruct pppd to send packets no larger than the specified size." /> + <property name="lcp-echo-failure" + description="If non-zero, instruct pppd to presume the connection to the peer has failed if the specified number of LCP echo-requests go unanswered by the peer. The "lcp-echo-interval" property must also be set to a non-zero value if this property is used." /> + <property name="lcp-echo-interval" + description="If non-zero, instruct pppd to send an LCP echo-request frame to the peer every n seconds (where n is the specified value). Note that some PPP peers will respond to echo requests and some will not, and it is not possible to autodetect this." /> + </setting> + <setting name="pppoe" > + <property name="parent" + alias="parent" + description="If given, specifies the parent interface name on which this PPPoE connection should be created. If this property is not specified, the connection is activated on the interface specified in "interface-name" of NMSettingConnection." /> + <property name="service" + alias="service" + description="If specified, instruct PPPoE to only initiate sessions with access concentrators that provide the specified service. For most providers, this should be left blank. It is only required if there are multiple access concentrators or a specific service is known to be required." /> + <property name="username" + alias="username" + description="Username used to authenticate with the PPPoE service." /> + <property name="password" + alias="password" + description="Password used to authenticate with the PPPoE service." /> + <property name="password-flags" + description="Flags indicating how to handle the "password" property." /> + </setting> + <setting name="proxy" > + <property name="method" + alias="method" + description="Method for proxy configuration, Default is NM_SETTING_PROXY_METHOD_NONE (0)" /> + <property name="browser-only" + alias="browser-only" + description="Whether the proxy configuration is for browser only." /> + <property name="pac-url" + alias="pac-url" + description="PAC URL for obtaining PAC file." /> + <property name="pac-script" + alias="pac-script" + description="PAC script for the connection." /> + </setting> + <setting name="serial" > + <property name="baud" + description="Speed to use for communication over the serial port. Note that this value usually has no effect for mobile broadband modems as they generally ignore speed settings and use the highest available speed." /> + <property name="bits" + description="Byte-width of the serial communication. The 8 in "8n1" for example." /> + <property name="parity" + description="Parity setting of the serial port." /> + <property name="stopbits" + description="Number of stop bits for communication on the serial port. Either 1 or 2. The 1 in "8n1" for example." /> + <property name="send-delay" + description="Time to delay between each byte sent to the modem, in microseconds." /> + </setting> + <setting name="sriov" > + <property name="total-vfs" + description="The total number of virtual functions to create. Note that when the sriov setting is present NetworkManager enforces the number of virtual functions on the interface (also when it is zero) during activation and resets it upon deactivation. To prevent any changes to SR-IOV parameters don't add a sriov setting to the connection." /> + <property name="vfs" + description="Array of virtual function descriptors. Each VF descriptor is a dictionary mapping attribute names to GVariant values. The 'index' entry is mandatory for each VF. When represented as string a VF is in the form: "INDEX [ATTR=VALUE[ ATTR=VALUE]...]". for example: "2 mac=00:11:22:33:44:55 spoof-check=true". Multiple VFs can be specified using a comma as separator. Currently, the following attributes are supported: mac, spoof-check, trust, min-tx-rate, max-tx-rate, vlans. The "vlans" attribute is represented as a semicolon-separated list of VLAN descriptors, where each descriptor has the form "ID[.PRIORITY[.PROTO]]". PROTO can be either 'q' for 802.1Q (the default) or 'ad' for 802.1ad." /> + <property name="autoprobe-drivers" + description="Whether to autoprobe virtual functions by a compatible driver. If set to NM_TERNARY_TRUE (1), the kernel will try to bind VFs to a compatible driver and if this succeeds a new network interface will be instantiated for each VF. If set to NM_TERNARY_FALSE (0), VFs will not be claimed and no network interfaces will be created for them. When set to NM_TERNARY_DEFAULT (-1), the global default is used; in case the global default is unspecified it is assumed to be NM_TERNARY_TRUE (1)." /> + </setting> + <setting name="tc" > + <property name="qdiscs" + description="Array of TC queueing disciplines. When the "tc" setting is present, qdiscs from this property are applied upon activation. If the property is empty, all qdiscs are removed and the device will only have the default qdisc assigned by kernel according to the "net.core.default_qdisc" sysctl. If the "tc" setting is not present, NetworkManager doesn't touch the qdiscs present on the interface." /> + <property name="tfilters" + description="Array of TC traffic filters. When the "tc" setting is present, filters from this property are applied upon activation. If the property is empty, NetworkManager removes all the filters. If the "tc" setting is not present, NetworkManager doesn't touch the filters present on the interface." /> + </setting> + <setting name="team" > + <property name="config" + alias="config" + description="The JSON configuration for the team network interface. The property should contain raw JSON configuration data suitable for teamd, because the value is passed directly to teamd. If not specified, the default configuration is used. See man teamd.conf for the format details." /> + <property name="notify-peers-count" + description="Corresponds to the teamd notify_peers.count." /> + <property name="notify-peers-interval" + description="Corresponds to the teamd notify_peers.interval." /> + <property name="mcast-rejoin-count" + description="Corresponds to the teamd mcast_rejoin.count." /> + <property name="mcast-rejoin-interval" + description="Corresponds to the teamd mcast_rejoin.interval." /> + <property name="runner" + description="Corresponds to the teamd runner.name. Permitted values are: "roundrobin", "broadcast", "activebackup", "loadbalance", "lacp", "random"." /> + <property name="runner-hwaddr-policy" + description="Corresponds to the teamd runner.hwaddr_policy." /> + <property name="runner-tx-hash" + description="Corresponds to the teamd runner.tx_hash." /> + <property name="runner-tx-balancer" + description="Corresponds to the teamd runner.tx_balancer.name." /> + <property name="runner-tx-balancer-interval" + description="Corresponds to the teamd runner.tx_balancer.interval." /> + <property name="runner-active" + description="Corresponds to the teamd runner.active." /> + <property name="runner-fast-rate" + description="Corresponds to the teamd runner.fast_rate." /> + <property name="runner-sys-prio" + description="Corresponds to the teamd runner.sys_prio." /> + <property name="runner-min-ports" + description="Corresponds to the teamd runner.min_ports." /> + <property name="runner-agg-select-policy" + description="Corresponds to the teamd runner.agg_select_policy." /> + <property name="link-watchers" + description="Link watchers configuration for the connection: each link watcher is defined by a dictionary, whose keys depend upon the selected link watcher. Available link watchers are 'ethtool', 'nsna_ping' and 'arp_ping' and it is specified in the dictionary with the key 'name'. Available keys are: ethtool: 'delay-up', 'delay-down', 'init-wait'; nsna_ping: 'init-wait', 'interval', 'missed-max', 'target-host'; arp_ping: all the ones in nsna_ping and 'source-host', 'validate-active', 'validate-inactive', 'send-always'. See teamd.conf man for more details." /> + </setting> + <setting name="team-port" > + <property name="config" + alias="config" + description="The JSON configuration for the team port. The property should contain raw JSON configuration data suitable for teamd, because the value is passed directly to teamd. If not specified, the default configuration is used. See man teamd.conf for the format details." /> + <property name="queue-id" + description="Corresponds to the teamd ports.PORTIFNAME.queue_id. When set to -1 means the parameter is skipped from the json config." /> + <property name="prio" + description="Corresponds to the teamd ports.PORTIFNAME.prio." /> + <property name="sticky" + description="Corresponds to the teamd ports.PORTIFNAME.sticky." /> + <property name="lacp-prio" + description="Corresponds to the teamd ports.PORTIFNAME.lacp_prio." /> + <property name="lacp-key" + description="Corresponds to the teamd ports.PORTIFNAME.lacp_key." /> + <property name="link-watchers" + description="Link watchers configuration for the connection: each link watcher is defined by a dictionary, whose keys depend upon the selected link watcher. Available link watchers are 'ethtool', 'nsna_ping' and 'arp_ping' and it is specified in the dictionary with the key 'name'. Available keys are: ethtool: 'delay-up', 'delay-down', 'init-wait'; nsna_ping: 'init-wait', 'interval', 'missed-max', 'target-host'; arp_ping: all the ones in nsna_ping and 'source-host', 'validate-active', 'validate-inactive', 'send-always'. See teamd.conf man for more details." /> + </setting> + <setting name="tun" > + <property name="mode" + alias="mode" + description="The operating mode of the virtual device. Allowed values are NM_SETTING_TUN_MODE_TUN (1) to create a layer 3 device and NM_SETTING_TUN_MODE_TAP (2) to create an Ethernet-like layer 2 one." /> + <property name="owner" + alias="owner" + description="The user ID which will own the device. If set to NULL everyone will be able to use the device." /> + <property name="group" + alias="group" + description="The group ID which will own the device. If set to NULL everyone will be able to use the device." /> + <property name="pi" + alias="pi" + description="If TRUE the interface will prepend a 4 byte header describing the physical interface to the packets." /> + <property name="vnet-hdr" + alias="vnet-hdr" + description="If TRUE the IFF_VNET_HDR the tunnel packets will include a virtio network header." /> + <property name="multi-queue" + alias="multi-queue" + description="If the property is set to TRUE, the interface will support multiple file descriptors (queues) to parallelize packet sending or receiving. Otherwise, the interface will only support a single queue." /> + </setting> + <setting name="user" > + </setting> + <setting name="veth" > + <property name="peer" + alias="peer" + description="This property specifies the peer interface name of the veth. This property is mandatory." /> + </setting> + <setting name="vlan" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID from which this VLAN interface should be created. If this property is not specified, the connection must contain an "802-3-ethernet" setting with a "mac-address" property." /> + <property name="id" + alias="id" + description="The VLAN identifier that the interface created by this connection should be assigned. The valid range is from 0 to 4094, without the reserved id 4095." /> + <property name="flags" + alias="flags" + description="One or more flags which control the behavior and features of the VLAN interface. Flags include NM_VLAN_FLAG_REORDER_HEADERS (0x1) (reordering of output packet headers), NM_VLAN_FLAG_GVRP (0x2) (use of the GVRP protocol), and NM_VLAN_FLAG_LOOSE_BINDING (0x4) (loose binding of the interface to its master device's operating state). NM_VLAN_FLAG_MVRP (0x8) (use of the MVRP protocol). The default value of this property is NM_VLAN_FLAG_REORDER_HEADERS, but it used to be 0. To preserve backward compatibility, the default-value in the D-Bus API continues to be 0 and a missing property on D-Bus is still considered as 0." /> + <property name="ingress-priority-map" + alias="ingress" + description="For incoming packets, a list of mappings from 802.1p priorities to Linux SKB priorities. The mapping is given in the format "from:to" where both "from" and "to" are unsigned integers, ie "7:3"." /> + <property name="egress-priority-map" + alias="egress" + description="For outgoing packets, a list of mappings from Linux SKB priorities to 802.1p priorities. The mapping is given in the format "from:to" where both "from" and "to" are unsigned integers, ie "7:3"." /> + </setting> + <setting name="vpn" > + <property name="service-type" + alias="vpn-type" + description="D-Bus service name of the VPN plugin that this setting uses to connect to its network. i.e. org.freedesktop.NetworkManager.vpnc for the vpnc plugin." /> + <property name="user-name" + alias="user" + description="If the VPN connection requires a user name for authentication, that name should be provided here. If the connection is available to more than one user, and the VPN requires each user to supply a different name, then leave this property empty. If this property is empty, NetworkManager will automatically supply the username of the user which requested the VPN connection." /> + <property name="data" + description="Dictionary of key/value pairs of VPN plugin specific data. Both keys and values must be strings." /> + <property name="secrets" + description="Dictionary of key/value pairs of VPN plugin specific secrets like passwords or private keys. Both keys and values must be strings." /> + <property name="persistent" + description="If the VPN service supports persistence, and this property is TRUE, the VPN will attempt to stay connected across link changes and outages, until explicitly disconnected." /> + <property name="timeout" + description="Timeout for the VPN service to establish the connection. Some services may take quite a long time to connect. Value of 0 means a default timeout, which is 60 seconds (unless overridden by vpn.timeout in configuration file). Values greater than zero mean timeout in seconds." /> + </setting> + <setting name="vrf" > + <property name="table" + alias="table" + description="The routing table for this VRF." /> + </setting> + <setting name="vxlan" > + <property name="parent" + alias="dev" + description="If given, specifies the parent interface name or parent connection UUID." /> + <property name="id" + alias="id" + description="Specifies the VXLAN Network Identifier (or VXLAN Segment Identifier) to use." /> + <property name="local" + alias="local" + description="If given, specifies the source IP address to use in outgoing packets." /> + <property name="remote" + alias="remote" + description="Specifies the unicast destination IP address to use in outgoing packets when the destination link layer address is not known in the VXLAN device forwarding database, or the multicast IP address to join." /> + <property name="source-port-min" + alias="source-port-min" + description="Specifies the minimum UDP source port to communicate to the remote VXLAN tunnel endpoint." /> + <property name="source-port-max" + alias="source-port-max" + description="Specifies the maximum UDP source port to communicate to the remote VXLAN tunnel endpoint." /> + <property name="destination-port" + alias="destination-port" + description="Specifies the UDP destination port to communicate to the remote VXLAN tunnel endpoint." /> + <property name="tos" + description="Specifies the TOS value to use in outgoing packets." /> + <property name="ttl" + description="Specifies the time-to-live value to use in outgoing packets." /> + <property name="ageing" + description="Specifies the lifetime in seconds of FDB entries learnt by the kernel." /> + <property name="limit" + description="Specifies the maximum number of FDB entries. A value of zero means that the kernel will store unlimited entries." /> + <property name="learning" + description="Specifies whether unknown source link layer addresses and IP addresses are entered into the VXLAN device forwarding database." /> + <property name="proxy" + description="Specifies whether ARP proxy is turned on." /> + <property name="rsc" + description="Specifies whether route short circuit is turned on." /> + <property name="l2-miss" + description="Specifies whether netlink LL ADDR miss notifications are generated." /> + <property name="l3-miss" + description="Specifies whether netlink IP ADDR miss notifications are generated." /> + </setting> + <setting name="wifi-p2p" > + <property name="peer" + alias="peer" + description="The P2P device that should be connected to. Currently, this is the only way to create or join a group." /> + <property name="wps-method" + description="Flags indicating which mode of WPS is to be used. There's little point in changing the default setting as NetworkManager will automatically determine the best method to use." /> + <property name="wfd-ies" + description="The Wi-Fi Display (WFD) Information Elements (IEs) to set. Wi-Fi Display requires a protocol specific information element to be set in certain Wi-Fi frames. These can be specified here for the purpose of establishing a connection. This setting is only useful when implementing a Wi-Fi Display client." /> + </setting> + <setting name="wimax" > + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the WiMAX device whose MAC address matches. This property does not change the MAC address of the device (known as MAC spoofing). Deprecated: 1" /> + <property name="network-name" + alias="nsp" + description="Network Service Provider (NSP) name of the WiMAX network this connection should use. Deprecated: 1" /> + </setting> + <setting name="wireguard" > + <property name="private-key" + description="The 256 bit private-key in base64 encoding." /> + <property name="private-key-flags" + description="Flags indicating how to handle the "private-key" property." /> + <property name="listen-port" + description="The listen-port. If listen-port is not specified, the port will be chosen randomly when the interface comes up." /> + <property name="fwmark" + description="The use of fwmark is optional and is by default off. Setting it to 0 disables it. Otherwise, it is a 32-bit fwmark for outgoing packets. Note that "ip4-auto-default-route" or "ip6-auto-default-route" enabled, implies to automatically choose a fwmark." /> + <property name="peer-routes" + description="Whether to automatically add routes for the AllowedIPs ranges of the peers. If TRUE (the default), NetworkManager will automatically add routes in the routing tables according to ipv4.route-table and ipv6.route-table. Usually you want this automatism enabled. If FALSE, no such routes are added automatically. In this case, the user may want to configure static routes in ipv4.routes and ipv6.routes, respectively. Note that if the peer's AllowedIPs is "0.0.0.0/0" or "::/0" and the profile's ipv4.never-default or ipv6.never-default setting is enabled, the peer route for this peer won't be added automatically." /> + <property name="mtu" + description="If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple fragments. If zero a default MTU is used. Note that contrary to wg-quick's MTU setting, this does not take into account the current routes at the time of activation." /> + <property name="ip4-auto-default-route" + description="Whether to enable special handling of the IPv4 default route. If enabled, the IPv4 default route from wireguard.peer-routes will be placed to a dedicated routing-table and two policy routing rules will be added. The fwmark number is also used as routing-table for the default-route, and if fwmark is zero, an unused fwmark/table is chosen automatically. This corresponds to what wg-quick does with Table=auto and what WireGuard calls "Improved Rule-based Routing". Note that for this automatism to work, you usually don't want to set ipv4.gateway, because that will result in a conflicting default route. Leaving this at the default will enable this option automatically if ipv4.never-default is not set and there are any peers that use a default-route as allowed-ips." /> + <property name="ip6-auto-default-route" + description="Like ip4-auto-default-route, but for the IPv6 default route." /> + </setting> + <setting name="wpan" > + <property name="mac-address" + alias="mac" + description="If specified, this connection will only apply to the IEEE 802.15.4 (WPAN) MAC layer device whose permanent MAC address matches." /> + <property name="short-address" + alias="short-addr" + description="Short IEEE 802.15.4 address to be used within a restricted environment." /> + <property name="pan-id" + alias="pan-id" + description="IEEE 802.15.4 Personal Area Network (PAN) identifier." /> + <property name="page" + alias="page" + description="IEEE 802.15.4 channel page. A positive integer or -1, meaning "do not set, use whatever the device is already set to"." /> + <property name="channel" + alias="channel" + description="IEEE 802.15.4 channel. A positive integer or -1, meaning "do not set, use whatever the device is already set to"." /> + </setting> +</nm-setting-docs> diff --git a/src/nmcli/meson.build b/src/nmcli/meson.build new file mode 100644 index 00000000..fab7329e --- /dev/null +++ b/src/nmcli/meson.build @@ -0,0 +1,97 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +if enable_nmcli + +# The file is called "nmcli-completion" but should be installed with +# name "nmcli". Currently it gets renamed by "tools/meson-post-install.sh", +# but if we depend on meson 0.46.0, we could use "rename" option. +install_data( + 'nmcli-completion', + install_dir: join_paths(nm_datadir, 'bash-completion', 'completions'), +) + +executable( + 'nmcli', + files( + 'agent.c', + 'common.c', + 'connections.c', + 'devices.c', + 'general.c', + 'nmcli.c', + 'polkit-agent.c', + 'settings.c', + 'utils.c', + ), + dependencies: [ + libnm_dep, + glib_dep, + readline_dep, + ], + link_with: [ + libnmc_setting, + libnmc_base, + libnm_client_aux_extern, + libnm_core_aux_extern, + libnm_core_aux_intern, + libnm_base, + libnm_log_null, + libnm_glib_aux, + libnm_std_aux, + libc_siphash, + ], + link_args: ldflags_linker_script_binary, + link_depends: linker_script_binary, + install: true, +) + +endif + +generate_docs_nm_settings_nmcli = executable( + 'generate-docs-nm-settings-nmcli', + files( + 'generate-docs-nm-settings-nmcli.c', + ), + dependencies: [ + libnm_dep, + glib_dep, + ], + link_with: [ + libnmc_setting, + libnmc_base, + libnm_core_aux_extern, + libnm_core_aux_intern, + libnm_base, + libnm_log_null, + libnm_glib_aux, + libnm_std_aux, + libc_siphash, + ], + link_args: ldflags_linker_script_binary, + link_depends: linker_script_binary, +) + +if enable_docs + generate_docs_nm_settings_nmcli_xml = custom_target( + 'generate-docs-nm-settings-nmcli.xml', + output: 'generate-docs-nm-settings-nmcli.xml', + command: [ generate_docs_nm_settings_nmcli ], + capture: true, + ) + + test( + 'check-local-generate-docs-nm-settings-nmcli', + find_program(join_paths(source_root, 'tools', 'check-compare-generated.sh')), + args: [ + source_root, + build_root, + 'src/nmcli/generate-docs-nm-settings-nmcli.xml', + ], + ) +else + settings_docs_source = configure_file( + input: 'generate-docs-nm-settings-nmcli.xml.in', + output: '@BASENAME@', + configuration: configuration_data(), + ) +endif diff --git a/src/nmcli/nmcli-completion b/src/nmcli/nmcli-completion new file mode 100644 index 00000000..83ec1e3c --- /dev/null +++ b/src/nmcli/nmcli-completion @@ -0,0 +1,116 @@ +# nmcli(1) completion + +_nmcli_array_delete_at() +{ + eval "local ARRAY=(\"\${$1[@]}\")" + local i + local tmp=() + local lower=$2 + local upper=${3:-$lower} + + # for some reason the following fails. So this clumsy workaround... + # A=(a "") + # echo " >> ${#A[@]}" + # >> 2 + # A=("${A[@]:1}") + # echo " >> ${#A[@]}" + # >> 0 + # ... seriously??? + + for i in "${!ARRAY[@]}"; do + if [[ "$i" -lt "$2" || "$i" -gt "${3-$2}" ]]; then + tmp=("${tmp[@]}" "${ARRAY[$i]}") + fi + done + eval "$1=(\"\${tmp[@]}\")" +} + +_nmcli() +{ + local cur prev words cword i output + _init_completion || return + + # we don't care about any arguments after the current cursor position + # because we only parse from left to right. So, if there are some arguments + # right of the cursor, just ignore them. Also don't care about ${words[0]}. + _nmcli_array_delete_at words $((cword+1)) ${#words[@]} + _nmcli_array_delete_at words 0 + + # _init_completion returns the words with all the quotes and escaping + # characters. We don't care about them, drop them at first. + for i in ${!words[@]}; do + words[i]="$(printf '%s' "${words[i]}" | xargs printf '%s\n' 2>/dev/null || true)" + done + + # In case the cursor is not at the end of the line, + # $cur consists of spaces that we want do remove. + # For example: `nmcli connection modify id <TAB> lo` + if [[ "$cur" =~ ^[[:space:]]+ ]]; then + cur='' + fi + + output="$(nmcli --complete-args "${words[@]}" 2>/dev/null)" + + # Bail out early if we're completing a file name + if [ $? = 65 ]; then + compopt -o default + COMPREPLY=() + return 0 + fi + + local IFS=$'\n' + COMPREPLY=( $( compgen -W '$output' -- $cur ) ) + + # Now escape special characters (spaces, single and double quotes), + # so that the argument is really regarded a single argument by bash. + # See http://stackoverflow.com/questions/1146098/properly-handling-spaces-and-quotes-in-bash-completion + local escaped_single_quote="'\''" + local i=0 + local entry + for entry in ${COMPREPLY[*]} + do + if [[ "${cur:0:1}" == "'" ]]; then + # started with single quote, escaping only other single quotes + # [']bla'bla"bla\bla bla --> [']bla'\''bla"bla\bla bla + COMPREPLY[$i]="${entry//\'/${escaped_single_quote}}" + elif [[ "${cur:0:1}" == '"' ]]; then + # started with double quote, escaping all double quotes and all backslashes + # ["]bla'bla"bla\bla bla --> ["]bla'bla\"bla\\bla bla + entry="${entry//\\/\\\\}" + entry="${entry//\"/\\\"}" + entry="${entry//!/\"\\!\"}" + COMPREPLY[$i]="$entry" + else + # no quotes in front, escaping _everything_ + # [ ]bla'bla"bla\bla bla --> [ ]bla\'bla\"bla\\bla\ bla + entry="${entry//\\/\\\\}" + entry="${entry//\'/\'}" + entry="${entry//\"/\\\"}" + entry="${entry// /\\ }" + entry="${entry//\(/\\(}" + entry="${entry//)/\\)}" + entry="${entry//!/\\!}" + entry="${entry//&/\\&}" + COMPREPLY[$i]="$entry" + fi + (( i++ )) + done + + # Work-around bash_completion issue where bash interprets a colon + # as a separator. + # Colon is escaped here. Change "\\:" back to ":". + # See also: + # http://stackoverflow.com/questions/28479216/how-to-give-correct-suggestions-to-tab-complete-when-my-words-contains-colons + # http://stackoverflow.com/questions/2805412/bash-completion-for-maven-escapes-colon/12495727 + i=0 + for entry in ${COMPREPLY[*]} + do + entry="${entry//\\\\:/:}" + COMPREPLY[$i]=${entry} + (( i++ )) + done + +} && +complete -F _nmcli nmcli + +# ex: ts=4 sw=4 et filetype=sh diff --git a/src/nmcli/nmcli.c b/src/nmcli/nmcli.c new file mode 100644 index 00000000..e592e054 --- /dev/null +++ b/src/nmcli/nmcli.c @@ -0,0 +1,1051 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Jiri Klimes <jklimes@redhat.com> + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include "nmcli.h" + +#include <stdio.h> +#include <stdlib.h> +#include <signal.h> +#include <termios.h> +#include <unistd.h> +#include <locale.h> +#include <glib-unix.h> +#include <readline/readline.h> +#include <readline/history.h> + +#include "libnmc-base/nm-client-utils.h" + +#include "polkit-agent.h" +#include "utils.h" +#include "common.h" +#include "connections.h" +#include "devices.h" +#include "settings.h" + +#if defined(NM_DIST_VERSION) + #define NMCLI_VERSION NM_DIST_VERSION +#else + #define NMCLI_VERSION VERSION +#endif + +#define _NMC_COLOR_PALETTE_INIT() \ + { \ + .ansi_seq = { \ + [NM_META_COLOR_CONNECTION_ACTIVATED] = "32", \ + [NM_META_COLOR_CONNECTION_ACTIVATING] = "33", \ + [NM_META_COLOR_CONNECTION_DISCONNECTING] = "31", \ + [NM_META_COLOR_CONNECTION_INVISIBLE] = "2", \ + [NM_META_COLOR_CONNECTION_EXTERNAL] = "32;2", \ + [NM_META_COLOR_CONNECTIVITY_FULL] = "32", \ + [NM_META_COLOR_CONNECTIVITY_LIMITED] = "33", \ + [NM_META_COLOR_CONNECTIVITY_NONE] = "31", \ + [NM_META_COLOR_CONNECTIVITY_PORTAL] = "33", \ + [NM_META_COLOR_DEVICE_ACTIVATED] = "32", \ + [NM_META_COLOR_DEVICE_ACTIVATING] = "33", \ + [NM_META_COLOR_DEVICE_DISCONNECTED] = "31", \ + [NM_META_COLOR_DEVICE_FIRMWARE_MISSING] = "31", \ + [NM_META_COLOR_DEVICE_PLUGIN_MISSING] = "31", \ + [NM_META_COLOR_DEVICE_UNAVAILABLE] = "2", \ + [NM_META_COLOR_DEVICE_DISABLED] = "31", \ + [NM_META_COLOR_DEVICE_EXTERNAL] = "32;2", \ + [NM_META_COLOR_MANAGER_RUNNING] = "32", \ + [NM_META_COLOR_MANAGER_STARTING] = "33", \ + [NM_META_COLOR_MANAGER_STOPPED] = "31", \ + [NM_META_COLOR_PERMISSION_AUTH] = "33", \ + [NM_META_COLOR_PERMISSION_NO] = "31", \ + [NM_META_COLOR_PERMISSION_YES] = "32", \ + [NM_META_COLOR_STATE_ASLEEP] = "31", \ + [NM_META_COLOR_STATE_CONNECTED_GLOBAL] = "32", \ + [NM_META_COLOR_STATE_CONNECTED_LOCAL] = "32", \ + [NM_META_COLOR_STATE_CONNECTED_SITE] = "32", \ + [NM_META_COLOR_STATE_CONNECTING] = "33", \ + [NM_META_COLOR_STATE_DISCONNECTED] = "31", \ + [NM_META_COLOR_STATE_DISCONNECTING] = "33", \ + [NM_META_COLOR_WIFI_SIGNAL_EXCELLENT] = "32", \ + [NM_META_COLOR_WIFI_SIGNAL_FAIR] = "35", \ + [NM_META_COLOR_WIFI_SIGNAL_GOOD] = "33", \ + [NM_META_COLOR_WIFI_SIGNAL_POOR] = "36", \ + [NM_META_COLOR_WIFI_SIGNAL_UNKNOWN] = "2", \ + [NM_META_COLOR_ENABLED] = "32", \ + [NM_META_COLOR_DISABLED] = "31", \ + }, \ + } + +static NmCli nm_cli = { + .client = NULL, + + .return_value = NMC_RESULT_SUCCESS, + + .timeout = -1, + + .secret_agent = NULL, + .pwds_hash = NULL, + .pk_listener = NULL, + + .should_wait = 0, + .nowait_flag = TRUE, + .nmc_config.print_output = NMC_PRINT_NORMAL, + .nmc_config.multiline_output = FALSE, + .mode_specified = FALSE, + .nmc_config.escape_values = TRUE, + .required_fields = NULL, + .ask = FALSE, + .complete = FALSE, + .nmc_config.show_secrets = FALSE, + .nmc_config.in_editor = FALSE, + .nmc_config.palette = _NMC_COLOR_PALETTE_INIT(), + .editor_status_line = FALSE, + .editor_save_confirmation = TRUE, +}; + +const NmCli *const nm_cli_global_readline = &nm_cli; +const NmCli *const nmc_meta_environment_arg = &nm_cli; + +/*****************************************************************************/ + +typedef struct { + NmCli *nmc; + int argc; + char **argv; +} ArgsInfo; + +/* --- Global variables --- */ +GMainLoop * loop = NULL; +struct termios termios_orig; + +NM_CACHED_QUARK_FCN("nmcli-error-quark", nmcli_error_quark); + +static void +complete_field_setting(GHashTable *h, NMMetaSettingType setting_type) +{ + const NMMetaSettingInfoEditor *setting_info = &nm_meta_setting_infos_editor[setting_type]; + guint i; + + for (i = 0; i < setting_info->properties_num; i++) { + g_hash_table_add(h, + g_strdup_printf("%s.%s", + setting_info->general->setting_name, + setting_info->properties[i]->property_name)); + } +} + +static void +complete_field(GHashTable *h, const NmcMetaGenericInfo *const *field) +{ + int i; + + for (i = 0; field[i]; i++) + g_hash_table_add(h, g_strdup(field[i]->name)); +} + +static void +complete_one(gpointer key, gpointer value, gpointer user_data) +{ + const char **option_with_value = user_data; + const char * option = option_with_value[0]; + const char * prefix = option_with_value[1]; + const char * name = key; + const char * last; + + last = strrchr(prefix, ','); + if (last) + last++; + else + last = prefix; + + if ((!*last && !strchr(name, '.')) || matches(last, name)) { + if (option != prefix) { + /* value prefix was not a standalone argument, + * it was part of --option=<value> argument. + * Repeat the part leading to "=". */ + g_print("%s=", option); + } + g_print("%.*s%s%s\n", + (int) (last - prefix), + prefix, + name, + strcmp(last, name) == 0 ? "," : ""); + } +} + +static void +complete_fields(const char *option, const char *prefix) +{ + guint i; + GHashTable *h; + const char *option_with_value[2] = {option, prefix}; + + h = g_hash_table_new_full(nm_str_hash, g_str_equal, g_free, NULL); + + complete_field(h, metagen_ip4_config); + complete_field(h, metagen_dhcp_config); + complete_field(h, metagen_ip6_config); + complete_field(h, metagen_con_show); + complete_field(h, metagen_con_active_general); + complete_field(h, metagen_con_active_vpn); + complete_field(h, nmc_fields_con_active_details_groups); + complete_field(h, metagen_device_status); + complete_field(h, metagen_device_detail_general); + complete_field(h, metagen_device_detail_connections); + complete_field(h, metagen_device_detail_capabilities); + complete_field(h, metagen_device_detail_wired_properties); + complete_field(h, metagen_device_detail_wifi_properties); + complete_field(h, metagen_device_detail_wimax_properties); + complete_field(h, nmc_fields_dev_wifi_list); + complete_field(h, nmc_fields_dev_wimax_list); + complete_field(h, nmc_fields_dev_show_master_prop); + complete_field(h, nmc_fields_dev_show_team_prop); + complete_field(h, nmc_fields_dev_show_vlan_prop); + complete_field(h, nmc_fields_dev_show_bluetooth); + complete_field(h, nmc_fields_dev_show_sections); + complete_field(h, nmc_fields_dev_lldp_list); + + for (i = 0; i < _NM_META_SETTING_TYPE_NUM; i++) + complete_field_setting(h, i); + + g_hash_table_foreach(h, complete_one, (gpointer) &option_with_value[0]); + g_hash_table_destroy(h); +} + +static void +complete_option_with_value(const char *option, const char *prefix, ...) +{ + va_list args; + const char *candidate; + + va_start(args, prefix); + while ((candidate = va_arg(args, const char *))) { + if (!*prefix || matches(prefix, candidate)) { + if (option != prefix) { + /* value prefix was not a standalone argument, + * it was part of --option=<value> argument. + * Repeat the part leading to "=". */ + g_print("%s=", option); + } + g_print("%s\n", candidate); + } + } + va_end(args); +} + +static void +usage(void) +{ + g_printerr(_( + "Usage: nmcli [OPTIONS] OBJECT { COMMAND | help }\n" + "\n" + "OPTIONS\n" + " -a, --ask ask for missing parameters\n" + " -c, --colors auto|yes|no whether to use colors in output\n" + " -e, --escape yes|no escape columns separators in values\n" + " -f, --fields <field,...>|all|common specify fields to output\n" + " -g, --get-values <field,...>|all|common shortcut for -m tabular -t -f\n" + " -h, --help print this help\n" + " -m, --mode tabular|multiline output mode\n" + " -o, --overview overview mode\n" + " -p, --pretty pretty output\n" + " -s, --show-secrets allow displaying passwords\n" + " -t, --terse terse output\n" + " -v, --version show program version\n" + " -w, --wait <seconds> set timeout waiting for finishing operations\n" + "\n" + "OBJECT\n" + " g[eneral] NetworkManager's general status and operations\n" + " n[etworking] overall networking control\n" + " r[adio] NetworkManager radio switches\n" + " c[onnection] NetworkManager's connections\n" + " d[evice] devices managed by NetworkManager\n" + " a[gent] NetworkManager secret agent or polkit agent\n" + " m[onitor] monitor NetworkManager changes\n" + "\n")); +} + +static gboolean +matches_arg(NmCli *nmc, int *argc, const char *const **argv, const char *pattern, char **arg) +{ + gs_free char *opt_free = NULL; + const char * opt = (*argv)[0]; + gs_free char *arg_tmp = NULL; + const char * s; + + nm_assert(opt); + nm_assert(opt[0] == '-'); + nm_assert(!arg || !*arg); + + if (nmc->return_value != NMC_RESULT_SUCCESS) { + /* Don't process further matches if there has been an error. */ + return FALSE; + } + + if (opt[1] == '-') { + /* We know one '-' was already seen by the caller. + * Skip it if there's a second one*/ + opt++; + } + + if (arg) { + /* If there's a "=" separator, replace it with NUL so that matches() + * works and consider the part after it to be the argument's value. */ + s = strchr(opt, '='); + if (s) { + opt = nm_strndup_a(300, opt, s - opt, &opt_free); + arg_tmp = g_strdup(&s[1]); + } + } + + if (!matches(opt, pattern)) + return FALSE; + + if (arg) { + if (arg_tmp) + *arg = g_steal_pointer(&arg_tmp); + else { + /* We need a value, but the option didn't contain a "=<value>" part. + * Proceed to the next argument. */ + if (*argc <= 1) { + g_string_printf(nmc->return_text, + _("Error: missing argument for '%s' option."), + opt); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + (*argc)--; + (*argv)++; + *arg = g_strdup(*argv[0]); + } + } + + return TRUE; +} + +/*************************************************************************************/ + +typedef enum { + NMC_USE_COLOR_AUTO, + NMC_USE_COLOR_YES, + NMC_USE_COLOR_NO, +} NmcColorOption; + +static char * +check_colors_construct_filename(const char *base_dir, + const char *name, + const char *term, + const char *type) +{ + return g_strdup_printf("%s/terminal-colors.d/%s%s%s%s%s", + base_dir, + name ? name : "", + term ? "@" : "", + term ? term : "", + (name || term) ? "." : "", + type); +} + +static NmcColorOption +check_colors_check_enabled_one_file(const char *base_dir, const char *name, const char *term) +{ + gs_free char *filename_e = NULL; + gs_free char *filename_d = NULL; + + filename_e = check_colors_construct_filename(base_dir, name, term, "enable"); + if (g_file_test(filename_e, G_FILE_TEST_EXISTS)) + return NMC_USE_COLOR_YES; + + filename_d = check_colors_construct_filename(base_dir, name, term, "disable"); + if (g_file_test(filename_d, G_FILE_TEST_EXISTS)) + return NMC_USE_COLOR_NO; + + return NMC_USE_COLOR_AUTO; +} + +static char * +check_colors_check_palette_one_file(const char *base_dir, const char *name, const char *term) +{ + static const char *const extensions[] = { + "scheme", + "schem", + }; + guint i; + + for (i = 0; i < G_N_ELEMENTS(extensions); i++) { + gs_free char *filename = NULL; + char * contents; + + filename = check_colors_construct_filename(base_dir, name, term, extensions[i]); + if (g_file_get_contents(filename, &contents, NULL, NULL)) + return contents; + } + + return NULL; +} + +static gboolean +check_colors_check_enabled(const char *base_dir_1, + const char *base_dir_2, + const char *name, + const char *term) +{ + int i; + + if (term && strchr(term, '/')) + term = NULL; + +#define CHECK_AND_RETURN(cmd) \ + G_STMT_START \ + { \ + NmcColorOption _color_option; \ + \ + _color_option = (cmd); \ + if (_color_option != NMC_USE_COLOR_AUTO) \ + return _color_option == NMC_USE_COLOR_YES; \ + } \ + G_STMT_END + + for (i = 0; i < 2; i++) { + const char *base_dir = (i == 0 ? base_dir_1 : base_dir_2); + + if (!base_dir) + continue; + if (name && term) + CHECK_AND_RETURN(check_colors_check_enabled_one_file(base_dir, name, term)); + if (name) + CHECK_AND_RETURN(check_colors_check_enabled_one_file(base_dir, name, NULL)); + if (term) + CHECK_AND_RETURN(check_colors_check_enabled_one_file(base_dir, NULL, term)); + if (TRUE) + CHECK_AND_RETURN(check_colors_check_enabled_one_file(base_dir, NULL, NULL)); + } +#undef CHECK_AND_RETURN + return TRUE; +} + +static char * +check_colors_check_palette(const char *base_dir_1, + const char *base_dir_2, + const char *name, + const char *term) +{ + int i; + + if (term && strchr(term, '/')) + term = NULL; + +#define CHECK_AND_RETURN(cmd) \ + G_STMT_START \ + { \ + char *_palette; \ + \ + _palette = (cmd); \ + if (_palette) \ + return _palette; \ + } \ + G_STMT_END + + for (i = 0; i < 2; i++) { + const char *base_dir = (i == 0 ? base_dir_1 : base_dir_2); + + if (!base_dir) + continue; + if (name && term) + CHECK_AND_RETURN(check_colors_check_palette_one_file(base_dir, name, term)); + if (name) + CHECK_AND_RETURN(check_colors_check_palette_one_file(base_dir, name, NULL)); + if (term) + CHECK_AND_RETURN(check_colors_check_palette_one_file(base_dir, NULL, term)); + if (TRUE) + CHECK_AND_RETURN(check_colors_check_palette_one_file(base_dir, NULL, NULL)); + } +#undef CHECK_AND_RETURN + return NULL; +} + +static gboolean +check_colors(NmcColorOption color_option, char **out_palette_str) +{ + const char * base_dir_1, *base_dir_2; + const char *const NAME = "nmcli"; + const char * term; + + *out_palette_str = NULL; + + if (!NM_IN_SET(color_option, NMC_USE_COLOR_AUTO, NMC_USE_COLOR_YES)) { + /* nothing to do. Colors are disabled. */ + return FALSE; + } + + if (color_option == NMC_USE_COLOR_AUTO && g_getenv("NO_COLOR")) { + /* https://no-color.org/ */ + return FALSE; + } + + term = g_getenv("TERM"); + + if (color_option == NMC_USE_COLOR_AUTO) { + if (nm_streq0(term, "dumb") || !isatty(STDOUT_FILENO)) + return FALSE; + } + + base_dir_1 = g_get_user_config_dir(); + base_dir_2 = "" SYSCONFDIR; + + if (base_dir_1) { + if (nm_streq(base_dir_1, base_dir_2) || !g_file_test(base_dir_1, G_FILE_TEST_EXISTS)) + base_dir_1 = NULL; + } + if (!g_file_test(base_dir_2, G_FILE_TEST_EXISTS)) + base_dir_2 = NULL; + + if (color_option == NMC_USE_COLOR_AUTO + && !check_colors_check_enabled(base_dir_1, base_dir_2, NAME, term)) + return FALSE; + + *out_palette_str = check_colors_check_palette(base_dir_1, base_dir_2, NAME, term); + return TRUE; +} + +static NM_UTILS_STRING_TABLE_LOOKUP_DEFINE( + _resolve_color_alias, + const char *, + { nm_assert(name); }, + { return NULL; }, + {"black", "30"}, + {"blink", "5"}, + {"blue", "34"}, + {"bold", "1"}, + {"brown", "33"}, + {"cyan", "36"}, + {"darkgray", "90"}, + {"gray", "37"}, + {"green", "32"}, + {"halfbright", "2"}, + {"lightblue", "94"}, + {"lightcyan", "96"}, + {"lightgray", "97"}, + {"lightgreen", "92"}, + {"lightmagenta", "95"}, + {"lightred", "91"}, + {"magenta", "35"}, + {"red", "31"}, + {"reset", "0"}, + {"reverse", "7"}, + {"underscore", "4"}, + {"white", "1;37"}, + {"yellow", "33" /* well, yellow */}, ); + +static NM_UTILS_STRING_TABLE_LOOKUP_DEFINE( + _nm_meta_color_from_name, + NMMetaColor, + { nm_assert(name); }, + { return NM_META_COLOR_NONE; }, + {"connection-activated", NM_META_COLOR_CONNECTION_ACTIVATED}, + {"connection-activating", NM_META_COLOR_CONNECTION_ACTIVATING}, + {"connection-disconnecting", NM_META_COLOR_CONNECTION_DISCONNECTING}, + {"connection-external", NM_META_COLOR_CONNECTION_EXTERNAL}, + {"connection-invisible", NM_META_COLOR_CONNECTION_INVISIBLE}, + {"connection-unknown", NM_META_COLOR_CONNECTION_UNKNOWN}, + {"connectivity-full", NM_META_COLOR_CONNECTIVITY_FULL}, + {"connectivity-limited", NM_META_COLOR_CONNECTIVITY_LIMITED}, + {"connectivity-none", NM_META_COLOR_CONNECTIVITY_NONE}, + {"connectivity-portal", NM_META_COLOR_CONNECTIVITY_PORTAL}, + {"connectivity-unknown", NM_META_COLOR_CONNECTIVITY_UNKNOWN}, + {"device-activated", NM_META_COLOR_DEVICE_ACTIVATED}, + {"device-activating", NM_META_COLOR_DEVICE_ACTIVATING}, + {"device-disabled", NM_META_COLOR_DEVICE_DISABLED}, + {"device-disconnected", NM_META_COLOR_DEVICE_DISCONNECTED}, + {"device-external", NM_META_COLOR_DEVICE_EXTERNAL}, + {"device-firmware-missing", NM_META_COLOR_DEVICE_FIRMWARE_MISSING}, + {"device-plugin-missing", NM_META_COLOR_DEVICE_PLUGIN_MISSING}, + {"device-unavailable", NM_META_COLOR_DEVICE_UNAVAILABLE}, + {"device-unknown", NM_META_COLOR_DEVICE_UNKNOWN}, + {"disabled", NM_META_COLOR_DISABLED}, + {"enabled", NM_META_COLOR_ENABLED}, + {"manager-running", NM_META_COLOR_MANAGER_RUNNING}, + {"manager-starting", NM_META_COLOR_MANAGER_STARTING}, + {"manager-stopped", NM_META_COLOR_MANAGER_STOPPED}, + {"permission-auth", NM_META_COLOR_PERMISSION_AUTH}, + {"permission-no", NM_META_COLOR_PERMISSION_NO}, + {"permission-unknown", NM_META_COLOR_PERMISSION_UNKNOWN}, + {"permission-yes", NM_META_COLOR_PERMISSION_YES}, + {"prompt", NM_META_COLOR_PROMPT}, + {"state-asleep", NM_META_COLOR_STATE_ASLEEP}, + {"state-connected-global", NM_META_COLOR_STATE_CONNECTED_GLOBAL}, + {"state-connected-local", NM_META_COLOR_STATE_CONNECTED_LOCAL}, + {"state-connected-site", NM_META_COLOR_STATE_CONNECTED_SITE}, + {"state-connecting", NM_META_COLOR_STATE_CONNECTING}, + {"state-disconnected", NM_META_COLOR_STATE_DISCONNECTED}, + {"state-disconnecting", NM_META_COLOR_STATE_DISCONNECTING}, + {"state-unknown", NM_META_COLOR_STATE_UNKNOWN}, + {"wifi-signal-excellent", NM_META_COLOR_WIFI_SIGNAL_EXCELLENT}, + {"wifi-signal-fair", NM_META_COLOR_WIFI_SIGNAL_FAIR}, + {"wifi-signal-good", NM_META_COLOR_WIFI_SIGNAL_GOOD}, + {"wifi-signal-poor", NM_META_COLOR_WIFI_SIGNAL_POOR}, + {"wifi-signal-unknown", NM_META_COLOR_WIFI_SIGNAL_UNKNOWN}, ); + +static gboolean +parse_color_scheme(char *palette_buffer, NmcColorPalette *out_palette, GError **error) +{ + char *p = palette_buffer; + + nm_assert(out_palette); + + *out_palette = (NmcColorPalette) _NMC_COLOR_PALETTE_INIT(); + + /* This reads through the raw color scheme file contents, identifying the + * color names and sequences, putting in terminating NULs in place, so that + * pointers into the buffer can readily be used as strings in the palette. */ + while (1) { + NMMetaColor name_idx; + const char *name; + const char *color; + + /* Leading whitespace. */ + while (nm_utils_is_separator(*p) || *p == '\n') + p++; + + if (*p == '\0') + break; + + /* Comments. */ + if (*p == '#') { + while (*p != '\n' && *p != '\0') + p++; + continue; + } + + /* Color name. */ + name = p; + while (g_ascii_isgraph(*p)) + p++; + if (*p == '\0') { + g_set_error(error, NMCLI_ERROR, 0, _("Unexpected end of file following '%s'\n"), name); + return FALSE; + } + + /* Separating whitespace. */ + if (!nm_utils_is_separator(*p)) { + *p = '\0'; + g_set_error(error, NMCLI_ERROR, 0, _("Expected whitespace following '%s'\n"), name); + return FALSE; + } + while (nm_utils_is_separator(*p)) { + *p = '\0'; + p++; + } + + /* Color sequence. */ + color = p; + if (!g_ascii_isgraph(*p)) { + g_set_error(error, NMCLI_ERROR, 0, _("Expected a value for '%s'\n"), name); + return FALSE; + } + while (g_ascii_isgraph(*p)) + p++; + + /* Trailing whitespace. */ + while (nm_utils_is_separator(*p)) { + *p = '\0'; + p++; + } + if (*p != '\0') { + if (*p != '\n') { + g_set_error(error, + NMCLI_ERROR, + 0, + _("Expected a line break following '%s'\n"), + color); + return FALSE; + } + *p = '\0'; + p++; + } + + name_idx = _nm_meta_color_from_name(name); + if (name_idx == NM_META_COLOR_NONE) { + g_debug("Ignoring an unrecognized color: '%s'\n", name); + continue; + } + + out_palette->ansi_seq[name_idx] = _resolve_color_alias(color) ?: color; + } + + return TRUE; +} + +static void +set_colors(NmcColorOption color_option, + bool * out_use_colors, + char ** out_palette_buffer, + NmcColorPalette *out_palette) +{ + gs_free char *palette_str = NULL; + gboolean use_colors; + gboolean palette_set = FALSE; + + nm_assert(out_use_colors); + nm_assert(out_palette); + nm_assert(out_palette_buffer && !*out_palette_buffer); + + use_colors = check_colors(color_option, &palette_str); + + *out_use_colors = use_colors; + + if (use_colors && palette_str) { + gs_free_error GError *error = NULL; + NmcColorPalette palette; + + if (!parse_color_scheme(palette_str, &palette, &error)) + g_debug("Error parsing color scheme: %s", error->message); + else { + *out_palette_buffer = g_steal_pointer(&palette_str); + *out_palette = palette; + palette_set = TRUE; + } + } + + if (!palette_set) + *out_palette = (NmcColorPalette) _NMC_COLOR_PALETTE_INIT(); +} + +/*************************************************************************************/ + +static gboolean +process_command_line(NmCli *nmc, int argc, char **argv_orig) +{ + static const NMCCommand nmcli_cmds[] = { + {"general", nmc_command_func_general, NULL, FALSE, FALSE}, + {"monitor", nmc_command_func_monitor, NULL, TRUE, FALSE}, + {"networking", nmc_command_func_networking, NULL, FALSE, FALSE}, + {"radio", nmc_command_func_radio, NULL, FALSE, FALSE}, + {"connection", nmc_command_func_connection, NULL, FALSE, FALSE}, + {"device", nmc_command_func_device, NULL, FALSE, FALSE}, + {"agent", nmc_command_func_agent, NULL, FALSE, FALSE}, + {NULL, nmc_command_func_overview, usage, TRUE, TRUE}, + }; + NmcColorOption colors = NMC_USE_COLOR_AUTO; + const char * base; + const char *const *argv; + + base = strrchr(argv_orig[0], '/'); + if (base == NULL) + base = argv_orig[0]; + else + base++; + + if (argc > 1 && nm_streq(argv_orig[1], "--complete-args")) { + nmc->complete = TRUE; + argv_orig[1] = argv_orig[0]; + argc--; + argv_orig++; + } + + argv = (const char *const *) argv_orig; + + next_arg(nmc, &argc, &argv, NULL); + + /* parse options */ + while (argc) { + gs_free char *value = NULL; + + if (argv[0][0] != '-') + break; + + if (argc == 1 && nmc->complete) { + nmc_complete_strings(argv[0], + "--terse", + "--pretty", + "--mode", + "--overview", + "--colors", + "--escape", + "--fields", + "--nocheck", + "--get-values", + "--wait", + "--version", + "--help"); + } + + if (argv[0][1] == '-' && argv[0][2] == '\0') { + /* '--' ends options */ + next_arg(nmc, &argc, &argv, NULL); + break; + } + + if (matches_arg(nmc, &argc, &argv, "-overview", NULL)) { + nmc->nmc_config_mutable.overview = TRUE; + } else if (matches_arg(nmc, &argc, &argv, "-terse", NULL)) { + if (nmc->nmc_config.print_output == NMC_PRINT_TERSE) { + g_string_printf(nmc->return_text, + _("Error: Option '--terse' is specified the second time.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } else if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) { + g_string_printf( + nmc->return_text, + _("Error: Option '--terse' is mutually exclusive with '--pretty'.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } else + nmc->nmc_config_mutable.print_output = NMC_PRINT_TERSE; + } else if (matches_arg(nmc, &argc, &argv, "-pretty", NULL)) { + if (nmc->nmc_config.print_output == NMC_PRINT_PRETTY) { + g_string_printf(nmc->return_text, + _("Error: Option '--pretty' is specified the second time.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } else if (nmc->nmc_config.print_output == NMC_PRINT_TERSE) { + g_string_printf( + nmc->return_text, + _("Error: Option '--pretty' is mutually exclusive with '--terse'.")); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } else + nmc->nmc_config_mutable.print_output = NMC_PRINT_PRETTY; + } else if (matches_arg(nmc, &argc, &argv, "-mode", &value)) { + nmc->mode_specified = TRUE; + if (argc == 1 && nmc->complete) + complete_option_with_value(argv[0], value, "tabular", "multiline", NULL); + if (matches(value, "tabular")) + nmc->nmc_config_mutable.multiline_output = FALSE; + else if (matches(value, "multiline")) + nmc->nmc_config_mutable.multiline_output = TRUE; + else { + g_string_printf(nmc->return_text, + _("Error: '%s' is not a valid argument for '%s' option."), + value, + argv[0]); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + } else if (matches_arg(nmc, &argc, &argv, "-colors", &value)) { + if (argc == 1 && nmc->complete) + complete_option_with_value(argv[0], value, "yes", "no", "auto", NULL); + if (matches(value, "auto")) + colors = NMC_USE_COLOR_AUTO; + else if (matches(value, "yes")) + colors = NMC_USE_COLOR_YES; + else if (matches(value, "no")) + colors = NMC_USE_COLOR_NO; + else { + g_string_printf(nmc->return_text, + _("Error: '%s' is not valid argument for '%s' option."), + value, + argv[0]); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + } else if (matches_arg(nmc, &argc, &argv, "-escape", &value)) { + if (argc == 1 && nmc->complete) + complete_option_with_value(argv[0], value, "yes", "no", NULL); + if (matches(value, "yes")) + nmc->nmc_config_mutable.escape_values = TRUE; + else if (matches(value, "no")) + nmc->nmc_config_mutable.escape_values = FALSE; + else { + g_string_printf(nmc->return_text, + _("Error: '%s' is not valid argument for '%s' option."), + value, + argv[0]); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + } else if (matches_arg(nmc, &argc, &argv, "-fields", &value)) { + if (argc == 1 && nmc->complete) + complete_fields(argv[0], value); + nmc->required_fields = g_strdup(value); + } else if (matches_arg(nmc, &argc, &argv, "-get-values", &value)) { + if (argc == 1 && nmc->complete) + complete_fields(argv[0], value); + nmc->required_fields = g_strdup(value); + nmc->nmc_config_mutable.print_output = NMC_PRINT_TERSE; + /* We want fixed tabular mode here, but just set the mode specified and rely on defaults: + * in this way we allow use of "-m multiline" to swap the output mode also if placed + * before the "-g <field>" option (-g may be still more practical and easy to remember than -t -f). + */ + nmc->mode_specified = TRUE; + } else if (matches_arg(nmc, &argc, &argv, "-nocheck", NULL)) { + /* ignore for backward compatibility */ + } else if (matches_arg(nmc, &argc, &argv, "-wait", &value)) { + unsigned long timeout; + + if (!nmc_string_to_uint(value, TRUE, 0, G_MAXINT, &timeout)) { + g_string_printf(nmc->return_text, _("Error: '%s' is not a valid timeout."), value); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + return FALSE; + } + nmc->timeout = (int) timeout; + } else if (matches_arg(nmc, &argc, &argv, "-version", NULL)) { + if (!nmc->complete) + g_print(_("nmcli tool, version %s\n"), NMCLI_VERSION); + return NMC_RESULT_SUCCESS; + } else if (matches_arg(nmc, &argc, &argv, "-help", NULL)) { + if (!nmc->complete) + usage(); + return NMC_RESULT_SUCCESS; + } else { + if (nmc->return_value == NMC_RESULT_SUCCESS) { + g_string_printf(nmc->return_text, + _("Error: Option '%s' is unknown, try 'nmcli -help'."), + argv[0]); + nmc->return_value = NMC_RESULT_ERROR_USER_INPUT; + } + return FALSE; + } + + next_arg(nmc, &argc, &argv, NULL); + } + + /* Ignore --overview when fields are set explicitly */ + if (nmc->required_fields) + nmc->nmc_config_mutable.overview = FALSE; + + set_colors(colors, + &nmc->nmc_config_mutable.use_colors, + &nmc->palette_buffer, + &nmc->nmc_config_mutable.palette); + + /* Now run the requested command */ + nmc_do_cmd(nmc, nmcli_cmds, *argv, argc, argv); + + return TRUE; +} + +static gboolean nmcli_sigint = FALSE; + +gboolean +nmc_seen_sigint(void) +{ + return nmcli_sigint; +} + +void +nmc_clear_sigint(void) +{ + nmcli_sigint = FALSE; +} + +void +nmc_exit(void) +{ + tcsetattr(STDIN_FILENO, TCSADRAIN, &termios_orig); + nmc_cleanup_readline(); + exit(1); +} + +static gboolean +signal_handler(gpointer user_data) +{ + int signo = GPOINTER_TO_INT(user_data); + + switch (signo) { + case SIGINT: + if (nmc_get_in_readline()) { + nmcli_sigint = TRUE; + } else { + nm_cli.return_value = 0x80 + signo; + g_string_printf(nm_cli.return_text, + _("Error: nmcli terminated by signal %s (%d)"), + strsignal(signo), + signo); + g_main_loop_quit(loop); + } + break; + case SIGTERM: + nm_cli.return_value = 0x80 + signo; + g_string_printf(nm_cli.return_text, + _("Error: nmcli terminated by signal %s (%d)"), + strsignal(signo), + signo); + nmc_exit(); + break; + } + + return G_SOURCE_CONTINUE; +} + +void +nm_cli_spawn_pager(const NmcConfig *nmc_config, NmcPagerData *pager_data) +{ + if (pager_data->pid != 0) + return; + pager_data->pid = nmc_terminal_spawn_pager(nmc_config); +} + +static void +nmc_cleanup(NmCli *nmc) +{ + pid_t ret; + + g_clear_object(&nmc->client); + + if (nmc->return_text) + g_string_free(g_steal_pointer(&nmc->return_text), TRUE); + + if (nmc->secret_agent) { + nm_secret_agent_old_unregister(NM_SECRET_AGENT_OLD(nmc->secret_agent), NULL, NULL); + g_clear_object(&nmc->secret_agent); + } + + nm_clear_pointer(&nmc->pwds_hash, g_hash_table_destroy); + + nm_clear_g_free(&nmc->required_fields); + + if (nmc->pager_data.pid != 0) { + pid_t pid = nm_steal_int(&nmc->pager_data.pid); + + fclose(stdout); + fclose(stderr); + do { + ret = waitpid(pid, NULL, 0); + } while (ret == -1 && errno == EINTR); + } + + nm_clear_g_free(&nmc->palette_buffer); + + nmc_polkit_agent_fini(nmc); +} + +int +main(int argc, char *argv[]) +{ + /* Set locale to use environment variables */ + setlocale(LC_ALL, ""); + +#ifdef GETTEXT_PACKAGE + /* Set i18n stuff */ + bindtextdomain(GETTEXT_PACKAGE, NMLOCALEDIR); + bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); + textdomain(GETTEXT_PACKAGE); +#endif + + /* Save terminal settings */ + tcgetattr(STDIN_FILENO, &termios_orig); + + nm_cli.return_text = g_string_new(_("Success")); + loop = g_main_loop_new(NULL, FALSE); + + g_unix_signal_add(SIGTERM, signal_handler, GINT_TO_POINTER(SIGTERM)); + g_unix_signal_add(SIGINT, signal_handler, GINT_TO_POINTER(SIGINT)); + + if (process_command_line(&nm_cli, argc, argv)) + g_main_loop_run(loop); + + if (nm_cli.complete) { + /* Remove error statuses from command completion runs. */ + if (nm_cli.return_value < NMC_RESULT_COMPLETE_FILE) + nm_cli.return_value = NMC_RESULT_SUCCESS; + } else if (nm_cli.return_value != NMC_RESULT_SUCCESS) { + /* Print result descripting text */ + g_printerr("%s\n", nm_cli.return_text->str); + } + + nmc_cleanup(&nm_cli); + g_main_loop_unref(loop); + + return nm_cli.return_value; +} diff --git a/src/nmcli/nmcli.h b/src/nmcli/nmcli.h new file mode 100644 index 00000000..f1303378 --- /dev/null +++ b/src/nmcli/nmcli.h @@ -0,0 +1,197 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#ifndef NMC_NMCLI_H +#define NMC_NMCLI_H + +#include "libnmc-base/nm-secret-agent-simple.h" +#include "libnmc-setting/nm-meta-setting-desc.h" + +struct _NMPolkitListener; + +typedef char *(*NmcCompEntryFunc)(const char *, int); + +/* nmcli exit codes */ +typedef enum { + /* Indicates successful execution */ + NMC_RESULT_SUCCESS = 0, + + /* Unknown / unspecified error */ + NMC_RESULT_ERROR_UNKNOWN = 1, + + /* Wrong invocation of nmcli */ + NMC_RESULT_ERROR_USER_INPUT = 2, + + /* A timeout expired */ + NMC_RESULT_ERROR_TIMEOUT_EXPIRED = 3, + + /* Error in connection activation */ + NMC_RESULT_ERROR_CON_ACTIVATION = 4, + + /* Error in connection deactivation */ + NMC_RESULT_ERROR_CON_DEACTIVATION = 5, + + /* Error in device disconnect */ + NMC_RESULT_ERROR_DEV_DISCONNECT = 6, + + /* Error in connection deletion */ + NMC_RESULT_ERROR_CON_DEL = 7, + + /* NetworkManager is not running */ + NMC_RESULT_ERROR_NM_NOT_RUNNING = 8, + + /* No more used, keep to preserve API */ + NMC_RESULT_ERROR_VERSIONS_MISMATCH = 9, + + /* Connection/Device/AP not found */ + NMC_RESULT_ERROR_NOT_FOUND = 10, + + /* --complete-args signals a file name may follow */ + NMC_RESULT_COMPLETE_FILE = 65, +} NMCResultCode; + +typedef enum { NMC_PRINT_TERSE = 0, NMC_PRINT_NORMAL = 1, NMC_PRINT_PRETTY = 2 } NMCPrintOutput; + +static inline NMMetaAccessorGetType +nmc_print_output_to_accessor_get_type(NMCPrintOutput print_output) +{ + return NM_IN_SET(print_output, NMC_PRINT_NORMAL, NMC_PRINT_PRETTY) + ? NM_META_ACCESSOR_GET_TYPE_PRETTY + : NM_META_ACCESSOR_GET_TYPE_PARSABLE; +} + +/* === Output fields === */ + +typedef enum { + NMC_OF_FLAG_FIELD_NAMES = 0x00000001, /* Print field names instead of values */ + NMC_OF_FLAG_SECTION_PREFIX = + 0x00000002, /* Use the first value as section prefix for the other field names - just in multiline */ + NMC_OF_FLAG_MAIN_HEADER_ADD = + 0x00000004, /* Print main header in addition to values/field names */ + NMC_OF_FLAG_MAIN_HEADER_ONLY = 0x00000008, /* Print main header only */ +} NmcOfFlags; + +typedef struct { + const char *ansi_seq[_NM_META_COLOR_NUM]; +} NmcColorPalette; + +extern const NMMetaType nmc_meta_type_generic_info; + +typedef struct _NmcOutputField NmcOutputField; +typedef struct _NmcMetaGenericInfo NmcMetaGenericInfo; + +struct _NmcOutputField { + const NMMetaAbstractInfo *info; + int width; /* Width in screen columns */ + void * value; /* Value of current field - char* or char** (NULL-terminated array) */ + gboolean value_is_array; /* Whether value is char** instead of char* */ + gboolean free_value; /* Whether to free the value */ + NmcOfFlags flags; /* Flags - whether and how to print values/field names/headers */ + NMMetaColor color; /* Use this color to print value */ +}; + +typedef struct _NmcConfig { + NMCPrintOutput print_output; /* Output mode */ + bool use_colors; /* Whether to use colors for output: option '--color' */ + bool multiline_output; /* Multiline output instead of default tabular */ + bool escape_values; /* Whether to escape ':' and '\' in terse tabular mode */ + bool in_editor; /* Whether running the editor - nmcli con edit' */ + bool + show_secrets; /* Whether to display secrets (both input and output): option '--show-secrets' */ + bool overview; /* Overview mode (hide default values) */ + NmcColorPalette palette; +} NmcConfig; + +typedef struct { + pid_t pid; +} NmcPagerData; + +typedef struct _NmcOutputData { + GPtrArray * + output_data; /* GPtrArray of arrays of NmcOutputField structs - accumulates data for output */ +} NmcOutputData; + +/* NmCli - main structure */ +typedef struct _NmCli { + NMClient *client; /* Pointer to NMClient of libnm */ + + NMCResultCode return_value; /* Return code of nmcli */ + GString * return_text; /* Reason text */ + + NmcPagerData pager_data; + + int timeout; /* Operation timeout */ + + NMSecretAgentSimple * secret_agent; /* Secret agent */ + GHashTable * pwds_hash; /* Hash table with passwords in passwd-file */ + struct _NMPolkitListener *pk_listener; /* polkit agent listener */ + + int should_wait; /* Semaphore indicating whether nmcli should not end or not yet */ + gboolean nowait_flag; /* '--nowait' option; used for passing to callbacks */ + gboolean mode_specified; /* Whether tabular/multiline mode was specified via '--mode' option */ + union { + const NmcConfig nmc_config; + NmcConfig nmc_config_mutable; + }; + char * required_fields; /* Required fields in output: '--fields' option */ + gboolean ask; /* Ask for missing parameters: option '--ask' */ + gboolean complete; /* Autocomplete the command line */ + gboolean editor_status_line; /* Whether to display status line in connection editor */ + gboolean + editor_save_confirmation; /* Whether to ask for confirmation on saving connections with 'autoconnect=yes' */ + + char *palette_buffer; /* Buffer with sequences for terminal-colors.d(5)-based coloring. */ +} NmCli; + +extern const NmCli *const nm_cli_global_readline; + +/* Error quark for GError domain */ +#define NMCLI_ERROR (nmcli_error_quark()) +GQuark nmcli_error_quark(void); + +extern GMainLoop *loop; + +gboolean nmc_seen_sigint(void); +void nmc_clear_sigint(void); +void nmc_set_sigquit_internal(void); +void nmc_exit(void); + +void nm_cli_spawn_pager(const NmcConfig *nmc_config, NmcPagerData *pager_data); + +void nmc_empty_output_fields(NmcOutputData *output_data); + +#define NMC_OUTPUT_DATA_DEFINE_SCOPED(out) \ + gs_unref_array GArray * out##_indices = NULL; \ + nm_auto(nmc_empty_output_fields) NmcOutputData out = { \ + .output_data = g_ptr_array_new_full(20, g_free), \ + } + +/*****************************************************************************/ + +struct _NMCCommand; + +typedef struct _NMCCommand { + const char *cmd; + void (*func)(const struct _NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); + void (*usage)(void); + bool needs_client; + bool needs_nm_running; +} NMCCommand; + +void nmc_command_func_agent(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); +void nmc_command_func_general(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); +void +nmc_command_func_networking(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); +void nmc_command_func_radio(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); +void nmc_command_func_monitor(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); +void +nmc_command_func_overview(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); +void +nmc_command_func_connection(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); +void nmc_command_func_device(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *argv); + +/*****************************************************************************/ + +#endif /* NMC_NMCLI_H */ diff --git a/src/nmcli/polkit-agent.c b/src/nmcli/polkit-agent.c new file mode 100644 index 00000000..7776d7e7 --- /dev/null +++ b/src/nmcli/polkit-agent.c @@ -0,0 +1,96 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2014 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include "polkit-agent.h" + +#include <stdio.h> +#include <sys/types.h> +#include <unistd.h> + +#include "libnmc-base/nm-polkit-listener.h" +#include "common.h" + +static char * +polkit_read_passwd(gpointer instance, + const char *action_id, + const char *message, + const char *user, + gpointer user_data) +{ + NmCli *nmc = user_data; + + g_print("%s\n", message); + g_print("(action_id: %s)\n", action_id); + + /* Ask user for polkit authorization password */ + if (user) { + return nmc_readline_echo(&nmc->nmc_config, FALSE, "password (%s): ", user); + } + return nmc_readline_echo(&nmc->nmc_config, FALSE, "password: "); +} + +static void +polkit_error(gpointer instance, const char *error, gpointer user_data) +{ + g_printerr(_("Error: polkit agent failed: %s\n"), error); +} + +gboolean +nmc_polkit_agent_init(NmCli *nmc, gboolean for_session, GError **error) +{ + NMPolkitListener *listener; + GDBusConnection * dbus_connection = NULL; + + g_return_val_if_fail(error == NULL || *error == NULL, FALSE); + + if (nmc->client && nm_client_get_dbus_connection(nmc->client)) { + dbus_connection = nm_client_get_dbus_connection(nmc->client); + listener = nm_polkit_listener_new(dbus_connection, for_session); + } else { + dbus_connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, error); + + if (!dbus_connection) { + return FALSE; + } + + listener = nm_polkit_listener_new(dbus_connection, for_session); + g_object_unref(dbus_connection); + } + + g_signal_connect(listener, + NM_POLKIT_LISTENER_SIGNAL_REQUEST_SYNC, + G_CALLBACK(polkit_read_passwd), + nmc); + g_signal_connect(listener, NM_POLKIT_LISTENER_SIGNAL_ERROR, G_CALLBACK(polkit_error), NULL); + + nmc->pk_listener = listener; + return TRUE; +} + +void +nmc_polkit_agent_fini(NmCli *nmc) +{ + if (nmc->pk_listener) { + g_clear_object(&nmc->pk_listener); + } +} + +gboolean +nmc_start_polkit_agent_start_try(NmCli *nmc) +{ + gs_free_error GError *error = NULL; + + /* We don't register polkit agent at all when running non-interactively */ + if (!nmc->ask) + return TRUE; + + if (!nmc_polkit_agent_init(nmc, FALSE, &error)) { + g_printerr(_("Warning: polkit agent initialization failed: %s\n"), error->message); + return FALSE; + } + return TRUE; +} diff --git a/src/nmcli/polkit-agent.h b/src/nmcli/polkit-agent.h new file mode 100644 index 00000000..776d0aa0 --- /dev/null +++ b/src/nmcli/polkit-agent.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2014 Red Hat, Inc. + */ + +#ifndef __NMC_POLKIT_AGENT_H__ +#define __NMC_POLKIT_AGENT_H__ + +#include "nmcli.h" + +gboolean nmc_polkit_agent_init(NmCli *nmc, gboolean for_session, GError **error); +void nmc_polkit_agent_fini(NmCli *nmc); + +gboolean nmc_start_polkit_agent_start_try(NmCli *nmc); + +#endif /* __NMC_POLKIT_AGENT_H__ */ diff --git a/src/nmcli/settings.c b/src/nmcli/settings.c new file mode 100644 index 00000000..6c93c021 --- /dev/null +++ b/src/nmcli/settings.c @@ -0,0 +1,762 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2015 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include "settings.h" + +#include <stdlib.h> +#include <arpa/inet.h> + +#include "libnm-core-aux-intern/nm-common-macros.h" + +#include "libnmc-base/nm-client-utils.h" +#include "libnmc-base/nm-vpn-helpers.h" +#include "libnmc-setting/nm-meta-setting-access.h" + +#include "utils.h" +#include "common.h" + +/*****************************************************************************/ + +static gboolean +get_answer(const char *prop, const char *value) +{ + char * tmp_str; + char * question; + gboolean answer = FALSE; + + if (value) + question = g_strdup_printf(_("Do you also want to set '%s' to '%s'? [yes]: "), prop, value); + else + question = g_strdup_printf(_("Do you also want to clear '%s'? [yes]: "), prop); + tmp_str = nmc_get_user_input(question); + if (!tmp_str || matches(tmp_str, "yes")) + answer = TRUE; + g_free(tmp_str); + g_free(question); + return answer; +} + +static void ipv4_method_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data); +static void ipv6_method_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data); + +static void +ipv4_addresses_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data) +{ + static gboolean answered = FALSE; + static gboolean answer = FALSE; + + g_signal_handlers_block_by_func(object, G_CALLBACK(ipv4_method_changed_cb), NULL); + + /* If we have some IP addresses set method to 'manual'. + * Else if the method was 'manual', change it back to 'auto'. + */ + if (nm_setting_ip_config_get_num_addresses(NM_SETTING_IP_CONFIG(object))) { + if (g_strcmp0(nm_setting_ip_config_get_method(NM_SETTING_IP_CONFIG(object)), + NM_SETTING_IP4_CONFIG_METHOD_MANUAL)) { + if (!answered) { + answered = TRUE; + answer = get_answer("ipv4.method", "manual"); + } + if (answer) + g_object_set(object, + NM_SETTING_IP_CONFIG_METHOD, + NM_SETTING_IP4_CONFIG_METHOD_MANUAL, + NULL); + } + } else { + answered = FALSE; + if (!g_strcmp0(nm_setting_ip_config_get_method(NM_SETTING_IP_CONFIG(object)), + NM_SETTING_IP4_CONFIG_METHOD_MANUAL)) + g_object_set(object, + NM_SETTING_IP_CONFIG_METHOD, + NM_SETTING_IP4_CONFIG_METHOD_AUTO, + NULL); + } + + g_signal_handlers_unblock_by_func(object, G_CALLBACK(ipv4_method_changed_cb), NULL); +} + +static void +ipv4_method_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data) +{ + static GPtrArray *old_value = NULL; + static gboolean answered = FALSE; + static gboolean answer = FALSE; + + g_signal_handlers_block_by_func(object, G_CALLBACK(ipv4_addresses_changed_cb), NULL); + + /* If method != manual, remove addresses (save them for restoring them later when method becomes 'manual' */ + if (g_strcmp0(nm_setting_ip_config_get_method(NM_SETTING_IP_CONFIG(object)), + NM_SETTING_IP4_CONFIG_METHOD_MANUAL)) { + if (nm_setting_ip_config_get_num_addresses(NM_SETTING_IP_CONFIG(object))) { + if (!answered) { + answered = TRUE; + answer = get_answer("ipv4.addresses", NULL); + } + if (answer) { + nm_clear_pointer(&old_value, g_ptr_array_unref); + g_object_get(object, NM_SETTING_IP_CONFIG_ADDRESSES, &old_value, NULL); + g_object_set(object, NM_SETTING_IP_CONFIG_ADDRESSES, NULL, NULL); + } + } + } else { + answered = FALSE; + if (old_value) { + gs_unref_ptrarray GPtrArray *v = g_steal_pointer(&old_value); + + g_object_set(object, NM_SETTING_IP_CONFIG_ADDRESSES, v, NULL); + } + } + + g_signal_handlers_unblock_by_func(object, G_CALLBACK(ipv4_addresses_changed_cb), NULL); +} + +static void +ipv6_addresses_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data) +{ + static gboolean answered = FALSE; + static gboolean answer = FALSE; + + g_signal_handlers_block_by_func(object, G_CALLBACK(ipv6_method_changed_cb), NULL); + + /* If we have some IP addresses set method to 'manual'. + * Else if the method was 'manual', change it back to 'auto'. + */ + if (nm_setting_ip_config_get_num_addresses(NM_SETTING_IP_CONFIG(object))) { + if (g_strcmp0(nm_setting_ip_config_get_method(NM_SETTING_IP_CONFIG(object)), + NM_SETTING_IP6_CONFIG_METHOD_MANUAL)) { + if (!answered) { + answered = TRUE; + answer = get_answer("ipv6.method", "manual"); + } + if (answer) + g_object_set(object, + NM_SETTING_IP_CONFIG_METHOD, + NM_SETTING_IP6_CONFIG_METHOD_MANUAL, + NULL); + } + } else { + answered = FALSE; + /* FIXME: editor_init_existing_connection() and registering handlers is not the + * right approach. + * + * This only happens to work because in nmcli's edit mode + * tends to append addresses -- instead of setting them. + * If we would change that (to behavior I'd expect), we'd get: + * + * nmcli> set ipv6.addresses fc01::1:5/68 + * Do you also want to set 'ipv6.method' to 'manual'? [yes]: y + * nmcli> set ipv6.addresses fc01::1:6/68 + * Do you also want to set 'ipv6.method' to 'manual'? [yes]: + * + * That's because nmc_setting_set_property() calls set_fcn(). With modifier '\0' + * (set), it would first clear all addresses before adding the address. Thereby + * emitting multiple property changed signals. + * + * That can be avoided by freezing/thawing the signals, but this solution + * here is ugly in general. + */ + if (!g_strcmp0(nm_setting_ip_config_get_method(NM_SETTING_IP_CONFIG(object)), + NM_SETTING_IP6_CONFIG_METHOD_MANUAL)) + g_object_set(object, + NM_SETTING_IP_CONFIG_METHOD, + NM_SETTING_IP6_CONFIG_METHOD_AUTO, + NULL); + } + + g_signal_handlers_unblock_by_func(object, G_CALLBACK(ipv6_method_changed_cb), NULL); +} + +static void +ipv6_method_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data) +{ + static GPtrArray *old_value = NULL; + static gboolean answered = FALSE; + static gboolean answer = FALSE; + + g_signal_handlers_block_by_func(object, G_CALLBACK(ipv6_addresses_changed_cb), NULL); + + /* If method != manual, remove addresses (save them for restoring them later when method becomes 'manual' */ + if (g_strcmp0(nm_setting_ip_config_get_method(NM_SETTING_IP_CONFIG(object)), + NM_SETTING_IP6_CONFIG_METHOD_MANUAL)) { + if (nm_setting_ip_config_get_num_addresses(NM_SETTING_IP_CONFIG(object))) { + if (!answered) { + answered = TRUE; + answer = get_answer("ipv6.addresses", NULL); + } + if (answer) { + nm_clear_pointer(&old_value, g_ptr_array_unref); + g_object_get(object, NM_SETTING_IP_CONFIG_ADDRESSES, &old_value, NULL); + g_object_set(object, NM_SETTING_IP_CONFIG_ADDRESSES, NULL, NULL); + } + } + } else { + answered = FALSE; + if (old_value) { + gs_unref_ptrarray GPtrArray *v = g_steal_pointer(&old_value); + + g_object_set(object, NM_SETTING_IP_CONFIG_ADDRESSES, v, NULL); + } + } + + g_signal_handlers_unblock_by_func(object, G_CALLBACK(ipv6_addresses_changed_cb), NULL); +} + +static void +proxy_method_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data) +{ + NMSettingProxyMethod method; + + method = nm_setting_proxy_get_method(NM_SETTING_PROXY(object)); + + if (method == NM_SETTING_PROXY_METHOD_NONE) { + g_object_set(object, + NM_SETTING_PROXY_PAC_URL, + NULL, + NM_SETTING_PROXY_PAC_SCRIPT, + NULL, + NULL); + } +} + +static void +wireless_band_channel_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data) +{ + const char * value = NULL, *mode; + char str[16]; + NMSettingWireless *s_wireless = NM_SETTING_WIRELESS(object); + + if (strcmp(g_param_spec_get_name(pspec), NM_SETTING_WIRELESS_BAND) == 0) { + value = nm_setting_wireless_get_band(s_wireless); + if (!value) + return; + } else { + guint32 channel = nm_setting_wireless_get_channel(s_wireless); + + if (channel == 0) + return; + + g_snprintf(str, sizeof(str), "%d", nm_setting_wireless_get_channel(s_wireless)); + value = str; + } + + mode = nm_setting_wireless_get_mode(NM_SETTING_WIRELESS(object)); + if (!mode || !*mode || strcmp(mode, NM_SETTING_WIRELESS_MODE_INFRA) == 0) { + g_print(_("Warning: %s.%s set to '%s', but it might be ignored in infrastructure mode\n"), + nm_setting_get_name(NM_SETTING(s_wireless)), + g_param_spec_get_name(pspec), + value); + } +} + +static void +connection_master_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_data) +{ + NMSettingConnection *s_con = NM_SETTING_CONNECTION(object); + NMConnection * connection = NM_CONNECTION(user_data); + NMSetting * s_ipv4, *s_ipv6; + const char * value, *tmp_str; + + value = nm_setting_connection_get_master(s_con); + if (value) { + s_ipv4 = nm_connection_get_setting_by_name(connection, NM_SETTING_IP4_CONFIG_SETTING_NAME); + s_ipv6 = nm_connection_get_setting_by_name(connection, NM_SETTING_IP6_CONFIG_SETTING_NAME); + if (s_ipv4 || s_ipv6) { + g_print(_("Warning: setting %s.%s requires removing ipv4 and ipv6 settings\n"), + nm_setting_get_name(NM_SETTING(s_con)), + g_param_spec_get_name(pspec)); + tmp_str = nmc_get_user_input(_("Do you want to remove them? [yes] ")); + if (!tmp_str || matches(tmp_str, "yes")) { + if (s_ipv4) + nm_connection_remove_setting(connection, G_OBJECT_TYPE(s_ipv4)); + if (s_ipv6) + nm_connection_remove_setting(connection, G_OBJECT_TYPE(s_ipv6)); + } + } + } +} + +void +nmc_setting_ip4_connect_handlers(NMSettingIPConfig *setting) +{ + g_return_if_fail(NM_IS_SETTING_IP4_CONFIG(setting)); + + g_signal_connect(setting, + "notify::" NM_SETTING_IP_CONFIG_ADDRESSES, + G_CALLBACK(ipv4_addresses_changed_cb), + NULL); + g_signal_connect(setting, + "notify::" NM_SETTING_IP_CONFIG_METHOD, + G_CALLBACK(ipv4_method_changed_cb), + NULL); +} + +void +nmc_setting_ip6_connect_handlers(NMSettingIPConfig *setting) +{ + g_return_if_fail(NM_IS_SETTING_IP6_CONFIG(setting)); + + g_signal_connect(setting, + "notify::" NM_SETTING_IP_CONFIG_ADDRESSES, + G_CALLBACK(ipv6_addresses_changed_cb), + NULL); + g_signal_connect(setting, + "notify::" NM_SETTING_IP_CONFIG_METHOD, + G_CALLBACK(ipv6_method_changed_cb), + NULL); +} + +void +nmc_setting_proxy_connect_handlers(NMSettingProxy *setting) +{ + g_return_if_fail(NM_IS_SETTING_PROXY(setting)); + + g_signal_connect(setting, + "notify::" NM_SETTING_PROXY_METHOD, + G_CALLBACK(proxy_method_changed_cb), + NULL); +} + +void +nmc_setting_wireless_connect_handlers(NMSettingWireless *setting) +{ + g_return_if_fail(NM_IS_SETTING_WIRELESS(setting)); + + g_signal_connect(setting, + "notify::" NM_SETTING_WIRELESS_BAND, + G_CALLBACK(wireless_band_channel_changed_cb), + NULL); + g_signal_connect(setting, + "notify::" NM_SETTING_WIRELESS_CHANNEL, + G_CALLBACK(wireless_band_channel_changed_cb), + NULL); +} + +void +nmc_setting_connection_connect_handlers(NMSettingConnection *setting, NMConnection *connection) +{ + g_return_if_fail(NM_IS_SETTING_CONNECTION(setting)); + + g_signal_connect(setting, + "notify::" NM_SETTING_CONNECTION_MASTER, + G_CALLBACK(connection_master_changed_cb), + connection); +} + +/*****************************************************************************/ + +static gboolean +_set_fcn_precheck_connection_secondaries(NMClient * client, + const char *value, + char ** value_coerced, + GError ** error) +{ + const GPtrArray * connections; + NMConnection * con; + gs_free const char **strv0 = NULL; + gs_strfreev char ** strv = NULL; + char ** iter; + gboolean modified = FALSE; + + strv0 = nm_utils_strsplit_set(value, " \t,"); + if (!strv0) + return TRUE; + + connections = nm_client_get_connections(client); + + strv = g_strdupv((char **) strv0); + for (iter = strv; *iter; iter++) { + if (nm_utils_is_uuid(*iter)) { + con = nmc_find_connection(connections, "uuid", *iter, NULL, FALSE); + if (!con) { + g_print(_("Warning: %s is not an UUID of any existing connection profile\n"), + *iter); + } else { + /* Currently, NM only supports VPN connections as secondaries */ + if (!nm_connection_is_type(con, NM_SETTING_VPN_SETTING_NAME)) { + g_set_error(error, 1, 0, _("'%s' is not a VPN connection profile"), *iter); + return FALSE; + } + } + } else { + con = nmc_find_connection(connections, "id", *iter, NULL, FALSE); + if (!con) { + g_set_error(error, 1, 0, _("'%s' is not a name of any exiting profile"), *iter); + return FALSE; + } + + /* Currently, NM only supports VPN connections as secondaries */ + if (!nm_connection_is_type(con, NM_SETTING_VPN_SETTING_NAME)) { + g_set_error(error, 1, 0, _("'%s' is not a VPN connection profile"), *iter); + return FALSE; + } + + /* translate id to uuid */ + g_free(*iter); + *iter = g_strdup(nm_connection_get_uuid(con)); + modified = TRUE; + } + } + + if (modified) + *value_coerced = g_strjoinv(" ", strv); + + return TRUE; +} + +/*****************************************************************************/ + +static void +_env_warn_fcn_handle( + const NMMetaEnvironment *environment, + gpointer environment_user_data, + NMMetaEnvWarnLevel warn_level, + const char * + fmt_l10n, /* the untranslated format string, but it is marked for translation using N_(). */ + va_list ap) +{ + NmCli * nmc = environment_user_data; + gs_free char *m = NULL; + + if (nmc->complete) + return; + + NM_PRAGMA_WARNING_DISABLE("-Wformat-nonliteral") + m = g_strdup_vprintf(_(fmt_l10n), ap); + NM_PRAGMA_WARNING_REENABLE + + switch (warn_level) { + case NM_META_ENV_WARN_LEVEL_WARN: + g_print(_("Warning: %s\n"), m); + return; + case NM_META_ENV_WARN_LEVEL_INFO: + g_print(_("Info: %s\n"), m); + return; + } + g_print(_("Error: %s\n"), m); +} + +static NMDevice *const * +_env_get_nm_devices(const NMMetaEnvironment *environment, + gpointer environment_user_data, + guint * out_len) +{ + NmCli * nmc = environment_user_data; + const GPtrArray *devices; + + nm_assert(nmc); + + /* the returned list is *not* NULL terminated. Need to + * provide and honor the out_len argument. */ + nm_assert(out_len); + + devices = nm_client_get_devices(nmc->client); + if (!devices) { + *out_len = 0; + return NULL; + } + + *out_len = devices->len; + return (NMDevice *const *) devices->pdata; +} + +static NMRemoteConnection *const * +_env_get_nm_connections(const NMMetaEnvironment *environment, + gpointer environment_user_data, + guint * out_len) +{ + NmCli * nmc = environment_user_data; + const GPtrArray *values; + + nm_assert(nmc); + + /* the returned list is *not* NULL terminated. Need to + * provide and honor the out_len argument. */ + nm_assert(out_len); + + values = nm_client_get_connections(nmc->client); + if (!values) { + *out_len = 0; + return NULL; + } + + *out_len = values->len; + return (NMRemoteConnection *const *) values->pdata; +} + +/*****************************************************************************/ + +const NMMetaEnvironment *const nmc_meta_environment = &((NMMetaEnvironment){ + .warn_fcn = _env_warn_fcn_handle, + .get_nm_devices = _env_get_nm_devices, + .get_nm_connections = _env_get_nm_connections, +}); + +static char * +get_property_val(NMSetting * setting, + const char * prop, + NMMetaAccessorGetType get_type, + gboolean show_secrets, + GError ** error) +{ + const NMMetaPropertyInfo *property_info; + + g_return_val_if_fail(NM_IS_SETTING(setting), NULL); + g_return_val_if_fail(!error || !*error, NULL); + g_return_val_if_fail( + NM_IN_SET(get_type, NM_META_ACCESSOR_GET_TYPE_PARSABLE, NM_META_ACCESSOR_GET_TYPE_PRETTY), + NULL); + + if ((property_info = nm_meta_property_info_find_by_setting(setting, prop))) { + if (property_info->property_type->get_fcn) { + NMMetaAccessorGetOutFlags out_flags = NM_META_ACCESSOR_GET_OUT_FLAGS_NONE; + char * to_free = NULL; + const char * value; + + value = property_info->property_type->get_fcn( + property_info, + nmc_meta_environment, + (gpointer) nmc_meta_environment_arg, + setting, + get_type, + show_secrets ? NM_META_ACCESSOR_GET_FLAGS_SHOW_SECRETS : 0, + &out_flags, + NULL, + (gpointer *) &to_free); + nm_assert(!out_flags); + return to_free ?: g_strdup(value); + } + } + + g_set_error_literal(error, 1, 0, _("don't know how to get the property value")); + return NULL; +} + +/* + * Generic function for getting property value. + * + * Gets property value as a string by calling specialized functions. + * + * Returns: current property value. The caller must free the returned string. + */ +char * +nmc_setting_get_property(NMSetting *setting, const char *prop, GError **error) +{ + return get_property_val(setting, prop, NM_META_ACCESSOR_GET_TYPE_PRETTY, TRUE, error); +} + +/* + * Similar to nmc_setting_get_property(), but returns the property in a string + * format that can be parsed via nmc_setting_set_property(). + */ +char * +nmc_setting_get_property_parsable(NMSetting *setting, const char *prop, GError **error) +{ + return get_property_val(setting, prop, NM_META_ACCESSOR_GET_TYPE_PARSABLE, TRUE, error); +} + +gboolean +nmc_setting_set_property(NMClient * client, + NMSetting * setting, + const char * prop, + NMMetaAccessorModifier modifier, + const char * value, + GError ** error) +{ + const NMMetaPropertyInfo *property_info; + gs_free char * value_to_free = NULL; + gboolean success; + + g_return_val_if_fail(NM_IS_SETTING(setting), FALSE); + g_return_val_if_fail(error == NULL || *error == NULL, FALSE); + g_return_val_if_fail(NM_IN_SET(modifier, + NM_META_ACCESSOR_MODIFIER_SET, + NM_META_ACCESSOR_MODIFIER_DEL, + NM_META_ACCESSOR_MODIFIER_ADD), + FALSE); + + if (!(property_info = nm_meta_property_info_find_by_setting(setting, prop))) + goto out_fail_read_only; + if (!property_info->property_type->set_fcn) + goto out_fail_read_only; + + if (modifier == NM_META_ACCESSOR_MODIFIER_DEL + && !property_info->property_type->set_supports_remove) { + /* The property is a plain property. It does not support '-'. + * + * Maybe we should fail, but just return silently. */ + return TRUE; + } + + if (value) { + switch (property_info->setting_info->general->meta_type) { + case NM_META_SETTING_TYPE_CONNECTION: + if (nm_streq(property_info->property_name, NM_SETTING_CONNECTION_SECONDARIES)) { + if (!_set_fcn_precheck_connection_secondaries(client, value, &value_to_free, error)) + return FALSE; + if (value_to_free) + value = value_to_free; + } + break; + default: + break; + } + } + + if (NM_IN_SET(modifier, NM_META_ACCESSOR_MODIFIER_ADD, NM_META_ACCESSOR_MODIFIER_DEL) + && (!value || !value[0])) { + /* nothing to do. */ + return TRUE; + } + + g_object_freeze_notify(G_OBJECT(setting)); + success = property_info->property_type->set_fcn(property_info, + nmc_meta_environment, + (gpointer) nmc_meta_environment_arg, + setting, + modifier, + value, + error); + g_object_thaw_notify(G_OBJECT(setting)); + return success; + +out_fail_read_only: + nm_utils_error_set(error, NM_UTILS_ERROR_UNKNOWN, _("the property can't be changed")); + return FALSE; +} + +/* + * Get valid property names for a setting. + * + * Returns: string array with the properties or NULL on failure. + * The returned value should be freed with g_strfreev() + */ +char ** +nmc_setting_get_valid_properties(NMSetting *setting) +{ + const NMMetaSettingInfoEditor *setting_info; + char ** valid_props; + guint i, num; + + setting_info = nm_meta_setting_info_editor_find_by_setting(setting); + + num = setting_info ? setting_info->properties_num : 0; + + valid_props = g_new(char *, num + 1); + for (i = 0; i < num; i++) + valid_props[i] = g_strdup(setting_info->properties[i]->property_name); + + valid_props[num] = NULL; + return valid_props; +} + +const char *const * +nmc_setting_get_property_allowed_values(NMSetting *setting, const char *prop, char ***out_to_free) +{ + const NMMetaPropertyInfo *property_info; + + g_return_val_if_fail(NM_IS_SETTING(setting), FALSE); + g_return_val_if_fail(out_to_free, FALSE); + + *out_to_free = NULL; + + if ((property_info = nm_meta_property_info_find_by_setting(setting, prop))) { + if (property_info->property_type->values_fcn) { + return property_info->property_type->values_fcn(property_info, out_to_free); + } else if (property_info->property_typ_data + && property_info->property_typ_data->values_static) + return property_info->property_typ_data->values_static; + } + + return NULL; +} + +/* + * Create a description string for a property. + * + * It returns a description got from property documentation, concatenated with + * nmcli specific description (if it exists). + * + * Returns: property description or NULL on failure. The caller must free the string. + */ +char * +nmc_setting_get_property_desc(NMSetting *setting, const char *prop) +{ + gs_free char * desc_to_free = NULL; + const char * setting_desc = NULL; + const char * setting_desc_title = ""; + const char * nmcli_desc = NULL; + const char * nmcli_desc_title = ""; + const char * nmcli_nl = ""; + const NMMetaPropertyInfo *property_info; + const char * desc = NULL; + + g_return_val_if_fail(NM_IS_SETTING(setting), FALSE); + + property_info = nm_meta_property_info_find_by_setting(setting, prop); + if (!property_info) + return NULL; + + if (property_info->describe_doc) { + setting_desc = _(property_info->describe_doc); + setting_desc_title = _("[NM property description]"); + } + + if (property_info->property_type->describe_fcn) { + desc = property_info->property_type->describe_fcn(property_info, &desc_to_free); + } else + desc = _(property_info->describe_message); + + if (desc) { + nmcli_desc = desc; + nmcli_desc_title = _("[nmcli specific description]"); + nmcli_nl = "\n"; + } + + return g_strdup_printf("%s\n%s\n%s%s%s%s", + setting_desc_title, + setting_desc ?: "", + nmcli_nl, + nmcli_desc_title, + nmcli_nl, + nmcli_desc ?: ""); +} + +/*****************************************************************************/ + +gboolean +setting_details(const NmcConfig *nmc_config, NMSetting *setting, const char *one_prop) +{ + const NMMetaSettingInfoEditor *setting_info; + gs_free_error GError *error = NULL; + gs_free char * fields_str = NULL; + + g_return_val_if_fail(NM_IS_SETTING(setting), FALSE); + + setting_info = nm_meta_setting_info_editor_find_by_setting(setting); + if (!setting_info) + return FALSE; + + if (one_prop) { + /* hack around setting-details being called for one setting. Must prefix the + * property name with the setting name. Later we should remove setting_details() + * and merge it into the caller. */ + fields_str = g_strdup_printf("%s.%s", nm_setting_get_name(setting), one_prop); + } + + if (!nmc_print( + nmc_config, + (gpointer[]){setting, NULL}, + NULL, + NULL, + (const NMMetaAbstractInfo *const[]){(const NMMetaAbstractInfo *) setting_info, NULL}, + fields_str, + &error)) + return FALSE; + + return TRUE; +} diff --git a/src/nmcli/settings.h b/src/nmcli/settings.h new file mode 100644 index 00000000..2dbe7607 --- /dev/null +++ b/src/nmcli/settings.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2014 Red Hat, Inc. + */ + +#ifndef NMC_SETTINGS_H +#define NMC_SETTINGS_H + +#include "libnmc-setting/nm-meta-setting-desc.h" + +#include "nmcli.h" + +/*****************************************************************************/ + +void nmc_setting_ip4_connect_handlers(NMSettingIPConfig *setting); +void nmc_setting_ip6_connect_handlers(NMSettingIPConfig *setting); +void nmc_setting_proxy_connect_handlers(NMSettingProxy *setting); +void nmc_setting_wireless_connect_handlers(NMSettingWireless *setting); +void nmc_setting_connection_connect_handlers(NMSettingConnection *setting, + NMConnection * connection); + +char **nmc_setting_get_valid_properties(NMSetting *setting); +char * nmc_setting_get_property_desc(NMSetting *setting, const char *prop); +const char *const * +nmc_setting_get_property_allowed_values(NMSetting *setting, const char *prop, char ***out_to_free); +char * nmc_setting_get_property(NMSetting *setting, const char *prop, GError **error); +char * nmc_setting_get_property_parsable(NMSetting *setting, const char *prop, GError **error); +gboolean nmc_setting_set_property(NMClient * client, + NMSetting * setting, + const char * prop, + NMMetaAccessorModifier modifier, + const char * val, + GError ** error); + +gboolean setting_details(const NmcConfig *nmc_config, NMSetting *setting, const char *one_prop); + +#endif /* NMC_SETTINGS_H */ diff --git a/src/nmcli/utils.c b/src/nmcli/utils.c new file mode 100644 index 00000000..6dd93f7b --- /dev/null +++ b/src/nmcli/utils.c @@ -0,0 +1,1821 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 Lennart Poettering + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#include "libnm-client-aux-extern/nm-default-client.h" + +#include "utils.h" + +#include <stdio.h> +#include <stdlib.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <sys/auxv.h> +#include <sys/prctl.h> + +#include "libnmc-base/nm-client-utils.h" +#include "libnmc-setting/nm-meta-setting-access.h" + +#include "common.h" +#include "nmcli.h" +#include "settings.h" + +#define ML_HEADER_WIDTH 79 +#define ML_VALUE_INDENT 40 + +/*****************************************************************************/ + +static const char * +_meta_type_nmc_generic_info_get_name(const NMMetaAbstractInfo *abstract_info, gboolean for_header) +{ + const NmcMetaGenericInfo *info = (const NmcMetaGenericInfo *) abstract_info; + + if (for_header) + return info->name_header ?: info->name; + return info->name; +} + +static const NMMetaAbstractInfo *const * +_meta_type_nmc_generic_info_get_nested(const NMMetaAbstractInfo *abstract_info, + guint * out_len, + gpointer * out_to_free) +{ + const NmcMetaGenericInfo *info; + + info = (const NmcMetaGenericInfo *) abstract_info; + + NM_SET_OUT(out_len, NM_PTRARRAY_LEN(info->nested)); + return (const NMMetaAbstractInfo *const *) info->nested; +} + +static gconstpointer +_meta_type_nmc_generic_info_get_fcn(const NMMetaAbstractInfo * abstract_info, + const NMMetaEnvironment * environment, + gpointer environment_user_data, + gpointer target, + gpointer target_data, + NMMetaAccessorGetType get_type, + NMMetaAccessorGetFlags get_flags, + NMMetaAccessorGetOutFlags *out_flags, + gboolean * out_is_default, + gpointer * out_to_free) +{ + const NmcMetaGenericInfo *info = (const NmcMetaGenericInfo *) abstract_info; + + nm_assert(!out_to_free || !*out_to_free); + nm_assert(out_flags && !*out_flags); + + if (!NM_IN_SET(get_type, + NM_META_ACCESSOR_GET_TYPE_PARSABLE, + NM_META_ACCESSOR_GET_TYPE_PRETTY, + NM_META_ACCESSOR_GET_TYPE_COLOR)) + g_return_val_if_reached(NULL); + + /* omitting the out_to_free value is only allowed for COLOR. */ + nm_assert(out_to_free || NM_IN_SET(get_type, NM_META_ACCESSOR_GET_TYPE_COLOR)); + + if (info->get_fcn) { + return info->get_fcn(environment, + environment_user_data, + info, + target, + target_data, + get_type, + get_flags, + out_flags, + out_is_default, + out_to_free); + } + + if (info->nested) { + NMC_HANDLE_COLOR(NM_META_COLOR_NONE); + return info->name; + } + + g_return_val_if_reached(NULL); +} + +const NMMetaType nmc_meta_type_generic_info = { + .type_name = "nmc-generic-info", + .get_name = _meta_type_nmc_generic_info_get_name, + .get_nested = _meta_type_nmc_generic_info_get_nested, + .get_fcn = _meta_type_nmc_generic_info_get_fcn, +}; + +/*****************************************************************************/ + +static const char * +colorize_string(const NmcConfig *nmc_config, NMMetaColor color, const char *str, char **out_to_free) +{ + const char *out = str; + + if (nmc_config && nmc_config->use_colors) { + *out_to_free = nmc_colorize(nmc_config, color, "%s", str); + out = *out_to_free; + } + + return out; +} + +/*****************************************************************************/ + +static gboolean +parse_global_arg(NmCli *nmc, const char *arg) +{ + if (nmc_arg_is_option(arg, "ask")) + nmc->ask = TRUE; + else if (nmc_arg_is_option(arg, "show-secrets")) + nmc->nmc_config_mutable.show_secrets = TRUE; + else + return FALSE; + + return TRUE; +} +/** + * next_arg: + * @nmc: NmCli data + * @*argc: pointer to left number of arguments to parse + * @***argv: pointer to const char *array of arguments still to parse + * @...: a %NULL terminated list of cmd options to match (e.g., "--active") + * + * Takes care of autocompleting options when needed and performs + * match against passed options while moving forward the pointer + * to the remaining arguments. + * + * Returns: the number of the matched option if a match is found against + * one of the custom options passed; 0 if no custom option matched and still + * some args need to be processed or autocompletion has been performed; + * -1 otherwise (no more args). + */ +int +next_arg(NmCli *nmc, int *argc, const char *const **argv, ...) +{ + va_list args; + const char *cmd_option; + + g_assert(*argc >= 0); + + do { + int cmd_option_pos = 1; + + if (*argc > 0) { + (*argc)--; + (*argv)++; + } + if (*argc == 0) + return -1; + + va_start(args, argv); + + if (nmc && nmc->complete && *argc == 1) { + while ((cmd_option = va_arg(args, const char *))) + nmc_complete_strings(**argv, cmd_option); + + if (***argv == '-') + nmc_complete_strings(**argv, "--ask", "--show-secrets"); + + va_end(args); + return 0; + } + + /* Check command dependent options first */ + while ((cmd_option = va_arg(args, const char *))) { + if (cmd_option[0] == '-' && cmd_option[1] == '-') { + /* Match as an option (leading "--" stripped) */ + if (nmc_arg_is_option(**argv, cmd_option + 2)) { + va_end(args); + return cmd_option_pos; + } + } else { + /* Match literally. */ + if (strcmp(**argv, cmd_option) == 0) { + va_end(args); + return cmd_option_pos; + } + } + cmd_option_pos++; + } + + va_end(args); + + } while (nmc && parse_global_arg(nmc, **argv)); + + return 0; +} + +gboolean +nmc_arg_is_help(const char *arg) +{ + if (!arg) + return FALSE; + if (matches(arg, "help") || (g_str_has_prefix(arg, "-") && matches(arg + 1, "help")) + || (g_str_has_prefix(arg, "--") && matches(arg + 2, "help"))) { + return TRUE; + } + return FALSE; +} + +gboolean +nmc_arg_is_option(const char *str, const char *opt_name) +{ + const char *p; + + if (!str || !*str) + return FALSE; + + if (str[0] != '-') + return FALSE; + + p = (str[1] == '-') ? str + 2 : str + 1; + + return (*p ? matches(p, opt_name) : FALSE); +} + +/* + * Helper function to parse command-line arguments. + * arg_arr: description of arguments to look for + * last: whether these are last expected arguments + * argc: command-line argument array size + * argv: command-line argument array + * error: error set on a failure (when FALSE is returned) + * Returns: TRUE on success, FALSE on an error and sets 'error' + */ +gboolean +nmc_parse_args(nmc_arg_t * arg_arr, + gboolean last, + int * argc, + const char *const **argv, + GError ** error) +{ + nmc_arg_t *p; + gboolean found; + gboolean have_mandatory; + + g_return_val_if_fail(arg_arr != NULL, FALSE); + g_return_val_if_fail(error == NULL || *error == NULL, FALSE); + + while (*argc > 0) { + found = FALSE; + + for (p = arg_arr; p->name; p++) { + if (strcmp(**argv, p->name) == 0) { + if (p->found) { + /* Don't allow repeated arguments, because the argument of the same + * name could be used later on the line for another purpose. Assume + * that's the case and return. + */ + return TRUE; + } + + if (p->has_value) { + (*argc)--; + (*argv)++; + if (!*argc) { + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: value for '%s' argument is required."), + *(*argv - 1)); + return FALSE; + } + *(p->value) = **argv; + } + p->found = TRUE; + found = TRUE; + break; + } + } + + if (!found) { + have_mandatory = TRUE; + for (p = arg_arr; p->name; p++) { + if (p->mandatory && !p->found) { + have_mandatory = FALSE; + break; + } + } + + if (have_mandatory && !last) + return TRUE; + + if (p->name) + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: Argument '%s' was expected, but '%s' provided."), + p->name, + **argv); + else + g_set_error(error, + NMCLI_ERROR, + NMC_RESULT_ERROR_USER_INPUT, + _("Error: Unexpected argument '%s'"), + **argv); + return FALSE; + } + + next_arg(NULL, argc, argv, NULL); + } + + return TRUE; +} + +/* + * Convert SSID to a hex string representation. + * Caller has to free the returned string using g_free() + */ +char * +ssid_to_hex(const char *str, gsize len) +{ + if (len == 0) + return NULL; + + return nm_utils_bin2hexstr_full(str, len, '\0', TRUE, NULL); +} + +/* + * Erase terminal line using ANSI escape sequences. + * It prints <ESC>[2K sequence to erase the line and then \r to return back + * to the beginning of the line. + * + * http://www.termsys.demon.co.uk/vtansi.htm + */ +void +nmc_terminal_erase_line(void) +{ + /* We intentionally use printf(), not g_print() here, to ensure that + * GLib doesn't mistakenly try to convert the string. + */ + printf("\33[2K\r"); + fflush(stdout); +} + +/* + * Print animated progress for an operation. + * Repeated calls of the function will show rotating slash in terminal followed + * by the string passed in 'str' argument. + */ +void +nmc_terminal_show_progress(const char *str) +{ + static int idx = 0; + const char slashes[4] = {'|', '/', '-', '\\'}; + + nmc_terminal_erase_line(); + g_print("%c %s", slashes[idx++], str ?: ""); + fflush(stdout); + if (idx == 4) + idx = 0; +} + +char * +nmc_colorize(const NmcConfig *nmc_config, NMMetaColor color, const char *fmt, ...) +{ + va_list args; + gs_free char *str = NULL; + const char * ansi_seq = NULL; + + va_start(args, fmt); + str = g_strdup_vprintf(fmt, args); + va_end(args); + + if (nmc_config->use_colors) + ansi_seq = nmc_config->palette.ansi_seq[color]; + + if (!ansi_seq) + return g_steal_pointer(&str); + + return g_strdup_printf("\33[%sm%s\33[0m", ansi_seq, str); +} + +/* + * Count characters belonging to terminal color escape sequences. + * @start points to beginning of the string, @end points to the end, + * or NULL if the string is nul-terminated. + */ +static int +nmc_count_color_escape_chars(const char *start, const char *end) +{ + int num = 0; + gboolean inside = FALSE; + + if (end == NULL) + end = start + strlen(start); + + while (start < end) { + if (*start == '\33' && *(start + 1) == '[') + inside = TRUE; + if (inside) + num++; + if (*start == 'm') + inside = FALSE; + start++; + } + return num; +} + +/* Filter out possible ANSI color escape sequences */ +/* It directly modifies the passed string @str. */ +void +nmc_filter_out_colors_inplace(char *str) +{ + const char *p1; + char * p2; + gboolean copy_char = TRUE; + + if (!str) + return; + + p1 = p2 = str; + while (*p1) { + if (*p1 == '\33' && *(p1 + 1) == '[') + copy_char = FALSE; + if (copy_char) + *p2++ = *p1; + if (!copy_char && *p1 == 'm') + copy_char = TRUE; + p1++; + } + *p2 = '\0'; +} + +/* Filter out possible ANSI color escape sequences */ +char * +nmc_filter_out_colors(const char *str) +{ + char *filtered; + + if (!str) + return NULL; + + filtered = g_strdup(str); + nmc_filter_out_colors_inplace(filtered); + return filtered; +} + +/* + * Ask user for input and return the string. + * The caller is responsible for freeing the returned string. + */ +char * +nmc_get_user_input(const char *ask_str) +{ + char * line = NULL; + size_t line_ln = 0; + ssize_t num; + + g_print("%s", ask_str); + num = getline(&line, &line_ln, stdin); + + /* Remove newline from the string */ + if (num < 1 || (num == 1 && line[0] == '\n')) { + g_free(line); + line = NULL; + } else { + if (line[num - 1] == '\n') + line[num - 1] = '\0'; + } + + return line; +} + +/* + * Split string in 'line' according to 'delim' to (argument) array. + */ +int +nmc_string_to_arg_array(const char *line, + const char *delim, + gboolean unquote, + char *** argv, + int * argc) +{ + gs_free const char **arr0 = NULL; + char ** arr; + + arr0 = nm_utils_strsplit_set(line ?: "", delim ?: " \t"); + if (!arr0) + arr = g_new0(char *, 1); + else + arr = g_strdupv((char **) arr0); + + if (unquote) { + int i = 0; + char * s; + size_t l; + const char *quotes = "\"'"; + + while (arr[i]) { + s = arr[i]; + l = strlen(s); + if (l >= 2) { + if (strchr(quotes, s[0]) && s[l - 1] == s[0]) { + memmove(s, s + 1, l - 2); + s[l - 2] = '\0'; + } + } + i++; + } + } + + *argv = arr; + *argc = g_strv_length(arr); + return 0; +} + +/* + * Convert string array (char **) to description string in the form of: + * "[string1, string2, ]" + * + * Returns: a newly allocated string. Caller must free it with g_free(). + */ +char * +nmc_util_strv_for_display(const char *const *strv, gboolean brackets) +{ + GString *result; + guint i = 0; + + result = g_string_sized_new(150); + if (brackets) + g_string_append_c(result, '['); + while (strv && strv[i]) { + if (result->len > 1) + g_string_append(result, ", "); + g_string_append(result, strv[i]); + i++; + } + if (brackets) + g_string_append_c(result, ']'); + + return g_string_free(result, FALSE); +} + +/* + * Find out how many columns an UTF-8 string occupies on the screen. + */ +int +nmc_string_screen_width(const char *start, const char *end) +{ + int width = 0; + const char *p = start; + + if (end == NULL) + end = start + strlen(start); + + while (p < end) { + width += g_unichar_iswide(g_utf8_get_char(p)) ? 2 + : g_unichar_iszerowidth(g_utf8_get_char(p)) ? 0 + : 1; + p = g_utf8_next_char(p); + } + + /* Subtract color escape sequences as they don't occupy space. */ + return width - nmc_count_color_escape_chars(start, NULL); +} + +void +set_val_str(NmcOutputField fields_array[], guint32 idx, char *value) +{ + fields_array[idx].value = value; + fields_array[idx].value_is_array = FALSE; + fields_array[idx].free_value = TRUE; +} + +void +set_val_strc(NmcOutputField fields_array[], guint32 idx, const char *value) +{ + fields_array[idx].value = (char *) value; + fields_array[idx].value_is_array = FALSE; + fields_array[idx].free_value = FALSE; +} + +void +set_val_arr(NmcOutputField fields_array[], guint32 idx, char **value) +{ + fields_array[idx].value = value; + fields_array[idx].value_is_array = TRUE; + fields_array[idx].free_value = TRUE; +} + +void +set_val_arrc(NmcOutputField fields_array[], guint32 idx, const char **value) +{ + fields_array[idx].value = (char **) value; + fields_array[idx].value_is_array = TRUE; + fields_array[idx].free_value = FALSE; +} + +void +set_val_color_all(NmcOutputField fields_array[], NMMetaColor color) +{ + int i; + + for (i = 0; fields_array[i].info; i++) { + fields_array[i].color = color; + } +} + +/* + * Free 'value' members in array of NmcOutputField + */ +void +nmc_free_output_field_values(NmcOutputField fields_array[]) +{ + NmcOutputField *iter = fields_array; + + while (iter && iter->info) { + if (iter->free_value) { + if (iter->value_is_array) + g_strfreev((char **) iter->value); + else + g_free((char *) iter->value); + iter->value = NULL; + } + iter++; + } +} + +/*****************************************************************************/ + +#define PRINT_DATA_COL_PARENT_NIL (G_MAXUINT) + +typedef struct _PrintDataCol { + union { + const struct _PrintDataCol *parent_col; + + /* while constructing the list of columns in _output_selection_append(), we keep track + * of the parent by index. The reason is, that at that point our columns are still + * tracked in a GArray which is growing (hence, the pointers are changing). + * Later, _output_selection_complete() converts the index into the actual pointer. + */ + guint _parent_idx; + }; + const NMMetaSelectionItem *selection_item; + guint self_idx; + bool is_leaf; +} PrintDataCol; + +static gboolean +_output_selection_append(GArray * cols, + guint parent_idx, + const NMMetaSelectionItem *selection_item, + GPtrArray * gfree_keeper, + GError ** error) +{ + gs_free gpointer nested_to_free = NULL; + guint col_idx; + guint i; + const NMMetaAbstractInfo *const *nested; + NMMetaSelectionResultList * selection; + + col_idx = cols->len; + + { + PrintDataCol col = { + .selection_item = selection_item, + ._parent_idx = parent_idx, + .self_idx = col_idx, + .is_leaf = TRUE, + }; + g_array_append_val(cols, col); + } + + nested = nm_meta_abstract_info_get_nested(selection_item->info, NULL, &nested_to_free); + + if (selection_item->sub_selection) { + if (!nested) { + gs_free char *allowed_fields = NULL; + + if (parent_idx != PRINT_DATA_COL_PARENT_NIL) { + const NMMetaSelectionItem *si; + + si = g_array_index(cols, PrintDataCol, parent_idx).selection_item; + allowed_fields = + nm_meta_abstract_info_get_nested_names_str(si->info, si->self_selection); + } + if (!allowed_fields) { + g_set_error(error, + NMCLI_ERROR, + 1, + _("invalid field '%s%s%s'; no such field"), + selection_item->self_selection ?: "", + selection_item->self_selection ? "." : "", + selection_item->sub_selection); + } else { + g_set_error(error, + NMCLI_ERROR, + 1, + _("invalid field '%s%s%s'; allowed fields: [%s]"), + selection_item->self_selection ?: "", + selection_item->self_selection ? "." : "", + selection_item->sub_selection, + allowed_fields); + } + return FALSE; + } + + selection = nm_meta_selection_create_parse_one(nested, + selection_item->self_selection, + selection_item->sub_selection, + FALSE, + error); + if (!selection) + return FALSE; + nm_assert(selection->num == 1); + } else if (nested) { + selection = nm_meta_selection_create_all(nested); + nm_assert(selection && selection->num > 0); + } else + selection = NULL; + + if (selection) { + g_ptr_array_add(gfree_keeper, selection); + + for (i = 0; i < selection->num; i++) { + if (!_output_selection_append(cols, col_idx, &selection->items[i], gfree_keeper, error)) + return FALSE; + } + + if (!NM_IN_SET(selection_item->info->meta_type, + &nm_meta_type_setting_info_editor, + &nmc_meta_type_generic_info)) + g_array_index(cols, PrintDataCol, col_idx).is_leaf = FALSE; + } + + return TRUE; +} + +static void +_output_selection_complete(GArray *cols) +{ + guint i; + + nm_assert(cols); + nm_assert(g_array_get_element_size(cols) == sizeof(PrintDataCol)); + + for (i = 0; i < cols->len; i++) { + PrintDataCol *col = &g_array_index(cols, PrintDataCol, i); + + if (col->_parent_idx == PRINT_DATA_COL_PARENT_NIL) + col->parent_col = NULL; + else { + nm_assert(col->_parent_idx < i); + col->parent_col = &g_array_index(cols, PrintDataCol, col->_parent_idx); + } + } +} + +/*****************************************************************************/ + +/** + * _output_selection_parse: + * @fields: a %NULL terminated array of meta-data fields + * @fields_str: a comma separated selector for fields. Nested fields + * can be specified using '.' notation. + * @out_cols: (transfer full): the result, parsed as an GArray of PrintDataCol items. + * The order of the items is as specified by @fields_str. Meta data + * items that contain nested elements are unpacked (note the is_leaf + * and parent properties of PrintDataCol). + * @out_gfree_keeper: (transfer full): an output GPtrArray that owns + * strings to which @out_cols points to. The lifetime of @out_cols + * and @out_gfree_keeper should correspond. + * @error: + * + * Returns: %TRUE on success. + */ +static gboolean +_output_selection_parse(const NMMetaAbstractInfo *const *fields, + const char * fields_str, + PrintDataCol ** out_cols_data, + guint * out_cols_len, + GPtrArray ** out_gfree_keeper, + GError ** error) +{ + NMMetaSelectionResultList *selection; + gs_unref_ptrarray GPtrArray *gfree_keeper = NULL; + gs_unref_array GArray *cols = NULL; + guint i; + + selection = nm_meta_selection_create_parse_list(fields, fields_str, FALSE, error); + if (!selection) + return FALSE; + + if (!selection->num) { + g_set_error(error, NMCLI_ERROR, 1, _("failure to select field")); + g_free(selection); + return FALSE; + } + + gfree_keeper = g_ptr_array_new_with_free_func(g_free); + g_ptr_array_add(gfree_keeper, selection); + + cols = g_array_new(FALSE, TRUE, sizeof(PrintDataCol)); + + for (i = 0; i < selection->num; i++) { + if (!_output_selection_append(cols, + PRINT_DATA_COL_PARENT_NIL, + &selection->items[i], + gfree_keeper, + error)) + return FALSE; + } + + _output_selection_complete(cols); + + *out_cols_len = cols->len; + *out_cols_data = (PrintDataCol *) g_array_free(g_steal_pointer(&cols), FALSE); + *out_gfree_keeper = g_steal_pointer(&gfree_keeper); + return TRUE; +} + +/*****************************************************************************/ + +/** + * parse_output_fields: + * @field_str: comma-separated field names to parse + * @fields_array: array of allowed fields + * @parse_groups: whether the fields can contain group prefix (e.g. general.driver) + * @group_fields: (out) (allow-none): array of field names for particular groups + * @error: (out) (allow-none): location to store error, or %NULL + * + * Parses comma separated fields in @fields_str according to @fields_array. + * When @parse_groups is %TRUE, fields can be in the form 'group.field'. Then + * @group_fields will be filled with the required field for particular group. + * @group_fields array corresponds to the returned array. + * Examples: + * @field_str: "type,name,uuid" | "ip4,general.device" | "ip4.address,ip6" + * returned array: 2 0 1 | 7 0 | 7 9 + * @group_fields: NULL NULL NULL | NULL "device" | "address" NULL + * + * Returns: #GArray with indices representing fields in @fields_array. + * Caller is responsible for freeing the array. + */ +GArray * +parse_output_fields(const char * fields_str, + const NMMetaAbstractInfo *const *fields_array, + gboolean parse_groups, + GPtrArray ** out_group_fields, + GError ** error) +{ + gs_free NMMetaSelectionResultList *selection = NULL; + GArray * array; + GPtrArray * group_fields = NULL; + guint i; + + g_return_val_if_fail(!error || !*error, NULL); + g_return_val_if_fail(!out_group_fields || !*out_group_fields, NULL); + + selection = nm_meta_selection_create_parse_list(fields_array, fields_str, TRUE, error); + if (!selection) + return NULL; + + array = g_array_sized_new(FALSE, FALSE, sizeof(int), selection->num); + if (parse_groups && out_group_fields) + group_fields = g_ptr_array_new_full(selection->num, g_free); + + for (i = 0; i < selection->num; i++) { + int idx = selection->items[i].idx; + + g_array_append_val(array, idx); + if (group_fields) + g_ptr_array_add(group_fields, g_strdup(selection->items[i].sub_selection)); + } + + if (group_fields) + *out_group_fields = group_fields; + return array; +} + +NmcOutputField * +nmc_dup_fields_array(const NMMetaAbstractInfo *const *fields, NmcOfFlags flags) +{ + NmcOutputField *row; + gsize l; + + for (l = 0; fields[l]; l++) {} + + row = g_new0(NmcOutputField, l + 1); + for (l = 0; fields[l]; l++) + row[l].info = fields[l]; + row[0].flags = flags; + return row; +} + +void +nmc_empty_output_fields(NmcOutputData *output_data) +{ + guint i; + + /* Free values in field structure */ + for (i = 0; i < output_data->output_data->len; i++) { + NmcOutputField *fld_arr = g_ptr_array_index(output_data->output_data, i); + nmc_free_output_field_values(fld_arr); + } + + /* Empty output_data array */ + if (output_data->output_data->len > 0) + g_ptr_array_remove_range(output_data->output_data, 0, output_data->output_data->len); + + g_ptr_array_unref(output_data->output_data); +} + +/*****************************************************************************/ + +typedef struct { + guint col_idx; + const PrintDataCol *col; + const char * title; + bool title_to_free : 1; + + /* whether the column should be printed. If not %TRUE, + * the column will be skipped. */ + bool to_print : 1; + + int width; +} PrintDataHeaderCell; + +typedef enum { + PRINT_DATA_CELL_FORMAT_TYPE_PLAIN = 0, + PRINT_DATA_CELL_FORMAT_TYPE_STRV, +} PrintDataCellFormatType; + +typedef struct { + guint row_idx; + const PrintDataHeaderCell *header_cell; + NMMetaColor color; + union { + const char * plain; + const char *const *strv; + } text; + PrintDataCellFormatType text_format : 3; + bool text_to_free : 1; +} PrintDataCell; + +static void +_print_data_header_cell_clear(gpointer cell_p) +{ + PrintDataHeaderCell *cell = cell_p; + + if (cell->title_to_free) { + g_free((char *) cell->title); + cell->title_to_free = FALSE; + } + cell->title = NULL; +} + +static void +_print_data_cell_clear_text(PrintDataCell *cell) +{ + switch (cell->text_format) { + case PRINT_DATA_CELL_FORMAT_TYPE_PLAIN: + if (cell->text_to_free) + g_free((char *) cell->text.plain); + cell->text.plain = NULL; + break; + case PRINT_DATA_CELL_FORMAT_TYPE_STRV: + if (cell->text_to_free) + g_strfreev((char **) cell->text.strv); + cell->text.strv = NULL; + break; + }; + cell->text_format = PRINT_DATA_CELL_FORMAT_TYPE_PLAIN; + cell->text_to_free = FALSE; +} + +static void +_print_data_cell_clear(gpointer cell_p) +{ + PrintDataCell *cell = cell_p; + + _print_data_cell_clear_text(cell); +} + +static void +_print_fill(const NmcConfig * nmc_config, + gpointer const * targets, + gpointer targets_data, + const PrintDataCol *cols, + guint cols_len, + GArray ** out_header_row, + GArray ** out_cells) +{ + GArray * cells; + GArray * header_row; + guint i_row, i_col; + guint targets_len; + NMMetaAccessorGetType text_get_type; + NMMetaAccessorGetFlags text_get_flags; + + header_row = g_array_sized_new(FALSE, TRUE, sizeof(PrintDataHeaderCell), cols_len); + g_array_set_clear_func(header_row, _print_data_header_cell_clear); + + for (i_col = 0; i_col < cols_len; i_col++) { + const PrintDataCol * col; + PrintDataHeaderCell * header_cell; + guint col_idx; + const NMMetaAbstractInfo *info; + + col = &cols[i_col]; + if (!col->is_leaf) + continue; + + info = col->selection_item->info; + + col_idx = header_row->len; + g_array_set_size(header_row, col_idx + 1); + + header_cell = &g_array_index(header_row, PrintDataHeaderCell, col_idx); + + header_cell->col_idx = col_idx; + header_cell->col = col; + + /* by default, the entire column is skipped. That is the case, + * unless we have a cell (below) which opts-in to be printed. */ + header_cell->to_print = FALSE; + + header_cell->title = nm_meta_abstract_info_get_name(info, TRUE); + if (nmc_config->multiline_output && col->parent_col + && NM_IN_SET(info->meta_type, + &nm_meta_type_property_info, + &nmc_meta_type_generic_info)) { + header_cell->title = g_strdup_printf( + "%s.%s", + nm_meta_abstract_info_get_name(col->parent_col->selection_item->info, FALSE), + header_cell->title); + header_cell->title_to_free = TRUE; + } + } + + targets_len = NM_PTRARRAY_LEN(targets); + + cells = g_array_sized_new(FALSE, TRUE, sizeof(PrintDataCell), targets_len * header_row->len); + g_array_set_clear_func(cells, _print_data_cell_clear); + g_array_set_size(cells, targets_len * header_row->len); + + text_get_type = nmc_print_output_to_accessor_get_type(nmc_config->print_output); + text_get_flags = NM_META_ACCESSOR_GET_FLAGS_ACCEPT_STRV; + if (nmc_config->show_secrets) + text_get_flags |= NM_META_ACCESSOR_GET_FLAGS_SHOW_SECRETS; + + for (i_row = 0; i_row < targets_len; i_row++) { + gpointer target = targets[i_row]; + PrintDataCell *cells_line = &g_array_index(cells, PrintDataCell, i_row * header_row->len); + + for (i_col = 0; i_col < header_row->len; i_col++) { + char * to_free = NULL; + PrintDataCell * cell = &cells_line[i_col]; + PrintDataHeaderCell * header_cell; + const NMMetaAbstractInfo *info; + NMMetaAccessorGetOutFlags text_out_flags, color_out_flags; + gconstpointer value; + gboolean is_default; + + header_cell = &g_array_index(header_row, PrintDataHeaderCell, i_col); + info = header_cell->col->selection_item->info; + + cell->row_idx = i_row; + cell->header_cell = header_cell; + + value = nm_meta_abstract_info_get(info, + nmc_meta_environment, + (gpointer) nmc_meta_environment_arg, + target, + targets_data, + text_get_type, + text_get_flags, + &text_out_flags, + &is_default, + (gpointer *) &to_free); + + nm_assert(!to_free || value == to_free); + + if ((is_default && nmc_config->overview) + || NM_FLAGS_HAS(text_out_flags, NM_META_ACCESSOR_GET_OUT_FLAGS_HIDE)) { + /* don't mark the entry for display. This is to shorten the output in case + * the property is the default value. But we only do that, if the user + * opts in to this behavior (-overview), or of the property marks itself + * eligible to be hidden. + * + * In general, only new API shall mark itself eligible to be hidden. + * Long established properties cannot, because it would be a change + * in behavior. */ + } else + header_cell->to_print = TRUE; + + if (NM_FLAGS_HAS(text_out_flags, NM_META_ACCESSOR_GET_OUT_FLAGS_STRV)) { + if (nmc_config->multiline_output) { + cell->text_format = PRINT_DATA_CELL_FORMAT_TYPE_STRV; + cell->text.strv = value; + cell->text_to_free = !!to_free; + } else { + if (value && ((const char *const *) value)[0]) { + cell->text.plain = g_strjoinv(" | ", (char **) value); + cell->text_to_free = TRUE; + } + if (to_free) + g_strfreev((char **) to_free); + } + } else { + cell->text.plain = value; + cell->text_to_free = !!to_free; + } + + cell->color = + GPOINTER_TO_INT(nm_meta_abstract_info_get(info, + nmc_meta_environment, + (gpointer) nmc_meta_environment_arg, + target, + targets_data, + NM_META_ACCESSOR_GET_TYPE_COLOR, + NM_META_ACCESSOR_GET_FLAGS_NONE, + &color_out_flags, + NULL, + NULL)); + + if (cell->text_format == PRINT_DATA_CELL_FORMAT_TYPE_PLAIN) { + if (NM_IN_SET(nmc_config->print_output, NMC_PRINT_NORMAL, NMC_PRINT_PRETTY) + && (!cell->text.plain || !cell->text.plain[0])) { + _print_data_cell_clear_text(cell); + cell->text.plain = "--"; + } else if (!cell->text.plain) + cell->text.plain = ""; + nm_assert(cell->text_format == PRINT_DATA_CELL_FORMAT_TYPE_PLAIN); + } + } + } + + for (i_col = 0; i_col < header_row->len; i_col++) { + PrintDataHeaderCell *header_cell = &g_array_index(header_row, PrintDataHeaderCell, i_col); + + header_cell->width = nmc_string_screen_width(header_cell->title, NULL); + + for (i_row = 0; i_row < targets_len; i_row++) { + const PrintDataCell *cells_line = + &g_array_index(cells, PrintDataCell, i_row * header_row->len); + const PrintDataCell *cell = &cells_line[i_col]; + const char *const * i_strv; + + switch (cell->text_format) { + case PRINT_DATA_CELL_FORMAT_TYPE_PLAIN: + header_cell->width = + NM_MAX(header_cell->width, nmc_string_screen_width(cell->text.plain, NULL)); + break; + case PRINT_DATA_CELL_FORMAT_TYPE_STRV: + i_strv = cell->text.strv; + if (i_strv) { + for (; *i_strv; i_strv++) { + header_cell->width = + NM_MAX(header_cell->width, nmc_string_screen_width(*i_strv, NULL)); + } + } + break; + } + } + + header_cell->width += 1; + } + + *out_header_row = header_row; + *out_cells = cells; +} + +static gboolean +_print_skip_column(const NmcConfig *nmc_config, const PrintDataHeaderCell *header_cell) +{ + const NMMetaSelectionItem *selection_item; + const NMMetaAbstractInfo * info; + + selection_item = header_cell->col->selection_item; + info = selection_item->info; + + if (!header_cell->to_print) + return TRUE; + + if (nmc_config->multiline_output) { + if (info->meta_type == &nm_meta_type_setting_info_editor) { + /* we skip the "name" entry for the setting in multiline output. */ + return TRUE; + } + if (info->meta_type == &nmc_meta_type_generic_info + && ((const NmcMetaGenericInfo *) info)->nested) { + /* skip the "name" entry for parent generic-infos */ + return TRUE; + } + } else { + if (NM_IN_SET(info->meta_type, + &nm_meta_type_setting_info_editor, + &nmc_meta_type_generic_info) + && selection_item->sub_selection) { + /* in tabular form, we skip the "name" entry for sections that have sub-selections. + * That is, for "ipv4.may-fail", but not for "ipv4". */ + return TRUE; + } + } + return FALSE; +} + +static void +_print_do(const NmcConfig * nmc_config, + const char * header_name_no_l10n, + guint col_len, + guint row_len, + const PrintDataHeaderCell *header_row, + const PrintDataCell * cells) +{ + int width1, width2; + int table_width = 0; + guint i_row, i_col; + nm_auto_free_gstring GString *str = NULL; + + g_assert(col_len); + + /* Main header */ + if (nmc_config->print_output == NMC_PRINT_PRETTY && header_name_no_l10n) { + gs_free char *line = NULL; + int header_width; + const char * header_name = _(header_name_no_l10n); + + header_width = nmc_string_screen_width(header_name, NULL) + 4; + + if (nmc_config->multiline_output) { + table_width = NM_MAX(header_width, ML_HEADER_WIDTH); + line = g_strnfill(ML_HEADER_WIDTH, '='); + } else { /* tabular */ + table_width = NM_MAX(table_width, header_width); + line = g_strnfill(table_width, '='); + } + + width1 = strlen(header_name); + width2 = nmc_string_screen_width(header_name, NULL); + g_print("%s\n", line); + g_print("%*s\n", (table_width + width2) / 2 + width1 - width2, header_name); + g_print("%s\n", line); + } + + str = !nmc_config->multiline_output ? g_string_sized_new(100) : NULL; + + /* print the header for the tabular form */ + if (NM_IN_SET(nmc_config->print_output, NMC_PRINT_NORMAL, NMC_PRINT_PRETTY) + && !nmc_config->multiline_output) { + for (i_col = 0; i_col < col_len; i_col++) { + const PrintDataHeaderCell *header_cell = &header_row[i_col]; + const char * title; + + if (_print_skip_column(nmc_config, header_cell)) + continue; + + title = header_cell->title; + + width1 = strlen(title); + width2 = + nmc_string_screen_width(title, NULL); /* Width of the string (in screen columns) */ + g_string_append_printf(str, + "%-*s", + (int) (header_cell->width + width1 - width2), + title); + g_string_append_c(str, ' '); /* Column separator */ + table_width += header_cell->width + width1 - width2 + 1; + } + + if (str->len) + g_string_truncate(str, str->len - 1); /* Chop off last column separator */ + g_print("%s\n", str->str); + g_string_truncate(str, 0); + + /* Print horizontal separator */ + if (nmc_config->print_output == NMC_PRINT_PRETTY) { + gs_free char *line = NULL; + + g_print("%s\n", (line = g_strnfill(table_width, '-'))); + } + } + + for (i_row = 0; i_row < row_len; i_row++) { + const PrintDataCell *current_line = &cells[i_row * col_len]; + + for (i_col = 0; i_col < col_len; i_col++) { + const PrintDataCell *cell = ¤t_line[i_col]; + const char *const * lines = NULL; + guint i_lines, lines_len; + + if (_print_skip_column(nmc_config, cell->header_cell)) + continue; + + lines_len = 0; + switch (cell->text_format) { + case PRINT_DATA_CELL_FORMAT_TYPE_PLAIN: + lines = &cell->text.plain; + lines_len = 1; + break; + case PRINT_DATA_CELL_FORMAT_TYPE_STRV: + nm_assert(nmc_config->multiline_output); + lines = cell->text.strv; + lines_len = NM_PTRARRAY_LEN(lines); + break; + } + + for (i_lines = 0; i_lines < lines_len; i_lines++) { + gs_free char *text_to_free = NULL; + const char * text; + + text = colorize_string(nmc_config, cell->color, lines[i_lines], &text_to_free); + if (nmc_config->multiline_output) { + gs_free char *prefix = NULL; + + if (cell->text_format == PRINT_DATA_CELL_FORMAT_TYPE_STRV) + prefix = g_strdup_printf("%s[%u]:", cell->header_cell->title, i_lines + 1); + else + prefix = g_strdup_printf("%s:", cell->header_cell->title); + width1 = strlen(prefix); + width2 = nmc_string_screen_width(prefix, NULL); + g_print("%-*s%s\n", + (int) (nmc_config->print_output == NMC_PRINT_TERSE + ? 0 + : ML_VALUE_INDENT + width1 - width2), + prefix, + text); + } else { + nm_assert(str); + if (nmc_config->print_output == NMC_PRINT_TERSE) { + if (nmc_config->escape_values) { + const char *p = text; + while (*p) { + if (*p == ':' || *p == '\\') + g_string_append_c(str, '\\'); /* Escaping by '\' */ + g_string_append_c(str, *p); + p++; + } + } else + g_string_append_printf(str, "%s", text); + g_string_append_c(str, ':'); /* Column separator */ + } else { + const PrintDataHeaderCell *header_cell = &header_row[i_col]; + + width1 = strlen(text); + width2 = nmc_string_screen_width( + text, + NULL); /* Width of the string (in screen columns) */ + g_string_append_printf(str, + "%-*s", + (int) (header_cell->width + width1 - width2), + text); + g_string_append_c(str, ' '); /* Column separator */ + table_width += header_cell->width + width1 - width2 + 1; + } + } + } + } + + if (!nmc_config->multiline_output) { + if (str->len) + g_string_truncate(str, str->len - 1); /* Chop off last column separator */ + g_print("%s\n", str->str); + + g_string_truncate(str, 0); + } + + if (nmc_config->print_output == NMC_PRINT_PRETTY && nmc_config->multiline_output) { + gs_free char *line = NULL; + + g_print("%s\n", (line = g_strnfill(ML_HEADER_WIDTH, '-'))); + } + } +} + +gboolean +nmc_print(const NmcConfig * nmc_config, + gpointer const * targets, + gpointer targets_data, + const char * header_name_no_l10n, + const NMMetaAbstractInfo *const *fields, + const char * fields_str, + GError ** error) +{ + gs_unref_ptrarray GPtrArray *gfree_keeper = NULL; + gs_free PrintDataCol *cols_data = NULL; + guint cols_len; + gs_unref_array GArray *header_row = NULL; + gs_unref_array GArray *cells = NULL; + + if (!_output_selection_parse(fields, fields_str, &cols_data, &cols_len, &gfree_keeper, error)) + return FALSE; + + _print_fill(nmc_config, targets, targets_data, cols_data, cols_len, &header_row, &cells); + + _print_do(nmc_config, + header_name_no_l10n, + header_row->len, + cells->len / header_row->len, + &g_array_index(header_row, PrintDataHeaderCell, 0), + &g_array_index(cells, PrintDataCell, 0)); + + return TRUE; +} + +/*****************************************************************************/ + +static void +pager_fallback(void) +{ + char buf[64]; + int rb; + int errsv; + + do { + rb = read(STDIN_FILENO, buf, sizeof(buf)); + if (rb == -1) { + errsv = errno; + if (errsv == EINTR) + continue; + g_printerr(_("Error reading nmcli output: %s\n"), nm_strerror_native(errsv)); + _exit(EXIT_FAILURE); + } + if (write(STDOUT_FILENO, buf, rb) == -1) { + errsv = errno; + g_printerr(_("Error writing nmcli output: %s\n"), nm_strerror_native(errsv)); + _exit(EXIT_FAILURE); + } + } while (rb > 0); + + _exit(EXIT_SUCCESS); +} + +pid_t +nmc_terminal_spawn_pager(const NmcConfig *nmc_config) +{ + const char *pager = getenv("PAGER"); + pid_t pager_pid; + pid_t parent_pid; + int fd[2]; + int errsv; + + if (nmc_config->in_editor || nmc_config->print_output == NMC_PRINT_TERSE + || !nmc_config->use_colors || g_strcmp0(pager, "") == 0 || getauxval(AT_SECURE)) + return 0; + + if (pipe(fd) == -1) { + errsv = errno; + g_printerr(_("Failed to create pager pipe: %s\n"), nm_strerror_native(errsv)); + return 0; + } + + parent_pid = getpid(); + + pager_pid = fork(); + if (pager_pid == -1) { + errsv = errno; + g_printerr(_("Failed to fork pager: %s\n"), nm_strerror_native(errsv)); + nm_close(fd[0]); + nm_close(fd[1]); + return 0; + } + + /* In the child start the pager */ + if (pager_pid == 0) { + dup2(fd[0], STDIN_FILENO); + nm_close(fd[0]); + nm_close(fd[1]); + + setenv("LESS", "FRSXMK", 1); + setenv("LESSCHARSET", "utf-8", 1); + + /* Make sure the pager goes away when the parent dies */ + if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) + _exit(EXIT_FAILURE); + + /* Check whether our parent died before we were able + * to set the death signal */ + if (getppid() != parent_pid) + _exit(EXIT_SUCCESS); + + if (pager) { + execlp(pager, pager, NULL); + execl("/bin/sh", "sh", "-c", pager, NULL); + } + + /* Debian's alternatives command for pagers is + * called 'pager'. Note that we do not call + * sensible-pagers here, since that is just a + * shell script that implements a logic that + * is similar to this one anyway, but is + * Debian-specific. */ + execlp("pager", "pager", NULL); + + execlp("less", "less", NULL); + execlp("more", "more", NULL); + + pager_fallback(); + /* not reached */ + } + + /* Return in the parent */ + if (dup2(fd[1], STDOUT_FILENO) < 0) { + errsv = errno; + g_printerr(_("Failed to duplicate pager pipe: %s\n"), nm_strerror_native(errsv)); + } + if (dup2(fd[1], STDERR_FILENO) < 0) { + errsv = errno; + g_printerr(_("Failed to duplicate pager pipe: %s\n"), nm_strerror_native(errsv)); + } + + nm_close(fd[0]); + nm_close(fd[1]); + return pager_pid; +} + +/*****************************************************************************/ + +static const char * +get_value_to_print(const NmcConfig * nmc_config, + const NmcOutputField *field, + gboolean field_name, + const char * not_set_str, + char ** out_to_free) +{ + gboolean is_array = field->value_is_array; + const char * value; + const char * out; + gs_free char *free_value = NULL; + + nm_assert(out_to_free && !*out_to_free); + + if (field_name) + value = nm_meta_abstract_info_get_name(field->info, FALSE); + else { + value = field->value ? (is_array ? (free_value = g_strjoinv(" | ", (char **) field->value)) + : (*((const char *) field->value)) ? field->value + : not_set_str) + : not_set_str; + } + + /* colorize the value */ + out = colorize_string(nmc_config, field->color, value, out_to_free); + + if (out && out == free_value) { + nm_assert(!*out_to_free); + *out_to_free = g_steal_pointer(&free_value); + } + + return out; +} + +/* + * Print both headers or values of 'field_values' array. + * Entries to print and their order are specified via indices in + * 'nmc->indices' array. + * Various flags influencing the output of fields are set up in the first item + * of 'field_values' array. + */ +void +print_required_fields(const NmcConfig * nmc_config, + NmcPagerData * pager_data, + NmcOfFlags of_flags, + const GArray * indices, + const char * header_name, + int indent, + const NmcOutputField *field_values) +{ + nm_auto_free_gstring GString *str = NULL; + int width1, width2; + int table_width = 0; + const char * not_set_str; + int i; + gboolean main_header_add = of_flags & NMC_OF_FLAG_MAIN_HEADER_ADD; + gboolean main_header_only = of_flags & NMC_OF_FLAG_MAIN_HEADER_ONLY; + gboolean field_names = of_flags & NMC_OF_FLAG_FIELD_NAMES; + gboolean section_prefix = of_flags & NMC_OF_FLAG_SECTION_PREFIX; + + nm_cli_spawn_pager(nmc_config, pager_data); + + /* --- Main header --- */ + if (nmc_config->print_output == NMC_PRINT_PRETTY && (main_header_add || main_header_only)) { + gs_free char *line = NULL; + int header_width; + + header_width = nmc_string_screen_width(header_name, NULL) + 4; + + if (nmc_config->multiline_output) { + table_width = NM_MAX(header_width, ML_HEADER_WIDTH); + line = g_strnfill(ML_HEADER_WIDTH, '='); + } else { /* tabular */ + table_width = NM_MAX(table_width, header_width); + line = g_strnfill(table_width, '='); + } + + width1 = strlen(header_name); + width2 = nmc_string_screen_width(header_name, NULL); + g_print("%s\n", line); + g_print("%*s\n", (table_width + width2) / 2 + width1 - width2, header_name); + g_print("%s\n", line); + } + + if (main_header_only) + return; + + /* No field headers are printed in terse mode nor for multiline output */ + if ((nmc_config->print_output == NMC_PRINT_TERSE || nmc_config->multiline_output) + && field_names) + return; + + /* Don't replace empty strings in terse mode */ + not_set_str = nmc_config->print_output == NMC_PRINT_TERSE ? "" : "--"; + + if (nmc_config->multiline_output) { + for (i = 0; i < indices->len; i++) { + int idx = g_array_index(indices, int, i); + gboolean is_array = field_values[idx].value_is_array; + + /* section prefix can't be an array */ + g_assert(!is_array || !section_prefix || idx != 0); + + if (section_prefix && idx == 0) /* The first field is section prefix */ + continue; + + if (is_array) { + gs_free char *val_to_free = NULL; + const char ** p, *val, *print_val; + int j; + + /* value is a null-terminated string array */ + + for (p = (const char **) field_values[idx].value, j = 1; p && *p; p++, j++) { + gs_free char *tmp = NULL; + + val = *p ?: not_set_str; + print_val = + colorize_string(nmc_config, field_values[idx].color, val, &val_to_free); + tmp = g_strdup_printf( + "%s%s%s[%d]:", + section_prefix ? (const char *) field_values[0].value : "", + section_prefix ? "." : "", + nm_meta_abstract_info_get_name(field_values[idx].info, FALSE), + j); + width1 = strlen(tmp); + width2 = nmc_string_screen_width(tmp, NULL); + g_print("%-*s%s\n", + (int) (nmc_config->print_output == NMC_PRINT_TERSE + ? 0 + : ML_VALUE_INDENT + width1 - width2), + tmp, + print_val); + } + } else { + gs_free char *val_to_free = NULL; + gs_free char *tmp = NULL; + const char * hdr_name = (const char *) field_values[0].value; + const char * val = (const char *) field_values[idx].value; + const char * print_val; + + /* value is a string */ + + val = val && *val ? val : not_set_str; + print_val = colorize_string(nmc_config, field_values[idx].color, val, &val_to_free); + tmp = + g_strdup_printf("%s%s%s:", + section_prefix ? hdr_name : "", + section_prefix ? "." : "", + nm_meta_abstract_info_get_name(field_values[idx].info, FALSE)); + width1 = strlen(tmp); + width2 = nmc_string_screen_width(tmp, NULL); + g_print("%-*s%s\n", + (int) (nmc_config->print_output == NMC_PRINT_TERSE + ? 0 + : ML_VALUE_INDENT + width1 - width2), + tmp, + print_val); + } + } + if (nmc_config->print_output == NMC_PRINT_PRETTY) { + gs_free char *line = NULL; + + g_print("%s\n", (line = g_strnfill(ML_HEADER_WIDTH, '-'))); + } + + return; + } + + /* --- Tabular mode: each line = one object --- */ + + str = g_string_new(NULL); + + for (i = 0; i < indices->len; i++) { + gs_free char *val_to_free = NULL; + int idx; + const char * value; + + idx = g_array_index(indices, int, i); + + value = get_value_to_print(nmc_config, + (NmcOutputField *) field_values + idx, + field_names, + not_set_str, + &val_to_free); + + if (nmc_config->print_output == NMC_PRINT_TERSE) { + if (nmc_config->escape_values) { + const char *p = value; + while (*p) { + if (*p == ':' || *p == '\\') + g_string_append_c(str, '\\'); /* Escaping by '\' */ + g_string_append_c(str, *p); + p++; + } + } else + g_string_append_printf(str, "%s", value); + g_string_append_c(str, ':'); /* Column separator */ + } else { + width1 = strlen(value); + width2 = + nmc_string_screen_width(value, NULL); /* Width of the string (in screen columns) */ + g_string_append_printf(str, + "%-*s", + field_values[idx].width + width1 - width2, + strlen(value) > 0 ? value : not_set_str); + g_string_append_c(str, ' '); /* Column separator */ + table_width += field_values[idx].width + width1 - width2 + 1; + } + } + + /* Print actual values */ + if (str->len > 0) { + g_string_truncate(str, str->len - 1); /* Chop off last column separator */ + if (indent > 0) { + gs_free char *indent_str = NULL; + + g_string_prepend(str, (indent_str = g_strnfill(indent, ' '))); + } + + g_print("%s\n", str->str); + + /* Print horizontal separator */ + if (nmc_config->print_output == NMC_PRINT_PRETTY && field_names) { + gs_free char *line = NULL; + + g_print("%s\n", (line = g_strnfill(table_width, '-'))); + } + } +} + +void +print_data_prepare_width(GPtrArray *output_data) +{ + int i, j; + size_t len; + NmcOutputField *row; + int num_fields = 0; + + if (!output_data || output_data->len < 1) + return; + + /* How many fields? */ + row = g_ptr_array_index(output_data, 0); + while (row->info) { + num_fields++; + row++; + } + + /* Find out maximal string lengths */ + for (i = 0; i < num_fields; i++) { + size_t max_width = 0; + for (j = 0; j < output_data->len; j++) { + gboolean field_names; + gs_free char *val_to_free = NULL; + const char * value; + + row = g_ptr_array_index(output_data, j); + field_names = row[0].flags & NMC_OF_FLAG_FIELD_NAMES; + value = get_value_to_print(NULL, row + i, field_names, "--", &val_to_free); + len = nmc_string_screen_width(value, NULL); + max_width = len > max_width ? len : max_width; + } + for (j = 0; j < output_data->len; j++) { + row = g_ptr_array_index(output_data, j); + row[i].width = max_width + 1; + } + } +} + +void +print_data(const NmcConfig * nmc_config, + NmcPagerData * pager_data, + const GArray * indices, + const char * header_name, + int indent, + const NmcOutputData *out) +{ + guint i; + + for (i = 0; i < out->output_data->len; i++) { + const NmcOutputField *field_values = g_ptr_array_index(out->output_data, i); + + print_required_fields(nmc_config, + pager_data, + field_values[0].flags, + indices, + header_name, + indent, + field_values); + } +} diff --git a/src/nmcli/utils.h b/src/nmcli/utils.h new file mode 100644 index 00000000..aadaab67 --- /dev/null +++ b/src/nmcli/utils.h @@ -0,0 +1,372 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2010 - 2018 Red Hat, Inc. + */ + +#ifndef NMC_UTILS_H +#define NMC_UTILS_H + +#include "nmcli.h" + +/* === Types === */ + +typedef struct { + const char * name; + gboolean has_value; + const char **value; + gboolean mandatory; + gboolean found; +} nmc_arg_t; + +/* === Functions === */ +int next_arg(NmCli *nmc, int *argc, const char *const **argv, ...); +gboolean nmc_arg_is_help(const char *arg); +gboolean nmc_arg_is_option(const char *arg, const char *opt_name); +gboolean nmc_parse_args(nmc_arg_t * arg_arr, + gboolean last, + int * argc, + const char *const **argv, + GError ** error); +char * ssid_to_hex(const char *str, gsize len); +void nmc_terminal_erase_line(void); +void nmc_terminal_show_progress(const char *str); +pid_t nmc_terminal_spawn_pager(const NmcConfig *nmc_config); +char * nmc_colorize(const NmcConfig *nmc_config, NMMetaColor color, const char *fmt, ...) + _nm_printf(3, 4); +void nmc_filter_out_colors_inplace(char *str); +char *nmc_filter_out_colors(const char *str); +char *nmc_get_user_input(const char *ask_str); +int nmc_string_to_arg_array(const char *line, + const char *delim, + gboolean unquote, + char *** argv, + int * argc); +char *nmc_util_strv_for_display(const char *const *strv, gboolean brackets); +int nmc_string_screen_width(const char *start, const char *end); +void set_val_str(NmcOutputField fields_array[], guint32 index, char *value); +void set_val_strc(NmcOutputField fields_array[], guint32 index, const char *value); +void set_val_arr(NmcOutputField fields_array[], guint32 index, char **value); +void set_val_arrc(NmcOutputField fields_array[], guint32 index, const char **value); +void set_val_color_all(NmcOutputField fields_array[], NMMetaColor color); +void nmc_free_output_field_values(NmcOutputField fields_array[]); + +GArray * parse_output_fields(const char * fields_str, + const NMMetaAbstractInfo *const *fields_array, + gboolean parse_groups, + GPtrArray ** group_fields, + GError ** error); +NmcOutputField *nmc_dup_fields_array(const NMMetaAbstractInfo *const *fields, NmcOfFlags flags); +void nmc_empty_output_fields(NmcOutputData *output_data); +void print_required_fields(const NmcConfig * nmc_config, + NmcPagerData * pager_data, + NmcOfFlags of_flags, + const GArray * indices, + const char * header_name, + int indent, + const NmcOutputField *field_values); +void print_data_prepare_width(GPtrArray *output_data); +void print_data(const NmcConfig * nmc_config, + NmcPagerData * pager_data, + const GArray * indices, + const char * header_name, + int indent, + const NmcOutputData *out); + +/*****************************************************************************/ + +extern const NMMetaEnvironment *const nmc_meta_environment; +extern const NmCli *const nmc_meta_environment_arg; + +typedef enum { + + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_RUNNING = 0, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_VERSION, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_STATE, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_STARTUP, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_CONNECTIVITY, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_NETWORKING, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIFI_HW, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIFI, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WWAN_HW, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WWAN, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIMAX_HW, + NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_WIMAX, + _NMC_GENERIC_INFO_TYPE_GENERAL_STATUS_NUM, + + NMC_GENERIC_INFO_TYPE_GENERAL_PERMISSIONS_PERMISSION = 0, + NMC_GENERIC_INFO_TYPE_GENERAL_PERMISSIONS_VALUE, + _NMC_GENERIC_INFO_TYPE_GENERAL_PERMISSIONS_NUM, + + NMC_GENERIC_INFO_TYPE_GENERAL_LOGGING_LEVEL = 0, + NMC_GENERIC_INFO_TYPE_GENERAL_LOGGING_DOMAINS, + _NMC_GENERIC_INFO_TYPE_GENERAL_LOGGING_NUM, + + NMC_GENERIC_INFO_TYPE_IP4_CONFIG_ADDRESS = 0, + NMC_GENERIC_INFO_TYPE_IP4_CONFIG_GATEWAY, + NMC_GENERIC_INFO_TYPE_IP4_CONFIG_ROUTE, + NMC_GENERIC_INFO_TYPE_IP4_CONFIG_DNS, + NMC_GENERIC_INFO_TYPE_IP4_CONFIG_DOMAIN, + NMC_GENERIC_INFO_TYPE_IP4_CONFIG_SEARCHES, + NMC_GENERIC_INFO_TYPE_IP4_CONFIG_WINS, + _NMC_GENERIC_INFO_TYPE_IP4_CONFIG_NUM, + + NMC_GENERIC_INFO_TYPE_IP6_CONFIG_ADDRESS = 0, + NMC_GENERIC_INFO_TYPE_IP6_CONFIG_GATEWAY, + NMC_GENERIC_INFO_TYPE_IP6_CONFIG_ROUTE, + NMC_GENERIC_INFO_TYPE_IP6_CONFIG_DNS, + NMC_GENERIC_INFO_TYPE_IP6_CONFIG_DOMAIN, + NMC_GENERIC_INFO_TYPE_IP6_CONFIG_SEARCHES, + _NMC_GENERIC_INFO_TYPE_IP6_CONFIG_NUM, + + NMC_GENERIC_INFO_TYPE_DHCP_CONFIG_OPTION = 0, + _NMC_GENERIC_INFO_TYPE_DHCP_CONFIG_NUM, + + NMC_GENERIC_INFO_TYPE_CON_SHOW_NAME = 0, + NMC_GENERIC_INFO_TYPE_CON_SHOW_UUID, + NMC_GENERIC_INFO_TYPE_CON_SHOW_TYPE, + NMC_GENERIC_INFO_TYPE_CON_SHOW_TIMESTAMP, + NMC_GENERIC_INFO_TYPE_CON_SHOW_TIMESTAMP_REAL, + NMC_GENERIC_INFO_TYPE_CON_SHOW_AUTOCONNECT, + NMC_GENERIC_INFO_TYPE_CON_SHOW_AUTOCONNECT_PRIORITY, + NMC_GENERIC_INFO_TYPE_CON_SHOW_READONLY, + NMC_GENERIC_INFO_TYPE_CON_SHOW_DBUS_PATH, + NMC_GENERIC_INFO_TYPE_CON_SHOW_ACTIVE, + NMC_GENERIC_INFO_TYPE_CON_SHOW_DEVICE, + NMC_GENERIC_INFO_TYPE_CON_SHOW_STATE, + NMC_GENERIC_INFO_TYPE_CON_SHOW_ACTIVE_PATH, + NMC_GENERIC_INFO_TYPE_CON_SHOW_SLAVE, + NMC_GENERIC_INFO_TYPE_CON_SHOW_FILENAME, + _NMC_GENERIC_INFO_TYPE_CON_SHOW_NUM, + + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_NAME = 0, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_UUID, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEVICES, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_IP_IFACE, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_STATE, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEFAULT, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DEFAULT6, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_SPEC_OBJECT, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_VPN, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_DBUS_PATH, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_CON_PATH, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_ZONE, + NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_MASTER_PATH, + _NMC_GENERIC_INFO_TYPE_CON_ACTIVE_GENERAL_NUM, + + NMC_GENERIC_INFO_TYPE_CON_VPN_TYPE = 0, + NMC_GENERIC_INFO_TYPE_CON_VPN_USERNAME, + NMC_GENERIC_INFO_TYPE_CON_VPN_GATEWAY, + NMC_GENERIC_INFO_TYPE_CON_VPN_BANNER, + NMC_GENERIC_INFO_TYPE_CON_VPN_VPN_STATE, + NMC_GENERIC_INFO_TYPE_CON_VPN_CFG, + _NMC_GENERIC_INFO_TYPE_CON_ACTIVE_VPN_NUM, + + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_DEVICE = 0, + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_TYPE, + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_STATE, + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_IP4_CONNECTIVITY, + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_IP6_CONNECTIVITY, + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_DBUS_PATH, + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CONNECTION, + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CON_UUID, + NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_CON_PATH, + _NMC_GENERIC_INFO_TYPE_DEVICE_STATUS_NUM, + + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DEVICE = 0, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_TYPE, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_TYPE, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DBUS_PATH, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_VENDOR, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PRODUCT, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DRIVER, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_DRIVER_VERSION, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_FIRMWARE_VERSION, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_HWADDR, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_MTU, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_STATE, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_REASON, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP4_CONNECTIVITY, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP6_CONNECTIVITY, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_UDI, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PATH, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IP_IFACE, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_IS_SOFTWARE, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_MANAGED, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_AUTOCONNECT, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_FIRMWARE_MISSING, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NM_PLUGIN_MISSING, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_PHYS_PORT_ID, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CONNECTION, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CON_UUID, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_CON_PATH, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_METERED, + _NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_GENERAL_NUM, + + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CONNECTIONS_AVAILABLE_CONNECTION_PATHS = 0, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CONNECTIONS_AVAILABLE_CONNECTIONS, + _NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CONNECTIONS_NUM, + + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_CARRIER_DETECT = 0, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_SPEED, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_IS_SOFTWARE, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_SRIOV, + _NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_CAPABILITIES_NUM, + + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIRED_PROPERTIES_CARRIER = 0, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIRED_PROPERTIES_S390_SUBCHANNELS, + _NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIRED_PROPERTIES_NUM, + + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WEP = 0, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WPA, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_WPA2, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_TKIP, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_CCMP, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_AP, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_ADHOC, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_2GHZ, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_5GHZ, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_MESH, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_IBSS_RSN, + _NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_WIFI_PROPERTIES_NUM, + + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_UP = 0, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_LOWER_UP, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_CARRIER, + NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_PROMISC, + _NMC_GENERIC_INFO_TYPE_DEVICE_DETAIL_INTERFACE_FLAGS_NUM, + +} NmcGenericInfoType; + +#define NMC_HANDLE_COLOR(color) \ + G_STMT_START \ + { \ + if (get_type == NM_META_ACCESSOR_GET_TYPE_COLOR) \ + return GINT_TO_POINTER(color); \ + } \ + G_STMT_END + +struct _NmcMetaGenericInfo { + union { + NMObjBaseInst parent; + const NMMetaType *meta_type; + }; + NmcGenericInfoType info_type; + const char * name; + const char * name_header; + const NmcMetaGenericInfo *const *nested; + +#define NMC_META_GENERIC_INFO_GET_FCN_ARGS \ + const NMMetaEnvironment *environment, gpointer environment_user_data, \ + const NmcMetaGenericInfo *info, gpointer target, gpointer target_data, \ + NMMetaAccessorGetType get_type, NMMetaAccessorGetFlags get_flags, \ + NMMetaAccessorGetOutFlags *out_flags, gboolean *out_is_default, gpointer *out_to_free + + gconstpointer (*get_fcn)(NMC_META_GENERIC_INFO_GET_FCN_ARGS); +}; + +#define NMC_META_GENERIC(n, ...) \ + (&((NmcMetaGenericInfo){.meta_type = &nmc_meta_type_generic_info, .name = n, __VA_ARGS__})) + +#define NMC_META_GENERIC_WITH_NESTED(n, nest, ...) \ + NMC_META_GENERIC(n, .nested = (nest), __VA_ARGS__) + +#define NMC_META_GENERIC_GROUP(_group_name, _nested, _name_header) \ + ((const NMMetaAbstractInfo *const *) ((const NmcMetaGenericInfo *const[]){ \ + NMC_META_GENERIC_WITH_NESTED(_group_name, _nested, .name_header = _name_header), \ + NULL, \ + })) + +static inline const char * +nmc_meta_generic_get_str_i18n(const char *s, NMMetaAccessorGetType get_type) +{ + if (!NM_IN_SET(get_type, NM_META_ACCESSOR_GET_TYPE_PRETTY, NM_META_ACCESSOR_GET_TYPE_PARSABLE)) + g_return_val_if_reached(NULL); + + if (!s) + return NULL; + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) + return gettext(s); + return s; +} + +static inline const char * +nmc_meta_generic_get_str_i18n_null(const char *s, NMMetaAccessorGetType get_type) +{ + if (get_type == NM_META_ACCESSOR_GET_TYPE_PARSABLE) { + /* in parsable mode, return NULL. That is useful if @s is a pretty string + * to describe a missing value (like "(unknown)"). We don't want to print + * that for parsable mode. */ + return NULL; + } + return nmc_meta_generic_get_str_i18n(s, get_type); +} + +static inline const char * +nmc_meta_generic_get_unknown(NMMetaAccessorGetType get_type) +{ + return nmc_meta_generic_get_str_i18n_null(N_("(unknown)"), get_type); +} + +static inline const char * +nmc_meta_generic_get_bool(gboolean val, NMMetaAccessorGetType get_type) +{ + return nmc_meta_generic_get_str_i18n(val ? N_("yes") : N_("no"), get_type); +} + +static inline const char * +nmc_meta_generic_get_bool_onoff(gboolean val, NMMetaAccessorGetType get_type) +{ + return nmc_meta_generic_get_str_i18n(val ? N_("on") : N_("off"), get_type); +} + +typedef enum { + NMC_META_GENERIC_GET_ENUM_TYPE_PARENTHESES, + NMC_META_GENERIC_GET_ENUM_TYPE_DASH, +} NmcMetaGenericGetEnumType; + +static inline char * +nmc_meta_generic_get_enum_with_detail(NmcMetaGenericGetEnumType get_enum_type, + gint64 enum_val, + const char * str_val, + NMMetaAccessorGetType get_type) +{ + if (!NM_IN_SET(get_type, NM_META_ACCESSOR_GET_TYPE_PRETTY, NM_META_ACCESSOR_GET_TYPE_PARSABLE)) + g_return_val_if_reached(NULL); + + if (!str_val) { + /* Pass %NULL for only printing the numeric value. */ + return g_strdup_printf("%lld", (long long) enum_val); + } + + switch (get_enum_type) { + case NMC_META_GENERIC_GET_ENUM_TYPE_PARENTHESES: + /* note that this function will always print "$NUM ($NICK)", also in PARSABLE + * mode. That might not be desired, but it's done for certain properties to preserve + * previous behavior. */ + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) + return g_strdup_printf(_("%lld (%s)"), (long long) enum_val, gettext(str_val)); + return g_strdup_printf("%lld (%s)", (long long) enum_val, str_val); + case NMC_META_GENERIC_GET_ENUM_TYPE_DASH: + /* note that this function will always print "$NUM ($NICK)", also in PARSABLE + * mode. That might not be desired, but it's done for certain properties to preserve + * previous behavior. */ + if (get_type == NM_META_ACCESSOR_GET_TYPE_PRETTY) + return g_strdup_printf(_("%lld - %s"), (long long) enum_val, gettext(str_val)); + return g_strdup_printf("%lld - %s", (long long) enum_val, str_val); + } + g_return_val_if_reached(NULL); +} + +/*****************************************************************************/ + +gboolean nmc_print(const NmcConfig * nmc_config, + gpointer const * targets, + gpointer targets_data, + const char * header_name_no_l10n, + const NMMetaAbstractInfo *const *fields, + const char * fields_str, + GError ** error); + +/*****************************************************************************/ + +#endif /* NMC_UTILS_H */ |