Debian Codegraph @

src/tools/zip/zip.cpp

raw
1 /* -*- Mode: C++; c-default-style: "k&r"; indent-tabs-mode: nil; tab-width: 2; c-basic-offset: 2 -*- */
2
3 /* libmwaw: tools
4 * Version: MPL 2.0 / LGPLv2+
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 2.0 (the "License"); you may not use this file except in compliance with
8 * the License or as specified alternatively below. You may obtain a copy of
9 * the License at http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * Major Contributor(s):
17 * Copyright (C) 2011, 2012 Alonso Laurent ([email protected])
18 *
19 *
20 * All Rights Reserved.
21 *
22 * For minor contributions see the git repository.
23 *
24 * Alternatively, the contents of this file may be used under the terms of
25 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
26 * in which case the provisions of the LGPLv2+ are applicable
27 * instead of those above.
28 */
29
30 #include <errno.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <time.h>
34 #include <zlib.h>
35
36 #include <fstream>
37 #include <iostream>
38
39 #include "input.h"
40 #include "zip.h"
41 #include "zip_internal.h"
42
43 namespace libmwaw_zip
44 {
45 static void writeU16(char *ptr, uint16_t data)
46 {
47 *(ptr++)=char(data&0xFF);
48 *(ptr++)=char(data>>8);
49 }
50 static void writeU32(char *ptr, uint32_t data)
51 {
52 *(ptr++)=char(data&0xFF);
53 *(ptr++)=char((data>>8)&0xFF);
54 *(ptr++)=char((data>>16)&0xFF);
55 *(ptr++)=char((data>>24)&0xFF);
56 }
57
58 static void writeTimeDate(char *ptr)
59 {
60 time_t now = time(0L);
61 struct tm timeinfo = *(localtime(&now));
62 auto time=uint16_t((timeinfo.tm_hour<<11)|(timeinfo.tm_min<<5));
63 auto date=uint16_t((timeinfo.tm_mon<<5)|timeinfo.tm_mday);
64 int year = 1900+timeinfo.tm_year;
65 if (year > 1980)
66 date |= uint16_t((year-1980)<<9);
67 writeU16(ptr, time);
68 writeU16(ptr+2, date);
69 }
70
71 // ------------------------------------------------------------
72 // File implementation
73 // ------------------------------------------------------------
74 Zip::File::File(std::string const &base, std::string const &dir)
75 : m_base(base)
76 , m_dir(dir)
77 , m_uncompressedLength(0)
78 , m_compressedLength(0)
79 , m_deflate(false)
80 , m_crc32(0)
81 , m_offsetInFile(0)
82 {
83 }
84
85 bool Zip::File::write(std::shared_ptr<InputStream> input, std::ostream &output)
86 {
87 if (!m_base.length())
88 return false;
89 if (!input || input->length()<0) {
90 MWAW_DEBUG_MSG(("Zip::File::write: called without input\n"));
91 return false;
92 }
93 // read the file
94 auto numBytes = static_cast<unsigned long>(input->length());
95 input->seek(0, InputStream::SK_SET);
96 unsigned long numBytesRead=0;
97 unsigned char const *buf= numBytes==0 ? 0 : input->read(numBytes, numBytesRead);
98 if (numBytesRead != static_cast<unsigned long>(numBytes) || (numBytesRead && !buf)) {
99 MWAW_DEBUG_MSG(("Zip::File::write: can not read the input\n"));
100 return false;
101 }
102 // crc32
103 m_uncompressedLength = m_compressedLength = uInt(numBytes);
104 m_crc32 = crc32(0L, Z_NULL, 0);
105 if (numBytes)
106 m_crc32 = crc32(m_crc32, reinterpret_cast<const Bytef *>(buf), m_uncompressedLength);
107
108 std::vector<unsigned char> buffer;
109 if (numBytes>10) {
110 buffer.resize(size_t(numBytes)-10);
111 z_stream zip;
112 zip.next_in = reinterpret_cast<Bytef *>(const_cast<unsigned char *>(buf));
113 zip.avail_in = m_uncompressedLength;
114 zip.total_in = 0;
115 zip.next_out = &reinterpret_cast<Bytef &>(buffer[0]);
116 zip.avail_out = uInt(numBytes)-10;
117 zip.total_out = 0;
118 zip.msg=0;
119 zip.zalloc=0;
120 zip.zfree=0;
121 zip.opaque=0;
122
123 /* optimize for speed and set all to default: expected negative
124 WindowBits value which supresses the zlib header (and checksum)
125 from the stream. */
126 #if defined(__clang__)
127 # pragma clang diagnostic push
128 # pragma clang diagnostic ignored "-Wold-style-cast"
129 #endif
130 if (deflateInit2(&zip, 1, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY)!=Z_OK ||
131 deflate(&zip,Z_FINISH)!=Z_STREAM_END)
132 buffer.resize(0);
133 else
134 m_compressedLength = uInt(zip.total_out);
135 #if defined(__clang__)
136 # pragma clang diagnostic pop
137 #endif
138 deflateEnd(&zip);
139 }
140
141 // write the data
142 m_offsetInFile = uLong(output.tellp());
143 char localHeader[] = {
144 0x50, 0x4b, 0x3, 0x4 /* 0:magic */, 0x14, 0 /* 4:version */,
145 0, 0 /* 6:flags */, 0, 0 /* 8:compression */,
146 0, 0 /* 10:time */, 0, 0 /* 12:date */, 0, 0, 0, 0 /* 14:checksum */,
147 0, 0, 0, 0 /* 18:compressed size */, 0, 0, 0, 0 /* 22:uncompressed size */,
148 0, 0 /* 26:file name size */, 0, 0 /* 28:extra size */
149 };
150 if (buffer.size()) {
151 m_deflate = true;
152 localHeader[8]=0x8; // deflate
153 }
154 std::string fName("");
155 if (m_dir.length() && m_dir[0]=='/')
156 fName = m_dir.substr(1)+m_base;
157 else
158 fName = m_dir+m_base;
159 writeTimeDate(localHeader+10);
160 writeU32(localHeader+14, uint32_t(m_crc32));
161 writeU32(localHeader+18, uint32_t(m_compressedLength));
162 writeU32(localHeader+22, uint32_t(m_uncompressedLength));
163 writeU16(localHeader+26, uint16_t(fName.length()));
164 output.write(localHeader, 30);
165 if (fName.length())
166 output.write(fName.c_str(), std::streamsize(fName.length()));
167
168 if (buffer.size())
169 output.write(reinterpret_cast<const char *>(&buffer[0]), std::streamsize(m_compressedLength));
170 else if (numBytes)
171 output.write(reinterpret_cast<const char *>(buf), std::streamsize(numBytes));
172 return true;
173 }
174
175 bool Zip::File::writeCentralInformation(std::ostream &output) const
176 {
177 if (!m_base.length())
178 return false;
179
180 char fileHeader[] = {
181 0x50, 0x4b, 0x1, 0x2 /* 0:magic */,
182 0x14, 0 /* 4:version */, 0x14, 0 /* 6:version needed*/,
183 0, 0 /* 8:flags */, 0, 0 /* 10:compression */,
184 0, 0 /* 12:time */, 0, 0 /* 14:date */, 0, 0, 0, 0 /* 16:checksum */,
185 0, 0, 0, 0 /* 20:compressed size */, 0, 0, 0, 0 /* 24:uncompressed size */,
186 0, 0 /* 28:file name size */, 0, 0 /* 30:extra size */,
187 0, 0 /* 32:comment size */,
188 0, 0 /* 34: disk # start */, 0, 0 /*36: ascii/text file */,
189 0, 0, 0, 0 /* 38:external attribute */, 0, 0, 0, 0/*42: offset of local header*/
190 };
191 if (m_deflate)
192 fileHeader[10]=0x8;
193 std::string fName("");
194 if (m_dir.length() && m_dir[0]=='/')
195 fName = m_dir.substr(1)+m_base;
196 else
197 fName = m_dir+m_base;
198 writeTimeDate(fileHeader+12);
199 writeU32(fileHeader+16, uint32_t(m_crc32));
200 writeU32(fileHeader+20, uint32_t(m_compressedLength));
201 writeU32(fileHeader+24, uint32_t(m_uncompressedLength));
202 writeU16(fileHeader+28, uint16_t(fName.length()));
203 writeU32(fileHeader+42, uint32_t(m_offsetInFile));
204 output.write(fileHeader, 46);
205 if (fName.length())
206 output.write(fName.c_str(), std::streamsize(fName.length()));
207
208 return true;
209 }
210
211 // ------------------------------------------------------------
212 // Directory implementation
213 // ------------------------------------------------------------
214 Zip::Directory::Directory(std::string const &dir)
215 : m_dir(dir)
216 , m_nameFileMap()
217 {
218 }
219
220 bool Zip::Directory::add(std::shared_ptr<InputStream> input, char const *base, std::ostream &output)
221 {
222 if (!base || !input) {
223 MWAW_DEBUG_MSG(("Zip::Directory::add: called without input\n"));
224 return false;
225 }
226 std::string name(base);
227 // first clean name
228 size_t len=name.length();
229 if (base[0]=='\\' || base[0]=='/') {
230 if (len==1) {
231 MWAW_DEBUG_MSG(("Zip::Directory::add: called with name <</>>\n"));
232 return false;
233 }
234 name=base+1;
235 }
236 if (m_nameFileMap.find(name) != m_nameFileMap.end()) {
237 MWAW_DEBUG_MSG(("Zip::Directory::add: a file was already added with this name: %s\n", name.c_str()));
238 return false;
239 }
240 File file(name, m_dir);
241 if (!file.write(input,output))
242 return false;
243 m_nameFileMap.insert(std::map<std::string, File>::value_type(name, file));
244 return true;
245 }
246
247 int Zip::Directory::writeCentralInformation(std::ostream &output) const
248 {
249 int num=0;
250 for (auto const &it : m_nameFileMap) {
251 File const &file=it.second;
252 if (file.writeCentralInformation(output))
253 num++;
254 }
255 return num;
256 }
257
258 // ------------------------------------------------------------
259 // Zip implementation
260 // ------------------------------------------------------------
261 Zip::Zip()
262 : m_output()
263 , m_nameDirectoryMap()
264 {
265 }
266
267 Zip::~Zip()
268 {
269 if (m_output.is_open())
270 close();
271 }
272
273 bool Zip::open(char const *filename)
274 {
275 if (!filename) {
276 MWAW_DEBUG_MSG(("Zip::open: called without any name\n"));
277 return false;
278 }
279 if (m_output.is_open()) {
280 MWAW_DEBUG_MSG(("Zip::open: oops, output is already opened\n"));
281 return false;
282 }
283 m_output.open(filename, std::ios::out | std::ios::binary);
284 if (!m_output.is_open()) {
285 MWAW_DEBUG_MSG(("Zip::open: can not opend %s\n", filename));
286 return false;
287 }
288
289 return true;
290 }
291
292 bool Zip::close()
293 {
294 if (!m_output.is_open()) {
295 MWAW_DEBUG_MSG(("Zip::close: the output is already closed\n"));
296 return false;
297 }
298
299 auto pos=uLong(m_output.tellp());
300 int numEntries = 0;
301 for (auto const &it : m_nameDirectoryMap) {
302 Directory const &dir=it.second;
303 numEntries += dir.writeCentralInformation(m_output);
304 }
305 char endHeader[] = {
306 0x50, 0x4b, 0x5, 0x6 /* 0:magic */,
307 0, 0 /*4: disk number */, 0, 0 /* 6: disk w/cd */,
308 0, 0 /*8: disk entries */, 0, 0 /* 10: total entries */,
309 0, 0, 0, 0 /*12: central directory size */,
310 0, 0, 0, 0 /*16: begin of central directory */,
311 0, 0 /* 20: comment length */
312 };
313 writeU16(endHeader+8, uint16_t(numEntries));
314 writeU16(endHeader+10, uint16_t(numEntries));
315 writeU32(endHeader+12, uint32_t(uLong(m_output.tellp())-pos));
316 writeU32(endHeader+16, uint32_t(pos));
317 m_output.write(endHeader,22);
318 m_output.close();
319 return true;
320 }
321
322 bool Zip::add(std::shared_ptr<InputStream> input, char const *base, char const *path)
323 {
324 if (!m_output.is_open())
325 return false;
326 if (!base || !input) {
327 MWAW_DEBUG_MSG(("Zip::add: called without input\n"));
328 return false;
329 }
330 // clean the directory name
331 std::string dir(path ? path : "");
332 size_t len = dir.length();
333 for (size_t c=0; c < len; c++) {
334 if (dir[c]=='\\')
335 dir[c]='/';
336 }
337 if (!len || (path && path[len-1]!='/'))
338 dir += '/';
339
340 if (m_nameDirectoryMap.find(dir)==m_nameDirectoryMap.end())
341 m_nameDirectoryMap.insert(std::map<std::string, Directory>::value_type(dir, Directory(dir)));
342 Directory &direct=m_nameDirectoryMap.find(dir)->second;
343 return direct.add(input, base, m_output);
344 }
345
346 }
347
348 // vim: set filetype=cpp tabstop=2 shiftwidth=2 cindent autoindent smartindent noexpandtab: