Skip to content

Possible unsound public API #11

Description

@charlesxsh
pub struct CopyingBufReader<R> {
    inner: R,
    pub buf: Box<[u8]>,
    pub pos: usize,
    pub amt: usize
}

impl<R: Read> CopyingBufReader<R> {
 pub fn refill(&mut self) {
        let buf_kept = self.amt - self.pos;
        let buf_len = self.buf.len();

        unsafe {
            ptr::copy(
                self.buf.as_ptr().offset(self.pos as isize),
                self.buf.as_mut_ptr(),
                buf_kept
            );
        }

        self.amt = buf_kept + self.inner.read(&mut self.buf[buf_kept..buf_len]).unwrap();
        self.pos = 0;
    }

    pub fn peek(&mut self) -> Option<u8> {
        if self.pos == self.amt {
            self.refill();
        }
        
        if self.amt > 0 {
            Some(unsafe { *self.buf.get_unchecked(self.pos) })
        } else {
            None
        }
    }
...

Publicly accessible function refill and peek does not have sufficient check before doing pointer calculation (public field pos is vulnerable), which might have memory issues. In Rust, we should not have memory issues by merely using safe functions.

Suggestions:

  1. add sufficient check
  2. make the field private
  3. mark the function with unsafe

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions