test-client: merge branch 'th/test-client-fixes'

https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/1528
This commit is contained in:
Thomas Haller 2023-02-08 10:50:39 +01:00
commit df228a5f8d
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
21 changed files with 1531 additions and 1175 deletions

View file

@ -53,10 +53,10 @@ variables:
#
# This is done by running `ci-fairy generate-template` and possibly bumping
# ".default_tag".
FEDORA_TAG: '2023-01-18.0-296fbfd97862'
UBUNTU_TAG: '2023-01-18.0-08fb4e6eb861'
DEBIAN_TAG: '2023-01-18.0-08fb4e6eb861'
CENTOS_TAG: '2023-01-18.0-296fbfd97862'
FEDORA_TAG: '2023-01-18.0-82ad875db2dc'
UBUNTU_TAG: '2023-01-18.0-1218be1cbc9d'
DEBIAN_TAG: '2023-01-18.0-1218be1cbc9d'
CENTOS_TAG: '2023-01-18.0-82ad875db2dc'
ALPINE_TAG: '2023-01-18.0-14c807942fa4'
FEDORA_EXEC: 'bash .gitlab-ci/fedora-install.sh'

View file

@ -5456,7 +5456,7 @@ endif
###############################################################################
check-local-tests-client: src/nmcli/nmcli src/tests/client/test-client.py
"$(srcdir)/src/tests/client/test-client.sh" "$(builddir)" "$(srcdir)" "$(PYTHON)"
LIBTOOL="$(LIBTOOL)" "$(srcdir)/src/tests/client/test-client.sh" "$(builddir)" "$(srcdir)" "$(PYTHON)" --
check_local += check-local-tests-client

View file

@ -12,11 +12,14 @@ set -xe
# Not all of these packages are strictly speaking necessary.
# This is a generous list of related packages.
SUDO=
[ "$EUID" -eq 0 ] || SUDO=sudo
install() {
if [ "$NM_INSTALL" != "" ]; then
$NM_INSTALL "$@"
else
sudo apt-get install -y "$@"
$SUDO apt-get install -y "$@"
fi
}

View file

@ -14,11 +14,14 @@ set -xe
DNF="$(command -v dnf &>/dev/null && echo dnf || echo yum)"
SUDO=
[ "$EUID" -eq 0 ] || SUDO=sudo
install() {
if [ "$NM_INSTALL" != "" ]; then
$NM_INSTALL "$@"
else
sudo "$DNF" install -y "$@"
$SUDO "$DNF" install -y "$@"
fi
}

View file

