1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QT_NO_TEXTODFWRITER
#include "qzipreader_p.h"
#include "qzipwriter_p.h"
#include <zlib.h>
// Zip standard version for archives handled by this API
// (actually, the only basic support of this version is implemented but it is enough for now)
#define ZIP_VERSION 20
#if 0
#define ZDEBUG qDebug
#else
#define ZDEBUG if (0) qDebug
#endif
QT_BEGIN_NAMESPACE
static inline uint readUInt(const uchar *data)
{
return (data[0]) + (data[1]<<8) + (data[2]<<16) + (data[3]<<24);
}
static inline ushort readUShort(const uchar *data)
{
return (data[0]) + (data[1]<<8);
}
static inline void writeUInt(uchar *data, uint i)
{
data[0] = i & 0xff;
data[1] = (i>>8) & 0xff;
data[2] = (i>>16) & 0xff;
data[3] = (i>>24) & 0xff;
}
static inline void writeUShort(uchar *data, ushort i)
{
data[0] = i & 0xff;
data[1] = (i>>8) & 0xff;
}
static inline void copyUInt(uchar *dest, const uchar *src)
{
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
dest[3] = src[3];
}
static inline void copyUShort(uchar *dest, const uchar *src)
{
dest[0] = src[0];
dest[1] = src[1];
}
static void writeMSDosDate(uchar *dest, const QDateTime& dt)
{
if (dt.isValid()) {
quint16 time =
(dt.time().hour() << 11) // 5 bit hour
| (dt.time().minute() << 5) // 6 bit minute
| (dt.time().second() >> 1); // 5 bit double seconds
dest[0] = time & 0xff;
dest[1] = time >> 8;
quint16 date =
((dt.date().year() - 1980) << 9) // 7 bit year 1980-based
| (dt.date().month() << 5) // 4 bit month
| (dt.date().day()); // 5 bit day
dest[2] = char(date);
dest[3] = char(date >> 8);
} else {
dest[0] = 0;
dest[1] = 0;
dest[2] = 0;
dest[3] = 0;
}
}
static int inflate(Bytef *dest, ulong *destLen, const Bytef *source, ulong sourceLen)
{
z_stream stream;
int err;
stream.next_in = const_cast<Bytef*>(source);
stream.avail_in = (uInt)sourceLen;
if ((uLong)stream.avail_in != sourceLen)
return Z_BUF_ERROR;
stream.next_out = dest;
stream.avail_out = (uInt)*destLen;
if ((uLong)stream.avail_out != *destLen)
return Z_BUF_ERROR;
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
err = inflateInit2(&stream, -MAX_WBITS);
if (err != Z_OK)
return err;
err = inflate(&stream, Z_FINISH);
if (err != Z_STREAM_END) {
inflateEnd(&stream);
if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
return Z_DATA_ERROR;
return err;
}
*destLen = stream.total_out;
err = inflateEnd(&stream);
return err;
}
static int deflate (Bytef *dest, ulong *destLen, const Bytef *source, ulong sourceLen)
{
z_stream stream;
int err;
stream.next_in = const_cast<Bytef*>(source);
stream.avail_in = (uInt)sourceLen;
stream.next_out = dest;
stream.avail_out = (uInt)*destLen;
if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
stream.opaque = (voidpf)0;
err = deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
if (err != Z_OK) return err;
err = deflate(&stream, Z_FINISH);
if (err != Z_STREAM_END) {
deflateEnd(&stream);
return err == Z_OK ? Z_BUF_ERROR : err;
}
*destLen = stream.total_out;
err = deflateEnd(&stream);
return err;
}
namespace WindowsFileAttributes {
enum {
Dir = 0x10, // FILE_ATTRIBUTE_DIRECTORY
File = 0x80, // FILE_ATTRIBUTE_NORMAL
TypeMask = 0x90,
ReadOnly = 0x01, // FILE_ATTRIBUTE_READONLY
PermMask = 0x01
};
}
namespace UnixFileAttributes {
enum {
Dir = 0040000, // __S_IFDIR
File = 0100000, // __S_IFREG
SymLink = 0120000, // __S_IFLNK
TypeMask = 0170000, // __S_IFMT
ReadUser = 0400, // __S_IRUSR
WriteUser = 0200, // __S_IWUSR
ExeUser = 0100, // __S_IXUSR
ReadGroup = 0040, // __S_IRGRP
WriteGroup = 0020, // __S_IWGRP
ExeGroup = 0010, // __S_IXGRP
ReadOther = 0004, // __S_IROTH
WriteOther = 0002, // __S_IWOTH
ExeOther = 0001, // __S_IXOTH
PermMask = 0777
};
}
static QFile::Permissions modeToPermissions(quint32 mode)
{
QFile::Permissions ret;
if (mode & UnixFileAttributes::ReadUser)
ret |= QFile::ReadOwner | QFile::ReadUser;
if (mode & UnixFileAttributes::WriteUser)
ret |= QFile::WriteOwner | QFile::WriteUser;
if (mode & UnixFileAttributes::ExeUser)
ret |= QFile::ExeOwner | QFile::ExeUser;
if (mode & UnixFileAttributes::ReadGroup)
ret |= QFile::ReadGroup;
if (mode & UnixFileAttributes::WriteGroup)
ret |= QFile::WriteGroup;
if (mode & UnixFileAttributes::ExeGroup)
ret |= QFile::ExeGroup;
if (mode & UnixFileAttributes::ReadOther)
ret |= QFile::ReadOther;
if (mode & UnixFileAttributes::WriteOther)
ret |= QFile::WriteOther;
if (mode & UnixFileAttributes::ExeOther)
ret |= QFile::ExeOther;
return ret;
}
static quint32 permissionsToMode(QFile::Permissions perms)
{
quint32 mode = 0;
if (perms & (QFile::ReadOwner | QFile::ReadUser))
mode |= UnixFileAttributes::ReadUser;
if (perms & (QFile::WriteOwner | QFile::WriteUser))
mode |= UnixFileAttributes::WriteUser;
if (perms & (QFile::ExeOwner | QFile::ExeUser))
mode |= UnixFileAttributes::WriteUser;
if (perms & QFile::ReadGroup)
mode |= UnixFileAttributes::ReadGroup;
if (perms & QFile::WriteGroup)
mode |= UnixFileAttributes::WriteGroup;
if (perms & QFile::ExeGroup)
mode |= UnixFileAttributes::ExeGroup;
if (perms & QFile::ReadOther)
mode |= UnixFileAttributes::ReadOther;
if (perms & QFile::WriteOther)
mode |= UnixFileAttributes::WriteOther;
if (perms & QFile::ExeOther)
mode |= UnixFileAttributes::ExeOther;
return mode;
}
static QDateTime readMSDosDate(const uchar *src)
{
uint dosDate = readUInt(src);
quint64 uDate;
uDate = (quint64)(dosDate >> 16);
uint tm_mday = (uDate & 0x1f);
uint tm_mon = ((uDate & 0x1E0) >> 5);
uint tm_year = (((uDate & 0x0FE00) >> 9) + 1980);
uint tm_hour = ((dosDate & 0xF800) >> 11);
uint tm_min = ((dosDate & 0x7E0) >> 5);
uint tm_sec = ((dosDate & 0x1f) << 1);
return QDateTime(QDate(tm_year, tm_mon, tm_mday), QTime(tm_hour, tm_min, tm_sec));
}
// for details, see http://www.pkware.com/documents/casestudies/APPNOTE.TXT
enum HostOS {
HostFAT = 0,
HostAMIGA = 1,
HostVMS = 2, // VAX/VMS
HostUnix = 3,
HostVM_CMS = 4,
HostAtari = 5, // what if it's a minix filesystem? [cjh]
HostHPFS = 6, // filesystem used by OS/2 (and NT 3.x)
HostMac = 7,
HostZ_System = 8,
HostCPM = 9,
HostTOPS20 = 10, // pkzip 2.50 NTFS
HostNTFS = 11, // filesystem used by Windows NT
HostQDOS = 12, // SMS/QDOS
HostAcorn = 13, // Archimedes Acorn RISC OS
HostVFAT = 14, // filesystem used by Windows 95, NT
HostMVS = 15,
HostBeOS = 16, // hybrid POSIX/database filesystem
HostTandem = 17,
HostOS400 = 18,
HostOSX = 19
};
Q_DECLARE_TYPEINFO(HostOS, Q_PRIMITIVE_TYPE);
enum GeneralPurposeFlag {
Encrypted = 0x01,
AlgTune1 = 0x02,
AlgTune2 = 0x04,
HasDataDescriptor = 0x08,
PatchedData = 0x20,
StrongEncrypted = 0x40,
Utf8Names = 0x0800,
CentralDirectoryEncrypted = 0x2000
};
Q_DECLARE_TYPEINFO(GeneralPurposeFlag, Q_PRIMITIVE_TYPE);
enum CompressionMethod {
CompressionMethodStored = 0,
CompressionMethodShrunk = 1,
CompressionMethodReduced1 = 2,
CompressionMethodReduced2 = 3,
CompressionMethodReduced3 = 4,
CompressionMethodReduced4 = 5,
CompressionMethodImploded = 6,
CompressionMethodReservedTokenizing = 7, // reserved for tokenizing
CompressionMethodDeflated = 8,
CompressionMethodDeflated64 = 9,
CompressionMethodPKImploding = 10,
CompressionMethodBZip2 = 12,
CompressionMethodLZMA = 14,
CompressionMethodTerse = 18,
CompressionMethodLz77 = 19,
CompressionMethodJpeg = 96,
CompressionMethodWavPack = 97,
CompressionMethodPPMd = 98,
CompressionMethodWzAES = 99
};
Q_DECLARE_TYPEINFO(CompressionMethod, Q_PRIMITIVE_TYPE);
struct LocalFileHeader
{
uchar signature[4]; // 0x04034b50
uchar version_needed[2];
uchar general_purpose_bits[2];
uchar compression_method[2];
uchar last_mod_file[4];
uchar crc_32[4];
uchar compressed_size[4];
uchar uncompressed_size[4];
uchar file_name_length[2];
uchar extra_field_length[2];
};
Q_DECLARE_TYPEINFO(LocalFileHeader, Q_PRIMITIVE_TYPE);
struct DataDescriptor
{
uchar crc_32[4];
uchar compressed_size[4];
uchar uncompressed_size[4];
};
Q_DECLARE_TYPEINFO(DataDescriptor, Q_PRIMITIVE_TYPE);
struct CentralFileHeader
{
uchar signature[4]; // 0x02014b50
uchar version_made[2];
uchar version_needed[2];
uchar general_purpose_bits[2];
uchar compression_method[2];
uchar last_mod_file[4];
uchar crc_32[4];
uchar compressed_size[4];
uchar uncompressed_size[4];
uchar file_name_length[2];
uchar extra_field_length[2];
uchar file_comment_length[2];
uchar disk_start[2];
uchar internal_file_attributes[2];
uchar external_file_attributes[4];
uchar offset_local_header[4];
LocalFileHeader toLocalHeader() const;
};
Q_DECLARE_TYPEINFO(CentralFileHeader, Q_PRIMITIVE_TYPE);
struct EndOfDirectory
{
uchar signature[4]; // 0x06054b50
uchar this_disk[2];
uchar start_of_directory_disk[2];
uchar num_dir_entries_this_disk[2];
uchar num_dir_entries[2];
uchar directory_size[4];
uchar dir_start_offset[4];
uchar comment_length[2];
};
Q_DECLARE_TYPEINFO(EndOfDirectory, Q_PRIMITIVE_TYPE);
struct FileHeader
{
CentralFileHeader h;
QByteArray file_name;
QByteArray extra_field;
QByteArray file_comment;
};
Q_DECLARE_TYPEINFO(FileHeader, Q_MOVABLE_TYPE);
class MQZipPrivate
{
public:
MQZipPrivate(QIODevice *device, bool ownDev)
: device(device), ownDevice(ownDev), dirtyFileTree(true), start_of_directory(0)
{
}
~MQZipPrivate()
{
if (ownDevice)
delete device;
}
MQZipReader::FileInfo fillFileInfo(int index) const;
QIODevice *device;
bool ownDevice;
bool dirtyFileTree;
QVector<FileHeader> fileHeaders;
QByteArray comment;
uint start_of_directory;
};
MQZipReader::FileInfo MQZipPrivate::fillFileInfo(int index) const
{
MQZipReader::FileInfo fileInfo;
FileHeader header = fileHeaders.at(index);
quint32 mode = readUInt(header.h.external_file_attributes);
const HostOS hostOS = HostOS(readUShort(header.h.version_made) >> 8);
switch (hostOS) {
case HostUnix:
mode = (mode >> 16) & 0xffff;
switch (mode & UnixFileAttributes::TypeMask) {
case UnixFileAttributes::SymLink:
fileInfo.isSymLink = true;
break;
case UnixFileAttributes::Dir:
fileInfo.isDir = true;
break;
case UnixFileAttributes::File:
default: // ### just for the case; should we warn?
fileInfo.isFile = true;
break;
}
fileInfo.permissions = modeToPermissions(mode);
break;
case HostFAT:
case HostNTFS:
case HostHPFS:
case HostVFAT:
switch (mode & WindowsFileAttributes::TypeMask) {
case WindowsFileAttributes::Dir:
fileInfo.isDir = true;
break;
case WindowsFileAttributes::File:
default:
fileInfo.isFile = true;
break;
}
fileInfo.permissions |= QFile::ReadOwner | QFile::ReadUser | QFile::ReadGroup | QFile::ReadOther;
if ((mode & WindowsFileAttributes::ReadOnly) == 0)
fileInfo.permissions |= QFile::WriteOwner | QFile::WriteUser | QFile::WriteGroup | QFile::WriteOther;
if (fileInfo.isDir)
fileInfo.permissions |= QFile::ExeOwner | QFile::ExeUser | QFile::ExeGroup | QFile::ExeOther;
break;
default:
qWarning("QZip: Zip entry format at %d is not supported.", index);
return fileInfo; // we don't support anything else
}
ushort general_purpose_bits = readUShort(header.h.general_purpose_bits);
// if bit 11 is set, the filename and comment fields must be encoded using UTF-8
const bool inUtf8 = (general_purpose_bits & Utf8Names) != 0;
fileInfo.filePath = inUtf8 ? QString::fromUtf8(header.file_name) : QString::fromLocal8Bit(header.file_name);
fileInfo.crc = readUInt(header.h.crc_32);
fileInfo.size = readUInt(header.h.uncompressed_size);
fileInfo.lastModified = readMSDosDate(header.h.last_mod_file);
// fix the file path, if broken (convert separators, eat leading and trailing ones)
fileInfo.filePath = QDir::fromNativeSeparators(fileInfo.filePath);
while (!fileInfo.filePath.isEmpty() && (fileInfo.filePath.at(0) == QLatin1Char('.') || fileInfo.filePath.at(0) == QLatin1Char('/')))
fileInfo.filePath = fileInfo.filePath.mid(1);
while (!fileInfo.filePath.isEmpty() && fileInfo.filePath.at(fileInfo.filePath.size() - 1) == QLatin1Char('/'))
fileInfo.filePath.chop(1);
return fileInfo;
}
class MQZipReaderPrivate : public MQZipPrivate
{
public:
MQZipReaderPrivate(QIODevice *device, bool ownDev)
: MQZipPrivate(device, ownDev), status(MQZipReader::NoError)
{
}
void scanFiles();
MQZipReader::Status status;
};
class MQZipWriterPrivate : public MQZipPrivate
{
public:
MQZipWriterPrivate(QIODevice *device, bool ownDev)
: MQZipPrivate(device, ownDev),
status(MQZipWriter::NoError),
permissions(QFile::ReadOwner | QFile::WriteOwner),
compressionPolicy(MQZipWriter::AlwaysCompress)
{
}
MQZipWriter::Status status;
QFile::Permissions permissions;
MQZipWriter::CompressionPolicy compressionPolicy;
enum EntryType { Directory, File, Symlink };
void addEntry(EntryType type, const QString &fileName, const QByteArray &contents);
};
LocalFileHeader CentralFileHeader::toLocalHeader() const
{
LocalFileHeader h;
writeUInt(h.signature, 0x04034b50);
copyUShort(h.version_needed, version_needed);
copyUShort(h.general_purpose_bits, general_purpose_bits);
copyUShort(h.compression_method, compression_method);
copyUInt(h.last_mod_file, last_mod_file);
copyUInt(h.crc_32, crc_32);
copyUInt(h.compressed_size, compressed_size);
copyUInt(h.uncompressed_size, uncompressed_size);
copyUShort(h.file_name_length, file_name_length);
copyUShort(h.extra_field_length, extra_field_length);
return h;
}
void MQZipReaderPrivate::scanFiles()
{
if (!dirtyFileTree)
return;
if (! (device->isOpen() || device->open(QIODevice::ReadOnly))) {
status = MQZipReader::FileOpenError;
return;
}
if ((device->openMode() & QIODevice::ReadOnly) == 0) { // only read the index from readable files.
status = MQZipReader::FileReadError;
return;
}
dirtyFileTree = false;
uchar tmp[4];
device->read((char *)tmp, 4);
if (readUInt(tmp) != 0x04034b50) {
qWarning("QZip: not a zip file!");
return;
}
// find EndOfDirectory header
int i = 0;
int start_of_directory = -1;
int num_dir_entries = 0;
EndOfDirectory eod;
while (start_of_directory == -1) {
const int pos = device->size() - int(sizeof(EndOfDirectory)) - i;
if (pos < 0 || i > 65535) {
qWarning("QZip: EndOfDirectory not found");
return;
}
device->seek(pos);
device->read((char *)&eod, sizeof(EndOfDirectory));
if (readUInt(eod.signature) == 0x06054b50)
break;
++i;
}
// have the eod
start_of_directory = readUInt(eod.dir_start_offset);
num_dir_entries = readUShort(eod.num_dir_entries);
ZDEBUG("start_of_directory at %d, num_dir_entries=%d", start_of_directory, num_dir_entries);
int comment_length = readUShort(eod.comment_length);
if (comment_length != i)
qWarning("QZip: failed to parse zip file.");
comment = device->read(qMin(comment_length, i));
device->seek(start_of_directory);
for (i = 0; i < num_dir_entries; ++i) {
FileHeader header;
int read = device->read((char *) &header.h, sizeof(CentralFileHeader));
if (read < (int)sizeof(CentralFileHeader)) {
qWarning("QZip: Failed to read complete header, index may be incomplete");
break;
}
if (readUInt(header.h.signature) != 0x02014b50) {
qWarning("QZip: invalid header signature, index may be incomplete");
break;
}
int l = readUShort(header.h.file_name_length);
header.file_name = device->read(l);
if (header.file_name.length() != l) {
qWarning("QZip: Failed to read filename from zip index, index may be incomplete");
break;
}
l = readUShort(header.h.extra_field_length);
header.extra_field = device->read(l);
if (header.extra_field.length() != l) {
qWarning("QZip: Failed to read extra field in zip file, skipping file, index may be incomplete");
break;
}
l = readUShort(header.h.file_comment_length);
header.file_comment = device->read(l);
if (header.file_comment.length() != l) {
qWarning("QZip: Failed to read read file comment, index may be incomplete");
break;
}
ZDEBUG("found file '%s'", header.file_name.data());
fileHeaders.append(header);
}
}
void MQZipWriterPrivate::addEntry(EntryType type, const QString &fileName, const QByteArray &contents/*, QFile::Permissions permissions, QZip::Method m*/)
{
#ifndef NDEBUG
static const char *const entryTypes[] = {
"directory",
"file ",
"symlink " };
ZDEBUG() << "adding" << entryTypes[type] <<":" << fileName.toUtf8().data() << (type == 2 ? QByteArray(" -> " + contents).constData() : "");
#endif
if (! (device->isOpen() || device->open(QIODevice::WriteOnly))) {
status = MQZipWriter::FileOpenError;
return;
}
device->seek(start_of_directory);
// don't compress small files
MQZipWriter::CompressionPolicy compression = compressionPolicy;
if (compressionPolicy == MQZipWriter::AutoCompress) {
if (contents.length() < 64)
compression = MQZipWriter::NeverCompress;
else
compression = MQZipWriter::AlwaysCompress;
}
FileHeader header;
memset(&header.h, 0, sizeof(CentralFileHeader));
writeUInt(header.h.signature, 0x02014b50);
writeUShort(header.h.version_needed, ZIP_VERSION);
writeUInt(header.h.uncompressed_size, contents.length());
writeMSDosDate(header.h.last_mod_file, QDateTime::currentDateTime());
QByteArray data = contents;
if (compression == MQZipWriter::AlwaysCompress) {
writeUShort(header.h.compression_method, CompressionMethodDeflated);
ulong len = contents.length();
// shamelessly copied form zlib
len += (len >> 12) + (len >> 14) + 11;
int res;
do {
data.resize(len);
res = deflate((uchar*)data.data(), &len, (const uchar*)contents.constData(), contents.length());
switch (res) {
case Z_OK:
data.resize(len);
break;
case Z_MEM_ERROR:
qWarning("QZip: Z_MEM_ERROR: Not enough memory to compress file, skipping");
data.resize(0);
break;
case Z_BUF_ERROR:
len *= 2;
break;
}
} while (res == Z_BUF_ERROR);
}
// TODO add a check if data.length() > contents.length(). Then try to store the original and revert the compression method to be uncompressed
writeUInt(header.h.compressed_size, data.length());
uint crc_32 = ::crc32(0, 0, 0);
crc_32 = ::crc32(crc_32, (const uchar *)contents.constData(), contents.length());
writeUInt(header.h.crc_32, crc_32);
// if bit 11 is set, the filename and comment fields must be encoded using UTF-8
ushort general_purpose_bits = Utf8Names; // always use utf-8
writeUShort(header.h.general_purpose_bits, general_purpose_bits);
const bool inUtf8 = (general_purpose_bits & Utf8Names) != 0;
header.file_name = inUtf8 ? fileName.toUtf8() : fileName.toLocal8Bit();
if (header.file_name.size() > 0xffff) {
qWarning("QZip: Filename is too long, chopping it to 65535 bytes");
header.file_name = header.file_name.left(0xffff); // ### don't break the utf-8 sequence, if any
}
if (header.file_comment.size() + header.file_name.size() > 0xffff) {
qWarning("QZip: File comment is too long, chopping it to 65535 bytes");
header.file_comment.truncate(0xffff - header.file_name.size()); // ### don't break the utf-8 sequence, if any
}
writeUShort(header.h.file_name_length, header.file_name.length());
//h.extra_field_length[2];
writeUShort(header.h.version_made, HostUnix << 8);
//uchar internal_file_attributes[2];
//uchar external_file_attributes[4];
quint32 mode = permissionsToMode(permissions);
switch (type) {
case Symlink:
mode |= UnixFileAttributes::SymLink;
break;
case Directory:
mode |= UnixFileAttributes::Dir;
break;
case File:
mode |= UnixFileAttributes::File;
break;
default:
Q_UNREACHABLE();
break;
}
writeUInt(header.h.external_file_attributes, mode << 16);
writeUInt(header.h.offset_local_header, start_of_directory);
fileHeaders.append(header);
LocalFileHeader h = header.h.toLocalHeader();
device->write((const char *)&h, sizeof(LocalFileHeader));
device->write(header.file_name);
device->write(data);
start_of_directory = device->pos();
dirtyFileTree = true;
}
////////////////////////////// Reader
/*!
\class QZipReader::FileInfo
\internal
Represents one entry in the zip table of contents.
*/
/*!
\variable FileInfo::filePath
The full filepath inside the archive.
*/
/*!
\variable FileInfo::isDir
A boolean type indicating if the entry is a directory.
*/
/*!
\variable FileInfo::isFile
A boolean type, if it is one this entry is a file.
*/
/*!
\variable FileInfo::isSymLink
A boolean type, if it is one this entry is symbolic link.
*/
/*!
\variable FileInfo::permissions
A list of flags for the permissions of this entry.
*/
/*!
\variable FileInfo::crc
The calculated checksum as a crc type.
*/
/*!
\variable FileInfo::size
The total size of the unpacked content.
*/
/*!
\class QZipReader
\internal
\since 4.5
\brief the QZipReader class provides a way to inspect the contents of a zip
archive and extract individual files from it.
QZipReader can be used to read a zip archive either from a file or from any
device. An in-memory QBuffer for instance. The reader can be used to read
which files are in the archive using fileInfoList() and entryInfoAt() but
also to extract individual files using fileData() or even to extract all
files in the archive using extractAll()
*/
/*!
Create a new zip archive that operates on the \a fileName. The file will be
opened with the \a mode.
*/
MQZipReader::MQZipReader(const QString &archive, QIODevice::OpenMode mode)
{
QScopedPointer<QFile> f(new QFile(archive));
const bool result = f->open(mode);
MQZipReader::Status status;
const QFileDevice::FileError error = f->error();
if (result && error == QFile::NoError) {
status = NoError;
} else {
if (error == QFile::ReadError)
status = FileReadError;
else if (error == QFile::OpenError)
status = FileOpenError;
else if (error == QFile::PermissionsError)
status = FilePermissionsError;
else
status = FileError;
}
d = new MQZipReaderPrivate(f.data(), /*ownDevice=*/true);
f.take();
d->status = status;
}
/*!
Create a new zip archive that operates on the archive found in \a device.
You have to open the device previous to calling the constructor and only a
device that is readable will be scanned for zip filecontent.
*/
MQZipReader::MQZipReader(QIODevice *device)
: d(new MQZipReaderPrivate(device, /*ownDevice=*/false))
{
Q_ASSERT(device);
}
/*!
Desctructor
*/
MQZipReader::~MQZipReader()
{
close();
delete d;
}
/*!
Returns device used for reading zip archive.
*/
QIODevice* MQZipReader::device() const
{
return d->device;
}
/*!
Returns \c true if the user can read the file; otherwise returns \c false.
*/
bool MQZipReader::isReadable() const
{
return d->device->isReadable();
}
/*!
Returns \c true if the file exists; otherwise returns \c false.
*/
bool MQZipReader::exists() const
{
QFile *f = qobject_cast<QFile*> (d->device);
if (f == 0)
return true;
return f->exists();
}
/*!
Returns the list of files the archive contains.
*/
QVector<MQZipReader::FileInfo> MQZipReader::fileInfoList() const
{
d->scanFiles();
QVector<FileInfo> files;
const int numFileHeaders = d->fileHeaders.size();
files.reserve(numFileHeaders);
for (int i = 0; i < numFileHeaders; ++i)
files.append(d->fillFileInfo(i));
return files;
}
/*!
Return the number of items in the zip archive.
*/
int MQZipReader::count() const
{
d->scanFiles();
return d->fileHeaders.count();
}
/*!
Returns a FileInfo of an entry in the zipfile.
The \a index is the index into the directory listing of the zipfile.
Returns an invalid FileInfo if \a index is out of boundaries.
\sa fileInfoList()
*/
MQZipReader::FileInfo MQZipReader::entryInfoAt(int index) const
{
d->scanFiles();
if (index >= 0 && index < d->fileHeaders.count())
return d->fillFileInfo(index);
return MQZipReader::FileInfo();
}
/*!
Fetch the file contents from the zip archive and return the uncompressed bytes.
*/
QByteArray MQZipReader::fileData(const QString &fileName) const
{
d->scanFiles();
int i;
for (i = 0; i < d->fileHeaders.size(); ++i) {
if (QString::fromUtf8(d->fileHeaders.at(i).file_name) == fileName)
break;
}
if (i == d->fileHeaders.size())
return QByteArray();
FileHeader header = d->fileHeaders.at(i);
ushort version_needed = readUShort(header.h.version_needed);
if (version_needed > ZIP_VERSION) {
qWarning("QZip: .ZIP specification version %d implementationis needed to extract the data.", version_needed);
return QByteArray();
}
ushort general_purpose_bits = readUShort(header.h.general_purpose_bits);
int compressed_size = readUInt(header.h.compressed_size);
int uncompressed_size = readUInt(header.h.uncompressed_size);
int start = readUInt(header.h.offset_local_header);
//qDebug("uncompressing file %d: local header at %d", i, start);
d->device->seek(start);
LocalFileHeader lh;
d->device->read((char *)&lh, sizeof(LocalFileHeader));
uint skip = readUShort(lh.file_name_length) + readUShort(lh.extra_field_length);
d->device->seek(d->device->pos() + skip);
int compression_method = readUShort(lh.compression_method);
//qDebug("file=%s: compressed_size=%d, uncompressed_size=%d", fileName.toLocal8Bit().data(), compressed_size, uncompressed_size);
if ((general_purpose_bits & Encrypted) != 0) {
qWarning("QZip: Unsupported encryption method is needed to extract the data.");
return QByteArray();
}
//qDebug("file at %lld", d->device->pos());
QByteArray compressed = d->device->read(compressed_size);
if (compression_method == CompressionMethodStored) {
// no compression
compressed.truncate(uncompressed_size);
return compressed;
} else if (compression_method == CompressionMethodDeflated) {
// Deflate
//qDebug("compressed=%d", compressed.size());
compressed.truncate(compressed_size);
QByteArray baunzip;
ulong len = qMax(uncompressed_size, 1);
int res;
do {
baunzip.resize(len);
res = inflate((uchar*)baunzip.data(), &len,
(const uchar*)compressed.constData(), compressed_size);
switch (res) {
case Z_OK:
if ((int)len != baunzip.size())
baunzip.resize(len);
break;
case Z_MEM_ERROR:
qWarning("QZip: Z_MEM_ERROR: Not enough memory");
break;
case Z_BUF_ERROR:
len *= 2;
break;
case Z_DATA_ERROR:
qWarning("QZip: Z_DATA_ERROR: Input data is corrupted");
break;
}
} while (res == Z_BUF_ERROR);
return baunzip;
}
qWarning("QZip: Unsupported compression method %d is needed to extract the data.", compression_method);
return QByteArray();
}
/*!
Extracts the full contents of the zip file into \a destinationDir on
the local filesystem.
In case writing or linking a file fails, the extraction will be aborted.
*/
bool MQZipReader::extractAll(const QString &destinationDir) const
{
QDir baseDir(destinationDir);
// create directories first
const QVector<FileInfo> allFiles = fileInfoList();
for (const FileInfo &fi : allFiles) {
const QString absPath = destinationDir + QDir::separator() + fi.filePath;
if (fi.isDir) {
if (!baseDir.mkpath(fi.filePath))
return false;
if (!QFile::setPermissions(absPath, fi.permissions))
return false;
}
}
// set up symlinks
for (const FileInfo &fi : allFiles) {
const QString absPath = destinationDir + QDir::separator() + fi.filePath;
if (fi.isSymLink) {
QString destination = QFile::decodeName(fileData(fi.filePath));
if (destination.isEmpty())
return false;
QFileInfo linkFi(absPath);
if (!QFile::exists(linkFi.absolutePath()))
QDir::root().mkpath(linkFi.absolutePath());
if (!QFile::link(destination, absPath))
return false;
/* cannot change permission of links
if (!QFile::setPermissions(absPath, fi.permissions))
return false;
*/
}
}
for (const FileInfo &fi : allFiles) {
const QString absPath = destinationDir + QDir::separator() + fi.filePath;
if (fi.isFile) {
QFile f(absPath);
if (!f.open(QIODevice::WriteOnly))
return false;
f.write(fileData(fi.filePath));
f.setPermissions(fi.permissions);
f.close();
}
}
return true;
}
/*!
\enum QZipReader::Status
The following status values are possible:
\value NoError No error occurred.
\value FileReadError An error occurred when reading from the file.
\value FileOpenError The file could not be opened.
\value FilePermissionsError The file could not be accessed.
\value FileError Another file error occurred.
*/
/*!
Returns a status code indicating the first error that was met by QZipReader,
or QZipReader::NoError if no error occurred.
*/
MQZipReader::Status MQZipReader::status() const
{
return d->status;
}
/*!
Close the zip file.
*/
void MQZipReader::close()
{
d->device->close();
}
////////////////////////////// Writer
/*!
\class QZipWriter
\internal
\since 4.5
\brief the QZipWriter class provides a way to create a new zip archive.
QZipWriter can be used to create a zip archive containing any number of files
and directories. The files in the archive will be compressed in a way that is
compatible with common zip reader applications.
*/
/*!
Create a new zip archive that operates on the \a archive filename. The file will
be opened with the \a mode.
\sa isValid()
*/
MQZipWriter::MQZipWriter(const QString &fileName, QIODevice::OpenMode mode)
{
QScopedPointer<QFile> f(new QFile(fileName));
MQZipWriter::Status status;
if (f->open(mode) && f->error() == QFile::NoError)
status = MQZipWriter::NoError;
else {
if (f->error() == QFile::WriteError)
status = MQZipWriter::FileWriteError;
else if (f->error() == QFile::OpenError)
status = MQZipWriter::FileOpenError;
else if (f->error() == QFile::PermissionsError)
status = MQZipWriter::FilePermissionsError;
else
status = MQZipWriter::FileError;
}
d = new MQZipWriterPrivate(f.data(), /*ownDevice=*/true);
f.take();
d->status = status;
}
/*!
Create a new zip archive that operates on the archive found in \a device.
You have to open the device previous to calling the constructor and
only a device that is readable will be scanned for zip filecontent.
*/
MQZipWriter::MQZipWriter(QIODevice *device)
: d(new MQZipWriterPrivate(device, /*ownDevice=*/false))
{
Q_ASSERT(device);
}
MQZipWriter::~MQZipWriter()
{
close();
delete d;
}
/*!
Returns device used for writing zip archive.
*/
QIODevice* MQZipWriter::device() const
{
return d->device;
}
/*!
Returns \c true if the user can write to the archive; otherwise returns \c false.
*/
bool MQZipWriter::isWritable() const
{
return d->device->isWritable();
}
/*!
Returns \c true if the file exists; otherwise returns \c false.
*/
bool MQZipWriter::exists() const
{
QFile *f = qobject_cast<QFile*> (d->device);
if (f == 0)
return true;
return f->exists();
}
/*!
\enum QZipWriter::Status
The following status values are possible:
\value NoError No error occurred.
\value FileWriteError An error occurred when writing to the device.
\value FileOpenError The file could not be opened.
\value FilePermissionsError The file could not be accessed.
\value FileError Another file error occurred.
*/
/*!
Returns a status code indicating the first error that was met by QZipWriter,
or QZipWriter::NoError if no error occurred.
*/
MQZipWriter::Status MQZipWriter::status() const
{
return d->status;
}
/*!
\enum QZipWriter::CompressionPolicy
\value AlwaysCompress A file that is added is compressed.
\value NeverCompress A file that is added will be stored without changes.
\value AutoCompress A file that is added will be compressed only if that will give a smaller file.
*/
/*!
Sets the policy for compressing newly added files to the new \a policy.
\note the default policy is AlwaysCompress
\sa compressionPolicy()
\sa addFile()
*/
void MQZipWriter::setCompressionPolicy(CompressionPolicy policy)
{
d->compressionPolicy = policy;
}
/*!
Returns the currently set compression policy.
\sa setCompressionPolicy()
\sa addFile()
*/
MQZipWriter::CompressionPolicy MQZipWriter::compressionPolicy() const
{
return d->compressionPolicy;
}
/*!
Sets the permissions that will be used for newly added files.
\note the default permissions are QFile::ReadOwner | QFile::WriteOwner.
\sa creationPermissions()
\sa addFile()
*/
void MQZipWriter::setCreationPermissions(QFile::Permissions permissions)
{
d->permissions = permissions;
}
/*!
Returns the currently set creation permissions.
\sa setCreationPermissions()
\sa addFile()
*/
QFile::Permissions MQZipWriter::creationPermissions() const
{
return d->permissions;
}
/*!
Add a file to the archive with \a data as the file contents.
The file will be stored in the archive using the \a fileName which
includes the full path in the archive.
The new file will get the file permissions based on the current
creationPermissions and it will be compressed using the zip compression
based on the current compression policy.
\sa setCreationPermissions()
\sa setCompressionPolicy()
*/
void MQZipWriter::addFile(const QString &fileName, const QByteArray &data)
{
d->addEntry(MQZipWriterPrivate::File, QDir::fromNativeSeparators(fileName), data);
}
/*!
Add a file to the archive with \a device as the source of the contents.
The contents returned from QIODevice::readAll() will be used as the
filedata.
The file will be stored in the archive using the \a fileName which
includes the full path in the archive.
*/
void MQZipWriter::addFile(const QString &fileName, QIODevice *device)
{
Q_ASSERT(device);
QIODevice::OpenMode mode = device->openMode();
bool opened = false;
if ((mode & QIODevice::ReadOnly) == 0) {
opened = true;
if (! device->open(QIODevice::ReadOnly)) {
d->status = FileOpenError;
return;
}
}
d->addEntry(MQZipWriterPrivate::File, QDir::fromNativeSeparators(fileName), device->readAll());
if (opened)
device->close();
}
/*!
Create a new directory in the archive with the specified \a dirName and
the \a permissions;
*/
void MQZipWriter::addDirectory(const QString &dirName)
{
QString name(QDir::fromNativeSeparators(dirName));
// separator is mandatory
if (!name.endsWith(QLatin1Char('/')))
name.append(QLatin1Char('/'));
d->addEntry(MQZipWriterPrivate::Directory, name, QByteArray());
}
/*!
Create a new symbolic link in the archive with the specified \a dirName
and the \a permissions;
A symbolic link contains the destination (relative) path and name.
*/
void MQZipWriter::addSymLink(const QString &fileName, const QString &destination)
{
d->addEntry(MQZipWriterPrivate::Symlink, QDir::fromNativeSeparators(fileName), QFile::encodeName(destination));
}
/*!
Closes the zip file.
*/
void MQZipWriter::close()
{
if (!(d->device->openMode() & QIODevice::WriteOnly)) {
d->device->close();
return;
}
//qDebug("QZip::close writing directory, %d entries", d->fileHeaders.size());
d->device->seek(d->start_of_directory);
// write new directory
for (int i = 0; i < d->fileHeaders.size(); ++i) {
const FileHeader &header = d->fileHeaders.at(i);
d->device->write((const char *)&header.h, sizeof(CentralFileHeader));
d->device->write(header.file_name);
d->device->write(header.extra_field);
d->device->write(header.file_comment);
}
int dir_size = d->device->pos() - d->start_of_directory;
// write end of directory
EndOfDirectory eod;
memset(&eod, 0, sizeof(EndOfDirectory));
writeUInt(eod.signature, 0x06054b50);
//uchar this_disk[2];
//uchar start_of_directory_disk[2];
writeUShort(eod.num_dir_entries_this_disk, d->fileHeaders.size());
writeUShort(eod.num_dir_entries, d->fileHeaders.size());
writeUInt(eod.directory_size, dir_size);
writeUInt(eod.dir_start_offset, d->start_of_directory);
writeUShort(eod.comment_length, d->comment.length());
d->device->write((const char *)&eod, sizeof(EndOfDirectory));
d->device->write(d->comment);
d->device->close();
}
QT_END_NAMESPACE
#endif // QT_NO_TEXTODFWRITER
|