Merge pull request #12044 from keszybz/ttyname-malloc-simplification

util-lib: use a fixed buffer size for terminal path
This commit is contained in:
Lennart Poettering 2019-03-26 10:05:29 +01:00 committed by GitHub
commit adca059d55
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 21 deletions

View file

@ -891,33 +891,24 @@ bool on_tty(void) {
}
int getttyname_malloc(int fd, char **ret) {
size_t l = 100;
char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */
int r;
assert(fd >= 0);
assert(ret);
for (;;) {
char path[l];
r = ttyname_r(fd, path, sizeof path); /* positive error */
assert(r >= 0);
if (r == ERANGE)
return -ENAMETOOLONG;
if (r > 0)
return -r;
r = ttyname_r(fd, path, sizeof(path));
if (r == 0) {
char *c;
c = strdup(skip_dev_prefix(path));
if (!c)
return -ENOMEM;
*ret = c;
return 0;
}
if (r != ERANGE)
return -r;
l *= 2;
}
c = strdup(skip_dev_prefix(path));
if (!c)
return -ENOMEM;
*ret = c;
return 0;
}

View file

@ -6,6 +6,7 @@
#include "alloc-util.h"
#include "fd-util.h"
#include "macro.h"
#include "path-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "tests.h"
@ -52,7 +53,16 @@ static void test_read_one_char(void) {
rewind(file);
assert_se(read_one_char(file, &r, 1000000, &need_nl) < 0);
unlink(name);
assert_se(unlink(name) >= 0);
}
static void test_getttyname_malloc(void) {
_cleanup_free_ char *ttyname = NULL;
_cleanup_close_ int master = -1;
assert_se((master = posix_openpt(O_RDWR|O_NOCTTY)) >= 0);
assert_se(getttyname_malloc(master, &ttyname) >= 0);
assert_se(PATH_IN_SET(ttyname, "ptmx", "pts/ptmx"));
}
int main(int argc, char *argv[]) {
@ -60,6 +70,7 @@ int main(int argc, char *argv[]) {
test_default_term_for_tty();
test_read_one_char();
test_getttyname_malloc();
return 0;
}