Debian Codegraph @

src/base/write/entry_whole.rs

raw symbols SCIP
1 // Copyright (c) 2021 Harry [Majored] [[email protected]]
2 // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE)
3
4 use std::borrow::Cow;
5
6 use crate::base::write::get_or_put_info_zip_unicode_comment_extra_field_mut;
7 use crate::base::write::get_or_put_info_zip_unicode_path_extra_field_mut;
8 use crate::base::write::{CentralDirectoryEntry, ZipFileWriter};
9 use crate::entry::ZipEntry;
10 use crate::error::{Result, Zip64ErrorCase, ZipError};
11 use crate::spec::extra_field::Zip64ExtendedInformationExtraFieldBuilder;
12 use crate::spec::header::{InfoZipUnicodeCommentExtraField, InfoZipUnicodePathExtraField};
13 use crate::spec::{
14 extra_field::ExtraFieldAsBytes,
15 header::{CentralDirectoryRecord, ExtraField, GeneralPurposeFlag, LocalFileHeader},
16 Compression,
17 };
18 use crate::StringEncoding;
19 #[cfg(any(feature = "deflate", feature = "bzip2", feature = "zstd", feature = "lzma", feature = "xz"))]
20 use futures_lite::io::Cursor;
21
22 use crate::spec::consts::{NON_ZIP64_MAX_NUM_FILES, NON_ZIP64_MAX_SIZE};
23 #[cfg(any(feature = "deflate", feature = "bzip2", feature = "zstd", feature = "lzma", feature = "xz"))]
24 use async_compression::futures::write;
25 use futures_lite::io::{AsyncWrite, AsyncWriteExt};
26
27 pub struct EntryWholeWriter<'b, 'c, W: AsyncWrite + Unpin> {
28 writer: &'b mut ZipFileWriter<W>,
29 entry: ZipEntry,
30 data: Cow<'c, [u8]>,
31 builder: Option<Zip64ExtendedInformationExtraFieldBuilder>,
32 lh_offset: u64,
33 precompressed: bool,
34 }
35
36 impl<'b, 'c, W: AsyncWrite + Unpin> EntryWholeWriter<'b, 'c, W> {
37 pub fn from_raw(writer: &'b mut ZipFileWriter<W>, entry: ZipEntry, data: &'c [u8]) -> Self {
38 Self { writer, entry, data: Cow::Borrowed(data), builder: None, lh_offset: 0, precompressed: false }
39 }
40
41 pub fn from_precompressed(writer: &'b mut ZipFileWriter<W>, entry: ZipEntry, data: &'c [u8]) -> Self {
42 Self { writer, entry, data: Cow::Borrowed(data), builder: None, lh_offset: 0, precompressed: true }
43 }
44
45 async fn compress(&mut self) {
46 if self.entry.compression() == Compression::Stored {
47 return;
48 }
49
50 #[cfg(any(
51 feature = "deflate",
52 feature = "bzip2",
53 feature = "zstd",
54 feature = "lzma",
55 feature = "xz",
56 feature = "deflate64"
57 ))]
58 {
59 let new_data = compress(&self.entry, &self.data).await;
60 self.data = Cow::Owned(new_data);
61 }
62 }
63
64 fn enforce_zip64_sizes(&mut self) -> Result<()> {
65 let uncompressed_larger = self.entry.uncompressed_size > NON_ZIP64_MAX_SIZE.into();
66 let compressed_larger = self.entry.compressed_size > NON_ZIP64_MAX_SIZE.into();
67
68 if !uncompressed_larger && !compressed_larger {
69 return Ok(());
70 }
71
72 self.enforce_zip64()?;
73
74 // TODO: accept ZipEntry with sizes already set
75 let builder = Zip64ExtendedInformationExtraFieldBuilder::new();
76 let builder = builder.sizes(self.entry.compressed_size(), self.entry.uncompressed_size());
77 self.builder = Some(builder);
78
79 self.entry.uncompressed_size = NON_ZIP64_MAX_SIZE.into();
80 self.entry.compressed_size = NON_ZIP64_MAX_SIZE.into();
81
82 Ok(())
83 }
84
85 fn enforce_zip64_offset(&mut self) -> Result<()> {
86 if self.lh_offset <= NON_ZIP64_MAX_SIZE.into() {
87 return Ok(());
88 }
89
90 self.enforce_zip64()?;
91
92 let builder = self.builder.take().unwrap_or(Zip64ExtendedInformationExtraFieldBuilder::new());
93 let builder = builder.relative_header_offset(self.lh_offset);
94 self.builder = Some(builder);
95
96 self.lh_offset = NON_ZIP64_MAX_SIZE.into();
97 Ok(())
98 }
99
100 fn enforce_zip64(&mut self) -> Result<()> {
101 if self.writer.force_no_zip64 {
102 return Err(ZipError::Zip64Needed(Zip64ErrorCase::LargeFile));
103 }
104 if !self.writer.is_zip64 {
105 self.writer.is_zip64 = true;
106 }
107
108 Ok(())
109 }
110
111 fn utf8_without_alternative(&mut self) -> bool {
112 let utf8_without_alternative =
113 self.entry.filename().is_utf8_without_alternative() && self.entry.comment().is_utf8_without_alternative();
114
115 if !utf8_without_alternative {
116 if matches!(self.entry.filename().encoding(), StringEncoding::Utf8) {
117 let u_file_name = self.entry.filename().as_bytes().to_vec();
118 if !u_file_name.is_empty() {
119 let basic_crc32 = crc32fast::hash(
120 self.entry.filename().alternative().unwrap_or_else(|| self.entry.filename().as_bytes()),
121 );
122 let upath_field =
123 get_or_put_info_zip_unicode_path_extra_field_mut(self.entry.extra_fields.as_mut());
124 if let InfoZipUnicodePathExtraField::V1 { crc32, unicode } = upath_field {
125 *crc32 = basic_crc32;
126 *unicode = u_file_name;
127 }
128 }
129 }
130 if matches!(self.entry.comment().encoding(), StringEncoding::Utf8) {
131 let u_comment = self.entry.comment().as_bytes().to_vec();
132 if !u_comment.is_empty() {
133 let basic_crc32 = crc32fast::hash(
134 self.entry.comment().alternative().unwrap_or_else(|| self.entry.comment().as_bytes()),
135 );
136 let ucom_field =
137 get_or_put_info_zip_unicode_comment_extra_field_mut(self.entry.extra_fields.as_mut());
138 if let InfoZipUnicodeCommentExtraField::V1 { crc32, unicode } = ucom_field {
139 *crc32 = basic_crc32;
140 *unicode = u_comment;
141 }
142 }
143 }
144 }
145
146 utf8_without_alternative
147 }
148
149 pub async fn write(mut self) -> Result<()> {
150 if !self.precompressed {
151 self.entry.uncompressed_size = self.data.len() as u64;
152 self.entry.crc32 = crc32fast::hash(&self.data);
153
154 self.compress().await;
155 }
156
157 self.entry.compressed_size = self.data.len() as u64;
158 self.enforce_zip64_sizes()?;
159
160 self.lh_offset = self.writer.writer.offset();
161 self.enforce_zip64_offset()?;
162
163 if let Some(builder) = self.builder {
164 if !builder.eof_only() {
165 self.entry.extra_fields.push(ExtraField::Zip64ExtendedInformation(builder.build()?));
166 self.builder = None;
167 } else {
168 self.builder = Some(builder);
169 }
170 }
171
172 let utf8_without_alternative = self.utf8_without_alternative();
173 let filename_basic = self.entry.filename().alternative().unwrap_or_else(|| self.entry.filename().as_bytes());
174 let comment_basic = self.entry.comment().alternative().unwrap_or_else(|| self.entry.comment().as_bytes());
175
176 let lf_header = LocalFileHeader {
177 compressed_size: self.entry.compressed_size() as u32,
178 uncompressed_size: self.entry.uncompressed_size() as u32,
179 compression: self.entry.compression().into(),
180 crc: self.entry.crc32(),
181 extra_field_length: self
182 .entry
183 .extra_fields()
184 .count_bytes()
185 .try_into()
186 .map_err(|_| ZipError::ExtraFieldTooLarge)?,
187 file_name_length: filename_basic.len().try_into().map_err(|_| ZipError::FileNameTooLarge)?,
188 mod_time: self.entry.last_modification_date().time,
189 mod_date: self.entry.last_modification_date().date,
190 version: crate::spec::version::as_needed_to_extract(&self.entry),
191 flags: GeneralPurposeFlag {
192 data_descriptor: false,
193 encrypted: false,
194 filename_unicode: utf8_without_alternative,
195 },
196 };
197
198 let mut header = CentralDirectoryRecord {
199 v_made_by: crate::spec::version::as_made_by(),
200 v_needed: lf_header.version,
201 compressed_size: lf_header.compressed_size,
202 uncompressed_size: lf_header.uncompressed_size,
203 compression: lf_header.compression,
204 crc: lf_header.crc,
205 extra_field_length: lf_header.extra_field_length,
206 file_name_length: lf_header.file_name_length,
207 file_comment_length: comment_basic.len().try_into().map_err(|_| ZipError::CommentTooLarge)?,
208 mod_time: lf_header.mod_time,
209 mod_date: lf_header.mod_date,
210 flags: lf_header.flags,
211 disk_start: 0,
212 inter_attr: self.entry.internal_file_attribute(),
213 exter_attr: self.entry.external_file_attribute(),
214 lh_offset: self.lh_offset as u32,
215 };
216
217 self.writer.writer.write_all(&crate::spec::consts::LFH_SIGNATURE.to_le_bytes()).await?;
218 self.writer.writer.write_all(&lf_header.as_slice()).await?;
219 self.writer.writer.write_all(filename_basic).await?;
220 self.writer.writer.write_all(&self.entry.extra_fields().as_bytes()).await?;
221 self.writer.writer.write_all(&self.data).await?;
222
223 if let Some(builder1) = self.builder {
224 self.entry.extra_fields.push(ExtraField::Zip64ExtendedInformation(builder1.build()?));
225 header.extra_field_length =
226 self.entry.extra_fields().count_bytes().try_into().map_err(|_| ZipError::ExtraFieldTooLarge)?;
227 }
228
229 self.writer.cd_entries.push(CentralDirectoryEntry { header, entry: self.entry });
230 // Ensure that we can fit this many files in this archive if forcing no zip64
231 if self.writer.cd_entries.len() > NON_ZIP64_MAX_NUM_FILES as usize {
232 if self.writer.force_no_zip64 {
233 return Err(ZipError::Zip64Needed(Zip64ErrorCase::TooManyFiles));
234 }
235 if !self.writer.is_zip64 {
236 self.writer.is_zip64 = true;
237 }
238 }
239 Ok(())
240 }
241 }
242
243 #[cfg(any(
244 feature = "deflate",
245 feature = "bzip2",
246 feature = "zstd",
247 feature = "lzma",
248 feature = "xz",
249 feature = "deflate64"
250 ))]
251 /// Compresses the data of a ZIP entry using the specified compression method and level.
252 pub async fn compress(entry: &ZipEntry, data: &[u8]) -> Vec<u8> {
253 // TODO: Reduce reallocations of Vec by making a lower-bound estimate of the length reduction and
254 // pre-initialising the Vec to that length. Then truncate() to the actual number of bytes written.
255 let level = entry.compression_level;
256
257 match entry.compression() {
258 #[cfg(feature = "deflate")]
259 Compression::Deflate => {
260 let mut writer = write::DeflateEncoder::with_quality(Cursor::new(Vec::new()), level);
261 writer.write_all(data).await.unwrap();
262 writer.close().await.unwrap();
263 writer.into_inner().into_inner()
264 }
265 #[cfg(feature = "deflate64")]
266 Compression::Deflate64 => panic!("compressing deflate64 is not supported"),
267 #[cfg(feature = "bzip2")]
268 Compression::Bz => {
269 let mut writer = write::BzEncoder::with_quality(Cursor::new(Vec::new()), level);
270 writer.write_all(data).await.unwrap();
271 writer.close().await.unwrap();
272 writer.into_inner().into_inner()
273 }
274 #[cfg(feature = "lzma")]
275 Compression::Lzma => {
276 let mut writer = write::LzmaEncoder::with_quality(Cursor::new(Vec::new()), level);
277 writer.write_all(data).await.unwrap();
278 writer.close().await.unwrap();
279 writer.into_inner().into_inner()
280 }
281 #[cfg(feature = "xz")]
282 Compression::Xz => {
283 let mut writer = write::XzEncoder::with_quality(Cursor::new(Vec::new()), level);
284 writer.write_all(data).await.unwrap();
285 writer.close().await.unwrap();
286 writer.into_inner().into_inner()
287 }
288 #[cfg(feature = "zstd")]
289 Compression::Zstd => {
290 let mut writer = write::ZstdEncoder::with_quality(Cursor::new(Vec::new()), level);
291 writer.write_all(data).await.unwrap();
292 writer.close().await.unwrap();
293 writer.into_inner().into_inner()
294 }
295 _ => unreachable!(),
296 }
297 }
298
299 /// Performs a CRC32 checksum on the provided data.
300 pub fn crc32(data: &[u8]) -> u32 {
301 crc32fast::hash(data)
302 }