I'm building an encrypting TCP proxy system where one peer sends a series of encrypted fixed-size messages to the other peer, which decrypts them. It uses Tokio 0.2, the
bytes crate for buffer management and Sodiumoxide for encryption. Every once in a while, the messages fail to decrypt. Turns out that this happens whenever more than one read is required to get a complete message.
The essence of the "read and decrypt" operation is a loop that calls
read_buf() on the TCP stream's
ReadHalf, which attempts to fill up a
BytesMut buffer. When the length of the buffer equals the expected message size, decryption is attempted and the buffer is cleared (with
On partial reads, something I don't expect is happening. A specific example is this:
- The sender sends two messages. Just for the sake of illustration, the two messages are "hello world" and "how are you".
- The receiver takes two calls to
read_buf()to read the the first message. For the purposes of this example, let's say the reads are of length 7 and 4. So the expected chunks would be "hello w" and "orld"
- What ends up in the buffer, however, is the following: "hello whow ". The last part of the first message was apparently discarded and the first part of the next message appears in it place.
I have a logic bug here that I can't spot, or I don't know the proper technique of accumulating data into the
BytesMut buffer. Any ideas what I am doing wrong?