@ -99,53 +99,32 @@ _file_monitor_new(const char *path)
/*****************************************************************************/
#if defined(HOSTNAME_PERSIST_GENTOO)
static char *
read_hostname_gentoo(const char *path)
read_hostname(const char *path, gboolean is_gentoo)
{
gs_free char *contents = NULL;
gs_strfreev char **all_lines = NULL;
const char *tmp;
guint i;
gs_free char *contents = NULL;
gs_free const char **all_lines = NULL;
const char *tmp;
gsize i;
if (!g_file_get_contents(path, &contents, NULL, NULL))
return NULL;
all_lines = g_strsplit(contents, "\n", 0);
for (i = 0; all_lines[i]; i++) {
g_strstrip(all_lines[i]);
if (all_lines[i][0] == '#' || all_lines[i][0] == '\0')
continue;
if (g_str_has_prefix(all_lines[i], "hostname=")) {
tmp = &all_lines[i][NM_STRLEN("hostname=")];
return g_shell_unquote(tmp, NULL);
all_lines = nm_strsplit_set_full(contents, "\n", NM_STRSPLIT_SET_FLAGS_STRSTRIP);
for (i = 0; (tmp = all_lines[i]); i++) {
if (is_gentoo) {
if (!NM_STR_HAS_PREFIX(tmp, "hostname="))
continue;
tmp = &tmp[NM_STRLEN("hostname=")];
} else {
if (tmp[0] == '#')
continue;
}
nm_assert(tmp && tmp[0] != '\0');
return g_shell_unquote(tmp, NULL);
}
return NULL;
}
#endif
#if defined(HOSTNAME_PERSIST_SLACKWARE)
static char *
read_hostname_slackware(const char *path)
{
gs_free char *contents = NULL;
gs_strfreev char **all_lines = NULL;
guint i = 0;
if (!g_file_get_contents(path, &contents, NULL, NULL))
return NULL;
all_lines = g_strsplit(contents, "\n", 0);
for (i = 0; all_lines[i]; i++) {
g_strstrip(all_lines[i]);
if (all_lines[i][0] == '#' || all_lines[i][0] == '\0')
continue;
return g_shell_unquote(&all_lines[i][0], NULL);
}
return NULL;
}
#endif
#if defined(HOSTNAME_PERSIST_SUSE)
static gboolean
@ -237,10 +216,11 @@ _set_hostname_read_file(NMHostnameManager *self)
#endif
#if defined(HOSTNAME_PERSIST_GENTOO)
hostname = read_hostname_gentoo(HOSTNAME_FILE);
hostname = read_hostname(HOSTNAME_FILE, TRUE);
#elif defined(HOSTNAME_PERSIST_SLACKWARE)
hostname = read_hostname_slackware(HOSTNAME_FILE);
hostname = read_hostname(HOSTNAME_FILE, FALSE);
#else
(void) read_hostname;
if (g_file_get_contents(HOSTNAME_FILE, &hostname, NULL, NULL))
g_strchomp(hostname);
#endif

View file

@ -16,7 +16,13 @@
/*****************************************************************************/
volatile int _nml_dbus_log_level = 0;
#define LOG_FILE_FD_UNSET -3
#define LOG_FILE_FD_NONE -2
#define LOG_FILE_FD_DEFUNCT -1
volatile int _nml_dbus_log_level = 0;
const char *_nml_dbus_log_file = NULL;
int _nml_dbus_log_file_fd = LOG_FILE_FD_UNSET;
int
_nml_dbus_log_level_init(void)
@ -40,6 +46,97 @@ _nml_dbus_log_level_init(void)
return l;
}
static const char *
_nml_dbus_log_file_init(void)
{
const char *s;
s = g_getenv("LIBNM_CLIENT_DEBUG_FILE");
if (nm_str_not_empty(s)) {
if (strstr(s, "%p")) {
gs_strfreev char **tokens = NULL;
char pid_str[100];
tokens = g_strsplit(s, "%p", -1);
nm_sprintf_buf(pid_str, "%lld", (long long) getpid());
s = nm_str_realloc(g_strjoinv(pid_str, tokens));
} else
s = g_strdup(s);
} else
s = "";
if (!g_atomic_pointer_compare_and_exchange(&_nml_dbus_log_file, NULL, s)) {
if (s[0] != '\0')
g_free((gpointer) s);
s = g_atomic_pointer_get(&_nml_dbus_log_file);
}
return s;
}
#define nml_dbus_log_file() \
({ \
const char *_l; \
\
_l = g_atomic_pointer_get(&_nml_dbus_log_file); \
if (G_UNLIKELY(!_l)) \
_l = _nml_dbus_log_file_init(); \
\
_l[0] ? _l : NULL; \
})
static int
_nml_dbus_log_file_fd_init(void)
{
static GMutex mutex;
NM_G_MUTEX_LOCKED(&mutex);
int fd;
fd = g_atomic_int_get(&_nml_dbus_log_file_fd);
if (fd == LOG_FILE_FD_UNSET) {
const char *name;
name = nml_dbus_log_file();
if (!name)
fd = LOG_FILE_FD_NONE;
else {
fd = open(name, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0600);
if (fd < 0)
fd = LOG_FILE_FD_DEFUNCT;
}
g_atomic_int_set(&_nml_dbus_log_file_fd, fd);
}
return fd;
}
#define nml_dbus_log_file_fd() \
({ \
int _fd2; \
\
_fd2 = g_atomic_int_get(&_nml_dbus_log_file_fd); \
if (G_UNLIKELY(_fd2 == LOG_FILE_FD_UNSET)) \
_fd2 = _nml_dbus_log_file_fd_init(); \
\
nm_assert(NM_IN_SET(_fd2, LOG_FILE_FD_NONE, LOG_FILE_FD_DEFUNCT) || _fd2 >= 0); \
_fd2; \
})
#define _log_printf(use_stdout, ...) \
G_STMT_START \
{ \
const int _fd = nml_dbus_log_file_fd(); \
\
if (_fd != LOG_FILE_FD_NONE) { \
if (_fd >= 0) \
dprintf(_fd, __VA_ARGS__); \
} else if (use_stdout) \
g_print(__VA_ARGS__); \
else \
g_printerr(__VA_ARGS__); \
} \
G_STMT_END
void
_nml_dbus_log(NMLDBusLogLevel level, gboolean use_stdout, const char *fmt, ...)
{
@ -94,21 +191,13 @@ _nml_dbus_log(NMLDBusLogLevel level, gboolean use_stdout, const char *fmt, ...)
pid = getpid();
if (use_stdout) {
g_print("libnm-dbus[%lld]: %s[%" G_GINT64_FORMAT ".%05" G_GINT64_FORMAT "] %s\n",
_log_printf(use_stdout,
"libnm-dbus[%lld]: %s[%" G_GINT64_FORMAT ".%05" G_GINT64_FORMAT "] %s\n",
(long long) pid,
prefix,
ts / NM_UTILS_NSEC_PER_SEC,
(ts / (NM_UTILS_NSEC_PER_SEC / 100000)) % 100000,
msg);
} else {
g_printerr("libnm-dbus[%lld]: %s[%" G_GINT64_FORMAT ".%05" G_GINT64_FORMAT "] %s\n",
(long long) pid,
prefix,
ts / NM_UTILS_NSEC_PER_SEC,
(ts / (NM_UTILS_NSEC_PER_SEC / 100000)) % 100000,
msg);
}
}
/*****************************************************************************/
@ -884,8 +973,10 @@ nm_utils_g_param_spec_is_default(const GParamSpec *pspec)
/**
* nm_utils_print:
* @output_mode: if 1 it uses g_print(). If 2, it uses g_printerr().
* If 0, it uses either g_print() or g_printerr(), depending
* on LIBNM_CLIENT_DEBUG (and the "stdout" flag).
* If 0, it uses the same output as internal libnm debug logging
* does. That is, depending on LIBNM_CLIENT_DEBUG's "stdout" flag
* it uses g_print() or g_printerr() and if LIBNM_CLIENT_DEBUG_FILE is
* set, it writes the output to file instead
* @msg: the message to print. The function does not append
* a trailing newline.
*
@ -896,6 +987,11 @@ nm_utils_g_param_spec_is_default(const GParamSpec *pspec)
* with these functions (it implements additional buffering). By
* using nm_utils_print(), the same logging mechanisms can be used.
*
* Also, libnm honors LIBNM_CLIENT_DEBUG_FILE environment. If this
* is set to a filename pattern (accepting "%p" for the process ID),
* then the debug log is written to that file instead. With @output_mode
* zero, the same location will be written. Since: 1.44.
*
* Since: 1.30
*/
void
@ -905,17 +1001,21 @@ nm_utils_print(int output_mode, const char *msg)
g_return_if_fail(msg);
if (output_mode == 0) {
switch (output_mode) {
case 0:
nml_dbus_log_enabled_full(NML_DBUS_LOG_LEVEL_ANY, &use_stdout);
output_mode = use_stdout ? 1 : 2;
}
if (output_mode == 1)
_log_printf(use_stdout, "%s", msg);
break;
case 1:
g_print("%s", msg);
else if (output_mode == 2)
break;
case 2:
g_printerr("%s", msg);
else
break;
default:
g_return_if_reached();
break;
}
}
/*****************************************************************************/

View file

@ -22,36 +22,36 @@
static void
usage(void)
{
g_printerr(_("Usage: nmcli agent { COMMAND | help }\n\n"
"COMMAND := { secret | polkit | all }\n\n"));
nmc_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"));
nmc_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"));
nmc_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"));
nmc_printerr(_("Usage: nmcli agent all { help }\n"
"\n"
"Runs nmcli as both NetworkManager secret and a polkit agent.\n\n"));
}
static char *pre_input_deftext;
@ -82,7 +82,7 @@ get_secrets_from_user(const NmcConfig *nmc_config,
/* Ask user for the password */
if (msg)
g_print("%s\n", msg);
nmc_print("%s\n", msg);
if (secret->value) {
/* Prefill the password if we have it. */
rl_startup_hook = set_deftext;
@ -138,7 +138,7 @@ do_agent_secret(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *
NM_SECRET_AGENT_SIMPLE_REQUEST_SECRETS,
G_CALLBACK(secrets_requested),
nmc);
g_print(_("nmcli successfully registered as a NetworkManager's secret agent.\n"));
nmc_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;
@ -148,7 +148,7 @@ do_agent_secret(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *
static void
polkit_registered(gpointer instance, gpointer user_data)
{
g_print(_("nmcli successfully registered as a polkit agent.\n"));
nmc_print(_("nmcli successfully registered as a polkit agent.\n"));
}
static void
@ -202,14 +202,14 @@ do_agent_all(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *arg
do_agent_secret(cmd, nmc, argc, argv);
r = nmc->return_value;
if (r != NMC_RESULT_SUCCESS) {
g_printerr("%s\n", nmc->return_text->str);
nmc_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);
nmc_printerr("%s\n", nmc->return_text->str);
g_string_truncate(nmc->return_text, 0);
}

View file

@ -354,15 +354,15 @@ print_ip_config(NMIPConfig *cfg,
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)) {
if (!nmc_print_table(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;
@ -385,15 +385,15 @@ print_dhcp_config(NMDhcpConfig *dhcp,
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)) {
if (!nmc_print_table(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;
@ -660,16 +660,16 @@ vpn_openconnect_get_secrets(NMConnection *connection, GPtrArray *secrets)
/* 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);
nmc_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));
nmc_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));
nmc_printerr(_("Error: openconnect failed with signal %d\n"), WTERMSIG(status));
/* Append port to the host value */
if (gateway && port) {
@ -743,7 +743,7 @@ get_secrets_from_user(const NmcConfig *nmc_config,
}
}
if (msg)
g_print("%s\n", msg);
nmc_print("%s\n", msg);
echo_on = secret->is_secret ? nmc_config->show_secrets : TRUE;
@ -760,10 +760,10 @@ get_secrets_from_user(const NmcConfig *nmc_config,
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);
nmc_print("%s\n", msg);
nmc_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. */
@ -895,7 +895,10 @@ static void
readline_cb(char *line)
{
rl_got_line = TRUE;
rl_string = line;
free(rl_string);
rl_string = line;
rl_callback_handler_remove();
}
@ -910,13 +913,15 @@ static char *
nmc_readline_helper(const NmcConfig *nmc_config, const char *prompt)
{
GSource *io_source;
char *result;
nmc_set_in_readline(TRUE);
io_source = nm_g_unix_fd_add_source(STDIN_FILENO, G_IO_IN, stdin_ready_cb, NULL);
read_again:
rl_string = NULL;
nm_clear_free(&rl_string);
rl_got_line = FALSE;
rl_callback_handler_install(prompt, readline_cb);
@ -942,7 +947,6 @@ read_again:
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 */
@ -955,16 +959,19 @@ read_again:
}
/* Return NULL, not empty string */
if (rl_string && *rl_string == '\0') {
g_free(rl_string);
rl_string = NULL;
}
if (rl_string && *rl_string == '\0')
nm_clear_free(&rl_string);
nm_clear_g_source_inst(&io_source);
nmc_set_in_readline(FALSE);
return rl_string;
if (!rl_string)
return NULL;
result = g_strdup(rl_string);
nm_clear_free(&rl_string);
return result;
}
/**
@ -1525,7 +1532,7 @@ nmc_do_cmd(NmCli *nmc, const NMCCommand cmds[], const char *cmd, int argc, const
if (argc == 1 && nmc->complete) {
for (c = cmds; c->cmd; ++c) {
if (!*cmd || matches(cmd, c->cmd))
g_print("%s\n", c->cmd);
nmc_print("%s\n", c->cmd);
}
nmc_complete_help(cmd);
g_task_return_boolean(task, TRUE);
@ -1605,7 +1612,7 @@ nmc_complete_strv(const char *prefix, gssize nargs, const char *const *args)
if (prefix && !matches(prefix, candidate))
continue;
g_print("%s\n", candidate);
nmc_print("%s\n", candidate);
}
}

File diff suppressed because it is too large Load diff

View file

@ -8,7 +8,7 @@
#include "nmcli.h"
void monitor_connections(NmCli *nmc);
void nmc_monitor_connections(NmCli *nmc);
const char *nmc_connection_check_deprecated(NMConnection *c);

View file

@ -838,34 +838,35 @@ 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"));
nmc_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(
nmc_printerr(
_("Usage: nmcli device status { help }\n"
"\n"
"Show status for all devices.\n"
@ -881,41 +882,41 @@ usage_device_status(void)
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"));
nmc_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"));
nmc_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"));
nmc_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(_(
nmc_printerr(_(
"Usage: nmcli device modify { ARGUMENTS | help }\n"
"\n"
"ARGUMENTS := <ifname> ([+|-]<setting>.<property> <value>)+\n"
@ -936,57 +937,57 @@ usage_device_modify(void)
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"));
nmc_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"));
nmc_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"));
nmc_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"));
nmc_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(
nmc_printerr(
_("Usage: nmcli device wifi { ARGUMENTS | help }\n"
"\n"
"Perform operation on Wi-Fi devices.\n"
@ -1035,24 +1036,24 @@ usage_device_wifi(void)
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"));
nmc_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
usage_device_checkpoint(void)
{
g_printerr(_("Usage: nmcli device checkpoint { ARGUMENTS | help }\n"
"\n"
"ARGUMENTS := [--timeout <seconds>] -- COMMAND...\n"
"\n"
"Runs the command with a configuration checkpoint taken and asks for a\n"
"confirmation when finished. When the confirmation is not given, the\n"
"checkpoint is automatically restored after timeout.\n\n"));
nmc_printerr(_("Usage: nmcli device checkpoint { ARGUMENTS | help }\n"
"\n"
"ARGUMENTS := [--timeout <seconds>] -- COMMAND...\n"
"\n"
"Runs the command with a configuration checkpoint taken and asks for a\n"
"confirmation when finished. When the confirmation is not given, the\n"
"checkpoint is automatically restored after timeout.\n\n"));
}
static void
@ -1109,7 +1110,7 @@ complete_device(NMDevice **devices, const char *prefix, gboolean wifi_only)
continue;
if (g_str_has_prefix(iface, prefix))
g_print("%s\n", iface);
nmc_print("%s\n", iface);
}
}
@ -1178,10 +1179,10 @@ get_device_list(NmCli *nmc, int *argc, const char *const **argv)
if (!g_ptr_array_find(queue, device, NULL))
g_ptr_array_add(queue, g_object_ref(device));
else
g_printerr(_("Warning: argument '%s' is duplicated.\n"), **argv);
nmc_printerr(_("Warning: argument '%s' is duplicated.\n"), **argv);
} else {
if (!nmc->complete)
g_printerr(_("Error: Device '%s' not found.\n"), **argv);
nmc_printerr(_("Error: Device '%s' not found.\n"), **argv);
g_string_printf(nmc->return_text, _("Error: not all devices found."));
nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND;
}
@ -1645,7 +1646,7 @@ show_device_info(NMDevice *device, NmCli *nmc)
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 */
nmc_print("\n"); /* Print empty line between groups in tabular mode */
was_output = FALSE;
@ -1654,13 +1655,14 @@ show_device_info(NMDevice *device, NmCli *nmc)
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);
nmc_print_table(
&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;
}
@ -1669,15 +1671,15 @@ show_device_info(NMDevice *device, NmCli *nmc)
== 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);
nmc_print_table(&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;
}
@ -1687,15 +1689,15 @@ show_device_info(NMDevice *device, NmCli *nmc)
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);
nmc_print_table(&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;
}
@ -1706,15 +1708,15 @@ show_device_info(NMDevice *device, NmCli *nmc)
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);
nmc_print_table(&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;
@ -1770,15 +1772,15 @@ show_device_info(NMDevice *device, NmCli *nmc)
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);
nmc_print_table(&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;
@ -1899,15 +1901,15 @@ show_device_info(NMDevice *device, NmCli *nmc)
== 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);
nmc_print_table(&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;
}
@ -1976,13 +1978,13 @@ do_devices_status(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const
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)) {
if (!nmc_print_table(&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;
@ -2032,7 +2034,7 @@ do_device_show(const NMCCommand *cmd, NmCli *nmc, int argc, const char *const *a
if (!show_device_info(devices[i], nmc))
break;
if (devices[i + 1])
g_print("\n"); /* Empty line */
nmc_print("\n"); /* Empty line */
}
g_free(devices);
@ -2123,12 +2125,12 @@ add_and_activate_check_state(AddAndActivateInfo *info)
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));
nmc_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(
nmc_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);
@ -2194,7 +2196,7 @@ add_and_activate_cb(GObject *client, GAsyncResult *result, gpointer user_data)
deprecated =
nmc_connection_check_deprecated(NM_CONNECTION(nm_active_connection_get_connection(active)));
if (deprecated)
g_printerr(_("Warning: %s.\n"), deprecated);
nmc_printerr(_("Warning: %s.\n"), deprecated);
if (nmc->nowait_flag) {
quit();
@ -2382,9 +2384,9 @@ device_removed_cb(NMClient *client, NMDevice *device, DeviceCbInfo *info)
return;
if (info->cmd_disconnect)
g_print(_("Device '%s' successfully disconnected.\n"), nm_device_get_iface(device));
nmc_print(_("Device '%s' successfully disconnected.\n"), nm_device_get_iface(device));
else
g_print(_("Device '%s' successfully removed.\n"), nm_device_get_iface(device));
nmc_print(_("Device '%s' successfully removed.\n"), nm_device_get_iface(device));
device_cb_info_finish(info, device);
}
@ -2395,7 +2397,7 @@ disconnect_state_cb(NMDevice *device, GParamSpec *pspec, DeviceCbInfo *info)
return;
if (nm_device_get_state(device) <= NM_DEVICE_STATE_DISCONNECTED) {
g_print(_("Device '%s' successfully disconnected.\n"), nm_device_get_iface(device));
nmc_print(_("Device '%s' successfully disconnected.\n"), nm_device_get_iface(device));
device_cb_info_finish(info, device);
}
}
@ -2454,8 +2456,8 @@ reapply_device_cb(GObject *object, GAsyncResult *result, gpointer user_data)
} 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));
nmc_print(_("Connection successfully reapplied to device '%s'.\n"),
nm_device_get_iface(device));
device_cb_info_finish(info, device);
}
}
@ -2535,8 +2537,8 @@ modify_reapply_cb(GObject *object, GAsyncResult *result, gpointer user_data)
} 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));
nmc_print(_("Connection successfully reapplied to device '%s'.\n"),
nm_device_get_iface(device));
}
quit();
@ -2635,10 +2637,10 @@ disconnect_device_cb(GObject *object, GAsyncResult *result, gpointer user_data)
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);
nmc_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);
@ -2650,7 +2652,8 @@ disconnect_device_cb(GObject *object, GAsyncResult *result, gpointer user_data)
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));
nmc_print(_("Device '%s' successfully disconnected.\n"),
nm_device_get_iface(device));
}
device_cb_info_finish(info, device);
}
@ -2712,15 +2715,15 @@ delete_device_cb(GObject *object, GAsyncResult *result, gpointer user_data)
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);
nmc_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));
nmc_print(_("Device '%s' successfully removed.\n"), nm_device_get_iface(device));
device_cb_info_finish(info, device);
}
}
@ -2876,7 +2879,7 @@ device_state(NMDevice *device, GParamSpec *pspec, NmCli *nmc)
nm_device_get_iface(device),
gettext(nmc_device_state_to_string_with_external(device)));
g_print("%s", str);
nmc_print("%s", str);
}
static void
@ -2888,7 +2891,7 @@ device_ac(NMDevice *device, GParamSpec *pspec, NmCli *nmc)
if (!id)
return;
g_print(_("%s: using connection '%s'\n"), nm_device_get_iface(device), id);
nmc_print(_("%s: using connection '%s'\n"), nm_device_get_iface(device), id);
}
static void
@ -2914,14 +2917,14 @@ device_unwatch(NmCli *nmc, NMDevice *device)
static void
device_added(NMClient *client, NMDevice *device, NmCli *nmc)
{
g_print(_("%s: device created\n"), nm_device_get_iface(device));
nmc_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));
nmc_print(_("%s: device removed\n"), nm_device_get_iface(device));
device_unwatch(nmc, device);
}
@ -3019,7 +3022,7 @@ find_ap_on_device(NMDevice *device, const char *bssid, const char *ssid, gboolea
/* Compare BSSIDs */
if (complete) {
if (g_str_has_prefix(candidate_bssid, bssid))
g_print("%s\n", candidate_bssid);
nmc_print("%s\n", candidate_bssid);
} else if (strcmp(bssid, candidate_bssid) != 0)
continue;
}
@ -3039,7 +3042,7 @@ find_ap_on_device(NMDevice *device, const char *bssid, const char *ssid, gboolea
/* Compare SSIDs */
if (complete) {
if (g_str_has_prefix(ssid_tmp, ssid))
g_print("%s\n", ssid_tmp);
nmc_print("%s\n", ssid_tmp);
} else if (strcmp(ssid, ssid_tmp) != 0) {
g_free(ssid_tmp);
continue;
@ -3107,7 +3110,7 @@ wifi_print_aps(NMDeviceWifi *wifi,
static gboolean empty_line = FALSE;
if (empty_line)
g_print("\n"); /* Empty line between devices' APs */
nmc_print("\n"); /* Empty line between devices' APs */
/* Main header name */
header_name = construct_header_name(base_hdr, nm_device_get_iface(NM_DEVICE(wifi)));
@ -3979,9 +3982,10 @@ do_device_wifi_connect(const NMCCommand *cmd, NmCli *nmc, int argc, const char *
/* 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);
nmc_printerr(
_("Warning: '%s' should be SSID for hidden APs; but it looks like a "
"BSSID.\n"),
param_user);
}
}
}
@ -4201,7 +4205,7 @@ set_wireless_security_for_hotspot(NMSettingWirelessSecurity *s_wsec,
NULL);
}
if (show_password)
g_print(_("Hotspot password: %s\n"), key);
nmc_print(_("Hotspot password: %s\n"), key);
return TRUE;
}
@ -4687,7 +4691,7 @@ print_wifi_connection(const NmcConfig *nmc_config, NMConnection *connection)
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);
nmc_print("SSID: %s\n", ssid);
string = g_string_sized_new(64);
g_string_append(string, "WIFI:");
@ -4700,21 +4704,21 @@ print_wifi_connection(const NmcConfig *nmc_config, NMConnection *connection)
if (key_mgmt == NULL) {
type = "nopass";
g_print("%s: %s\n", _("Security"), _("None"));
nmc_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"));
nmc_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"));
nmc_print("%s: WPA\n", _("Security"));
} else if (strcmp(key_mgmt, "owe") == 0) {
type = "nopass";
g_print("%s: OWE\n", _("Security"));
nmc_print("%s: OWE\n", _("Security"));
}
if (psk)
g_print("%s: %s\n", _("Password"), psk);
nmc_print("%s: %s\n", _("Password"), psk);
string_append_mecard(string, "T:", type);
string_append_mecard(string, "S:", ssid);
@ -4727,7 +4731,7 @@ print_wifi_connection(const NmcConfig *nmc_config, NMConnection *connection)
if (nmc_config->use_colors)
nmc_print_qrcode(string->str);
g_print("\n");
nmc_print("\n");
}
static gboolean
@ -5090,7 +5094,7 @@ checkpoints_changed_cb(GObject *object, GParamSpec *pspec, CheckpointCbInfo *inf
if (!info->child_id) {
/* The command is done, we're in the confirmation prompt. */
g_print("%s\n", _("No"));
nmc_print("%s\n", _("No"));
g_main_loop_quit(loop);
}
}
@ -5331,7 +5335,7 @@ nmc_command_func_device(const NMCCommand *cmd, NmCli *nmc, int argc, const char
}
void
monitor_devices(NmCli *nmc)
nmc_monitor_devices(NmCli *nmc)
{
do_devices_monitor(NULL, nmc, 0, NULL);
}

View file

@ -12,7 +12,7 @@ void nmc_complete_device(NMClient *client, const char *prefix, gboolean wifi_onl
void nmc_complete_bssid(NMClient *client, const char *ifname, const char *bssid_prefix);
void monitor_devices(NmCli *nmc);
void nmc_monitor_devices(NmCli *nmc);
NMDevice **nmc_get_devices_sorted(NMClient *client);

View file

@ -299,19 +299,19 @@ static const NmcMetaGenericInfo
static void
usage_general(void)
{
g_printerr(_("Usage: nmcli general { COMMAND | help }\n\n"
"COMMAND := { status | hostname | permissions | logging | reload }\n\n"
" status\n\n"
" hostname [<hostname>]\n\n"
" permissions\n\n"
" logging [level <log level>] [domains <log domains>]\n\n"
" reload [<flags>]\n\n"));
nmc_printerr(_("Usage: nmcli general { COMMAND | help }\n\n"
"COMMAND := { status | hostname | permissions | logging | reload }\n\n"
" status\n\n"
" hostname [<hostname>]\n\n"
" permissions\n\n"
" logging [level <log level>] [domains <log domains>]\n\n"
" reload [<flags>]\n\n"));
}
static void
usage_general_status(void)
{
g_printerr(
nmc_printerr(
_("Usage: nmcli general status { help }\n"
"\n"
"Show overall status of NetworkManager.\n"
@ -321,7 +321,7 @@ usage_general_status(void)
static void
usage_general_hostname(void)
{
g_printerr(
nmc_printerr(
_("Usage: nmcli general hostname { ARGUMENTS | help }\n"
"\n"
"ARGUMENTS := [<hostname>]\n"
@ -334,87 +334,88 @@ usage_general_hostname(void)
static void
usage_general_permissions(void)
{
g_printerr(_("Usage: nmcli general permissions { help }\n"
"\n"
"Show caller permissions for authenticated operations.\n\n"));
nmc_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"));
nmc_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"));
nmc_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"));
nmc_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"));
nmc_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"));
nmc_printerr(_("Usage: nmcli networking off { help }\n"
"\n"
"Switch networking off.\n\n"));
}
static void
usage_networking_connectivity(void)
{
g_printerr(
nmc_printerr(
_("Usage: nmcli networking connectivity { ARGUMENTS | help }\n"
"\n"
"ARGUMENTS := [check]\n"
@ -426,48 +427,48 @@ usage_networking_connectivity(void)
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"));
nmc_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"));
nmc_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"));
nmc_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"));
nmc_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"));
nmc_printerr(_("Usage: nmcli monitor\n"
"\n"
"Monitor NetworkManager changes.\n"
"Prints a line whenever a change occurs in NetworkManager\n\n"));
}
static void
@ -491,13 +492,13 @@ show_nm_status(NmCli *nmc, const char *pretty_header_name, const char *print_fld
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)) {
if (!nmc_print_table(&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);
@ -570,13 +571,13 @@ print_permissions(void *user_data)
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)) {
if (!nmc_print_table(&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;
}
@ -724,13 +725,13 @@ show_general_logging(NmCli *nmc)
} 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)) {
if (!nmc_print_table(&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;
}
@ -748,7 +749,7 @@ nmc_complete_strings_nocase(const char *prefix, ...)
va_start(args, prefix);
while ((candidate = va_arg(args, const char *))) {
if (strncasecmp(prefix, candidate, len) == 0)
g_print("%s\n", candidate);
nmc_print("%s\n", candidate);
}
va_end(args);
}
@ -919,13 +920,13 @@ do_general_hostname(const NMCCommand *cmd, NmCli *nmc, int argc, const char *con
g_object_get(nmc->client, NM_CLIENT_HOSTNAME, &s, NULL);
if (s)
g_print("%s\n", s);
nmc_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_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);
@ -1234,7 +1235,7 @@ networkmanager_running(NMClient *client, GParamSpec *param, NmCli *nmc)
str = nmc_colorize(&nmc->nmc_config,
running ? NM_META_COLOR_MANAGER_RUNNING : NM_META_COLOR_MANAGER_STOPPED,
running ? _("NetworkManager is running") : _("NetworkManager is stopped"));
g_print("%s\n", str);
nmc_print("%s\n", str);
g_free(str);
}
@ -1244,7 +1245,7 @@ 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);
nmc_print(_("Hostname set to '%s'\n"), hostname);
}
static void
@ -1259,9 +1260,9 @@ client_primary_connection(NMClient *client, GParamSpec *param, NmCli *nmc)
if (!id)
id = nm_active_connection_get_uuid(primary);
g_print(_("'%s' is now the primary connection\n"), id);
nmc_print(_("'%s' is now the primary connection\n"), id);
} else {
g_print(_("There's no primary connection\n"));
nmc_print(_("There's no primary connection\n"));
}
}
@ -1276,7 +1277,7 @@ client_connectivity(NMClient *client, GParamSpec *param, NmCli *nmc)
connectivity_to_color(connectivity),
_("Connectivity is now '%s'\n"),
gettext(nm_connectivity_to_string(connectivity)));
g_print("%s", str);
nmc_print("%s", str);
g_free(str);
}
@ -1291,7 +1292,7 @@ client_state(NMClient *client, GParamSpec *param, NmCli *nmc)
state_to_color(state),
_("Networkmanager is now in the '%s' state\n"),
gettext(nm_state_to_string(state)));
g_print("%s", str);
nmc_print("%s", str);
g_free(str);
}
@ -1310,9 +1311,9 @@ device_overview(NmCli *nmc, NMDevice *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"));
nmc_print("\t%d %s\n", activatable->len, _("connection available"));
else if (activatable->len > 1)
g_print("\t%d %s\n", activatable->len, _("connections available"));
nmc_print("\t%d %s\n", activatable->len, _("connections available"));
}
}
@ -1401,7 +1402,7 @@ device_overview(NmCli *nmc, NMDevice *device)
if (outbuf->len >= 2) {
g_string_truncate(outbuf, outbuf->len - 2);
g_print("\t%s\n", outbuf->str);
nmc_print("\t%s\n", outbuf->str);
}
g_string_free(outbuf, TRUE);
@ -1428,7 +1429,7 @@ ac_overview(NmCli *nmc, NMActiveConnection *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);
nmc_print("\t%s\n", outbuf->str);
}
ip = nm_active_connection_get_ip4_config(ac);
@ -1439,7 +1440,7 @@ ac_overview(NmCli *nmc, NMActiveConnection *ac)
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));
nmc_print("\tinet4 %s/%d\n", nm_ip_address_get_address(a), nm_ip_address_get_prefix(a));
}
p = nm_ip_config_get_routes(ip);
@ -1449,7 +1450,7 @@ ac_overview(NmCli *nmc, NMActiveConnection *ac)
nm_str_buf_reset(&str);
_nm_ip_route_to_string(a, &str);
g_print("\troute4 %s\n", nm_str_buf_get_str(&str));
nmc_print("\troute4 %s\n", nm_str_buf_get_str(&str));
}
}
@ -1461,7 +1462,7 @@ ac_overview(NmCli *nmc, NMActiveConnection *ac)
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));
nmc_print("\tinet6 %s/%d\n", nm_ip_address_get_address(a), nm_ip_address_get_prefix(a));
}
p = nm_ip_config_get_routes(ip);
@ -1471,7 +1472,7 @@ ac_overview(NmCli *nmc, NMActiveConnection *ac)
nm_str_buf_reset(&str);
_nm_ip_route_to_string(a, &str);
g_print("\troute6 %s\n", nm_str_buf_get_str(&str));
nmc_print("\troute6 %s\n", nm_str_buf_get_str(&str));
}
}
@ -1509,11 +1510,11 @@ nmc_command_func_overview(const NMCCommand *cmd, NmCli *nmc, int argc, const cha
color,
_("%s VPN connection"),
nm_active_connection_get_id(ac));
g_print("%s\n", tmp);
nmc_print("%s\n", tmp);
g_free(tmp);
ac_overview(nmc, ac);
g_print("\n");
nmc_print("\n");
}
devices = nmc_get_devices_sorted(nmc->client);
@ -1541,16 +1542,16 @@ nmc_command_func_overview(const NMCCommand *cmd, NmCli *nmc, int argc, const cha
nm_device_get_iface(device),
gettext(nmc_device_state_to_string_with_external(device)));
}
g_print("%s\n", tmp);
nmc_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));
nmc_print("\t\"%s\"\n", nm_device_get_description(device));
device_overview(nmc, device);
if (ac)
ac_overview(nmc, ac);
g_print("\n");
nmc_print("\n");
}
g_free(devices);
@ -1566,31 +1567,32 @@ nmc_command_func_overview(const NMCCommand *cmd, NmCli *nmc, int argc, const cha
}
if (i == 0)
g_print("DNS configuration:\n");
nmc_print("DNS configuration:\n");
tmp = g_strjoinv(" ", (char **) strv);
g_print("\tservers: %s\n", tmp);
nmc_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);
nmc_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));
nmc_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");
nmc_print("\ttype: vpn\n");
nmc_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"));
nmc_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
@ -1632,6 +1634,6 @@ nmc_command_func_monitor(const NMCCommand *cmd, NmCli *nmc, int argc, const char
nmc->should_wait++;
monitor_devices(nmc);
monitor_connections(nmc);
nmc_monitor_devices(nmc);
nmc_monitor_connections(nmc);
}

