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 AAPT_FORMAT_ARCHIVE_H
18 #define AAPT_FORMAT_ARCHIVE_H
19 
20 #include <fstream>
21 #include <memory>
22 #include <string>
23 #include <vector>
24 
25 #include "androidfw/StringPiece.h"
26 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
27 
28 #include "Diagnostics.h"
29 #include "io/Io.h"
30 #include "util/BigBuffer.h"
31 #include "util/Files.h"
32 
33 namespace aapt {
34 
35 struct ArchiveEntry {
36   enum : uint32_t {
37     kCompress = 0x01,
38     kAlign = 0x02,
39   };
40 
41   std::string path;
42   uint32_t flags;
43   size_t uncompressed_size;
44 };
45 
46 class IArchiveWriter : public ::google::protobuf::io::CopyingOutputStream {
47  public:
48   virtual ~IArchiveWriter() = default;
49 
50   virtual bool WriteFile(const android::StringPiece& path, uint32_t flags, io::InputStream* in) = 0;
51 
52   // Starts a new entry and allows caller to write bytes to it sequentially.
53   // Only use StartEntry if code you do not control needs to write to a CopyingOutputStream.
54   // Prefer WriteFile instead of manually calling StartEntry/FinishEntry.
55   virtual bool StartEntry(const android::StringPiece& path, uint32_t flags) = 0;
56 
57   // Called to finish writing an entry previously started by StartEntry.
58   // Prefer WriteFile instead of manually calling StartEntry/FinishEntry.
59   virtual bool FinishEntry() = 0;
60 
61   // CopyingOutputStream implementation that allows sequential writes to this archive. Only
62   // valid between calls to StartEntry and FinishEntry.
63   virtual bool Write(const void* buffer, int size) = 0;
64 
65   // Returns true if there was an error writing to the archive.
66   // The resulting error message can be retrieved from GetError().
67   virtual bool HadError() const = 0;
68 
69   // Returns the error message if HadError() returns true.
70   virtual std::string GetError() const = 0;
71 };
72 
73 std::unique_ptr<IArchiveWriter> CreateDirectoryArchiveWriter(IDiagnostics* diag,
74                                                              const android::StringPiece& path);
75 
76 std::unique_ptr<IArchiveWriter> CreateZipFileArchiveWriter(IDiagnostics* diag,
77                                                            const android::StringPiece& path);
78 
79 }  // namespace aapt
80 
81 #endif /* AAPT_FORMAT_ARCHIVE_H */
82