From fae149b361bc52096d6bd41ec219a0f61936d96c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Helleu?= Date: Sat, 4 Apr 2020 18:10:02 +0200 Subject: [PATCH] python: fix crash when invalid UTF-8 string is in a WeeChat hashtable converted to a Python dict (closes #1463) --- ChangeLog.adoc | 4 ++++ src/plugins/python/weechat-python.c | 28 +++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/ChangeLog.adoc b/ChangeLog.adoc index c1200cbd3..4696879f5 100644 --- a/ChangeLog.adoc +++ b/ChangeLog.adoc @@ -18,6 +18,10 @@ https://weechat.org/files/releasenotes/ReleaseNotes-devel.html[release notes] [[v2.9]] == Version 2.9 (under dev) +Bug fixes:: + + * python: fix crash when invalid UTF-8 string is in a WeeChat hashtable converted to a Python dict (issue #1463) + Tests:: * irc: add tests on IRC color functions diff --git a/src/plugins/python/weechat-python.c b/src/plugins/python/weechat-python.c index b1ec9bb3a..4ef9e553d 100644 --- a/src/plugins/python/weechat-python.c +++ b/src/plugins/python/weechat-python.c @@ -234,13 +234,31 @@ weechat_python_hashtable_map_cb (void *data, dict = (PyObject *)data; - dict_key = Py_BuildValue ("s", key); - dict_value = Py_BuildValue ("s", value); +#if PY_MAJOR_VERSION >= 3 + /* key */ + if (weechat_utf8_is_valid (key, -1, NULL)) + dict_key = Py_BuildValue ("s", key); /* Python 3: str */ + else + dict_key = Py_BuildValue ("y", key); /* Python 3: bytes */ + /* value */ + if (weechat_utf8_is_valid (value, -1, NULL)) + dict_value = Py_BuildValue ("s", value); /* Python 3: str */ + else + dict_value = Py_BuildValue ("y", value); /* Python 3: bytes */ +#else + /* key */ + dict_key = Py_BuildValue ("s", key); /* Python 2: str */ + /* value */ + dict_value = Py_BuildValue ("s", value); /* Python 2: str */ +#endif - PyDict_SetItem (dict, dict_key, dict_value); + if (dict_key && dict_value) + PyDict_SetItem (dict, dict_key, dict_value); - Py_DECREF (dict_key); - Py_DECREF (dict_value); + if (dict_key) + Py_DECREF (dict_key); + if (dict_value) + Py_DECREF (dict_value); } /*