View file

@ -166,13 +166,13 @@ complete_one(gpointer key, gpointer value, gpointer user_data)
/* value prefix was not a standalone argument,
* it was part of --option=<value> argument.
* Repeat the part leading to "=". */
g_print("%s=", option);
nmc_print("%s=", option);
}
g_print("%.*s%s%s\n",
(int) (last - prefix),
prefix,
name,
strcmp(last, name) == 0 ? "," : "");
nmc_print("%.*s%s%s\n",
(int) (last - prefix),
prefix,
name,
strcmp(last, name) == 0 ? "," : "");
}
}
@ -228,9 +228,9 @@ complete_option_with_value(const char *option, const char *prefix, ...)
/* value prefix was not a standalone argument,
* it was part of --option=<value> argument.
* Repeat the part leading to "=". */
g_print("%s=", option);
nmc_print("%s=", option);
}
g_print("%s\n", candidate);
nmc_print("%s\n", candidate);
}
}
va_end(args);
@ -239,7 +239,7 @@ complete_option_with_value(const char *option, const char *prefix, ...)
static void
usage(void)
{
g_printerr(_(
nmc_printerr(_(
"Usage: nmcli [OPTIONS] OBJECT { COMMAND | help }\n"
"\n"
"OPTIONS\n"
@ -889,7 +889,7 @@ process_command_line(NmCli *nmc, int argc, char **argv_orig)
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);
nmc_print(_("nmcli tool, version %s\n"), NMCLI_VERSION);
return NMC_RESULT_SUCCESS;
} else if (matches_arg(nmc, &argc, &argv, "-help", NULL)) {
if (!nmc->complete)
@ -1047,7 +1047,7 @@ main(int argc, char *argv[])
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_printerr("%s\n", nm_cli.return_text->str);
}
nmc_cleanup(&nm_cli);

View file

@ -13,6 +13,7 @@
#include "libnmc-base/nm-polkit-listener.h"
#include "common.h"
#include "utils.h"
static char *
polkit_read_passwd(gpointer instance,
@ -23,8 +24,8 @@ polkit_read_passwd(gpointer instance,
{
NmCli *nmc = user_data;
g_print("%s\n", message);
g_print("(action_id: %s)\n", action_id);
nmc_print("%s\n", message);
nmc_print("(action_id: %s)\n", action_id);
/* Ask user for polkit authorization password */
if (user) {
@ -36,7 +37,7 @@ polkit_read_passwd(gpointer instance,
static void
polkit_error(gpointer instance, const char *error, gpointer user_data)
{
g_printerr(_("Error: polkit agent failed: %s\n"), error);
nmc_printerr(_("Error: polkit agent failed: %s\n"), error);
}
gboolean
@ -89,7 +90,7 @@ nmc_start_polkit_agent_start_try(NmCli *nmc)
return TRUE;
if (!nmc_polkit_agent_init(nmc, FALSE, &error)) {
g_printerr(_("Warning: polkit agent initialization failed: %s\n"), error->message);
nmc_printerr(_("Warning: polkit agent initialization failed: %s\n"), error->message);
return FALSE;
}
return TRUE;

View file

@ -246,10 +246,10 @@ wireless_band_channel_changed_cb(GObject *object, GParamSpec *pspec, gpointer us
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);
nmc_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);
}
}
@ -266,9 +266,9 @@ connection_master_changed_cb(GObject *object, GParamSpec *pspec, gpointer user_d
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));
nmc_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)
@ -373,8 +373,8 @@ _set_fcn_precheck_connection_secondaries(NMClient *client,
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);
nmc_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)) {
@ -431,13 +431,13 @@ _env_warn_fcn_handle(
switch (warn_level) {
case NM_META_ENV_WARN_LEVEL_WARN:
g_print(_("Warning: %s\n"), m);
nmc_print(_("Warning: %s\n"), m);
return;
case NM_META_ENV_WARN_LEVEL_INFO:
g_print(_("Info: %s\n"), m);
nmc_print(_("Info: %s\n"), m);
return;
}
g_print(_("Error: %s\n"), m);
nmc_print(_("Error: %s\n"), m);
}
static NMDevice *const *
@ -759,7 +759,7 @@ setting_details(const NmcConfig *nmc_config, NMSetting *setting, const char *one
fields_str = g_strdup_printf("%s.%s", nm_setting_get_name(setting), one_prop);
}
if (!nmc_print(
if (!nmc_print_table(
nmc_config,
(gpointer[]){setting, NULL},
NULL,

View file

@ -346,7 +346,7 @@ ssid_to_hex(const char *str, gsize len)
void
nmc_terminal_erase_line(void)
{
/* We intentionally use printf(), not g_print() here, to ensure that
/* We intentionally use printf(), not nmc_print() here, to ensure that
* GLib doesn't mistakenly try to convert the string.
*/
printf("\33[2K\r");
@ -365,7 +365,7 @@ nmc_terminal_show_progress(const char *str)
const char slashes[4] = {'|', '/', '-', '\\'};
nmc_terminal_erase_line();
g_print("%c %s", slashes[idx++], str ?: "");
nmc_print("%c %s", slashes[idx++], str ?: "");
fflush(stdout);
if (idx == 4)
idx = 0;
@ -467,7 +467,7 @@ nmc_get_user_input(const char *ask_str)
size_t line_ln = 0;
ssize_t num;
g_print("%s", ask_str);
nmc_print("%s", ask_str);
num = getline(&line, &line_ln, stdin);
/* Remove newline from the string */
@ -1251,9 +1251,9 @@ _print_do(const NmcConfig *nmc_config,
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);
nmc_print("%s\n", line);
nmc_print("%*s\n", (table_width + width2) / 2 + width1 - width2, header_name);
nmc_print("%s\n", line);
}
str = !nmc_config->multiline_output ? g_string_sized_new(100) : NULL;
@ -1283,14 +1283,14 @@ _print_do(const NmcConfig *nmc_config,
if (str->len)
g_string_truncate(str, str->len - 1); /* Chop off last column separator */
g_print("%s\n", str->str);
nmc_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, '-')));
nmc_print("%s\n", (line = g_strnfill(table_width, '-')));
}
}
@ -1332,12 +1332,12 @@ _print_do(const NmcConfig *nmc_config,
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);
nmc_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) {
@ -1373,7 +1373,7 @@ _print_do(const NmcConfig *nmc_config,
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);
nmc_print("%s\n", str->str);
g_string_truncate(str, 0);
}
@ -1381,19 +1381,19 @@ _print_do(const NmcConfig *nmc_config,
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, '-')));
nmc_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)
nmc_print_table(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;
@ -1458,7 +1458,7 @@ nmc_terminal_spawn_pager(const NmcConfig *nmc_config)
if (pipe(fd) == -1) {
errsv = errno;
g_printerr(_("Failed to create pager pipe: %s\n"), nm_strerror_native(errsv));
nmc_printerr(_("Failed to create pager pipe: %s\n"), nm_strerror_native(errsv));
return 0;
}
@ -1471,7 +1471,7 @@ nmc_terminal_spawn_pager(const NmcConfig *nmc_config)
pager_pid = fork();
if (pager_pid == -1) {
errsv = errno;
g_printerr(_("Failed to fork pager: %s\n"), nm_strerror_native(errsv));
nmc_printerr(_("Failed to fork pager: %s\n"), nm_strerror_native(errsv));
nm_close(fd[0]);
nm_close(fd[1]);
return 0;
@ -1515,11 +1515,11 @@ nmc_terminal_spawn_pager(const NmcConfig *nmc_config)
/* 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));
nmc_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));
nmc_printerr(_("Failed to duplicate pager pipe: %s\n"), nm_strerror_native(errsv));
}
nm_close(fd[0]);
@ -1608,9 +1608,9 @@ print_required_fields(const NmcConfig *nmc_config,
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);
nmc_print("%s\n", line);
nmc_print("%*s\n", (table_width + width2) / 2 + width1 - width2, header_name);
nmc_print("%s\n", line);
}
if (main_header_only)
@ -1656,12 +1656,12 @@ print_required_fields(const NmcConfig *nmc_config,
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);
nmc_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;
@ -1681,18 +1681,18 @@ print_required_fields(const NmcConfig *nmc_config,
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);
nmc_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, '-')));
nmc_print("%s\n", (line = g_strnfill(ML_HEADER_WIDTH, '-')));
}
return;
@ -1749,13 +1749,13 @@ print_required_fields(const NmcConfig *nmc_config,
g_string_prepend(str, (indent_str = g_strnfill(indent, ' ')));
}
g_print("%s\n", str->str);
nmc_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, '-')));
nmc_print("%s\n", (line = g_strnfill(table_width, '-')));
}
}
}

View file

@ -359,13 +359,43 @@ nmc_meta_generic_get_enum_with_detail(NmcMetaGenericGetEnumType get_enum_type,
/*****************************************************************************/
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);
gboolean nmc_print_table(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);
/*****************************************************************************/
#if 0
/* For manual testing to sync output with LIBNM_CLIENT_DEBUG/LIBNM_CLIENT_DEBUG_FILE */
#define nmc_print(...) \
G_STMT_START \
{ \
gs_free char *_ss = g_strdup_printf(__VA_ARGS__); \
gs_free char *_ss1 = g_strdup_printf("nmcli[out]: %s", _ss); \
\
nm_utils_print(0, _ss1); \
nm_utils_print(1, _ss); \
} \
G_STMT_END
#define nmc_printerr(...) \
G_STMT_START \
{ \
gs_free char *_ss = g_strdup_printf(__VA_ARGS__); \
gs_free char *_ss1 = g_strdup_printf("nmcli[err]: %s", _ss); \
\
nm_utils_print(0, _ss1); \
nm_utils_print(2, _ss); \
} \
G_STMT_END
#else
#define nmc_print(...) g_print(__VA_ARGS__)
#define nmc_printerr(...) g_printerr(__VA_ARGS__)
#endif
/*****************************************************************************/

View file

@ -7,6 +7,10 @@ test(
build_root,
source_root,
python.path(),
'--',
],
env: [
'LIBTOOL=',
],
timeout: 120,
)

