From cfe5c4a43bd47c21c377dc15acee43771b66bc54 Mon Sep 17 00:00:00 2001 From: levlam Date: Sat, 4 Jun 2022 14:57:29 +0300 Subject: [PATCH] Ensure that strings passed to TDLib's log message callback are UTF-8 encoded. --- td/telegram/Client.cpp | 15 ++++++++++++++- td/telegram/Client.h | 2 +- td/telegram/td_json_client.h | 2 +- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/td/telegram/Client.cpp b/td/telegram/Client.cpp index e9f9bf548..a102efbfd 100644 --- a/td/telegram/Client.cpp +++ b/td/telegram/Client.cpp @@ -24,6 +24,8 @@ #include "td/utils/port/RwMutex.h" #include "td/utils/port/thread.h" #include "td/utils/Slice.h" +#include "td/utils/StringBuilder.h" +#include "td/utils/utf8.h" #include #include @@ -679,7 +681,18 @@ static std::atomic log_message_callback; static void log_message_callback_wrapper(int verbosity_level, CSlice message) { auto callback = log_message_callback.load(std::memory_order_relaxed); if (callback != nullptr) { - callback(verbosity_level, message.c_str()); + if (check_utf8(message)) { + callback(verbosity_level, message.c_str()); + } else { + size_t pos = 0; + while (1 <= message[pos] && message[pos] <= 126) { + pos++; + } + CHECK(pos + 1 < message.size()); + auto utf8_message = PSTRING() << message.substr(0, pos) + << url_encode(message.substr(pos, message.size() - pos - 1)) << '\n'; + callback(verbosity_level, utf8_message.c_str()); + } } } diff --git a/td/telegram/Client.h b/td/telegram/Client.h index f765d0264..b8c1e814f 100644 --- a/td/telegram/Client.h +++ b/td/telegram/Client.h @@ -129,7 +129,7 @@ class ClientManager final { * \param verbosity_level Log verbosity level with which the message was added (-1 - 1024). * If 0, then TDLib will crash as soon as the callback returns. * None of the TDLib methods can be called from the callback. - * \param message Null-terminated string with the message added to the log. + * \param message Null-terminated UTF-8-encoded string with the message added to the log. */ using LogMessageCallbackPtr = void (*)(int verbosity_level, const char *message); diff --git a/td/telegram/td_json_client.h b/td/telegram/td_json_client.h index e27a3bae7..e6e0c2ded 100644 --- a/td/telegram/td_json_client.h +++ b/td/telegram/td_json_client.h @@ -91,7 +91,7 @@ TDJSON_EXPORT const char *td_execute(const char *request); * \param verbosity_level Log verbosity level with which the message was added (-1 - 1024). * If 0, then TDLib will crash as soon as the callback returns. * None of the TDLib methods can be called from the callback. - * \param message Null-terminated string with the logged message. The string isn't guaranteed to be encoded in UTF-8. + * \param message Null-terminated UTF-8-encoded string with the message added to the log. */ typedef void (*td_log_message_callback_ptr)(int verbosity_level, const char *message);