Skip to content

Commit

Permalink
change unwrap to ok_or or unwrap_or{_default}
Browse files Browse the repository at this point in the history
Replace a plain `unwrap()` with `ok_or` or `unwrap_or` or
`unwrap_or_default`, to prevent from binaries or libs from panicking
at runtime.
  • Loading branch information
dongsupark committed Nov 30, 2023
1 parent ee3918a commit cf40389
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 22 deletions.
35 changes: 25 additions & 10 deletions omaha/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,11 @@ impl<'__input: 'a, 'a> hard_xml::XmlRead<'__input> for Manifest<'a> {
}
}

if let Token::ElementEnd { end: ElementEnd::Empty, .. }
= reader.next().unwrap()?
if let Ok(Token::ElementEnd { end: ElementEnd::Empty, .. })
= reader.next().ok_or(XmlError::MissingField {
name: "Manifest".to_owned(),
field: "version".to_owned(),
})?
{
return Ok(Manifest {
version: __self_version
Expand All @@ -170,8 +173,11 @@ impl<'__input: 'a, 'a> hard_xml::XmlRead<'__input> for Manifest<'a> {

while (reader.find_attribute()?).is_some() {}

if let Token::ElementEnd { end: ElementEnd::Empty, .. }
= reader.next().unwrap()?
if let Ok(Token::ElementEnd { end: ElementEnd::Empty, .. })
= reader.next().ok_or(XmlError::MissingField {
name: "Manifest".to_owned(),
field: "version".to_owned(),
})?
{
continue;
}
Expand All @@ -197,8 +203,11 @@ impl<'__input: 'a, 'a> hard_xml::XmlRead<'__input> for Manifest<'a> {

while (reader.find_attribute()?).is_some() {}

if let Token::ElementEnd { end: ElementEnd::Empty, .. }
= reader.next().unwrap()?
if let Ok(Token::ElementEnd { end: ElementEnd::Empty, .. })
= reader.next().ok_or(XmlError::MissingField {
name: "Manifest".to_owned(),
field: "version".to_owned(),
})?
{
continue;
}
Expand Down Expand Up @@ -264,8 +273,11 @@ impl<'__input: 'a, 'a> hard_xml::XmlRead<'__input> for UpdateCheck<'a> {
}
}

if let Token::ElementEnd { end: ElementEnd::Empty, .. }
= reader.next().unwrap()?
if let Ok(Token::ElementEnd { end: ElementEnd::Empty, .. })
= reader.next().ok_or(XmlError::MissingField {
name: "UpdateCheck".to_owned(),
field: "manifest".to_owned(),
})?
{
return Ok(UpdateCheck {
status: __self_status
Expand All @@ -288,8 +300,11 @@ impl<'__input: 'a, 'a> hard_xml::XmlRead<'__input> for UpdateCheck<'a> {
reader.read_till_element_start("urls")?;

while (reader.find_attribute()?).is_some() {}
if let Token::ElementEnd { end: ElementEnd::Empty, .. }
= reader.next().unwrap()?
if let Ok(Token::ElementEnd { end: ElementEnd::Empty, .. })
= reader.next().ok_or(XmlError::MissingField {
name: "UpdateCheck".to_owned(),
field: "manifest".to_owned(),
})?
{
continue;
}
Expand Down
14 changes: 7 additions & 7 deletions update-format-crau/src/delta_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::fs::File;
use std::path::Path;
use log::{debug, info};
use bzip2::read::BzDecoder;
use anyhow::{Context, Result, bail};
use anyhow::{Context, Result, anyhow, bail};

use protobuf::Message;

Expand Down Expand Up @@ -91,7 +91,7 @@ pub fn get_signatures_bytes<'a>(f: &'a mut BufReader<File>, header: &'a DeltaUpd
_ => None,
};

Ok(signatures_bytes.unwrap())
signatures_bytes.ok_or(anyhow!("failed to get signature bytes slice"))
}

// Return data length, including header and manifest.
Expand All @@ -103,13 +103,13 @@ pub fn get_header_data_length(header: &DeltaUpdateFileHeader, manifest: &proto::
// Payload data structure:
// | header | manifest | data blobs | signatures |

header.translate_offset(manifest.signatures_offset.unwrap()) as usize
header.translate_offset(manifest.signatures_offset.unwrap_or_default()) as usize
}

// Take a buffer reader, delta file header, manifest as input.
// Return path to data blobs, without header, manifest, or signatures.
pub fn get_data_blobs<'a>(f: &'a mut BufReader<File>, header: &'a DeltaUpdateFileHeader, manifest: &proto::DeltaArchiveManifest, tmpfile: &Path) -> Result<File> {
let tmpdir = tmpfile.parent().unwrap();
let tmpdir = tmpfile.parent().ok_or(anyhow!("unable to get parent directory"))?;
fs::create_dir_all(tmpdir).context(format!("failed to create directory {:?}", tmpdir))?;
let mut outfile = File::create(tmpfile).context(format!("failed to create file {:?}", tmpfile))?;

Expand All @@ -118,8 +118,8 @@ pub fn get_data_blobs<'a>(f: &'a mut BufReader<File>, header: &'a DeltaUpdateFil
// get_header_data_length.
// Iterate each partition_operations to get data offset and data length.
for pop in &manifest.partition_operations {
let data_offset = pop.data_offset.unwrap();
let data_length = pop.data_length.unwrap();
let data_offset = pop.data_offset.ok_or(anyhow!("unable to get data offset"))?;
let data_length = pop.data_length.ok_or(anyhow!("unable to get data length"))?;

let mut partdata = vec![0u8; data_length as usize];

Expand All @@ -128,7 +128,7 @@ pub fn get_data_blobs<'a>(f: &'a mut BufReader<File>, header: &'a DeltaUpdateFil
f.read_exact(&mut partdata).context(format!("failed to read data with length {:?}", data_length))?;

// In case of bzip2-compressed chunks, extract.
if pop.type_.unwrap() == proto::install_operation::Type::REPLACE_BZ.into() {
if pop.type_.ok_or(anyhow!("unable to get type_ from partition operations"))? == proto::install_operation::Type::REPLACE_BZ.into() {
let mut bzdecoder = BzDecoder::new(&partdata[..]);
let mut partdata_unpacked = Vec::new();
bzdecoder.read_to_end(&mut partdata_unpacked).context(format!("failed to unpack bzip2ed data at offset {:?}", translated_offset))?;
Expand Down
20 changes: 15 additions & 5 deletions update-format-crau/src/verify_sig.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{Context, Result, bail};
use anyhow::{Context, Result, anyhow, bail};
use rsa::{RsaPrivateKey, RsaPublicKey};
use rsa::pkcs1::{DecodeRsaPrivateKey, DecodeRsaPublicKey};
use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey};
Expand Down Expand Up @@ -40,7 +40,12 @@ pub fn verify_rsa_pkcs_buf(databuf: &[u8], signature: &[u8], public_key: RsaPubl

let verifying_key = pkcs1v15::VerifyingKey::<Sha256>::new(public_key);

verifying_key.verify(databuf, &pkcs1v15::Signature::try_from(signature).unwrap()).context(format!("failed to verify signature ({:?})", signature))
verifying_key
.verify(
databuf,
&pkcs1v15::Signature::try_from(signature).context(anyhow!("unable to convert signature into pkcs1v15::Signature"))?,
)
.context(format!("failed to verify signature ({:?})", signature))
}

// Takes a data buffer, signature and a public key, to verify the data
Expand All @@ -52,11 +57,16 @@ pub fn verify_rsa_pkcs_buf(databuf: &[u8], signature: &[u8], public_key: RsaPubl
pub fn verify_rsa_pkcs_prehash(digestbuf: &[u8], signature: &[u8], public_key: RsaPublicKey) -> Result<()> {
let verifying_key = pkcs1v15::VerifyingKey::<Sha256>::new(public_key);

verifying_key.verify_prehash(digestbuf, &pkcs1v15::Signature::try_from(signature).unwrap()).context(format!("failed to verify_prehash signature ({:?})", signature))
verifying_key
.verify_prehash(
digestbuf,
&pkcs1v15::Signature::try_from(signature).context(anyhow!("unable to convert signature into pkcs1v15::Signature"))?,
)
.context(format!("failed to verify_prehash signature ({:?})", signature))
}

pub fn get_private_key_pkcs_pem(private_key_path: &str, key_type: KeyType) -> Result<RsaPrivateKey> {
let private_key_buf = fs::read_to_string(private_key_path).unwrap();
let private_key_buf = fs::read_to_string(private_key_path).context(format!("failed to read private key from path {:?}", private_key_path))?;
let out_key = match key_type {
KeyType::KeyTypePkcs1 => RsaPrivateKey::from_pkcs1_pem(private_key_buf.as_str()).or_else(|error| {
bail!("failed to parse PKCS1 PEM message: {:?}", error);
Expand All @@ -73,7 +83,7 @@ pub fn get_private_key_pkcs_pem(private_key_path: &str, key_type: KeyType) -> Re
}

pub fn get_public_key_pkcs_pem(public_key_path: &str, key_type: KeyType) -> Result<RsaPublicKey> {
let public_key_buf = fs::read_to_string(public_key_path).unwrap();
let public_key_buf = fs::read_to_string(public_key_path).context(format!("failed to read public key from path {:?}", public_key_path))?;
let out_key = match key_type {
KeyType::KeyTypePkcs1 => RsaPublicKey::from_pkcs1_pem(public_key_buf.as_str()).or_else(|error| {
bail!("failed to parse PKCS1 PEM message: {:?}", error);
Expand Down

0 comments on commit cf40389

Please sign in to comment.