blob: 28ecf87d57fa03e97bab2056233ce359ff7d8f36 [file] [log] [blame]
Jooyung Han5d94bfc2021-08-06 14:07:49 +09001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Utilities for zip handling
18
19use anyhow::{bail, Result};
20use bytes::Buf;
21use std::io::{Read, Seek, SeekFrom};
22use zip::ZipArchive;
23
24const EOCD_MIN_SIZE: usize = 22;
25const EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET: usize = 16;
26const EOCD_MAGIC: u32 = 0x06054b50;
27
28#[derive(Debug, PartialEq)]
29pub struct ZipSections {
30 pub central_directory_offset: u32,
31 pub central_directory_size: u32,
32 pub eocd_offset: u32,
33 pub eocd_size: u32,
34}
35
36/// Discover the layout of a zip file.
37pub fn zip_sections<R: Read + Seek>(mut reader: R) -> Result<(R, ZipSections)> {
38 // open a zip to parse EOCD
39 let archive = ZipArchive::new(reader)?;
40 let eocd_size = archive.comment().len() + EOCD_MIN_SIZE;
41 if archive.offset() != 0 {
42 bail!("Invalid ZIP: offset should be 0, but {}.", archive.offset());
43 }
44 // retrieve reader back
45 reader = archive.into_inner();
46 // the current position should point EOCD offset
47 let eocd_offset = reader.seek(SeekFrom::Current(0))?;
48 let mut eocd = vec![0u8; eocd_size as usize];
49 reader.read_exact(&mut eocd)?;
50 if (&eocd[0..]).get_u32_le() != EOCD_MAGIC {
51 bail!("Invalid ZIP: ZipArchive::new() should point EOCD after reading.");
52 }
53 let central_directory_offset = get_central_directory_offset(&eocd)?;
54 let central_directory_size = eocd_offset as u32 - central_directory_offset;
55 Ok((
56 reader,
57 ZipSections {
58 central_directory_offset,
59 central_directory_size,
60 eocd_offset: eocd_offset as u32,
61 eocd_size: eocd_size as u32,
62 },
63 ))
64}
65
66fn get_central_directory_offset(buf: &[u8]) -> Result<u32> {
67 if buf.len() < EOCD_MIN_SIZE {
68 bail!("Invalid EOCD size: {}", buf.len());
69 }
70 Ok((&buf[EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET..]).get_u32_le())
71}