| 1 | // Copyright (c) 2021-2022 Harry [Majored] [[email protected]] |
| 2 | // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE) |
| 3 | |
| 4 | //! A module which supports writing ZIP files. |
| 5 | //! |
| 6 | //! # Example |
| 7 | //! ### Whole data (u8 slice) |
| 8 | //! ```no_run |
| 9 | //! # #[cfg(feature = "deflate")] |
| 10 | //! # { |
| 11 | //! # use async_zip::{Compression, ZipEntryBuilder, base::write::ZipFileWriter}; |
| 12 | //! # use async_zip::error::ZipError; |
| 13 | //! # |
| 14 | //! # async fn run() -> Result<(), ZipError> { |
| 15 | //! let mut writer = ZipFileWriter::new(Vec::<u8>::new()); |
| 16 | //! |
| 17 | //! let data = b"This is an example file."; |
| 18 | //! let opts = ZipEntryBuilder::new(String::from("foo.txt").into(), Compression::Deflate); |
| 19 | //! |
| 20 | //! writer.write_entry_whole(opts, data).await?; |
| 21 | //! writer.close().await?; |
| 22 | //! # Ok(()) |
| 23 | //! # } |
| 24 | //! # } |
| 25 | //! ``` |
| 26 | //! ### Stream data (unknown size & data) |
| 27 | //! ```no_run |
| 28 | //! # #[cfg(feature = "deflate")] |
| 29 | //! # { |
| 30 | //! # use async_zip::{Compression, ZipEntryBuilder, base::write::ZipFileWriter}; |
| 31 | //! # use std::io::Cursor; |
| 32 | //! # use async_zip::error::ZipError; |
| 33 | //! # use futures_lite::io::AsyncWriteExt; |
| 34 | //! # use tokio_util::compat::TokioAsyncWriteCompatExt; |
| 35 | //! # |
| 36 | //! # async fn run() -> Result<(), ZipError> { |
| 37 | //! let mut writer = ZipFileWriter::new(Vec::<u8>::new()); |
| 38 | //! |
| 39 | //! let data = b"This is an example file."; |
| 40 | //! let opts = ZipEntryBuilder::new(String::from("bar.txt").into(), Compression::Deflate); |
| 41 | //! |
| 42 | //! let mut entry_writer = writer.write_entry_stream(opts).await?; |
| 43 | //! entry_writer.write_all(data).await.unwrap(); |
| 44 | //! |
| 45 | //! entry_writer.close().await?; |
| 46 | //! writer.close().await?; |
| 47 | //! # Ok(()) |
| 48 | //! # } |
| 49 | //! # } |
| 50 | //! ``` |
| 51 | |
| 52 | pub(crate) mod compressed_writer; |
| 53 | pub(crate) mod entry_stream; |
| 54 | pub(crate) mod entry_whole; |
| 55 | pub(crate) mod io; |
| 56 | |
| 57 | #[cfg(any( |
| 58 | feature = "deflate", |
| 59 | feature = "bzip2", |
| 60 | feature = "zstd", |
| 61 | feature = "lzma", |
| 62 | feature = "xz", |
| 63 | feature = "deflate64" |
| 64 | ))] |
| 65 | pub use entry_whole::compress; |
| 66 | |
| 67 | pub use entry_stream::EntryStreamWriter; |
| 68 | pub use entry_whole::crc32; |
| 69 | |
| 70 | #[cfg(feature = "tokio")] |
| 71 | use tokio_util::compat::{Compat, TokioAsyncWriteCompatExt}; |
| 72 | |
| 73 | use crate::entry::ZipEntry; |
| 74 | use crate::error::Result; |
| 75 | use crate::spec::extra_field::ExtraFieldAsBytes; |
| 76 | use crate::spec::header::{ |
| 77 | CentralDirectoryRecord, EndOfCentralDirectoryHeader, ExtraField, InfoZipUnicodeCommentExtraField, |
| 78 | InfoZipUnicodePathExtraField, Zip64EndOfCentralDirectoryLocator, Zip64EndOfCentralDirectoryRecord, |
| 79 | }; |
| 80 | |
| 81 | #[cfg(feature = "tokio")] |
| 82 | use crate::tokio::write::ZipFileWriter as TokioZipFileWriter; |
| 83 | |
| 84 | use entry_whole::EntryWholeWriter; |
| 85 | use io::offset::AsyncOffsetWriter; |
| 86 | |
| 87 | use crate::spec::consts::{NON_ZIP64_MAX_NUM_FILES, NON_ZIP64_MAX_SIZE}; |
| 88 | use futures_lite::io::{AsyncWrite, AsyncWriteExt}; |
| 89 | |
| 90 | pub(crate) struct CentralDirectoryEntry { |
| 91 | pub header: CentralDirectoryRecord, |
| 92 | pub entry: ZipEntry, |
| 93 | } |
| 94 | |
| 95 | /// A ZIP file writer which acts over AsyncWrite implementers. |
| 96 | /// |
| 97 | /// # Note |
| 98 | /// - [`ZipFileWriter::close()`] must be called before a stream writer goes out of scope. |
| 99 | pub struct ZipFileWriter<W> { |
| 100 | pub(crate) writer: AsyncOffsetWriter<W>, |
| 101 | pub(crate) cd_entries: Vec<CentralDirectoryEntry>, |
| 102 | /// If true, will error if a Zip64 struct must be written. |
| 103 | force_no_zip64: bool, |
| 104 | /// Whether to write Zip64 end of directory structs. |
| 105 | pub(crate) is_zip64: bool, |
| 106 | comment_opt: Option<String>, |
| 107 | } |
| 108 | |
| 109 | impl<W: AsyncWrite + Unpin> ZipFileWriter<W> { |
| 110 | /// Construct a new ZIP file writer from a mutable reference to a writer. |
| 111 | pub fn new(writer: W) -> Self { |
| 112 | Self { |
| 113 | writer: AsyncOffsetWriter::new(writer), |
| 114 | cd_entries: Vec::new(), |
| 115 | comment_opt: None, |
| 116 | is_zip64: false, |
| 117 | force_no_zip64: false, |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// Force the ZIP writer to operate in non-ZIP64 mode. |
| 122 | /// If any files would need ZIP64, an error will be raised. |
| 123 | pub fn force_no_zip64(mut self) -> Self { |
| 124 | self.force_no_zip64 = true; |
| 125 | self |
| 126 | } |
| 127 | |
| 128 | /// Force the ZIP writer to emit Zip64 structs at the end of the archive. |
| 129 | /// Zip64 extended fields will only be written if needed. |
| 130 | pub fn force_zip64(mut self) -> Self { |
| 131 | self.is_zip64 = true; |
| 132 | self |
| 133 | } |
| 134 | |
| 135 | /// Write a new ZIP entry of known size and data. |
| 136 | pub async fn write_entry_whole<E: Into<ZipEntry>>(&mut self, entry: E, data: &[u8]) -> Result<()> { |
| 137 | EntryWholeWriter::from_raw(self, entry.into(), data).write().await |
| 138 | } |
| 139 | |
| 140 | /// Write a new ZIP entry of known size and data, with the data already being compressed. |
| 141 | /// |
| 142 | /// The provided entry's compression method, CRC, and uncompressed size must be set. Use with `base::write::compress` |
| 143 | /// and `base::write::crc32` to precompress. |
| 144 | pub async fn write_entry_whole_precompressed<E: Into<ZipEntry>>(&mut self, entry: E, data: &[u8]) -> Result<()> { |
| 145 | EntryWholeWriter::from_precompressed(self, entry.into(), data).write().await |
| 146 | } |
| 147 | |
| 148 | /// Write an entry of unknown size and data via streaming (ie. using a data descriptor). |
| 149 | /// The generated Local File Header will be invalid, with no compressed size, uncompressed size, |
| 150 | /// and a null CRC. This might cause problems with the destination reader. |
| 151 | pub async fn write_entry_stream<E: Into<ZipEntry>>(&mut self, entry: E) -> Result<EntryStreamWriter<'_, W>> { |
| 152 | EntryStreamWriter::from_raw(self, entry.into()).await |
| 153 | } |
| 154 | |
| 155 | /// Write an entry of unknown size and data via streaming (ie. using a data descriptor), with the data already being compressed. |
| 156 | /// |
| 157 | /// The provided entry's compression method, CRC, and uncompressed size must be set. Use with `base::write::compress` |
| 158 | /// and `base::write::crc32` to precompress. |
| 159 | /// |
| 160 | /// The generated Local File Header will be invalid, with no compressed size, uncompressed size, |
| 161 | /// and a null CRC. This might cause problems with the destination reader. |
| 162 | pub async fn write_entry_stream_precompressed<E: Into<ZipEntry>>( |
| 163 | &mut self, |
| 164 | entry: E, |
| 165 | ) -> Result<EntryStreamWriter<'_, W>> { |
| 166 | EntryStreamWriter::from_raw_precompressed(self, entry.into()).await |
| 167 | } |
| 168 | |
| 169 | /// Set the ZIP file comment. |
| 170 | pub fn comment(&mut self, comment: String) { |
| 171 | self.comment_opt = Some(comment); |
| 172 | } |
| 173 | |
| 174 | /// Returns a mutable reference to the inner writer. |
| 175 | /// |
| 176 | /// Care should be taken when using this inner writer as doing so may invalidate internal state of this writer. |
| 177 | pub fn inner_mut(&mut self) -> &mut W { |
| 178 | self.writer.inner_mut() |
| 179 | } |
| 180 | |
| 181 | /// Consumes this ZIP writer and completes all closing tasks. |
| 182 | /// |
| 183 | /// This includes: |
| 184 | /// - Writing all central directory headers. |
| 185 | /// - Writing the end of central directory header. |
| 186 | /// - Writing the file comment. |
| 187 | /// |
| 188 | /// Failure to call this function before going out of scope would result in a corrupted ZIP file. |
| 189 | pub async fn close(mut self) -> Result<W> { |
| 190 | let cd_offset = self.writer.offset(); |
| 191 | |
| 192 | for entry in &self.cd_entries { |
| 193 | let filename_basic = |
| 194 | entry.entry.filename().alternative().unwrap_or_else(|| entry.entry.filename().as_bytes()); |
| 195 | let comment_basic = entry.entry.comment().alternative().unwrap_or_else(|| entry.entry.comment().as_bytes()); |
| 196 | |
| 197 | self.writer.write_all(&crate::spec::consts::CDH_SIGNATURE.to_le_bytes()).await?; |
| 198 | self.writer.write_all(&entry.header.as_slice()).await?; |
| 199 | self.writer.write_all(filename_basic).await?; |
| 200 | self.writer.write_all(&entry.entry.extra_fields().as_bytes()).await?; |
| 201 | self.writer.write_all(comment_basic).await?; |
| 202 | } |
| 203 | |
| 204 | let central_directory_size = self.writer.offset() - cd_offset; |
| 205 | let central_directory_size_u32 = if central_directory_size > NON_ZIP64_MAX_SIZE as u64 { |
| 206 | NON_ZIP64_MAX_SIZE |
| 207 | } else { |
| 208 | central_directory_size as u32 |
| 209 | }; |
| 210 | let num_entries_in_directory = self.cd_entries.len() as u64; |
| 211 | let num_entries_in_directory_u16 = if num_entries_in_directory > NON_ZIP64_MAX_NUM_FILES as u64 { |
| 212 | NON_ZIP64_MAX_NUM_FILES |
| 213 | } else { |
| 214 | num_entries_in_directory as u16 |
| 215 | }; |
| 216 | let cd_offset_u32 = if cd_offset > NON_ZIP64_MAX_SIZE as u64 { |
| 217 | if self.force_no_zip64 { |
| 218 | return Err(crate::error::ZipError::Zip64Needed(crate::error::Zip64ErrorCase::LargeFile)); |
| 219 | } else { |
| 220 | self.is_zip64 = true; |
| 221 | } |
| 222 | NON_ZIP64_MAX_SIZE |
| 223 | } else { |
| 224 | cd_offset as u32 |
| 225 | }; |
| 226 | |
| 227 | // Add the zip64 EOCDR and EOCDL if we are in zip64 mode. |
| 228 | if self.is_zip64 { |
| 229 | let eocdr_offset = self.writer.offset(); |
| 230 | |
| 231 | let eocdr = Zip64EndOfCentralDirectoryRecord { |
| 232 | size_of_zip64_end_of_cd_record: 44, |
| 233 | version_made_by: crate::spec::version::as_made_by(), |
| 234 | version_needed_to_extract: 46, |
| 235 | disk_number: 0, |
| 236 | disk_number_start_of_cd: 0, |
| 237 | num_entries_in_directory_on_disk: num_entries_in_directory, |
| 238 | num_entries_in_directory, |
| 239 | directory_size: central_directory_size, |
| 240 | offset_of_start_of_directory: cd_offset, |
| 241 | }; |
| 242 | self.writer.write_all(&crate::spec::consts::ZIP64_EOCDR_SIGNATURE.to_le_bytes()).await?; |
| 243 | self.writer.write_all(&eocdr.as_bytes()).await?; |
| 244 | |
| 245 | let eocdl = Zip64EndOfCentralDirectoryLocator { |
| 246 | number_of_disk_with_start_of_zip64_end_of_central_directory: 0, |
| 247 | relative_offset: eocdr_offset, |
| 248 | total_number_of_disks: 1, |
| 249 | }; |
| 250 | self.writer.write_all(&crate::spec::consts::ZIP64_EOCDL_SIGNATURE.to_le_bytes()).await?; |
| 251 | self.writer.write_all(&eocdl.as_bytes()).await?; |
| 252 | } |
| 253 | |
| 254 | let header = EndOfCentralDirectoryHeader { |
| 255 | disk_num: 0, |
| 256 | start_cent_dir_disk: 0, |
| 257 | num_of_entries_disk: num_entries_in_directory_u16, |
| 258 | num_of_entries: num_entries_in_directory_u16, |
| 259 | size_cent_dir: central_directory_size_u32, |
| 260 | cent_dir_offset: cd_offset_u32, |
| 261 | file_comm_length: self.comment_opt.as_ref().map(|v| v.len() as u16).unwrap_or_default(), |
| 262 | }; |
| 263 | |
| 264 | self.writer.write_all(&crate::spec::consts::EOCDR_SIGNATURE.to_le_bytes()).await?; |
| 265 | self.writer.write_all(&header.as_slice()).await?; |
| 266 | if let Some(comment) = self.comment_opt { |
| 267 | self.writer.write_all(comment.as_bytes()).await?; |
| 268 | } |
| 269 | |
| 270 | Ok(self.writer.into_inner()) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | #[cfg(feature = "tokio")] |
| 275 | impl<W> ZipFileWriter<Compat<W>> |
| 276 | where |
| 277 | W: tokio::io::AsyncWrite + Unpin, |
| 278 | { |
| 279 | /// Construct a new ZIP file writer from a mutable reference to a writer. |
| 280 | pub fn with_tokio(writer: W) -> TokioZipFileWriter<W> { |
| 281 | Self { |
| 282 | writer: AsyncOffsetWriter::new(writer.compat_write()), |
| 283 | cd_entries: Vec::new(), |
| 284 | comment_opt: None, |
| 285 | is_zip64: false, |
| 286 | force_no_zip64: false, |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | pub(crate) fn get_or_put_info_zip_unicode_path_extra_field_mut( |
| 292 | extra_fields: &mut Vec<ExtraField>, |
| 293 | ) -> &mut InfoZipUnicodePathExtraField { |
| 294 | if !extra_fields.iter().any(|field| matches!(field, ExtraField::InfoZipUnicodePath(_))) { |
| 295 | extra_fields |
| 296 | .push(ExtraField::InfoZipUnicodePath(InfoZipUnicodePathExtraField::V1 { crc32: 0, unicode: vec![] })); |
| 297 | } |
| 298 | |
| 299 | for field in extra_fields.iter_mut() { |
| 300 | if let ExtraField::InfoZipUnicodePath(extra_field) = field { |
| 301 | return extra_field; |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | panic!("InfoZipUnicodePathExtraField not found after insertion") |
| 306 | } |
| 307 | |
| 308 | pub(crate) fn get_or_put_info_zip_unicode_comment_extra_field_mut( |
| 309 | extra_fields: &mut Vec<ExtraField>, |
| 310 | ) -> &mut InfoZipUnicodeCommentExtraField { |
| 311 | if !extra_fields.iter().any(|field| matches!(field, ExtraField::InfoZipUnicodeComment(_))) { |
| 312 | extra_fields |
| 313 | .push(ExtraField::InfoZipUnicodeComment(InfoZipUnicodeCommentExtraField::V1 { crc32: 0, unicode: vec![] })); |
| 314 | } |
| 315 | |
| 316 | for field in extra_fields.iter_mut() { |
| 317 | if let ExtraField::InfoZipUnicodeComment(extra_field) = field { |
| 318 | return extra_field; |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | panic!("InfoZipUnicodeCommentExtraField not found after insertion") |
| 323 | } |