Skip to content

Commit e118fa8

Browse files
committed
Refactoring IO for overwriting file
1 parent c088d4d commit e118fa8

File tree

10 files changed

+79
-101
lines changed

10 files changed

+79
-101
lines changed

intel-sgx/dcap-artifact-retrieval/src/cli.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
use std::path::{Path, PathBuf};
99

1010
use clap::clap_app;
11-
use pcs::{PckID, DcapArtifactIssuer};
11+
use pcs::{PckID, DcapArtifactIssuer, WriteOption};
1212
use reqwest::Url;
1313
use rustc_serialize::hex::ToHex;
1414
use serde::de::{value, IntoDeserializer};
@@ -72,19 +72,19 @@ fn download_dcap_artifacts(
7272
// instead we mimic it using pckcert API.
7373
let pckcerts = prov_client.pckcerts_with_fallback(&pckid)?;
7474

75-
let pckcerts_file = pckcerts.store(output_dir, pckid.qe_id.as_slice())?;
75+
let pckcerts_file = pckcerts.store(output_dir, pckid.qe_id.as_slice(), WriteOption { overwrite: true })?;
7676

7777
if verbose {
78-
println!(" pckcerts: {}", pckcerts_file);
78+
println!(" pckcerts: {}", pckcerts_file.unwrap().display());
7979
}
8080

8181
let fmspc = pckcerts.fmspc()?;
8282
let evaluation_data_numbers = prov_client
8383
.tcb_evaluation_data_numbers()?;
8484

85-
let file = evaluation_data_numbers.write_to_file(output_dir)?;
85+
let file = evaluation_data_numbers.write_to_file(output_dir, WriteOption { overwrite: true })?;
8686
if verbose {
87-
println!(" tcb evaluation data numbers: {}\n", file);
87+
println!(" tcb evaluation data numbers: {}\n", file.unwrap().display());
8888
}
8989

9090
for number in evaluation_data_numbers.evaluation_data_numbers()?.numbers() {
@@ -93,9 +93,9 @@ fn download_dcap_artifacts(
9393

9494
match tcb_info {
9595
Ok(tcb_info) => {
96-
let file = tcb_info.store(output_dir)?;
96+
let file = tcb_info.store(output_dir, WriteOption { overwrite: true })?;
9797
if verbose {
98-
println!(" tcb info: {}", file);
98+
println!(" tcb info: {}", file.unwrap().display());
9999
}
100100
},
101101
Err(Error::PCSError(StatusCode::Gone, _)) => {
@@ -114,9 +114,9 @@ fn download_dcap_artifacts(
114114

115115
match qe_identity {
116116
Ok(qe_identity) => {
117-
let file = qe_identity.write_to_file(output_dir)?;
117+
let file = qe_identity.write_to_file(output_dir, WriteOption { overwrite: true })?;
118118
if verbose {
119-
println!(" qe identity: {}\n", file);
119+
println!(" qe identity: {}\n", file.unwrap().display());
120120
}
121121
}
122122
Err(Error::PCSError(StatusCode::Gone, _)) => {
@@ -132,17 +132,17 @@ fn download_dcap_artifacts(
132132
}
133133
let pckcrl = prov_client
134134
.pckcrl(DcapArtifactIssuer::PCKProcessorCA)
135-
.and_then(|crl| crl.write_to_file_as(output_dir, DcapArtifactIssuer::PCKProcessorCA).map_err(|e| e.into()))?;
135+
.and_then(|crl| crl.write_to_file_as(output_dir, DcapArtifactIssuer::PCKProcessorCA, WriteOption { overwrite: true }).map_err(|e| e.into()))?;
136136
if verbose {
137137
println!("==[ generic ]==");
138-
println!(" PCKProcessorCA Crl: {}", pckcrl);
138+
println!(" PCKProcessorCA Crl: {}", pckcrl.unwrap().display());
139139
}
140140

141141
let pckcrl = prov_client
142142
.pckcrl(DcapArtifactIssuer::PCKPlatformCA)
143-
.and_then(|crl| crl.write_to_file_as(output_dir, DcapArtifactIssuer::PCKPlatformCA).map_err(|e| e.into()))?;
143+
.and_then(|crl| crl.write_to_file_as(output_dir, DcapArtifactIssuer::PCKPlatformCA, WriteOption { overwrite: true }).map_err(|e| e.into()))?;
144144
if verbose {
145-
println!(" PCKPlatformCA Crl: {}", pckcrl);
145+
println!(" PCKPlatformCA Crl: {}", pckcrl.unwrap().display());
146146
}
147147
Ok(())
148148
}

intel-sgx/dcap-artifact-retrieval/src/provisioning_client/intel.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
//! - <https://download.01.org/intel-sgx/dcap-1.1/linux/docs/Intel_SGX_PCK_Certificate_CRL_Spec-1.1.pdf>
1313
1414
use pcs::{
15-
CpuSvn, DcapArtifactIssuer, EncPpid, EnclaveIdentity, Fmspc, PceId, PceIsvsvn, PckCert, PckCerts, PckCrl, PlatformType, PlatformTypeForTcbInfo, QeId, QeIdentitySigned, RawTcbEvaluationDataNumbers, TcbInfo, Unverified, platform
15+
CpuSvn, DcapArtifactIssuer, EncPpid, EnclaveIdentity, Fmspc, PceId, PceIsvsvn, PckCert, PckCerts, PckCrl, PlatformType,
16+
PlatformTypeForTcbInfo, QeId, QeIdentitySigned, RawTcbEvaluationDataNumbers, TcbInfo, Unverified, platform,
1617
};
1718
use rustc_serialize::hex::ToHex;
1819
use std::borrow::Cow;
@@ -590,7 +591,7 @@ mod tests {
590591

591592
use pcs::{
592593
DcapArtifactIssuer, EnclaveIdentity, Fmspc, PckID, Platform, RawTcbEvaluationDataNumbers,
593-
TcbEvaluationDataNumbers,
594+
TcbEvaluationDataNumbers, WriteOption,
594595
};
595596

596597
use crate::provisioning_client::{
@@ -639,7 +640,7 @@ mod tests {
639640
"Intel SGX Root CA"
640641
);
641642
pcks.fmspc().unwrap();
642-
pcks.store(OUTPUT_TEST_DIR, pckid.qe_id.as_slice()).unwrap();
643+
pcks.store(OUTPUT_TEST_DIR, pckid.qe_id.as_slice(), WriteOption { overwrite: true }).unwrap();
643644
}
644645
}
645646
}
@@ -869,7 +870,7 @@ mod tests {
869870
.unwrap();
870871
assert!(client
871872
.tcbinfo(&pckcerts.fmspc().unwrap(), None)
872-
.and_then(|tcb| { Ok(tcb.store(OUTPUT_TEST_DIR).unwrap()) })
873+
.and_then(|tcb| { Ok(tcb.store(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()) })
873874
.is_ok());
874875
}
875876
}
@@ -941,7 +942,7 @@ mod tests {
941942
Err(super::Error::PCSError(status_code, _)) if status_code == super::StatusCode::Gone => continue,
942943
res @Err(_) => res.unwrap(),
943944
};
944-
tcb.store(OUTPUT_TEST_DIR).unwrap();
945+
tcb.store(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap();
945946
}
946947
}
947948
}
@@ -1023,7 +1024,7 @@ mod tests {
10231024
let client = intel_builder.build(reqwest_client());
10241025
assert!(client
10251026
.pckcrl(ca)
1026-
.and_then(|crl| { Ok(crl.write_to_file(OUTPUT_TEST_DIR).unwrap()) })
1027+
.and_then(|crl| { Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()) })
10271028
.is_ok());
10281029
}
10291030
}
@@ -1095,7 +1096,7 @@ mod tests {
10951096
let client = intel_builder.build(reqwest_client());
10961097
let qe_id = client.qe_identity(None).unwrap();
10971098
assert_eq!(qe_id.enclave_type(), EnclaveIdentity::QE);
1098-
assert!(qe_id.write_to_file(OUTPUT_TEST_DIR).is_ok());
1099+
assert!(qe_id.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).is_ok());
10991100
}
11001101
}
11011102

