From 91222a67c817f4752778a5afe9e9400336b2b90a Mon Sep 17 00:00:00 2001 From: Emanuele Torre Date: Sun, 10 Jan 2021 04:41:30 +0100 Subject: [PATCH] LibCore: get_password() now removes the trailing '\n' read by getline() This avoids unintentionally adding a newline character at the end of user passwords when they are set using passwd(1). I also fixed these two issues: - The return value of getline() was being saved in an `int` variable instead of in a `ssize_t` variable; I replaced the `int` keyword with `auto` to fix this issue. - Prior to this patch, get_password() could potentially return tcsetattr()'s errno instead of getline()'s errno in case of an error. We now make sure it always returns the right errno in case of an error. --- Libraries/LibCore/GetPassword.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Libraries/LibCore/GetPassword.cpp b/Libraries/LibCore/GetPassword.cpp index 73d123bd0a..028e987c59 100644 --- a/Libraries/LibCore/GetPassword.cpp +++ b/Libraries/LibCore/GetPassword.cpp @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, Peter Elliott + * Copyright (c) 2021, Emanuele Torre * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -48,12 +49,19 @@ Result get_password(const StringView& prompt) char* password = nullptr; size_t n = 0; - int ret = getline(&password, &n, stdin); + auto line_length = getline(&password, &n, stdin); + int saved_errno = errno; + tcsetattr(STDIN_FILENO, TCSAFLUSH, &original); putchar('\n'); - if (ret < 0) { - return errno; - } + + if (line_length < 0) + return saved_errno; + + ASSERT(line_length != 0); + + // Remove trailing '\n' read by getline(). + password[line_length - 1] = '\0'; String s(password); free(password);