summaryrefslogtreecommitdiff
path: root/Libraries
diff options
context:
space:
mode:
authorEmanuele Torre <torreemanuele6@gmail.com>2021-01-10 04:41:30 +0100
committerAndreas Kling <kling@serenityos.org>2021-01-10 16:40:05 +0100
commit91222a67c817f4752778a5afe9e9400336b2b90a (patch)
tree671fd9de34344e58e58e5d71b72eff99298e71c6 /Libraries
parent9e5aa6f794ef9ab5828d5874c2e40de9a4fa8349 (diff)
downloadserenity-91222a67c817f4752778a5afe9e9400336b2b90a.zip
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.
Diffstat (limited to 'Libraries')
-rw-r--r--Libraries/LibCore/GetPassword.cpp16
1 files 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 <pelliott@ualberta.ca>
+ * Copyright (c) 2021, Emanuele Torre <torreemanuele6@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -48,12 +49,19 @@ Result<String, int> 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);