Home | History | Annotate | Download | only in ziparchive
      1 /*
      2  * Copyright (C) 2015 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 #ifndef LIBZIPARCHIVE_ZIPWRITER_H_
     18 #define LIBZIPARCHIVE_ZIPWRITER_H_
     19 
     20 #include <cstdio>
     21 #include <ctime>
     22 #include <zlib.h>
     23 
     24 #include <memory>
     25 #include <string>
     26 #include <vector>
     27 
     28 #include "android-base/macros.h"
     29 #include "utils/Compat.h"
     30 
     31 /**
     32  * Writes a Zip file via a stateful interface.
     33  *
     34  * Example:
     35  *
     36  *   FILE* file = fopen("path/to/zip.zip", "wb");
     37  *
     38  *   ZipWriter writer(file);
     39  *
     40  *   writer.StartEntry("test.txt", ZipWriter::kCompress | ZipWriter::kAlign);
     41  *   writer.WriteBytes(buffer, bufferLen);
     42  *   writer.WriteBytes(buffer2, bufferLen2);
     43  *   writer.FinishEntry();
     44  *
     45  *   writer.StartEntry("empty.txt", 0);
     46  *   writer.FinishEntry();
     47  *
     48  *   writer.Finish();
     49  *
     50  *   fclose(file);
     51  */
     52 class ZipWriter {
     53 public:
     54   enum {
     55     /**
     56      * Flag to compress the zip entry using deflate.
     57      */
     58     kCompress = 0x01,
     59 
     60     /**
     61      * Flag to align the zip entry data on a 32bit boundary. Useful for
     62      * mmapping the data at runtime.
     63      */
     64     kAlign32 = 0x02,
     65   };
     66 
     67   /**
     68    * A struct representing a zip file entry.
     69    */
     70   struct FileEntry {
     71     std::string path;
     72     uint16_t compression_method;
     73     uint32_t crc32;
     74     uint32_t compressed_size;
     75     uint32_t uncompressed_size;
     76     uint16_t last_mod_time;
     77     uint16_t last_mod_date;
     78     uint32_t padding_length;
     79     off64_t local_file_header_offset;
     80   };
     81 
     82   static const char* ErrorCodeString(int32_t error_code);
     83 
     84   /**
     85    * Create a ZipWriter that will write into a FILE stream. The file should be opened with
     86    * open mode of "wb" or "w+b". ZipWriter does not take ownership of the file stream. The
     87    * caller is responsible for closing the file.
     88    */
     89   explicit ZipWriter(FILE* f);
     90 
     91   // Move constructor.
     92   ZipWriter(ZipWriter&& zipWriter);
     93 
     94   // Move assignment.
     95   ZipWriter& operator=(ZipWriter&& zipWriter);
     96 
     97   /**
     98    * Starts a new zip entry with the given path and flags.
     99    * Flags can be a bitwise OR of ZipWriter::kCompress and ZipWriter::kAlign.
    100    * Subsequent calls to WriteBytes(const void*, size_t) will add data to this entry.
    101    * Returns 0 on success, and an error value < 0 on failure.
    102    */
    103   int32_t StartEntry(const char* path, size_t flags);
    104 
    105   /**
    106    * Starts a new zip entry with the given path and flags, where the
    107    * entry will be aligned to the given alignment.
    108    * Flags can only be ZipWriter::kCompress. Using the flag ZipWriter::kAlign32
    109    * will result in an error.
    110    * Subsequent calls to WriteBytes(const void*, size_t) will add data to this entry.
    111    * Returns 0 on success, and an error value < 0 on failure.
    112    */
    113   int32_t StartAlignedEntry(const char* path, size_t flags, uint32_t alignment);
    114 
    115   /**
    116    * Same as StartEntry(const char*, size_t), but sets a last modified time for the entry.
    117    */
    118   int32_t StartEntryWithTime(const char* path, size_t flags, time_t time);
    119 
    120   /**
    121    * Same as StartAlignedEntry(const char*, size_t), but sets a last modified time for the entry.
    122    */
    123   int32_t StartAlignedEntryWithTime(const char* path, size_t flags, time_t time,
    124                                     uint32_t alignment);
    125 
    126   /**
    127    * Writes bytes to the zip file for the previously started zip entry.
    128    * Returns 0 on success, and an error value < 0 on failure.
    129    */
    130   int32_t WriteBytes(const void* data, size_t len);
    131 
    132   /**
    133    * Finish a zip entry started with StartEntry(const char*, size_t) or
    134    * StartEntryWithTime(const char*, size_t, time_t). This must be called before
    135    * any new zip entries are started, or before Finish() is called.
    136    * Returns 0 on success, and an error value < 0 on failure.
    137    */
    138   int32_t FinishEntry();
    139 
    140   /**
    141    * Discards the last-written entry. Can only be called after an entry has been written using
    142    * FinishEntry().
    143    * Returns 0 on success, and an error value < 0 on failure.
    144    */
    145   int32_t DiscardLastEntry();
    146 
    147   /**
    148    * Sets `out_entry` to the last entry written after a call to FinishEntry().
    149    * Returns 0 on success, and an error value < 0 if no entries have been written.
    150    */
    151   int32_t GetLastEntry(FileEntry* out_entry);
    152 
    153   /**
    154    * Writes the Central Directory Headers and flushes the zip file stream.
    155    * Returns 0 on success, and an error value < 0 on failure.
    156    */
    157   int32_t Finish();
    158 
    159 private:
    160   DISALLOW_COPY_AND_ASSIGN(ZipWriter);
    161 
    162   int32_t HandleError(int32_t error_code);
    163   int32_t PrepareDeflate();
    164   int32_t StoreBytes(FileEntry* file, const void* data, size_t len);
    165   int32_t CompressBytes(FileEntry* file, const void* data, size_t len);
    166   int32_t FlushCompressedBytes(FileEntry* file);
    167 
    168   enum class State {
    169     kWritingZip,
    170     kWritingEntry,
    171     kDone,
    172     kError,
    173   };
    174 
    175   FILE* file_;
    176   bool seekable_;
    177   off64_t current_offset_;
    178   State state_;
    179   std::vector<FileEntry> files_;
    180   FileEntry current_file_entry_;
    181 
    182   std::unique_ptr<z_stream, void(*)(z_stream*)> z_stream_;
    183   std::vector<uint8_t> buffer_;
    184 };
    185 
    186 #endif /* LIBZIPARCHIVE_ZIPWRITER_H_ */
    187