shared/ask-password-api: return "error" when dialogue is cancelled

test-ask-password-api would crash if ^D was pressed.
If think the callers generally expect a non-empty strv as reply. Let's
return an error if we have nothing to return.

Also modernize test-ask-password-api a bit.
This commit is contained in:
Zbigniew Jędrzejewski-Szmek 2020-02-06 09:32:16 +01:00
parent 39e96f844a
commit 72c08a471c
2 changed files with 19 additions and 13 deletions

View File

@ -658,11 +658,15 @@ int ask_password_tty(
goto finish;
skipped:
if (keyname)
(void) add_to_keyring_and_log(keyname, flags, l);
if (strv_isempty(l))
r = log_debug_errno(SYNTHETIC_ERRNO(ECANCELED), "Password query was cancelled.");
else {
if (keyname)
(void) add_to_keyring_and_log(keyname, flags, l);
*ret = TAKE_PTR(l);
r = 0;
*ret = TAKE_PTR(l);
r = 0;
}
finish:
if (ttyfd >= 0 && reset_tty) {

View File

@ -1,24 +1,26 @@
/* SPDX-License-Identifier: LGPL-2.1+ */
#include "alloc-util.h"
#include "ask-password-api.h"
#include "log.h"
#include "strv.h"
#include "tests.h"
static void ask_password(void) {
static void test_ask_password(void) {
int r;
_cleanup_strv_free_ char **ret = NULL;
r = ask_password_tty(-1, "hello?", "da key", 0, 0, NULL, &ret);
assert(r >= 0);
assert(strv_length(ret) == 1);
log_info("Got %s", *ret);
if (r == -ECANCELED)
assert_se(ret == NULL);
else {
assert_se(r >= 0);
assert_se(strv_length(ret) == 1);
log_info("Got \"%s\"", *ret);
}
}
int main(int argc, char **argv) {
log_parse_environment();
test_setup_logging(LOG_DEBUG);
ask_password();
test_ask_password();
return EXIT_SUCCESS;
}