View file

@ -90,27 +90,33 @@ ENV_NM_TEST_ASAN_OPTIONS = "NM_TEST_ASAN_OPTIONS"
ENV_NM_TEST_LSAN_OPTIONS = "NM_TEST_LSAN_OPTIONS"
ENV_NM_TEST_UBSAN_OPTIONS = "NM_TEST_UBSAN_OPTIONS"
#
# Run nmcli under valgrind. If unset, we honor NMTST_USE_VALGRIND instead.
# Valgrind is always disabled, if NM_TEST_REGENERATE is enabled.
ENV_NM_TEST_VALGRIND = "NM_TEST_VALGRIND"
ENV_LIBTOOL = "LIBTOOL"
###############################################################################
import sys
import os
import errno
import unittest
import socket
import itertools
import subprocess
import shlex
import re
import fcntl
import collections
import dbus
import time
import random
import dbus.service
import dbus.mainloop.glib
import dbus.service
import errno
import fcntl
import io
from signal import SIGINT
import itertools
import os
import random
import re
import shlex
import signal
import socket
import subprocess
import sys
import tempfile
import time
import unittest
import gi
@ -208,10 +214,10 @@ class Util:
}
@classmethod
def signal_no_to_str(cls, signal):
s = cls._signal_no_lookup.get(signal, None)
def signal_no_to_str(cls, sig):
s = cls._signal_no_lookup.get(sig, None)
if s is None:
return "<unknown %d>" % (signal)
return "<unknown %d>" % (sig)
return s
@staticmethod
@ -228,6 +234,19 @@ class Util:
t = basestring
return isinstance(s, t)
@staticmethod
def is_bool(s, defval=False):
if s is None:
return defval
if isinstance(s, int):
return s != 0
if isinstance(s, str):
if s.lower() in ["1", "y", "yes", "true", "on"]:
return True
if s.lower() in ["0", "n", "no", "false", "off"]:
return False
raise ValueError('Argument "%s" is not a boolean' % (s,))
@staticmethod
def as_bytes(s):
if Util.is_string(s):
@ -251,7 +270,8 @@ class Util:
).search
@staticmethod
def quote(s):
def shlex_quote(s):
# Reimplement shlex.quote().
if Util.python_has_version(3, 3):
return shlex.quote(s)
if not s:
@ -260,6 +280,11 @@ class Util:
return s
return "'" + s.replace("'", "'\"'\"'") + "'"
@staticmethod
def shlex_join(args):
# Reimplement shlex.join()
return " ".join(Util.shlex_quote(s) for s in args)
@staticmethod
def popen_wait(p, timeout=0):
(res, b_stdout, b_stderr) = Util.popen_wait_read(
@ -455,6 +480,48 @@ class Util:
for color in [[], ["--color", "yes"]]:
yield mode + fmt + color
@staticmethod
def valgrind_check_log(valgrind_log, logname):
if valgrind_log is None:
return
fd, name = valgrind_log
os.close(fd)
if not os.path.isfile(name):
raise Exception("valgrind log %s unexpectedly does not exist" % (name,))
if os.path.getsize(name) != 0:
out = subprocess.run(
[
"sed",
"-e",
"/^--[0-9]\+-- WARNING: unhandled .* syscall: /,/^--[0-9]\+-- it at http.*\.$/d",
name,
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
if out.returncode != 0:
raise Exception('Calling "sed" to search valgrind log failed')
if out.stdout:
print("valgrind log %s for %s is not empty:" % (name, logname))
print("\n%s\n" % (out.stdout.decode("utf-8", errors="replace"),))
raise Exception("valgrind log %s unexpectedly is not empty" % (name,))
os.remove(name)
@staticmethod
def pexpect_expect_all(pexp, *pattern_list):
# This will call "pexpect.expect()" on pattern_list,
# expecting all entries to match exactly once, in any
# order.
pattern_list = list(pattern_list)
while pattern_list:
idx = pexp.expect(pattern_list)
del pattern_list[idx]
###############################################################################
@ -493,14 +560,23 @@ class Configuration:
#
# Only by setting NM_TEST_CLIENT_CHECK_L10N=1, these tests are included
# as well.
v = os.environ.get(ENV_NM_TEST_CLIENT_CHECK_L10N, "0") == "1"
v = Util.is_bool(os.environ.get(ENV_NM_TEST_CLIENT_CHECK_L10N, None))
elif name == ENV_NM_TEST_REGENERATE:
# in the "regenerate" mode, the tests will rewrite the files on disk against
# which we assert. That is useful, if there are intentional changes and
# we want to regenerate the expected output.
v = os.environ.get(ENV_NM_TEST_REGENERATE, "0") == "1"
v = Util.is_bool(os.environ.get(ENV_NM_TEST_REGENERATE, None))
elif name == ENV_NM_TEST_WITH_LINENO:
v = os.environ.get(ENV_NM_TEST_WITH_LINENO, "0") == "1"
v = Util.is_bool(os.environ.get(ENV_NM_TEST_WITH_LINENO, None))
elif name == ENV_NM_TEST_VALGRIND:
if self.get(ENV_NM_TEST_REGENERATE):
v = False
else:
v = os.environ.get(ENV_NM_TEST_VALGRIND, None)
if v:
v = Util.is_bool(v)
else:
v = Util.is_bool(os.environ.get("NMTST_USE_VALGRIND", None))
elif name in [
ENV_NM_TEST_ASAN_OPTIONS,
ENV_NM_TEST_LSAN_OPTIONS,
@ -517,6 +593,21 @@ class Configuration:
v = "print_stacktrace=1:halt_on_error=1"
else:
assert False
elif name == ENV_LIBTOOL:
v = os.environ.get(name, None)
if v is None:
v = os.path.abspath(
os.path.dirname(self.get(ENV_NM_TEST_CLIENT_NMCLI_PATH))
+ "/../../libtool"
)
if not os.path.isfile(v):
v = None
else:
v = [v]
elif not v:
v = None
else:
v = shlex.split(v)
else:
raise Exception()
self._values[name] = v
@ -575,17 +666,37 @@ class NMStubServer:
)
self._p = p
def shutdown(self):
def shutdown(self, kill_mode="random"):
conn = self._conn
p = self._p
self._nmobj = None
self._nmiface = None
self._conn = None
self._p = None
p.stdin.close()
p.kill()
# The test stub service watches stdin and will do a proper
# shutdown when it closes. That means, to send signals about
# going away.
# On the other hand, just killing it will cause the process
# from dropping off the bus.
if kill_mode == "kill":
p.kill()
elif kill_mode == "stdin-close":
p.stdin.close()
else:
assert kill_mode == "random"
ops = [p.stdin.close, p.kill]
random.shuffle(ops)
ops[0]()
r = random.random()
if r < 0.75:
if r < 0.5:
time.sleep(r * 0.2)
ops[1]()
if Util.popen_wait(p, 1) is None:
raise Exception("Stub service did not exit in time")
p.stdin.close()
if self._conn_get_main_object(conn) is not None:
raise Exception(
"Stub service is not still here although it should shut down"
@ -721,20 +832,28 @@ class AsyncProcess:
###############################################################################
class NmTestBase(unittest.TestCase):
MAX_JOBS = 15
class TestNmcli(unittest.TestCase):
def __init__(self, *args, **kwargs):
self._calling_num = {}
self._skip_test_for_l10n_diff = []
self._async_jobs = []
self._results = []
self.srv = None
return unittest.TestCase.__init__(self, *args, **kwargs)
unittest.TestCase.__init__(self, *args, **kwargs)
def srv_start(self):
self.srv_shutdown()
self.srv = NMStubServer(self._testMethodName)
MAX_JOBS = 15
def srv_shutdown(self):
if self.srv is not None:
srv = self.srv
self.srv = None
srv.shutdown()
class TestNmcli(NmTestBase):
def ReplaceTextConUuid(self, con_name, replacement):
return Util.ReplaceTextSimple(
Util.memoize_nullary(lambda: self.srv.findConnectionUuid(con_name)),
@ -769,6 +888,39 @@ class TestNmcli(NmTestBase):
return content_expect, results_expect
def nmcli_construct_argv(self, args, with_valgrind=None):
if with_valgrind is None:
with_valgrind = conf.get(ENV_NM_TEST_VALGRIND)
valgrind_log = None
cmd = conf.get(ENV_NM_TEST_CLIENT_NMCLI_PATH)
if with_valgrind:
valgrind_log = tempfile.mkstemp(prefix="nm-test-client-valgrind.")
argv = [
"valgrind",
"--quiet",
"--error-exitcode=37",
"--leak-check=full",
"--gen-suppressions=all",
(
"--suppressions="
+ PathConfiguration.top_srcdir()
+ "/valgrind.suppressions"
),
"--num-callers=100",
"--log-file=" + valgrind_log[1],
cmd,
]
libtool = conf.get(ENV_LIBTOOL)
if libtool:
argv = list(libtool) + ["--mode=execute"] + argv
else:
argv = [cmd]
argv.extend(args)
return argv, valgrind_log
def call_nmcli_l(
self,
args,
@ -852,10 +1004,14 @@ class TestNmcli(NmTestBase):
)
def call_nmcli_pexpect(self, args):
env = self._env(extra_env={"NO_COLOR": "1"})
return pexpect.spawn(
conf.get(ENV_NM_TEST_CLIENT_NMCLI_PATH), args, timeout=10, env=env
)
argv, valgrind_log = self.nmcli_construct_argv(args)
pexp = pexpect.spawn(argv[0], argv[1:], timeout=10, env=env)
typ = collections.namedtuple("CallNmcliPexpect", ["pexp", "valgrind_log"])
return typ(pexp, valgrind_log)
def _env(
self, lang="C", calling_num=None, fatal_warnings=_DEFAULT_ARG, extra_env=None
@ -870,7 +1026,12 @@ class TestNmcli(NmTestBase):
self.fail("invalid language %s" % (lang))
env = {}
for k in ["LD_LIBRARY_PATH", "DBUS_SESSION_BUS_ADDRESS"]:
for k in [
"LD_LIBRARY_PATH",
"DBUS_SESSION_BUS_ADDRESS",
"LIBNM_CLIENT_DEBUG",
"LIBNM_CLIENT_DEBUG_FILE",
]:
val = os.environ.get(k, None)
if val is not None:
env[k] = val
@ -951,7 +1112,10 @@ class TestNmcli(NmTestBase):
else:
self.fail("invalid language %s" % (lang))
args = [conf.get(ENV_NM_TEST_CLIENT_NMCLI_PATH)] + list(args)
# Running under valgrind is not yet supported for those tests.
args, valgrind_log = self.nmcli_construct_argv(args, with_valgrind=False)
assert valgrind_log is None
if replace_stdout is not None:
replace_stdout = list(replace_stdout)
@ -1024,7 +1188,7 @@ class TestNmcli(NmTestBase):
self.assertEqual(returncode, -5)
if check_on_disk:
cmd = "$NMCLI %s" % (" ".join([Util.quote(a) for a in args[1:]]))
cmd = "$NMCLI %s" % (Util.shlex_join(args[1:]),)
cmd = Util.replace_text(cmd, replace_cmd)
if returncode < 0:
@ -1111,9 +1275,7 @@ class TestNmcli(NmTestBase):
self.async_wait()
if self.srv is not None:
self.srv.shutdown()
self.srv = None
self.srv_shutdown()
self._calling_num = None
@ -1229,7 +1391,7 @@ class TestNmcli(NmTestBase):
def nm_test(func):
def f(self):
self.srv = NMStubServer(self._testMethodName)
self.srv_start()
func(self)
self._nm_test_post()
@ -1867,61 +2029,60 @@ class TestNmcli(NmTestBase):
@nm_test
def test_ask_mode(self):
nmc = self.call_nmcli_pexpect(["--ask", "c", "add"])
nmc.expect("Connection type:")
nmc.sendline("ethernet")
nmc.expect("Interface name:")
nmc.sendline("eth0")
nmc.expect("There are 3 optional settings for Wired Ethernet.")
nmc.expect("Do you want to provide them\? \(yes/no\) \[yes]")
nmc.sendline("no")
nmc.expect("There are 2 optional settings for IPv4 protocol.")
nmc.expect("Do you want to provide them\? \(yes/no\) \[yes]")
nmc.sendline("no")
nmc.expect("There are 2 optional settings for IPv6 protocol.")
nmc.expect("Do you want to provide them\? \(yes/no\) \[yes]")
nmc.sendline("no")
nmc.expect("There are 4 optional settings for Proxy.")
nmc.expect("Do you want to provide them\? \(yes/no\) \[yes]")
nmc.sendline("no")
nmc.expect("Connection 'ethernet' \(.*\) successfully added.")
nmc.expect(pexpect.EOF)
nmc.pexp.expect("Connection type:")
nmc.pexp.sendline("ethernet")
nmc.pexp.expect("Interface name:")
nmc.pexp.sendline("eth0")
nmc.pexp.expect("There are 3 optional settings for Wired Ethernet.")
nmc.pexp.expect("Do you want to provide them\? \(yes/no\) \[yes]")
nmc.pexp.sendline("no")
nmc.pexp.expect("There are 2 optional settings for IPv4 protocol.")
nmc.pexp.expect("Do you want to provide them\? \(yes/no\) \[yes]")
nmc.pexp.sendline("no")
nmc.pexp.expect("There are 2 optional settings for IPv6 protocol.")
nmc.pexp.expect("Do you want to provide them\? \(yes/no\) \[yes]")
nmc.pexp.sendline("no")
nmc.pexp.expect("There are 4 optional settings for Proxy.")
nmc.pexp.expect("Do you want to provide them\? \(yes/no\) \[yes]")
nmc.pexp.sendline("no")
nmc.pexp.expect("Connection 'ethernet' \(.*\) successfully added.")
nmc.pexp.expect(pexpect.EOF)
Util.valgrind_check_log(nmc.valgrind_log, "test_ask_mode")
@skip_without_pexpect
@nm_test
def test_monitor(self):
# FIXME: this test is currently known to fail. Skip it.
# https://bugzilla.redhat.com/show_bug.cgi?id=2154288
raise unittest.SkipTest("test is known to randomly fail (rhbz#2154288)")
def start_mon():
def start_mon(self):
nmc = self.call_nmcli_pexpect(["monitor"])
nmc.expect("NetworkManager is running")
nmc.pexp.expect("NetworkManager is running")
return nmc
def end_mon(nmc):
nmc.kill(SIGINT)
nmc.expect(pexpect.EOF)
def end_mon(self, nmc):
nmc.pexp.kill(signal.SIGINT)
nmc.pexp.expect(pexpect.EOF)
Util.valgrind_check_log(nmc.valgrind_log, "test_monitor")
nmc = start_mon()
nmc = start_mon(self)
self.srv.op_AddObj("WiredDevice", iface="eth0")
nmc.expect("eth0: device created\r\n")
nmc.pexp.expect("eth0: device created\r\n")
self.srv.addConnection(
{"connection": {"type": "802-3-ethernet", "id": "con-1"}}
)
nmc.expect("con-1: connection profile created\r\n")
nmc.pexp.expect("con-1: connection profile created\r\n")
end_mon(nmc)
end_mon(self, nmc)
nmc = start_mon()
self.srv.shutdown()
self.srv = None
nmc.expect("eth0: device removed")
nmc.expect("con-1: connection profile removed")
nmc.expect("NetworkManager is stopped")
end_mon(nmc)
nmc = start_mon(self)
self.srv_shutdown()
Util.pexpect_expect_all(
nmc.pexp,
"con-1: connection profile removed",
"eth0: device removed",
)
nmc.pexp.expect("NetworkManager is stopped")
end_mon(self, nmc)
###############################################################################
@ -1971,16 +2132,13 @@ def main():
"eval `dbus-launch --sh-syntax`;\n"
+ 'trap "kill $DBUS_SESSION_BUS_PID" EXIT;\n'
+ "\n"
+ " ".join(
+ Util.shlex_join(
[
Util.quote(a)
for a in [
sys.executable,
__file__,
"--started-with-dbus-session",
]
+ sys.argv[1:]
sys.executable,
__file__,
"--started-with-dbus-session",
]
+ sys.argv[1:]
)
+ " \n"
+ "",

View file

@ -1,5 +1,30 @@
#!/bin/bash
# Runs the "test-python.sh" test, setting proper environment variables
# for the build tree.
#
# - the first three arguments are the BUILDDIR, SRCDIR and PYTHON paths.
# The following arguments are passed on to "test-python.sh".
#
# - you can use "--" to separate the extra arguments.
#
# The full format is
#
# $ src/tests/client/test-client.sh "$BUILDDIR" "$SRCDIR" "$PYTHON" -- "${EXTRA[@]}"
#
# - "$BUILDDIR" "$SRCDIR" and "$PYTHON" can be set to "", to fallback
# to a default.
#
# The safe way to call it is thus
#
# $ src/tests/client/test-client.sh "" "" "" -- "${EXTRA[@]}"
#
# but for brevity, you can also call
#
# $ src/tests/client/test-client.sh -- "${EXTRA[@]}"
#
# if (and only if) "${EXTRA[@]}" does not contain "--".
set -e
die() {
@ -7,29 +32,45 @@ die() {
exit 1
}
if [ "$2" != "" ]; then
SRCDIR="$(realpath "$2")"
if [ "$4" = "--" ] ; then
ARGS=("${@:1:3}")
EXTRA=("${@:5}")
elif [ "$3" = "--" ]; then
ARGS=("${@:1:2}")
EXTRA=("${@:4}")
elif [ "$2" = "--" ]; then
ARGS=("${@:1:1}")
EXTRA=("${@:3}")
elif [ "$1" = "--" ]; then
ARGS=()
EXTRA=("${@:2}")
else
ARGS=("${@:1:3}")
EXTRA=("${@:4}")
fi
if [ "${ARGS[1]}" != "" ]; then
SRCDIR="$(realpath "${ARGS[1]}")"
else
SRCDIR="$(realpath "$(dirname "$BASH_SOURCE")/../../..")"
fi
if [ "$1" != "" ]; then
BUILDDIR="$(realpath "$1")"
if [ "${ARGS[0]}" != "" ]; then
BUILDDIR="$(realpath "${ARGS[0]}")"
elif test -d "$SRCDIR/build" ; then
BUILDDIR="$(realpath "$SRCDIR/build")"
else
BUILDDIR="$SRCDIR"
fi
test -d "$BUILDDIR" || die "BUILDDIR \"$BUILDDIR\" does not exist?"
test -d "$SRCDIR" || die "SRCDIR \"$SRCDIR\" does not exist?"
if [ "$3" != "" ]; then
PYTHON="$3"
if [ "${ARGS[2]}" != "" ]; then
PYTHON="${ARGS[2]}"
elif [ "$PYTHON" == "" ]; then
PYTHON="$(command -v python)" || die "python not found?"
fi
test -d "$BUILDDIR" || die "BUILDDIR \"$BUILDDIR\" does not exist?"
test -d "$SRCDIR" || die "SRCDIR \"$SRCDIR\" does not exist?"
test -f "$BUILDDIR/src/nmcli/nmcli" || die "\"$BUILDDIR/src/nmcli/nmcli\" does not exist?"
if test -f "$BUILDDIR/src/libnm-client-impl/.libs/libnm.so" ; then
@ -57,7 +98,7 @@ export NM_TEST_CLIENT_BUILDDIR="$BUILDDIR"
# test output is grouped together.
r="ok"
"$PYTHON" "$SRCDIR/src/tests/client/test-client.py" -v &> "$BUILDDIR/src/tests/client/test-client.log" || r=fail
"$PYTHON" "$SRCDIR/src/tests/client/test-client.py" -v "${EXTRA[@]}" &> "$BUILDDIR/src/tests/client/test-client.log" || r=fail
cat "$BUILDDIR/src/tests/client/test-client.log"