From 57998018d9569be2f908faa034945db258577556 Mon Sep 17 00:00:00 2001 From: Antonio Gutierrez Date: Sat, 20 Jul 2019 02:44:15 +0200 Subject: [PATCH 1/2] Use thread-safe functions instead of unsafe ones (crypt, ttyname) * Use dynamically-allocated buffer for ttyname_r buffer * In case there is an error with the crypt/crypt_r then raise the error, instead of failing silently. * Check for EINVAL (invalid argument) in errno when adding not supported cryptographic methods, such as Blowfish in the case of glibc, but raise other errors. * Use _SC_TTY_MAX_LENGTH for TTY_NAME_MAX Signed-off-by: Antonio Gutierrez --- .../2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst | 1 + Modules/posixmodule.c | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst diff --git a/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst b/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst new file mode 100644 index 00000000000000..aa0884ee1bad3f --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst @@ -0,0 +1 @@ +Use ttyname_r instead of ttyname for thread safety diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c index 5664027b2d3a3e..aeb0e9ddb1953c 100644 --- a/Modules/posixmodule.c +++ b/Modules/posixmodule.c @@ -2774,13 +2774,24 @@ static PyObject * os_ttyname_impl(PyObject *module, int fd) /*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/ { - char *ret; - ret = ttyname(fd); - if (ret == NULL) { + long size = sysconf(_SC_TTY_NAME_MAX); + if (size == -1) { + return posix_error(); + } + char *buffer = (char *)PyMem_RawMalloc(size); + if (buffer == NULL) { + return PyErr_NoMemory(); + } + int ret = ttyname_r(fd, buffer, size); + if (ret != 0) { + PyMem_RawFree(buffer); + errno = ret; return posix_error(); } - return PyUnicode_DecodeFSDefault(ret); + PyObject *res = PyUnicode_DecodeFSDefault(buffer); + PyMem_RawFree(buffer); + return res; } #endif From 1614f7d770a10b2434474dbc3df73df623a4a284 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Tue, 8 Oct 2019 19:00:03 -0700 Subject: [PATCH 2/2] tweak NEWS --- .../next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst b/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst index aa0884ee1bad3f..b31496c7017447 100644 --- a/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst +++ b/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst @@ -1 +1 @@ -Use ttyname_r instead of ttyname for thread safety +In :mod:`posix`, use ``ttyname_r`` instead of ``ttyname`` for thread safety.