| 1 | // Copyright (c) 2021 Harry [Majored] [[email protected]] |
| 2 | // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE) |
| 3 | |
| 4 | use crate::base::write::compressed_writer::CompressedAsyncWriter; |
| 5 | use crate::base::write::get_or_put_info_zip_unicode_comment_extra_field_mut; |
| 6 | use crate::base::write::get_or_put_info_zip_unicode_path_extra_field_mut; |
| 7 | use crate::base::write::io::offset::AsyncOffsetWriter; |
| 8 | use crate::base::write::CentralDirectoryEntry; |
| 9 | use crate::base::write::ZipFileWriter; |
| 10 | use crate::entry::ZipEntry; |
| 11 | use crate::error::{Result, Zip64ErrorCase, ZipError}; |
| 12 | use crate::spec::extra_field::ExtraFieldAsBytes; |
| 13 | use crate::spec::header::InfoZipUnicodeCommentExtraField; |
| 14 | use crate::spec::header::InfoZipUnicodePathExtraField; |
| 15 | use crate::spec::header::{ |
| 16 | CentralDirectoryRecord, ExtraField, GeneralPurposeFlag, HeaderId, LocalFileHeader, |
| 17 | Zip64ExtendedInformationExtraField, |
| 18 | }; |
| 19 | use crate::string::StringEncoding; |
| 20 | |
| 21 | use std::io::Error; |
| 22 | use std::pin::Pin; |
| 23 | use std::task::{Context, Poll}; |
| 24 | |
| 25 | use crate::base::read::get_zip64_extra_field_mut; |
| 26 | use crate::spec::consts::{NON_ZIP64_MAX_NUM_FILES, NON_ZIP64_MAX_SIZE}; |
| 27 | use crc32fast::Hasher; |
| 28 | use futures_lite::io::{AsyncWrite, AsyncWriteExt}; |
| 29 | |
| 30 | /// An entry writer which supports the streaming of data (ie. the writing of unknown size or data at runtime). |
| 31 | /// |
| 32 | /// # Note |
| 33 | /// - This writer cannot be manually constructed; instead, use [`ZipFileWriter::write_entry_stream()`]. |
| 34 | /// - [`EntryStreamWriter::close()`] must be called before a stream writer goes out of scope. |
| 35 | /// - Utilities for working with [`AsyncWrite`] values are provided by [`AsyncWriteExt`]. |
| 36 | pub struct EntryStreamWriter<'b, W: AsyncWrite + Unpin> { |
| 37 | writer: AsyncOffsetWriter<CompressedAsyncWriter<'b, W>>, |
| 38 | cd_entries: &'b mut Vec<CentralDirectoryEntry>, |
| 39 | entry: ZipEntry, |
| 40 | hasher: Hasher, |
| 41 | lfh: LocalFileHeader, |
| 42 | lfh_offset: u64, |
| 43 | data_offset: u64, |
| 44 | force_no_zip64: bool, |
| 45 | /// To write back to the original writer if zip64 is required. |
| 46 | is_zip64: &'b mut bool, |
| 47 | precompressed: bool, |
| 48 | } |
| 49 | |
| 50 | impl<'b, W: AsyncWrite + Unpin> EntryStreamWriter<'b, W> { |
| 51 | pub(crate) async fn from_raw( |
| 52 | writer: &'b mut ZipFileWriter<W>, |
| 53 | mut entry: ZipEntry, |
| 54 | ) -> Result<EntryStreamWriter<'b, W>> { |
| 55 | let lfh_offset = writer.writer.offset(); |
| 56 | let lfh = EntryStreamWriter::write_lfh(writer, &mut entry).await?; |
| 57 | let data_offset = writer.writer.offset(); |
| 58 | let force_no_zip64 = writer.force_no_zip64; |
| 59 | |
| 60 | let cd_entries = &mut writer.cd_entries; |
| 61 | let is_zip64 = &mut writer.is_zip64; |
| 62 | let writer = |
| 63 | AsyncOffsetWriter::new(CompressedAsyncWriter::from_raw(&mut writer.writer, entry.compression(), false)); |
| 64 | |
| 65 | Ok(EntryStreamWriter { |
| 66 | writer, |
| 67 | cd_entries, |
| 68 | entry, |
| 69 | lfh, |
| 70 | lfh_offset, |
| 71 | data_offset, |
| 72 | hasher: Hasher::new(), |
| 73 | force_no_zip64, |
| 74 | is_zip64, |
| 75 | precompressed: false, |
| 76 | }) |
| 77 | } |
| 78 | |
| 79 | pub(crate) async fn from_raw_precompressed( |
| 80 | writer: &'b mut ZipFileWriter<W>, |
| 81 | mut entry: ZipEntry, |
| 82 | ) -> Result<EntryStreamWriter<'b, W>> { |
| 83 | let lfh_offset = writer.writer.offset(); |
| 84 | let lfh = EntryStreamWriter::write_lfh(writer, &mut entry).await?; |
| 85 | let data_offset = writer.writer.offset(); |
| 86 | let force_no_zip64 = writer.force_no_zip64; |
| 87 | |
| 88 | let cd_entries = &mut writer.cd_entries; |
| 89 | let is_zip64 = &mut writer.is_zip64; |
| 90 | let writer = |
| 91 | AsyncOffsetWriter::new(CompressedAsyncWriter::from_raw(&mut writer.writer, entry.compression(), true)); |
| 92 | |
| 93 | Ok(EntryStreamWriter { |
| 94 | writer, |
| 95 | cd_entries, |
| 96 | entry, |
| 97 | lfh, |
| 98 | lfh_offset, |
| 99 | data_offset, |
| 100 | hasher: Hasher::new(), |
| 101 | force_no_zip64, |
| 102 | is_zip64, |
| 103 | precompressed: true, |
| 104 | }) |
| 105 | } |
| 106 | |
| 107 | async fn write_lfh(writer: &'b mut ZipFileWriter<W>, entry: &mut ZipEntry) -> Result<LocalFileHeader> { |
| 108 | // Always emit a zip64 extended field, even if we don't need it, because we *might* need it. |
| 109 | // If we are forcing no zip, we will have to error later if the file is too large. |
| 110 | let (lfh_compressed, lfh_uncompressed) = if !writer.force_no_zip64 { |
| 111 | if !writer.is_zip64 { |
| 112 | writer.is_zip64 = true; |
| 113 | } |
| 114 | entry.extra_fields.push(ExtraField::Zip64ExtendedInformation(Zip64ExtendedInformationExtraField { |
| 115 | header_id: HeaderId::ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD, |
| 116 | uncompressed_size: Some(entry.uncompressed_size), |
| 117 | compressed_size: Some(entry.compressed_size), |
| 118 | relative_header_offset: None, |
| 119 | disk_start_number: None, |
| 120 | })); |
| 121 | |
| 122 | (NON_ZIP64_MAX_SIZE, NON_ZIP64_MAX_SIZE) |
| 123 | } else { |
| 124 | if entry.compressed_size > NON_ZIP64_MAX_SIZE as u64 || entry.uncompressed_size > NON_ZIP64_MAX_SIZE as u64 |
| 125 | { |
| 126 | return Err(ZipError::Zip64Needed(Zip64ErrorCase::LargeFile)); |
| 127 | } |
| 128 | |
| 129 | (entry.compressed_size as u32, entry.uncompressed_size as u32) |
| 130 | }; |
| 131 | |
| 132 | let utf8_without_alternative = |
| 133 | entry.filename().is_utf8_without_alternative() && entry.comment().is_utf8_without_alternative(); |
| 134 | if !utf8_without_alternative { |
| 135 | if matches!(entry.filename().encoding(), StringEncoding::Utf8) { |
| 136 | let u_file_name = entry.filename().as_bytes().to_vec(); |
| 137 | if !u_file_name.is_empty() { |
| 138 | let basic_crc32 = |
| 139 | crc32fast::hash(entry.filename().alternative().unwrap_or_else(|| entry.filename().as_bytes())); |
| 140 | let upath_field = get_or_put_info_zip_unicode_path_extra_field_mut(entry.extra_fields.as_mut()); |
| 141 | if let InfoZipUnicodePathExtraField::V1 { crc32, unicode } = upath_field { |
| 142 | *crc32 = basic_crc32; |
| 143 | *unicode = u_file_name; |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | if matches!(entry.comment().encoding(), StringEncoding::Utf8) { |
| 148 | let u_comment = entry.comment().as_bytes().to_vec(); |
| 149 | if !u_comment.is_empty() { |
| 150 | let basic_crc32 = |
| 151 | crc32fast::hash(entry.comment().alternative().unwrap_or_else(|| entry.comment().as_bytes())); |
| 152 | let ucom_field = get_or_put_info_zip_unicode_comment_extra_field_mut(entry.extra_fields.as_mut()); |
| 153 | if let InfoZipUnicodeCommentExtraField::V1 { crc32, unicode } = ucom_field { |
| 154 | *crc32 = basic_crc32; |
| 155 | *unicode = u_comment; |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | let filename_basic = entry.filename().alternative().unwrap_or_else(|| entry.filename().as_bytes()); |
| 162 | |
| 163 | let lfh = LocalFileHeader { |
| 164 | compressed_size: lfh_compressed, |
| 165 | uncompressed_size: lfh_uncompressed, |
| 166 | compression: entry.compression().into(), |
| 167 | crc: entry.crc32, |
| 168 | extra_field_length: entry |
| 169 | .extra_fields() |
| 170 | .count_bytes() |
| 171 | .try_into() |
| 172 | .map_err(|_| ZipError::ExtraFieldTooLarge)?, |
| 173 | file_name_length: filename_basic.len().try_into().map_err(|_| ZipError::FileNameTooLarge)?, |
| 174 | mod_time: entry.last_modification_date().time, |
| 175 | mod_date: entry.last_modification_date().date, |
| 176 | version: crate::spec::version::as_needed_to_extract(entry), |
| 177 | flags: GeneralPurposeFlag { |
| 178 | data_descriptor: true, |
| 179 | encrypted: false, |
| 180 | filename_unicode: utf8_without_alternative, |
| 181 | }, |
| 182 | }; |
| 183 | |
| 184 | writer.writer.write_all(&crate::spec::consts::LFH_SIGNATURE.to_le_bytes()).await?; |
| 185 | writer.writer.write_all(&lfh.as_slice()).await?; |
| 186 | writer.writer.write_all(filename_basic).await?; |
| 187 | writer.writer.write_all(&entry.extra_fields().as_bytes()).await?; |
| 188 | |
| 189 | Ok(lfh) |
| 190 | } |
| 191 | |
| 192 | /// Consumes this entry writer and completes all closing tasks. |
| 193 | /// |
| 194 | /// This includes: |
| 195 | /// - Finalising the CRC32 hash value for the written data. |
| 196 | /// - Calculating the compressed and uncompressed byte sizes. |
| 197 | /// - Constructing a central directory header. |
| 198 | /// - Pushing that central directory header to the [`ZipFileWriter`]'s store. |
| 199 | /// |
| 200 | /// Failure to call this function before going out of scope would result in a corrupted ZIP file. |
| 201 | pub async fn close(mut self) -> Result<()> { |
| 202 | self.writer.close().await?; |
| 203 | |
| 204 | if !self.precompressed { |
| 205 | self.entry.crc32 = self.hasher.finalize(); |
| 206 | self.entry.uncompressed_size = self.writer.offset(); |
| 207 | } |
| 208 | |
| 209 | let inner_writer = self.writer.into_inner().into_inner(); |
| 210 | let compressed_size = inner_writer.offset() - self.data_offset; |
| 211 | |
| 212 | let (cdr_compressed_size, cdr_uncompressed_size, lh_offset) = if self.force_no_zip64 { |
| 213 | if self.entry.uncompressed_size > NON_ZIP64_MAX_SIZE as u64 |
| 214 | || compressed_size > NON_ZIP64_MAX_SIZE as u64 |
| 215 | || self.lfh_offset > NON_ZIP64_MAX_SIZE as u64 |
| 216 | { |
| 217 | return Err(ZipError::Zip64Needed(Zip64ErrorCase::LargeFile)); |
| 218 | } |
| 219 | (self.entry.uncompressed_size as u32, compressed_size as u32, self.lfh_offset as u32) |
| 220 | } else { |
| 221 | // When streaming an entry, we are always using a zip64 field. |
| 222 | match get_zip64_extra_field_mut(&mut self.entry.extra_fields) { |
| 223 | // This case shouldn't be necessary but is included for completeness. |
| 224 | None => { |
| 225 | self.entry.extra_fields.push(ExtraField::Zip64ExtendedInformation( |
| 226 | Zip64ExtendedInformationExtraField { |
| 227 | header_id: HeaderId::ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD, |
| 228 | uncompressed_size: Some(self.entry.uncompressed_size), |
| 229 | compressed_size: Some(compressed_size), |
| 230 | relative_header_offset: Some(self.lfh_offset), |
| 231 | disk_start_number: None, |
| 232 | }, |
| 233 | )); |
| 234 | } |
| 235 | Some(zip64) => { |
| 236 | zip64.uncompressed_size = Some(self.entry.uncompressed_size); |
| 237 | zip64.compressed_size = Some(compressed_size); |
| 238 | zip64.relative_header_offset = Some(self.lfh_offset); |
| 239 | } |
| 240 | } |
| 241 | self.lfh.extra_field_length = |
| 242 | self.entry.extra_fields().count_bytes().try_into().map_err(|_| ZipError::ExtraFieldTooLarge)?; |
| 243 | |
| 244 | (NON_ZIP64_MAX_SIZE, NON_ZIP64_MAX_SIZE, NON_ZIP64_MAX_SIZE) |
| 245 | }; |
| 246 | |
| 247 | inner_writer.write_all(&crate::spec::consts::DATA_DESCRIPTOR_SIGNATURE.to_le_bytes()).await?; |
| 248 | inner_writer.write_all(&self.entry.crc32.to_le_bytes()).await?; |
| 249 | inner_writer.write_all(&cdr_compressed_size.to_le_bytes()).await?; |
| 250 | inner_writer.write_all(&cdr_uncompressed_size.to_le_bytes()).await?; |
| 251 | |
| 252 | let comment_basic = self.entry.comment().alternative().unwrap_or_else(|| self.entry.comment().as_bytes()); |
| 253 | |
| 254 | let cdh = CentralDirectoryRecord { |
| 255 | compressed_size: cdr_compressed_size, |
| 256 | uncompressed_size: cdr_uncompressed_size, |
| 257 | crc: self.entry.crc32, |
| 258 | v_made_by: crate::spec::version::as_made_by(), |
| 259 | v_needed: self.lfh.version, |
| 260 | compression: self.lfh.compression, |
| 261 | extra_field_length: self.lfh.extra_field_length, |
| 262 | file_name_length: self.lfh.file_name_length, |
| 263 | file_comment_length: comment_basic.len().try_into().map_err(|_| ZipError::CommentTooLarge)?, |
| 264 | mod_time: self.lfh.mod_time, |
| 265 | mod_date: self.lfh.mod_date, |
| 266 | flags: self.lfh.flags, |
| 267 | disk_start: 0, |
| 268 | inter_attr: self.entry.internal_file_attribute(), |
| 269 | exter_attr: self.entry.external_file_attribute(), |
| 270 | lh_offset, |
| 271 | }; |
| 272 | |
| 273 | self.cd_entries.push(CentralDirectoryEntry { header: cdh, entry: self.entry }); |
| 274 | // Ensure that we can fit this many files in this archive if forcing no zip64 |
| 275 | if self.cd_entries.len() > NON_ZIP64_MAX_NUM_FILES as usize { |
| 276 | if self.force_no_zip64 { |
| 277 | return Err(ZipError::Zip64Needed(Zip64ErrorCase::TooManyFiles)); |
| 278 | } |
| 279 | if !*self.is_zip64 { |
| 280 | *self.is_zip64 = true; |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | Ok(()) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | impl<'a, W: AsyncWrite + Unpin> AsyncWrite for EntryStreamWriter<'a, W> { |
| 289 | fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<std::result::Result<usize, Error>> { |
| 290 | let poll = Pin::new(&mut self.writer).poll_write(cx, buf); |
| 291 | |
| 292 | if let Poll::Ready(Ok(written)) = poll { |
| 293 | self.hasher.update(&buf[0..written]); |
| 294 | } |
| 295 | |
| 296 | poll |
| 297 | } |
| 298 | |
| 299 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<std::result::Result<(), Error>> { |
| 300 | Pin::new(&mut self.writer).poll_flush(cx) |
| 301 | } |
| 302 | |
| 303 | fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<std::result::Result<(), Error>> { |
| 304 | Pin::new(&mut self.writer).poll_close(cx) |
| 305 | } |
| 306 | } |