@@ -1107,7 +1108,7 @@ mod tests {
11071108
let client = intel_builder.build(reqwest_client());
11081109
let qe_id = client.tdqe_identity(None).unwrap();
11091110
assert_eq!(qe_id.enclave_type(), EnclaveIdentity::TDQE);
1110-
assert!(qe_id.write_to_file(OUTPUT_TEST_DIR).is_ok());
1111+
assert!(qe_id.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).is_ok());
11111112
}
11121113

11131114
#[test]

intel-sgx/dcap-artifact-retrieval/src/provisioning_client/pccs.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ mod tests {
441441

442442
use pcs::{
443443
EnclaveIdentity, Fmspc, PckID, Platform, RawTcbEvaluationDataNumbers,
444-
TcbEvaluationDataNumbers,
444+
TcbEvaluationDataNumbers, WriteOption,
445445
};
446446

447447
use super::Client;
@@ -633,7 +633,7 @@ mod tests {
633633

634634
assert!(client
635635
.tcbinfo(&pckcerts.fmspc().unwrap(), None)
636-
.and_then(|tcb| { Ok(tcb.store(OUTPUT_TEST_DIR).unwrap()) })
636+
.and_then(|tcb| { Ok(tcb.store(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()) })
637637
.is_ok());
638638
}
639639
}
@@ -676,7 +676,7 @@ mod tests {
676676
Err(super::Error::PCSError(status_code, _)) if status_code == super::StatusCode::Gone => continue,
677677
res @Err(_) => res.unwrap(),
678678
};
679-
tcb.store(OUTPUT_TEST_DIR).unwrap();
679+
tcb.store(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap();
680680
}
681681
}
682682
}
@@ -731,11 +731,11 @@ mod tests {
731731
let client = make_client(api_version);
732732
assert!(client
733733
.pckcrl(DcapArtifactIssuer::PCKProcessorCA)
734-
.and_then(|crl| Ok(crl.write_to_file(OUTPUT_TEST_DIR).unwrap()))
734+
.and_then(|crl| Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()))
735735
.is_ok());
736736
assert!(client
737737
.pckcrl(DcapArtifactIssuer::PCKPlatformCA)
738-
.and_then(|crl| Ok(crl.write_to_file(OUTPUT_TEST_DIR).unwrap()))
738+
.and_then(|crl| Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()))
739739
.is_ok());
740740
}
741741
}
@@ -784,7 +784,7 @@ mod tests {
784784
let client = make_client(api_version);
785785
let qe_id = client.qe_identity(None);
786786
assert!(qe_id.is_ok());
787-
assert!(qe_id.unwrap().write_to_file(OUTPUT_TEST_DIR).is_ok());
787+
assert!(qe_id.unwrap().write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).is_ok());
788788
}
789789
}
790790

