From d6f441bdf4b87762c1fab9773902994367959860 Mon Sep 17 00:00:00 2001 From: Antoine Poinsot Date: Tue, 15 Jun 2021 01:22:34 +0200 Subject: [PATCH] hsm_encryption: merge getline() logic between stdin and non-stdin Avoid duplicating it, to minimize the potential for divergence. Signed-off-by: Antoine Poinsot --- common/hsm_encryption.c | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/common/hsm_encryption.c b/common/hsm_encryption.c index 2bc457a27..3b676c5db 100644 --- a/common/hsm_encryption.c +++ b/common/hsm_encryption.c @@ -80,6 +80,18 @@ void discard_key(struct secret *key TAKES) tal_free(key); } +/* Read a line from stdin, do not take the newline character into account. */ +static bool getline_stdin_pass(char **passwd, size_t *passwd_size) +{ + if (getline(passwd, passwd_size, stdin) < 0) + return false; + + if ((*passwd)[strlen(*passwd) - 1] == '\n') + (*passwd)[strlen(*passwd) - 1] = '\0'; + + return true; +} + char *read_stdin_pass(char **reason) { struct termios current_term, temp_term; @@ -99,13 +111,10 @@ char *read_stdin_pass(char **reason) return NULL; } - /* Read the password, do not take the newline character into account. */ - if (getline(&passwd, &passwd_size, stdin) < 0) { + if (!getline_stdin_pass(&passwd, &passwd_size)) { *reason = "Could not read pass from stdin."; return NULL; } - if (passwd[strlen(passwd) - 1] == '\n') - passwd[strlen(passwd) - 1] = '\0'; /* Restore the original terminal */ if (tcsetattr(fileno(stdin), TCSAFLUSH, ¤t_term) != 0) { @@ -113,14 +122,9 @@ char *read_stdin_pass(char **reason) free(passwd); return NULL; } - } else { - /* Read from stdin, do not take the newline character into account. */ - if (getline(&passwd, &passwd_size, stdin) < 0) { - *reason = "Could not read pass from stdin."; - return NULL; - } - if (passwd[strlen(passwd) - 1] == '\n') - passwd[strlen(passwd) - 1] = '\0'; + } else if (!getline_stdin_pass(&passwd, &passwd_size)) { + *reason = "Could not read pass from stdin."; + return NULL; } return passwd;