Skip to content

Commit b153848

Browse files
authored
Add bounds check and get rid of allocation for set_{user,owner}_password (#142)
1 parent fd96274 commit b153848

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

src/pdf/document.rs

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use num_enum::TryFromPrimitive;
1010

1111
use crate::pdf::{PdfGraftMap, PdfObject, PdfPage};
1212
use crate::{
13-
context, Buffer, CjkFontOrdering, Destination, DestinationKind, Document, Error, Font, Image,
14-
Outline, Point, SimpleFontEncoding, Size, WriteMode,
13+
context, Buffer, CjkFontOrdering, Destination, DestinationKind, Document, Error, FilePath,
14+
Font, Image, Outline, Point, SimpleFontEncoding, Size, WriteMode,
1515
};
1616

1717
bitflags! {
@@ -202,11 +202,15 @@ impl PdfWriteOptions {
202202
}
203203

204204
pub fn set_owner_password(&mut self, pwd: &str) -> &mut Self {
205-
let len = pwd.len() + 1;
206-
let c_pwd = CString::new(pwd).unwrap();
205+
assert!(pwd.len() < self.inner.opwd_utf8.len());
207206
unsafe {
208-
ptr::copy_nonoverlapping(c_pwd.as_ptr(), self.inner.opwd_utf8.as_mut_ptr(), len);
207+
ptr::copy_nonoverlapping(
208+
pwd.as_ptr().cast(),
209+
self.inner.opwd_utf8.as_mut_ptr(),
210+
pwd.len(),
211+
);
209212
}
213+
self.inner.opwd_utf8[pwd.len()] = 0;
210214
self
211215
}
212216

@@ -216,11 +220,15 @@ impl PdfWriteOptions {
216220
}
217221

218222
pub fn set_user_password(&mut self, pwd: &str) -> &mut Self {
219-
let len = pwd.len() + 1;
220-
let c_pwd = CString::new(pwd).unwrap();
223+
assert!(pwd.len() < self.inner.upwd_utf8.len());
221224
unsafe {
222-
ptr::copy_nonoverlapping(c_pwd.as_ptr(), self.inner.upwd_utf8.as_mut_ptr(), len);
225+
ptr::copy_nonoverlapping(
226+
pwd.as_ptr().cast(),
227+
self.inner.upwd_utf8.as_mut_ptr(),
228+
pwd.len(),
229+
);
223230
}
231+
self.inner.upwd_utf8[pwd.len()] = 0;
224232
self
225233
}
226234
}
@@ -245,8 +253,8 @@ impl PdfDocument {
245253
}
246254
}
247255

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

0 commit comments

Comments
 (0)