intel-sgx/pcs/src/io.rs

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,30 +13,40 @@ use serde::de::DeserializeOwned;
1313

1414
use crate::Error;
1515

16+
pub struct WriteOption {
17+
pub overwrite: bool
18+
}
19+
1620
/// Write given object in json to given filename under given dir (override existing file).
17-
pub fn write_to_file<T: serde::ser::Serialize>(obj: &T, dir: &str, filename: &str) -> Result<(), Error> {
21+
pub fn write_to_file<T: serde::ser::Serialize>(obj: &T, dir: &str, filename: &str, options: WriteOption) -> Result<Option<PathBuf>, Error> {
1822
let path = Path::new(dir);
1923
let path = path.join(filename);
20-
write_to_path(&path, obj)
24+
25+
if !options.overwrite && path.exists() {
26+
return Ok(None)
27+
}
28+
29+
write_to_path(&path, obj)?;
30+
Ok(Some(path))
2131
}
2232

2333
/// Write given object in json to given filename under given dir if file is not exist.
2434
///
2535
/// - Returns `Ok(None)` if file already exist.
2636
/// - Returns `Ok(Some(filename))` if succeed to write to new file.
27-
pub fn write_to_file_if_not_exist<T: serde::ser::Serialize>(
28-
obj: &T,
29-
dir: &str,
30-
filename: &str,
31-
) -> Result<Option<PathBuf>, Error> {
32-
let path = Path::new(dir);
33-
let path = path.join(filename);
34-
if path.exists() {
35-
return Ok(None);
36-
}
37-
write_to_path(&path, obj)?;
38-
Ok(Some(path))
39-
}
37+
// pub fn write_to_file_if_not_exist<T: serde::ser::Serialize>(
38+
// obj: &T,
39+
// dir: &str,
40+
// filename: &str,
41+
// ) -> Result<Option<PathBuf>, Error> {
42+
// let path = Path::new(dir);
43+
// let path = path.join(filename);
44+
// if path.exists() {
45+
// return Ok(None);
46+
// }
47+
// write_to_path(&path, obj)?;
48+
// Ok(Some(path))
49+
// }
4050

4151
fn write_to_path<T: serde::ser::Serialize>(path: &PathBuf, obj: &T) -> Result<(), Error> {
4252
let mut fp = File::create(&path)?;

intel-sgx/pcs/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ pub use crate::pckcrt::{PckCert, PckCerts, SGXPCKCertificateExtension, SGXType,
3232
pub use crate::qe_identity::{EnclaveIdentity, QeIdentity, QeIdentitySigned};
3333
pub use crate::tcb_info::{AdvisoryID, Fmspc, TcbInfo, TcbData, TcbLevel, TdxModule, TdxModuleIdentity, TdxModuleTcbLevel, TdxModuleTcbLevelIsvSvn, PlatformTypeForTcbInfo};
3434
pub use crate::tcb_evaluation_data_numbers::{RawTcbEvaluationDataNumbers, TcbEvalNumber, TcbEvaluationDataNumbers, TcbPolicy};
35+
pub use crate::io::WriteOption;
3536

3637
mod io;
3738
mod iso8601;

intel-sgx/pcs/src/pckcrl.rs

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,11 @@
44
* License, v. 2.0. If a copy of the MPL was not distributed with this
55
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
66
*/
7-
8-
use std::path::PathBuf;
9-
107
use pkix::pem::PEM_CRL;
118
use serde::{Deserialize, Deserializer, Serialize};
129
use std::marker::PhantomData;
10+
use std::path::PathBuf;
11+
1312
#[cfg(feature = "verify")]
1413
use {
1514
mbedtls::alloc::List as MbedtlsList,
@@ -19,6 +18,8 @@ use {
1918
std::ops::Deref,
2019
};
2120

21+
#[cfg(feature = "verify")]
22+
use crate::io::WriteOption;
2223
use crate::io::{self};
2324
use crate::{DcapArtifactIssuer, Error, Unverified, VerificationType, Verified};
2425

@@ -117,27 +118,14 @@ impl<V: VerificationType> PckCrl<V> {
117118
}
118119

119120
#[cfg(feature = "verify")]
120-
pub fn write_to_file(&self, output_dir: &str) -> Result<String, Error> {
121-
let filename = self.filename()?;
122-
io::write_to_file(&self, output_dir, &filename)?;
123-
Ok(filename)
124-
}
125-
126-
pub fn write_to_file_as(&self, output_dir: &str, ca: DcapArtifactIssuer) -> Result<String, Error> {
127-
let filename = Self::filename_from_ca(ca);
128-
io::write_to_file(&self, output_dir, &filename)?;
129-
Ok(filename)
130-
}
131-
132-
#[cfg(feature = "verify")]
133-
pub fn write_to_file_if_not_exist(&self, output_dir: &str) -> Result<Option<PathBuf>, Error> {
121+
pub fn write_to_file(&self, output_dir: &str, option: WriteOption) -> Result<Option<PathBuf>, Error> {
134122
let filename = self.filename()?;
135-
io::write_to_file_if_not_exist(&self, output_dir, &filename)
123+
io::write_to_file(&self, output_dir, &filename, option)
136124
}
137125

138-
pub fn write_to_file_if_not_exist_as(&self, output_dir: &str, ca: DcapArtifactIssuer) -> Result<Option<PathBuf>, Error> {
126+
pub fn write_to_file_as(&self, output_dir: &str, ca: DcapArtifactIssuer, option: WriteOption) -> Result<Option<PathBuf>, Error> {
139127
let filename = Self::filename_from_ca(ca);
140-
io::write_to_file_if_not_exist(&self, output_dir, &filename)
128+
io::write_to_file(&self, output_dir, &filename, option)
141129
}
142130

143131
pub fn crl_as_pem(&self) -> &String {

intel-sgx/pcs/src/pckcrt.rs

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use {
3232
super::{DcapArtifactIssuer, PckCrl},
3333
};
3434

35-
use crate::io::{self};
35+
use crate::io::{self, WriteOption};
3636
use crate::tcb_info::{Fmspc, TcbData, TcbLevel};
3737
use crate::{CpuSvn, Error, Unverified, VerificationType, Verified, platform};
3838

@@ -502,15 +502,9 @@ impl PckCerts {
502502
format!("{}.certs", base16::encode_lower(qe_id))
503503
}
504504

505-
pub fn store(&self, output_dir: &str, qe_id: &[u8]) -> Result<String, Error> {
505+
pub fn store(&self, output_dir: &str, qe_id: &[u8], option: WriteOption) -> Result<Option<PathBuf>, Error> {
506506
let filename = PckCerts::filename(qe_id);
507-
io::write_to_file(&self, output_dir, &filename)?;
508-
Ok(filename)
509-
}
510-
511-
pub fn store_if_not_exist(&self, output_dir: &str, qe_id: &[u8]) -> Result<Option<PathBuf>, Error> {
512-
let filename = PckCerts::filename(qe_id);
513-
io::write_to_file_if_not_exist(&self, output_dir, &filename)
507+
io::write_to_file(&self, output_dir, &filename, option)
514508
}
515509

516510
pub fn restore(input_dir: &str, qe_id: &[u8]) -> Result<Self, Error> {
@@ -730,8 +724,8 @@ impl<V: VerificationType> PckCert<V> {
730724
&self.cert
731725
}
732726

733-
pub fn write_to_file(&self, output_dir: &str, filename: &str) -> Result<(), Error> {
734-
Ok(io::write_to_file(&self, output_dir, &filename)?)
727+
pub fn write_to_file(&self, output_dir: &str, filename: &str, option: WriteOption) -> Result<Option<PathBuf>, Error> {
728+
io::write_to_file(&self, output_dir, &filename, option)
735729
}
736730

737731
pub fn sgx_extension(&self) -> Result<SGXPCKCertificateExtension, ASN1Error> {

intel-sgx/pcs/src/qe_identity.rs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use {
2020
pkix::pem::PEM_CERTIFICATE, pkix::x509::GenericCertificate, pkix::FromBer, std::ops::Deref,
2121
};
2222

23-
use crate::io::{self};
23+
use crate::io::{self, WriteOption};
2424
use crate::{Error, TcbStatus, Unverified, VerificationType, Verified};
2525

2626
#[derive(Serialize, Default, Deserialize, Clone, Debug, PartialEq, Eq)]
@@ -374,17 +374,10 @@ impl QeIdentitySigned {
374374
io::compose_filename(Self::filename_prefix(enclave_type), Self::FILENAME_EXTENSION, evaluation_data_number)
375375
}
376376

377-
pub fn write_to_file(&self, output_dir: &str) -> Result<String, Error> {
377+
pub fn write_to_file(&self, output_dir: &str, option: WriteOption) -> Result<Option<PathBuf>, Error> {
378378
let id = QeIdentity::<Unverified>::try_from(self)?;
379379
let filename = Self::create_filename(&self.enclave_type, Some(id.tcb_evaluation_data_number));
380-
io::write_to_file(&self, output_dir, &filename)?;
381-
Ok(filename)
382-
}
383-
384-
pub fn write_to_file_if_not_exist(&self, output_dir: &str) -> Result<Option<PathBuf>, Error> {
385-
let id = QeIdentity::<Unverified>::try_from(self)?;
386-
let filename = Self::create_filename(&self.enclave_type, Some(id.tcb_evaluation_data_number));
387-
io::write_to_file_if_not_exist(&self, output_dir, &filename)
380+
io::write_to_file(&self, output_dir, &filename, option)
388381
}
389382

390383
pub fn read_from_file(input_dir: &str, enclave_type: EnclaveIdentity, evaluation_data_number: Option<u64>) -> Result<Self, Error> {

0 commit comments

Comments
 (0)