Skip to content

Commit 001a2cb

Browse files
eryugeyliubogithub
authored andcommitted
server: trim extra '\0's in bytes_to_cstr()
Currently bytes_to_cstr() expects one and only one '\0' and the end of the buffer, but we've seen lookup request with name buffer having multiple '\0's at the end and caused failures. To make it more robust, trim extra zeros in buffer, this also follows what virtiofsd does. Signed-off-by: Eryu Guan <eguan@linux.alibaba.com>
1 parent 0144710 commit 001a2cb

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/api/server.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1395,9 +1395,21 @@ fn reply_error(err: io::Error, unique: u64, mut w: Writer) -> Result<usize> {
13951395
}
13961396

13971397
fn bytes_to_cstr(buf: &[u8]) -> Result<&CStr> {
1398-
// Convert to a `CStr` first so that we can drop the '\0' byte at the end
1399-
// and make sure there are no interior '\0' bytes.
1400-
CStr::from_bytes_with_nul(buf).map_err(Error::InvalidCString)
1398+
// There might be multiple 0s at the end of buf, find & use the first one and trim other zeros.
1399+
let len = buf.len();
1400+
let mut n: usize = 0;
1401+
for c in buf.iter() {
1402+
if c == &0 {
1403+
break;
1404+
}
1405+
n += 1;
1406+
}
1407+
let nul_pos = if n + 1 >= len { len } else { n + 1 };
1408+
let newbuf = &buf[0..nul_pos];
1409+
1410+
// Convert to a `CStr` so that we can drop the '\0' byte at the end and make sure there are no
1411+
// interior '\0' bytes.
1412+
CStr::from_bytes_with_nul(newbuf).map_err(Error::InvalidCString)
14011413
}
14021414

14031415
fn add_dirent(

0 commit comments

Comments
 (0)