Skip to content

Add bounds check and get rid of allocation for set_{user,owner}_password #142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 24, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions src/pdf/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use num_enum::TryFromPrimitive;

use crate::pdf::{PdfGraftMap, PdfObject, PdfPage};
use crate::{
context, Buffer, CjkFontOrdering, Destination, DestinationKind, Document, Error, Font, Image,
Outline, Point, SimpleFontEncoding, Size, WriteMode,
context, Buffer, CjkFontOrdering, Destination, DestinationKind, Document, Error, FilePath,
Font, Image, Outline, Point, SimpleFontEncoding, Size, WriteMode,
};

bitflags! {
Expand Down Expand Up @@ -202,11 +202,15 @@ impl PdfWriteOptions {
}

pub fn set_owner_password(&mut self, pwd: &str) -> &mut Self {
let len = pwd.len() + 1;
let c_pwd = CString::new(pwd).unwrap();
assert!(pwd.len() < self.inner.opwd_utf8.len());
unsafe {
ptr::copy_nonoverlapping(c_pwd.as_ptr(), self.inner.opwd_utf8.as_mut_ptr(), len);
ptr::copy_nonoverlapping(
pwd.as_ptr().cast(),
self.inner.opwd_utf8.as_mut_ptr(),
pwd.len(),
);
}
self.inner.opwd_utf8[pwd.len()] = 0;
self
}

Expand All @@ -216,11 +220,15 @@ impl PdfWriteOptions {
}

pub fn set_user_password(&mut self, pwd: &str) -> &mut Self {
let len = pwd.len() + 1;
let c_pwd = CString::new(pwd).unwrap();
assert!(pwd.len() < self.inner.upwd_utf8.len());
unsafe {
ptr::copy_nonoverlapping(c_pwd.as_ptr(), self.inner.upwd_utf8.as_mut_ptr(), len);
ptr::copy_nonoverlapping(
pwd.as_ptr().cast(),
self.inner.upwd_utf8.as_mut_ptr(),
pwd.len(),
);
}
self.inner.upwd_utf8[pwd.len()] = 0;
self
}
}
Expand All @@ -245,8 +253,8 @@ impl PdfDocument {
}
}

pub fn open(filename: &str) -> Result<Self, Error> {
let doc = Document::open(filename)?;
pub fn open<P: AsRef<FilePath> + ?Sized>(p: &P) -> Result<Self, Error> {
let doc = Document::open(p)?;
Self::try_from(doc)
}

Expand Down