From c9cc3fa24bf614dab769ebb060a3abc25c47dbab Mon Sep 17 00:00:00 2001 From: Christian Klauser Date: Sat, 13 Apr 2024 16:11:24 +0200 Subject: [PATCH] Use CStr::from_bytes_until_nul to read rdkafka config Commit 353812ff958b4b65f9e65dd22a60e770ed6ba948 replaced the more finicky `CStr::from_bytes_with_nul` with `String::from_utf8_lossy`. That eliminated a panic but the returned Rust string now contained NUL bytes. This might have accidentally worked in FFI APIs that take C strings, but it fails when such a string is passed to a Rust API, such as integer parsing in `stream_consumer.rs:217`. The newer `CStr::from_bytes_until_nul` function 1. does not panic 2. ends the string at the first NUL byte It does return an error when there is no NUL byte in the input slice. While it would be possible to fall back to `String::from_utf8_lossy` in that case, I'm not sure that would be a good idea. If we are in that situation, librdkafka clearly has messed something up completely. The contents of the buffer are then more likely complete garbage. --- src/config.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index fc116d2a7..29a83863c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -23,7 +23,7 @@ //! [librdkafka-config]: https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md use std::collections::HashMap; -use std::ffi::CString; +use std::ffi::{CStr, CString}; use std::iter::FromIterator; use std::os::raw::c_char; use std::ptr; @@ -150,8 +150,9 @@ impl NativeClientConfig { } // Convert the C string to a Rust string. - Ok(String::from_utf8_lossy(&buf) - .trim_matches(char::from(0)) + Ok(CStr::from_bytes_until_nul(&buf) + .expect("rd_kafka_conf_get to write a NUL-terminated string.") + .to_string_lossy() .to_string()) } }