kzip.cpp   kzip.cpp 
skipping to change at line 22 skipping to change at line 22
Library General Public License for more details. Library General Public License for more details.
You should have received a copy of the GNU Library General Public Licens e You should have received a copy of the GNU Library General Public Licens e
along with this library; see the file COPYING.LIB. If not, write to along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. Boston, MA 02110-1301, USA.
*/ */
/* /*
This class implements a kioslave to access ZIP files from KDE. This class implements a kioslave to access ZIP files from KDE.
you can use it in QIODevice::ReadOnly or in QIODevice::WriteOnly mode, you can use it in QIODevice::ReadOnly or in QIODevice::WriteOnly mod
and it e, and it
behaves just as expected (i hope ;-) ). behaves just as expected (i hope ;-) ).
It can also be used in QIODevice::ReadWrite mode, in this case one can It can also be used in QIODevice::ReadWrite mode, in this case one c
append files to an existing zip archive. when you append new files, whi an
ch append files to an existing zip archive. when you append new files,
are not yet in the zip, it works as expected, they are appended at the which
end. are not yet in the zip, it works as expected, they are appended at t
when you append a file, which is already in the file, the reference to he end.
the when you append a file, which is already in the file, the reference
old file is dropped and the new one is added to the zip. but the to the
old data from the file itself is not deleted, it is still in the old file is dropped and the new one is added to the zip. but the
zipfile. so when you want to have a small and garbagefree zipfile, old data from the file itself is not deleted, it is still in the
just read the contents of the appended zipfile and write it to a new on zipfile. so when you want to have a small and garbagefree zipfile,
e just read the contents of the appended zipfile and write it to a new
in QIODevice::WriteOnly mode. especially take care of this, when you do one
n't want in QIODevice::WriteOnly mode. especially take care of this, when you
to leak information of how intermediate versions of files in the zip don't want
were looking. to leak information of how intermediate versions of files in the zip
For more information on the zip fileformat go to were looking.
http://www.pkware.com/support/appnote.html . For more information on the zip fileformat go to
http://www.pkware.com/support/appnote.html .
*/ */
#include "kzip.h" #include "kzip.h"
#include "kfilterdev.h" #include "kfilterdev.h"
#include "klimitediodevice.h" #include "klimitediodevice.h"
#include <QtCore/QHash> #include <QtCore/QHash>
#include <QtCore/QByteArray> #include <QtCore/QByteArray>
#include <QtCore/QFile> #include <QtCore/QFile>
#include <QtCore/QDir> #include <QtCore/QDir>
#include <QtCore/QDate> #include <QtCore/QDate>
#include <QtCore/QList> #include <QtCore/QList>
#include <QDebug> #include <QDebug>
#include <zlib.h> #include <zlib.h>
#include <time.h> #include <time.h>
#include <string.h> #include <string.h>
#include <sys/stat.h> #include <sys/stat.h>
#ifdef WIN32 #ifdef Q_OS_WIN
#include "kdewin32/sys/stat.h" #include "kdewin32/sys/stat.h"
#endif #endif
const int max_path_len = 4095; // maximum number of character a path may co ntain const int max_path_len = 4095; // maximum number of character a path may co ntain
static void transformToMsDos(const QDateTime& dt, char* buffer) static void transformToMsDos(const QDateTime& dt, char* buffer)
{ {
if ( dt.isValid() ) if ( dt.isValid() )
{ {
const quint16 time = const quint16 time =
( dt.time().hour() << 11 ) // 5 bit hour ( dt.time().hour() << 11 ) // 5 bit hour
| ( dt.time().minute() << 5 ) // 6 bit minute | ( dt.time().minute() << 5 ) // 6 bit minute
| ( dt.time().second() >> 1 ); // 5 bit double seconds | ( dt.time().second() >> 1 ); // 5 bit double seconds
buffer[0] = char(time); buffer[0] = char(time);
buffer[1] = char(time >> 8); buffer[1] = char(time >> 8);
const quint16 date = const quint16 date =
( ( dt.date().year() - 1980 ) << 9 ) // 7 bit year 1980-based ( ( dt.date().year() - 1980 ) << 9 ) // 7 bit year
| ( dt.date().month() << 5 ) // 4 bit month 1980-based
| ( dt.date().day() ); // 5 bit day | ( dt.date().month() << 5 ) // 4 bit month
| ( dt.date().day() ); // 5 bit day
buffer[2] = char(date);
buffer[3] = char(date >> 8); buffer[2] = char(date);
} buffer[3] = char(date >> 8);
else // !dt.isValid(), assume 1980-01-01 midnight }
{ else // !dt.isValid(), assume 1980-01-01 midnight
buffer[0] = 0; {
buffer[1] = 0; buffer[0] = 0;
buffer[2] = 33; buffer[1] = 0;
buffer[3] = 0; buffer[2] = 33;
} buffer[3] = 0;
}
} }
static time_t transformFromMsDos(const char* buffer) static time_t transformFromMsDos(const char* buffer)
{ {
quint16 time = (uchar)buffer[0] | ( (uchar)buffer[1] << 8 ); quint16 time = (uchar)buffer[0] | ( (uchar)buffer[1] << 8 );
int h = time >> 11; int h = time >> 11;
int m = ( time & 0x7ff ) >> 5; int m = ( time & 0x7ff ) >> 5;
int s = ( time & 0x1f ) * 2 ; int s = ( time & 0x1f ) * 2 ;
QTime qt(h, m, s); QTime qt(h, m, s);
quint16 date = (uchar)buffer[2] | ( (uchar)buffer[3] << 8 ); quint16 date = (uchar)buffer[2] | ( (uchar)buffer[3] << 8 );
int y = ( date >> 9 ) + 1980; int y = ( date >> 9 ) + 1980;
int o = ( date & 0x1ff ) >> 5; int o = ( date & 0x1ff ) >> 5;
int d = ( date & 0x1f ); int d = ( date & 0x1f );
QDate qd(y, o, d); QDate qd(y, o, d);
QDateTime dt( qd, qt ); QDateTime dt( qd, qt );
return dt.toTime_t(); return dt.toTime_t();
} }
// == parsing routines for zip headers // == parsing routines for zip headers
/** all relevant information about parsing file information */ /** all relevant information about parsing file information */
struct ParseFileInfo { struct ParseFileInfo {
// file related info // file related info
mode_t perm; // permissions of this file mode_t perm; // permissions of this file
time_t atime; // last access time (UNIX format) time_t atime; // last access time (UNIX format)
time_t mtime; // modification time (UNIX format) time_t mtime; // modification time (UNIX format)
time_t ctime; // creation time (UNIX format) time_t ctime; // creation time (UNIX format)
int uid; // user id (-1 if not specified) int uid; // user id (-1 if not specified)
int gid; // group id (-1 if not specified) int gid; // group id (-1 if not specified)
QByteArray guessed_symlink; // guessed symlink target QByteArray guessed_symlink; // guessed symlink target
int extralen; // length of extra field int extralen; // length of extra field
// parsing related info // parsing related info
bool exttimestamp_seen; // true if extended timestamp extra field bool exttimestamp_seen; // true if extended timestamp extra field
// has been parsed // has been parsed
bool newinfounix_seen; // true if Info-ZIP Unix New extra field has bool newinfounix_seen; // true if Info-ZIP Unix New extra field has
// been parsed // been parsed
ParseFileInfo() : perm(0100644), uid(-1), gid(-1), extralen(0), ParseFileInfo() : perm(0100644), uid(-1), gid(-1), extralen(0),
exttimestamp_seen(false), newinfounix_seen(false) { exttimestamp_seen(false), newinfounix_seen(false) {
ctime = mtime = atime = time(0); ctime = mtime = atime = time(0);
} }
}; };
/** updates the parse information with the given extended timestamp extra f ield. /** updates the parse information with the given extended timestamp extra f ield.
* @param buffer start content of buffer known to contain an extended * @param buffer start content of buffer known to contain an extended
* timestamp extra field (without magic & size) * timestamp extra field (without magic & size)
* @param size size of field content (must not count magic and size entrie s) * @param size size of field content (must not count magic and size entrie s)
* @param islocal true if this is a local field, false if central * @param islocal true if this is a local field, false if central
* @param pfi ParseFileInfo object to be updated * @param pfi ParseFileInfo object to be updated
* @return true if processing was successful * @return true if processing was successful
*/ */
static bool parseExtTimestamp(const char *buffer, int size, bool islocal, static bool parseExtTimestamp(const char *buffer, int size, bool islocal,
ParseFileInfo &pfi) { ParseFileInfo &pfi) {
if (size < 1) { if (size < 1) {
qDebug() << "premature end of extended timestamp (#1)"; qDebug() << "premature end of extended timestamp (#1)";
return false; return false;
}/*end if*/ }/*end if*/
int flags = *buffer; // read flags int flags = *buffer; // read flags
buffer += 1; buffer += 1;
size -= 1; size -= 1;
if (flags & 1) { // contains modification time if (flags & 1) { // contains modification time
if (size < 4) { if (size < 4) {
qDebug() << "premature end of extended timestamp (#2)"; qDebug() << "premature end of extended timestamp (#2)";
return false; return false;
}/*end if*/ }/*end if*/
pfi.mtime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8 pfi.mtime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
| (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24); | (uchar)buffer[2] << 16 | (uchar)buffer[3]
buffer += 4; << 24);
size -= 4; buffer += 4;
size -= 4;
}/*end if*/ }/*end if*/
// central extended field cannot contain more than the modification time // central extended field cannot contain more than the modification time
// even if other flags are set // even if other flags are set
if (!islocal) { if (!islocal) {
pfi.exttimestamp_seen = true; pfi.exttimestamp_seen = true;
return true; return true;
}/*end if*/ }/*end if*/
if (flags & 2) { // contains last access time if (flags & 2) { // contains last access time
if (size < 4) { if (size < 4) {
qDebug() << "premature end of extended timestamp (#3)"; qDebug() << "premature end of extended timestamp (#3)";
return true; return true;
}/*end if*/ }/*end if*/
pfi.atime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8 pfi.atime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
| (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24); | (uchar)buffer[2] << 16 | (uchar)buffer[3]
buffer += 4; << 24);
size -= 4; buffer += 4;
size -= 4;
}/*end if*/ }/*end if*/
if (flags & 4) { // contains creation time if (flags & 4) { // contains creation time
if (size < 4) { if (size < 4) {
qDebug() << "premature end of extended timestamp (#4)"; qDebug() << "premature end of extended timestamp (#4)";
return true; return true;
}/*end if*/ }/*end if*/
pfi.ctime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8 pfi.ctime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
| (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24); | (uchar)buffer[2] << 16 | (uchar)buffer[3]
buffer += 4; << 24);
buffer += 4;
}/*end if*/ }/*end if*/
pfi.exttimestamp_seen = true; pfi.exttimestamp_seen = true;
return true; return true;
} }
/** updates the parse information with the given Info-ZIP Unix old extra fi eld. /** updates the parse information with the given Info-ZIP Unix old extra fi eld.
* @param buffer start of content of buffer known to contain an Info-ZIP * @param buffer start of content of buffer known to contain an Info-ZIP
* Unix old extra field (without magic & size) * Unix old extra field (without magic & size)
* @param size size of field content (must not count magic and size entrie s) * @param size size of field content (must not count magic and size entrie s)
* @param islocal true if this is a local field, false if central * @param islocal true if this is a local field, false if central
* @param pfi ParseFileInfo object to be updated * @param pfi ParseFileInfo object to be updated
* @return true if processing was successful * @return true if processing was successful
*/ */
static bool parseInfoZipUnixOld(const char *buffer, int size, bool islocal, static bool parseInfoZipUnixOld(const char *buffer, int size, bool islocal,
ParseFileInfo &pfi) { ParseFileInfo &pfi) {
// spec mandates to omit this field if one of the newer fields are availa ble // spec mandates to omit this field if one of the newer fields are availa ble
if (pfi.exttimestamp_seen || pfi.newinfounix_seen) return true; if (pfi.exttimestamp_seen || pfi.newinfounix_seen) return true;
if (size < 8) { if (size < 8) {
qDebug() << "premature end of Info-ZIP unix extra field old"; qDebug() << "premature end of Info-ZIP unix extra field old";
return false; return false;
}/*end if*/ }/*end if*/
pfi.atime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8 pfi.atime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
| (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24); | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
buffer += 4; buffer += 4;
pfi.mtime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8 pfi.mtime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
| (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24); | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
buffer += 4; buffer += 4;
if (islocal && size >= 12) { if (islocal && size >= 12) {
pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8; pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
buffer += 2; buffer += 2;
pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8; pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
buffer += 2; buffer += 2;
}/*end if*/ }/*end if*/
return true; return true;
} }
#if 0 // not needed yet #if 0 // not needed yet
/** updates the parse information with the given Info-ZIP Unix new extra fi eld. /** updates the parse information with the given Info-ZIP Unix new extra fi eld.
* @param buffer start of content of buffer known to contain an Info-ZIP * @param buffer start of content of buffer known to contain an Info-ZIP
* Unix new extra field (without magic & size) * Unix new extra field (without magic & size)
* @param size size of field content (must not count magic and size entrie s) * @param size size of field content (must not count magic and size entrie s)
* @param islocal true if this is a local field, false if central * @param islocal true if this is a local field, false if central
* @param pfi ParseFileInfo object to be updated * @param pfi ParseFileInfo object to be updated
* @return true if processing was successful * @return true if processing was successful
*/ */
static bool parseInfoZipUnixNew(const char *buffer, int size, bool islocal, static bool parseInfoZipUnixNew(const char *buffer, int size, bool islocal,
ParseFileInfo &pfi) { ParseFileInfo &pfi) {
if (!islocal) { // contains nothing in central field if (!islocal) { // contains nothing in central field
pfi.newinfounix = true; pfi.newinfounix = true;
return true; return true;
}/*end if*/ }/*end if*/
if (size < 4) { if (size < 4) {
qDebug() << "premature end of Info-ZIP unix extra field new"; qDebug() << "premature end of Info-ZIP unix extra field new";
return false; return false;
}/*end if*/ }/*end if*/
pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8; pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
buffer += 2; buffer += 2;
pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8; pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
buffer += 2; buffer += 2;
pfi.newinfounix = true; pfi.newinfounix = true;
return true; return true;
} }
skipping to change at line 275 skipping to change at line 275
* @param pfi ParseFileInfo object which to write the results into * @param pfi ParseFileInfo object which to write the results into
* @return true if parsing was successful * @return true if parsing was successful
*/ */
static bool parseExtraField(const char *buffer, int size, bool islocal, static bool parseExtraField(const char *buffer, int size, bool islocal,
ParseFileInfo &pfi) { ParseFileInfo &pfi) {
// extra field in central directory doesn't contain useful data, so we // extra field in central directory doesn't contain useful data, so we
// don't bother parsing it // don't bother parsing it
if (!islocal) return true; if (!islocal) return true;
while (size >= 4) { // as long as a potential extra field can be read while (size >= 4) { // as long as a potential extra field can be read
int magic = (uchar)buffer[0] | (uchar)buffer[1] << 8; int magic = (uchar)buffer[0] | (uchar)buffer[1] << 8;
buffer += 2; buffer += 2;
int fieldsize = (uchar)buffer[0] | (uchar)buffer[1] << 8; int fieldsize = (uchar)buffer[0] | (uchar)buffer[1] << 8;
buffer += 2; buffer += 2;
size -= 4; size -= 4;
if (fieldsize > size) { if (fieldsize > size) {
//qDebug() << "fieldsize: " << fieldsize << " size: " << size; //qDebug() << "fieldsize: " << fieldsize << " size: " << size;
qDebug() << "premature end of extra fields reached"; qDebug() << "premature end of extra fields reached";
break; break;
}/*end if*/ }/*end if*/
switch (magic) { switch (magic) {
case 0x5455: // extended timestamp case 0x5455: // extended timestamp
if (!parseExtTimestamp(buffer, fieldsize, islocal, pfi)) return fal if (!parseExtTimestamp(buffer, fieldsize, islocal, pfi)) ret
se; urn false;
break; break;
case 0x5855: // old Info-ZIP unix extra field case 0x5855: // old Info-ZIP unix extra field
if (!parseInfoZipUnixOld(buffer, fieldsize, islocal, pfi)) return f if (!parseInfoZipUnixOld(buffer, fieldsize, islocal, pfi)) r
alse; eturn false;
break; break;
#if 0 // not needed yet #if 0 // not needed yet
case 0x7855: // new Info-ZIP unix extra field case 0x7855: // new Info-ZIP unix extra field
if (!parseInfoZipUnixNew(buffer, fieldsize, islocal, pfi)) return f if (!parseInfoZipUnixNew(buffer, fieldsize, islocal, pfi)) r
alse; eturn false;
break; break;
#endif #endif
default: default:
/* ignore everything else */; /* ignore everything else */;
}/*end switch*/ }/*end switch*/
buffer += fieldsize; buffer += fieldsize;
size -= fieldsize; size -= fieldsize;
}/*wend*/ }/*wend*/
return true; return true;
} }
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
/////////////////////////// KZip /////////////////////////////////////// /////////////////////////// KZip ///////////////////////////////////////
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
class KZip::KZipPrivate class KZip::KZipPrivate
{ {
public: public:
KZipPrivate() KZipPrivate()
: m_crc( 0 ), : m_crc( 0 ),
m_currentFile( 0 ), m_currentFile( 0 ),
m_currentDev( 0 ), m_currentDev( 0 ),
m_compression( 8 ), m_compression( 8 ),
m_extraField( KZip::NoExtraField ), m_extraField( KZip::NoExtraField ),
m_offset( 0 ) m_offset( 0 )
{} {}
unsigned long m_crc; // checksum unsigned long m_crc; // checksum
KZipFileEntry* m_currentFile; // file currently being written KZipFileEntry* m_currentFile; // file currently being writt
QIODevice* m_currentDev; // filterdev used to write to th en
e above file QIODevice* m_currentDev; // filterdev used to write to
QList<KZipFileEntry*> m_fileList; // flat list of all files, for the the above file
index (saves a recursive method ;) QList<KZipFileEntry*> m_fileList; // flat list of all files, for
int m_compression; the index (saves a recursive method ;)
KZip::ExtraField m_extraField; int m_compression;
// m_offset holds the offset of the place in the zip, KZip::ExtraField m_extraField;
// where new data can be appended. after openarchive it points to 0, wh // m_offset holds the offset of the place in the zip,
en in // where new data can be appended. after openarchive it points to 0,
// writeonly mode, or it points to the beginning of the central directo when in
ry. // writeonly mode, or it points to the beginning of the central dire
// each call to writefile updates this value. ctory.
unsigned int m_offset; // each call to writefile updates this value.
unsigned int m_offset;
}; };
KZip::KZip( const QString& fileName ) KZip::KZip( const QString& fileName )
: KArchive( fileName ),d(new KZipPrivate) : KArchive( fileName ),d(new KZipPrivate)
{ {
} }
KZip::KZip( QIODevice * dev ) KZip::KZip( QIODevice * dev )
: KArchive( dev ),d(new KZipPrivate) : KArchive( dev ),d(new KZipPrivate)
{ {
} }
KZip::~KZip() KZip::~KZip()
{ {
//qDebug() << this; //qDebug() << this;
if( isOpen() ) if( isOpen() )
close(); close();
delete d; delete d;
} }
bool KZip::openArchive( QIODevice::OpenMode mode ) bool KZip::openArchive( QIODevice::OpenMode mode )
{ {
//qDebug(); //qDebug();
d->m_fileList.clear(); d->m_fileList.clear();
if ( mode == QIODevice::WriteOnly ) if ( mode == QIODevice::WriteOnly )
return true; return true;
char buffer[47]; char buffer[47];
// Check that it's a valid ZIP file // Check that it's a valid ZIP file
// KArchive::open() opened the underlying device already. // KArchive::open() opened the underlying device already.
uint offset = 0; // holds offset, where we read uint offset = 0; // holds offset, where we read
int n; int n;
// contains information gathered from the local file headers // contains information gathered from the local file headers
QHash<QByteArray, ParseFileInfo> pfi_map; QHash<QByteArray, ParseFileInfo> pfi_map;
QIODevice* dev = device(); QIODevice* dev = device();
// We set a bool for knowing if we are allowed to skip the start of the // We set a bool for knowing if we are allowed to skip the start of
file the file
bool startOfFile = true; bool startOfFile = true;
for (;;) // repeat until 'end of entries' signature is reached for (;;) // repeat until 'end of entries' signature is reached
{ {
//qDebug() << "loop starts"; //qDebug() << "loop starts";
//qDebug() << "dev->pos() now : " << dev->pos(); //qDebug() << "dev->pos() now : " << dev->pos();
n = dev->read( buffer, 4 ); n = dev->read( buffer, 4 );
if (n < 4) if (n < 4)
{ {
qWarning() << "Invalid ZIP file. Unexpected end of file. (#1)"; qWarning() << "Invalid ZIP file. Unexpected end of f
ile. (#1)";
return false; return false;
} }
if ( !memcmp( buffer, "PK\5\6", 4 ) ) // 'end of entries' if ( !memcmp( buffer, "PK\5\6", 4 ) ) // 'end of entries'
{ {
//qDebug() << "PK56 found end of archive"; //qDebug() << "PK56 found end of archive";
startOfFile = false; startOfFile = false;
break; break;
} }
if ( !memcmp( buffer, "PK\3\4", 4 ) ) // local file header if ( !memcmp( buffer, "PK\3\4", 4 ) ) // local file header
{ {
//qDebug() << "PK34 found local file header"; //qDebug() << "PK34 found local file header";
startOfFile = false; startOfFile = false;
// can this fail ??? // can this fail ???
dev->seek( dev->pos() + 2 ); // skip 'version needed to extract' dev->seek( dev->pos() + 2 ); // skip 'version needed to extr
act'
// read static header stuff
n = dev->read( buffer, 24 ); // read static header stuff
if (n < 24) { n = dev->read( buffer, 24 );
qWarning() << "Invalid ZIP file. Unexpected end of file. (# if (n < 24) {
4)"; qWarning() << "Invalid ZIP file. Unexpected
return false; end of file. (#4)";
} return false;
}
int gpf = (uchar)buffer[0]; // "general purpose flag" not "gener
al protection fault" ;-) int gpf = (uchar)buffer[0]; // "general purpose flag" no
int compression_mode = (uchar)buffer[2] | (uchar)buffer[3] << 8; t "general protection fault" ;-)
time_t mtime = transformFromMsDos( buffer+4 ); int compression_mode = (uchar)buffer[2] | (uchar)buffer[3] <
< 8;
qint64 compr_size = (uchar)buffer[12] | (uchar)buffer[13] << 8 time_t mtime = transformFromMsDos( buffer+4 );
| (uchar)buffer[14] << 16 | (uchar)buffer[15
] << 24; qint64 compr_size = (uchar)buffer[12] | (uchar)buffer[13] <<
qint64 uncomp_size = (uchar)buffer[16] | (uchar)buffer[17] << 8 8
| (uchar)buffer[18] << 16 | (uchar)buffer[19 | (uchar)buffer[14] << 16 | (uchar)b
] << 24; uffer[15] << 24;
int namelen = (uchar)buffer[20] | (uchar)buffer[21] << 8; qint64 uncomp_size = (uchar)buffer[16] | (uchar)buffer[17] <
int extralen = (uchar)buffer[22] | (uchar)buffer[23] << 8; < 8
| (uchar)buffer[18] << 16 | (uchar)b
/* uffer[19] << 24;
qDebug() << "general purpose bit flag: " << gpf; int namelen = (uchar)buffer[20] | (uchar)buffer[21] << 8;
qDebug() << "compressed size: " << compr_size; int extralen = (uchar)buffer[22] | (uchar)buffer[23] << 8;
qDebug() << "uncompressed size: " << uncomp_size;
qDebug() << "namelen: " << namelen; /*
qDebug() << "extralen: " << extralen; qDebug() << "general purpose bit flag: " << gpf;
qDebug() << "archive size: " << dev->size(); qDebug() << "compressed size: " << compr_size;
*/ qDebug() << "uncompressed size: " << uncomp_size;
qDebug() << "namelen: " << namelen;
// read fileName qDebug() << "extralen: " << extralen;
Q_ASSERT( namelen > 0 ); qDebug() << "archive size: " << dev->size();
QByteArray fileName = dev->read(namelen); */
if ( fileName.size() < namelen ) {
qWarning() << "Invalid ZIP file. Name not completely read ( // read fileName
#2)"; Q_ASSERT( namelen > 0 );
QByteArray fileName = dev->read(namelen);
if ( fileName.size() < namelen ) {
qWarning() << "Invalid ZIP file. Name not co
mpletely read (#2)";
return false; return false;
} }
ParseFileInfo pfi;
pfi.mtime = mtime;
ParseFileInfo pfi; // read and parse the beginning of the extra field,
pfi.mtime = mtime; // skip rest of extra field in case it is too long
unsigned int extraFieldEnd = dev->pos() + extralen;
pfi.extralen = extralen;
int handledextralen = qMin(extralen, (int)sizeof buffer);
//if ( handledextralen )
// qDebug() << "handledextralen: " << handledextr
alen;
n = dev->read(buffer, handledextralen);
// no error msg necessary as we deliberately truncate the ex
tra field
if (!parseExtraField(buffer, handledextralen, true, pfi))
{
qWarning() << "Invalid ZIP File. Broken ExtraField."
;
return false;
}
// jump to end of extra field
dev->seek( extraFieldEnd );
// read and parse the beginning of the extra field, // we have to take care of the 'general purpose bit flag'.
// skip rest of extra field in case it is too long // if bit 3 is set, the header doesn't contain the l
unsigned int extraFieldEnd = dev->pos() + extralen; ength of
pfi.extralen = extralen; // the file and we look for the signature 'PK\7\8'.
int handledextralen = qMin(extralen, (int)sizeof buffer); if ( gpf & 8 )
{
//if ( handledextralen ) // here we have to read through the compressed data
// qDebug() << "handledextralen: " << handledextralen; to find
n = dev->read(buffer, handledextralen);
// no error msg necessary as we deliberately truncate the extra
field
if (!parseExtraField(buffer, handledextralen, true, pfi))
{
qWarning() << "Invalid ZIP File. Broken ExtraField.";
return false;
}
// jump to end of extra field
dev->seek( extraFieldEnd );
// we have to take care of the 'general purpose bit flag'.
// if bit 3 is set, the header doesn't contain the length of
// the file and we look for the signature 'PK\7\8'.
if ( gpf & 8 )
{
// here we have to read through the compressed data to find
// the next PKxx // the next PKxx
qDebug() << "trying to seek for next PK78"; qDebug() << "trying to seek for next PK78";
bool foundSignature = false; bool foundSignature = false;
while (!foundSignature) while (!foundSignature)
{ {
n = dev->read( buffer, 1 ); n = dev->read( buffer, 1 );
if (n < 1) if (n < 1)
{ {
qWarning() << "Invalid ZIP file. Unexpected end of qWarning() << "Invalid ZIP f
file. (#2)"; ile. Unexpected end of file. (#2)";
return false; return false;
} }
if ( buffer[0] != 'P' ) if ( buffer[0] != 'P' )
continue; continue;
n = dev->read( buffer, 3 ); n = dev->read( buffer, 3 );
if (n < 3) if (n < 3)
{ {
qWarning() << "Invalid ZIP file. Unexpected end of qWarning() << "Invalid ZIP f
file. (#3)"; ile. Unexpected end of file. (#3)";
return false; return false;
} }
// we have to detect three magic tokens here: // we have to detect three magic tok
// PK34 for the next local header in case there is no da ens here:
ta descriptor // PK34 for the next local header in case there is n
// PK12 for the central header in case there is no data o data descriptor
descriptor // PK12 for the central header in case there is no d
// PK78 for the data descriptor in case it is following ata descriptor
the compressed data // PK78 for the data descriptor in case it is follow
ing the compressed data
if ( buffer[0] == 'K' && buffer[1] == 7 && buffer[2] ==
8 ) if ( buffer[0] == 'K' && buffer[1] == 7 && buffer[2]
{ == 8 )
foundSignature = true; {
dev->seek( dev->pos() + 12 ); // skip the 'data_des foundSignature = true;
criptor' dev->seek( dev->pos() + 12 )
} ; // skip the 'data_descriptor'
else if ( ( buffer[0] == 'K' && buffer[1] == 1 && buffer }
[2] == 2 ) else if ( ( buffer[0] == 'K' && buffer[1] == 1 && bu
|| ( buffer[0] == 'K' && buffer[1] == 3 && buffer[2 ffer[2] == 2 )
] == 4 ) ) || ( buffer[0] == 'K' && buffer[1] == 3 &&
{ buffer[2] == 4 ) )
foundSignature = true; {
dev->seek( dev->pos() - 4 ); // go back 4 bytes, so foundSignature = true;
that the magic bytes can be found... dev->seek( dev->pos() - 4 );
} // go back 4 bytes, so that the magic bytes can be found...
else if ( buffer[0] == 'P' || buffer[1] == 'P' || buffe }
r[2] == 'P' ) else if ( buffer[0] == 'P' || buffer
{ [1] == 'P' || buffer[2] == 'P' )
// We have another P character so we must go back a {
little to check if it is a magic // We have another P charact
dev->seek( dev->pos() - 3 ); er so we must go back a little to check if it is a magic
} dev->seek( dev->pos() - 3 );
}
}
} }
else }
{ else
// here we skip the compressed data and jump to the next hea {
der // here we skip the compressed data and jump to the
//qDebug() << "general purpose bit flag indicates, that loca next header
l file header contains valid size"; //qDebug() << "general purpose bit flag indicates, t
hat local file header contains valid size";
// check if this could be a symbolic link // check if this could be a symbolic link
if (compression_mode == NoCompression if (compression_mode == NoCompression
&& uncomp_size <= max_path_len && uncomp_size <= max_path_len
&& uncomp_size > 0) { && uncomp_size > 0) {
// read content and store it // read content and store it
// If it's not a symlink, then we'll just discard the d // If it's not a symlink, then we'll
ata for now. just discard the data for now.
pfi.guessed_symlink = dev->read(uncomp_size); pfi.guessed_symlink = dev->read(uncomp_size);
if (pfi.guessed_symlink.size() < uncomp_size) { if (pfi.guessed_symlink.size() < uncomp_size) {
qWarning() << "Invalid ZIP file. Unexpected end of f ile. (#5)"; qWarning() << "Invalid ZIP file. Unexpected end of f ile. (#5)";
return false; return false;
} }
} else { } else {
if ( compr_size > dev->size() ) if ( compr_size > dev->size() )
{ {
// here we cannot trust the compressed size, so scan // here we cannot trust the compressed size,
through the compressed so scan through the compressed
// data to find the next header // data to find the next header
bool foundSignature = false; bool foundSignature = false;
while (!foundSignature) while (!foundSignature)
{ {
n = dev->read( buffer, 1 ); n = dev->read( buffer, 1 );
if (n < 1) if (n < 1)
{ {
qWarning() << "Invalid ZIP file. Une xpected end of file. (#2)"; qWarning() << "Invalid ZIP file. Une xpected end of file. (#2)";
return false; return false;
skipping to change at line 580 skipping to change at line 580
if ( ( buffer[0] == 'K' && buffer[1] == 1 && buffer[2] == 2 ) if ( ( buffer[0] == 'K' && buffer[1] == 1 && buffer[2] == 2 )
|| ( buffer[0] == 'K' && buffer[1] = = 3 && buffer[2] == 4 ) ) || ( buffer[0] == 'K' && buffer[1] = = 3 && buffer[2] == 4 ) )
{ {
foundSignature = true; foundSignature = true;
dev->seek( dev->pos() - 4 ); dev->seek( dev->pos() - 4 );
// go back 4 bytes, so that the magi c bytes can be found // go back 4 bytes, so that the magi c bytes can be found
// in the next cycle... // in the next cycle...
} }
} }
} }
else else
{ {
// qDebug() << "before interesting dev->pos(): " << dev ->pos(); // qDebug() << "before interesting dev->pos(): " << dev ->pos();
bool success = dev->seek( dev->pos() + compr_size ); // can this fail ??? bool success = dev->seek( dev->pos() + compr_size ); // can this fail ???
success = success; // annoying unused variable warni ng success = success; // annoying unused variable warni ng
Q_ASSERT( success ); // let's see... Q_ASSERT( success ); // let' s see...
/* qDebug() << "after interesting dev->pos(): " << dev- >pos(); /* qDebug() << "after interesting dev->pos(): " << dev- >pos();
if ( success ) if ( success )
qDebug() << "dev->at was successful... "; qDebug() << "dev->at was successful... ";
else else
qDebug() << "dev->at failed... ";*/ qDebug() << "dev->at failed... ";*/
} }
} }
// not needed any more // not needed any more
/* // here we calculate the length of the file in the zip /* // here we calculate the length of the file in the zip
// with headers and jump to the next header. // with headers and jump to the next header.
uint skip = compr_size + namelen + extralen; uint skip = compr_size + namelen + extralen;
offset += 30 + skip;*/ offset += 30 + skip;*/
} }
pfi_map.insert(fileName, pfi); pfi_map.insert(fileName, pfi);
} }
else if ( !memcmp( buffer, "PK\1\2", 4 ) ) // central block else if ( !memcmp( buffer, "PK\1\2", 4 ) ) // central block
{ {
//qDebug() << "PK12 found central block"; //qDebug() << "PK12 found central block";
startOfFile = false; startOfFile = false;
// so we reached the central header at the end of the zip file // so we reached the central header at the end of th
// here we get all interesting data out of the central header e zip file
// of a file // here we get all interesting data out of the centr
offset = dev->pos() - 4; al header
// of a file
//set offset for appending new files offset = dev->pos() - 4;
if ( d->m_offset == 0L ) d->m_offset = offset;
//set offset for appending new files
n = dev->read( buffer + 4, 42 ); if ( d->m_offset == 0L ) d->m_offset = offset;
if (n < 42) {
qWarning() << "Invalid ZIP file, central entry too short"; n = dev->read( buffer + 4, 42 );
// not long enough for valid entry if (n < 42) {
return false; qWarning() << "Invalid ZIP file, central ent
} ry too short"; // not long enough for valid entry
return false;
//int gpf = (uchar)buffer[9] << 8 | (uchar)buffer[10]; }
//kDebug() << "general purpose flag=" << gpf;
// length of the fileName (well, pathname indeed) //int gpf = (uchar)buffer[9] << 8 | (uchar)buffer[10
int namelen = (uchar)buffer[29] << 8 | (uchar)buffer[28]; ];
Q_ASSERT( namelen > 0 ); //kDebug() << "general purpose flag=" << gpf;
QByteArray bufferName = dev->read( namelen ); // length of the fileName (well, pathname indeed)
if ( bufferName.size() < namelen ) int namelen = (uchar)buffer[29] << 8 | (uchar)buffer
qWarning() << "Invalid ZIP file. Name not completely read"; [28];
Q_ASSERT( namelen > 0 );
ParseFileInfo pfi = pfi_map.value( bufferName, ParseFileInfo() QByteArray bufferName = dev->read( namelen );
); if ( bufferName.size() < namelen )
qWarning() << "Invalid ZIP file. Name not co
QString name( QFile::decodeName(bufferName) ); mpletely read";
//qDebug() << "name: " << name; ParseFileInfo pfi = pfi_map.value( bufferName, Parse
// only in central header ! see below. FileInfo() );
// length of extra attributes
int extralen = (uchar)buffer[31] << 8 | (uchar)buffer[30]; QString name( QFile::decodeName(bufferName) );
// length of comment for this file
int commlen = (uchar)buffer[33] << 8 | (uchar)buffer[32]; //qDebug() << "name: " << name;
// compression method of this file // only in central header ! see below.
int cmethod = (uchar)buffer[11] << 8 | (uchar)buffer[10]; // length of extra attributes
int extralen = (uchar)buffer[31] << 8 | (uchar)buffe
//qDebug() << "cmethod: " << cmethod; r[30];
//qDebug() << "extralen: " << extralen; // length of comment for this file
int commlen = (uchar)buffer[33] << 8 | (uchar)buffe
// crc32 of the file r[32];
uint crc32 = (uchar)buffer[19] << 24 | (uchar)buffer[18] << 16 // compression method of this file
| int cmethod = (uchar)buffer[11] << 8 | (uchar)buffe
(uchar)buffer[17] << 8 | (uchar)buffer[16]; r[10];
// uncompressed file size //qDebug() << "cmethod: " << cmethod;
uint ucsize = (uchar)buffer[27] << 24 | (uchar)buffer[26] << 16 //qDebug() << "extralen: " << extralen;
|
(uchar)buffer[25] << 8 | (uchar)buffer[24]; // crc32 of the file
// compressed file size uint crc32 = (uchar)buffer[19] << 24 | (uchar)buffer
uint csize = (uchar)buffer[23] << 24 | (uchar)buffer[22] << 16 [18] << 16 |
| (uchar)buffer[17] << 8 | (uchar)b
(uchar)buffer[21] << 8 | (uchar)buffer[20]; uffer[16];
// uncompressed file size
uint ucsize = (uchar)buffer[27] << 24 | (uchar)buffe
r[26] << 16 |
(uchar)buffer[25] << 8 | (uchar)buffer[24];
// compressed file size
uint csize = (uchar)buffer[23] << 24 | (uchar)buffer
[22] << 16 |
(uchar)buffer[21] << 8 | (uchar)buffer[20];
// offset of local header // offset of local header
uint localheaderoffset = (uchar)buffer[45] << 24 | (uchar)buffe uint localheaderoffset = (uchar)buffer[45] << 24 | (
r[44] << 16 | uchar)buffer[44] << 16 |
(uchar)buffer[43] << 8 | (uchar)buffer[42]; (uchar)buffer[43] << 8 | (uchar)buffer[42];
// some clever people use different extra field lengths // some clever people use different extra field leng
// in the central header and in the local header... funny. ths
// so we need to get the localextralen to calculate the offset // in the central header and in the local header...
// from localheaderstart to dataoffset funny.
int localextralen = pfi.extralen; // FIXME: this will not work // so we need to get the localextralen to calculate
if the offset
// no local header exists // from localheaderstart to dataoffset
int localextralen = pfi.extralen; // FIXME: this wil
//qDebug() << "localextralen: " << localextralen; l not work if
// no local header e
// offset, where the real data for uncompression starts xists
uint dataoffset = localheaderoffset + 30 + localextralen + name
len; //comment only in central header //qDebug() << "localextralen: " << localextralen;
//qDebug() << "esize: " << esize; // offset, where the real data for uncompression sta
//qDebug() << "eoffset: " << eoffset; rts
//qDebug() << "csize: " << csize; uint dataoffset = localheaderoffset + 30 + localextr
alen + namelen; //comment only in central header
int os_madeby = (uchar)buffer[5];
bool isdir = false; //qDebug() << "esize: " << esize;
int access = 0100644; //qDebug() << "eoffset: " << eoffset;
//qDebug() << "csize: " << csize;
if (os_madeby == 3) { // good ole unix
access = (uchar)buffer[40] | (uchar)buffer[41] << 8; int os_madeby = (uchar)buffer[5];
} bool isdir = false;
int access = 0100644;
QString entryName;
if (os_madeby == 3) { // good ole unix
if ( name.endsWith( '/' ) ) // Entries with a trailing slash ar access = (uchar)buffer[40] | (uchar)buffer[41] << 8;
e directories }
{
isdir = true; QString entryName;
name = name.left( name.length() - 1 );
if (os_madeby != 3) access = S_IFDIR | 0755; if ( name.endsWith( '/' ) ) // Entries with a traili
ng slash are directories
{
isdir = true;
name = name.left( name.length() - 1 );
if (os_madeby != 3) access = S_IFDIR | 0755;
else Q_ASSERT(access & S_IFDIR); else Q_ASSERT(access & S_IFDIR);
} }
int pos = name.lastIndexOf( '/' ); int pos = name.lastIndexOf( '/' );
if ( pos == -1 ) if ( pos == -1 )
entryName = name; entryName = name;
else else
entryName = name.mid( pos + 1 ); entryName = name.mid( pos + 1 );
Q_ASSERT( !entryName.isEmpty() ); Q_ASSERT( !entryName.isEmpty() );
KArchiveEntry* entry; KArchiveEntry* entry;
if ( isdir ) if ( isdir )
{ {
QString path = QDir::cleanPath( name ); QString path = QDir::cleanPath( name );
const KArchiveEntry* ent = rootDir()->entry( path ); const KArchiveEntry* ent = rootDir()->entry(
if ( ent && ent->isDirectory() ) path );
{ if ( ent && ent->isDirectory() )
//qDebug() << "Directory already exists, NOT going to a {
dd it again"; //qDebug() << "Directory already exi
entry = 0; sts, NOT going to add it again";
} entry = 0;
else }
{ else
entry = new KArchiveDirectory( this, entryName, access, {
(int)pfi.mtime, rootDir()->user(), rootDir()->group(), QString() ); entry = new KArchiveDirectory( this,
//qDebug() << "KArchiveDirectory created, entryName= " entryName, access, (int)pfi.mtime, rootDir()->user(), rootDir()->group(),
<< entryName << ", name=" << name; QString() );
} //qDebug() << "KArchiveDirectory cre
} ated, entryName= " << entryName << ", name=" << name;
else }
{ }
QString symlink; else
{
QString symlink;
if (S_ISLNK(access)) { if (S_ISLNK(access)) {
symlink = QFile::decodeName(pfi.guessed_symlink); symlink = QFile::decodeName(pfi.guessed_symlink);
} }
entry = new KZipFileEntry( this, entryName, access, pfi.mti me, entry = new KZipFileEntry( this, entryName, access, pfi.mtime,
rootDir()->user(), rootDir()->group( ), rootDir()->user(), rootDir()->group( ),
symlink, name, dataoffset, symlink, name, dataoffset,
ucsize, cmethod, csize ); ucsize, cmethod, csize );
static_cast<KZipFileEntry *>(entry)->setHeaderStart( localh static_cast<KZipFileEntry *>(entry)->setHead
eaderoffset ); erStart( localheaderoffset );
static_cast<KZipFileEntry*>(entry)->setCRC32(crc32); static_cast<KZipFileEntry*>(entry)->setCRC32
//qDebug() << "KZipFileEntry created, entryName= " << entry (crc32);
Name << ", name=" << name; //qDebug() << "KZipFileEntry created, entryN
d->m_fileList.append( static_cast<KZipFileEntry *>( entry ) ame= " << entryName << ", name=" << name;
); d->m_fileList.append( static_cast<KZipFileEn
} try *>( entry ) );
}
if ( entry )
{ if ( entry )
if ( pos == -1 ) {
{ if ( pos == -1 )
rootDir()->addEntry(entry); {
} rootDir()->addEntry(entry);
else }
{ else
// In some tar files we can find dir/./file => call cle {
anPath // In some tar files we can find dir
QString path = QDir::cleanPath( name.left( pos ) ); /./file => call cleanPath
// Ensure container directory exists, create otherwise QString path = QDir::cleanPath( name
KArchiveDirectory * tdir = findOrCreate( path ); .left( pos ) );
tdir->addEntry(entry); // Ensure container directory exists
} , create otherwise
} KArchiveDirectory * tdir = findOrCre
ate( path );
//calculate offset to next entry tdir->addEntry(entry);
offset += 46 + commlen + extralen + namelen; }
bool b = dev->seek(offset); }
Q_ASSERT( b );
if ( !b ) //calculate offset to next entry
return false; offset += 46 + commlen + extralen + namelen;
} bool b = dev->seek(offset);
else if ( startOfFile ) Q_ASSERT( b );
{ if ( !b )
// The file does not start with any ZIP header (e.g. self-extra return false;
ctable ZIP files) }
// Therefore we need to find the first PK\003\004 (local header else if ( startOfFile )
) {
qDebug() << "Try to skip start of file"; // The file does not start with any ZIP header (e.g.
startOfFile = false; self-extractable ZIP files)
bool foundSignature = false; // Therefore we need to find the first PK\003\004 (l
ocal header)
while (!foundSignature) qDebug() << "Try to skip start of file";
{ startOfFile = false;
n = dev->read( buffer, 1 ); bool foundSignature = false;
if (n < 1)
{ while (!foundSignature)
qWarning() << "Invalid ZIP file. Unexpected end of file {
. " ; n = dev->read( buffer, 1 );
return false; if (n < 1)
} {
qWarning() << "Invalid ZIP file. Une
if ( buffer[0] != 'P' ) xpected end of file. " ;
continue; return false;
}
n = dev->read( buffer, 3 );
if (n < 3) if ( buffer[0] != 'P' )
{ continue;
qWarning() << "Invalid ZIP file. Unexpected end of file
. " ; n = dev->read( buffer, 3 );
return false; if (n < 3)
} {
qWarning() << "Invalid ZIP file. Une
// We have to detect the magic token for a local header: PK xpected end of file. " ;
\003\004 return false;
/* }
* Note: we do not need to check the other magics, if the Z
IP file has no // We have to detect the magic token for a l
* local header, then it has not any files! ocal header: PK\003\004
*/ /*
if ( buffer[0] == 'K' && buffer[1] == 3 && buffer[2] == 4 ) * Note: we do not need to check the other m
{ agics, if the ZIP file has no
foundSignature = true; * local header, then it has not any files!
dev->seek( dev->pos() - 4 ); // go back 4 bytes, so tha */
t the magic bytes can be found... if ( buffer[0] == 'K' && buffer[1] == 3 && b
} uffer[2] == 4 )
else if ( buffer[0] == 'P' || buffer[1] == 'P' || buffer[2] {
== 'P' ) foundSignature = true;
{ dev->seek( dev->pos() - 4 ); // go b
// We have another P character so we must go back a ack 4 bytes, so that the magic bytes can be found...
little to check if it is a magic }
dev->seek( dev->pos() - 3 ); else if ( buffer[0] == 'P' || buffer[1] == '
} P' || buffer[2] == 'P' )
} {
} // We have another P charact
else er so we must go back a little to check if it is a magic
{ dev->seek( dev->pos() - 3 );
qWarning() << "Invalid ZIP file. Unrecognized header at offset }
" << offset; }
}
return false; else
} {
} qWarning() << "Invalid ZIP file. Unrecognized header
//qDebug() << "*** done *** "; at offset " << offset;
return true;
return false;
}
}
//qDebug() << "*** done *** ";
return true;
} }
bool KZip::closeArchive() bool KZip::closeArchive()
{ {
if ( ! ( mode() & QIODevice::WriteOnly ) ) if ( ! ( mode() & QIODevice::WriteOnly ) )
{ {
//qDebug() << "readonly"; //qDebug() << "readonly";
return true; return true;
} }
//ReadWrite or WriteOnly //ReadWrite or WriteOnly
//write all central dir file entries //write all central dir file entries
// to be written at the end of the file... // to be written at the end of the file...
char buffer[ 22 ]; // first used for 12, then for 22 at the end char buffer[ 22 ]; // first used for 12, then for 22 at the end
uLong crc = crc32(0L, Z_NULL, 0); uLong crc = crc32(0L, Z_NULL, 0);
qint64 centraldiroffset = device()->pos(); qint64 centraldiroffset = device()->pos();
//qDebug() << "closearchive: centraldiroffset: " << centraldiroffset; //qDebug() << "closearchive: centraldiroffset: " << centraldiroffset
qint64 atbackup = centraldiroffset; ;
QMutableListIterator<KZipFileEntry*> it( d->m_fileList ); qint64 atbackup = centraldiroffset;
QMutableListIterator<KZipFileEntry*> it( d->m_fileList );
while(it.hasNext())
{ //set crc and compressed size in each local file header while(it.hasNext())
it.next(); { //set crc and compressed size in each local file header
if ( !device()->seek( it.value()->headerStart() + 14 ) ) it.next();
return false; if ( !device()->seek( it.value()->headerStart() + 14 ) )
return false;
//qDebug() << "closearchive setcrcandcsize: fileName:" //qDebug() << "closearchive setcrcandcsize: fileName:"
// << it.current()->path() // << it.current()->path()
// << "encoding:" << it.current()->encoding(); // << "encoding:" << it.current()->encoding();
uLong mycrc = it.value()->crc32(); uLong mycrc = it.value()->crc32();
buffer[0] = char(mycrc); // crc checksum, at headerStart+14 buffer[0] = char(mycrc); // crc checksum, at headerStart+14
buffer[1] = char(mycrc >> 8); buffer[1] = char(mycrc >> 8);
buffer[2] = char(mycrc >> 16); buffer[2] = char(mycrc >> 16);
buffer[3] = char(mycrc >> 24); buffer[3] = char(mycrc >> 24);
int mysize1 = it.value()->compressedSize(); int mysize1 = it.value()->compressedSize();
buffer[4] = char(mysize1); // compressed file size, at headerStart+ buffer[4] = char(mysize1); // compressed file size, at heade
18 rStart+18
buffer[5] = char(mysize1 >> 8); buffer[5] = char(mysize1 >> 8);
buffer[6] = char(mysize1 >> 16); buffer[6] = char(mysize1 >> 16);
buffer[7] = char(mysize1 >> 24); buffer[7] = char(mysize1 >> 24);
int myusize = it.value()->size(); int myusize = it.value()->size();
buffer[8] = char(myusize); // uncompressed file size, at headerStar buffer[8] = char(myusize); // uncompressed file size, at hea
t+22 derStart+22
buffer[9] = char(myusize >> 8); buffer[9] = char(myusize >> 8);
buffer[10] = char(myusize >> 16); buffer[10] = char(myusize >> 16);
buffer[11] = char(myusize >> 24); buffer[11] = char(myusize >> 24);
if ( device()->write( buffer, 12 ) != 12 ) if ( device()->write( buffer, 12 ) != 12 )
return false; return false;
} }
device()->seek( atbackup ); device()->seek( atbackup );
it.toFront(); it.toFront();
while (it.hasNext()) while (it.hasNext())
{ {
it.next(); it.next();
//qDebug() << "fileName:" << it.current()->path() //qDebug() << "fileName:" << it.current()->path()
// << "encoding:" << it.current()->encoding(); // << "encoding:" << it.current()->encoding();
QByteArray path = QFile::encodeName(it.value()->path()); QByteArray path = QFile::encodeName(it.value()->path());
const int extra_field_len = 9; const int extra_field_len = 9;
int bufferSize = extra_field_len + path.length() + 46; int bufferSize = extra_field_len + path.length() + 46;
char* buffer = new char[ bufferSize ]; char* buffer = new char[ bufferSize ];
memset(buffer, 0, 46); // zero is a nice default for most header fi elds memset(buffer, 0, 46); // zero is a nice default for most he ader fields
const char head[] = const char head[] =
{ {
'P', 'K', 1, 2, // central file header signature 'P', 'K', 1, 2, // central file header signature
0x14, 3, // version made by (3 == UNIX) 0x14, 3, // version made by (3 == UNIX)
0x14, 0 // version needed to extract 0x14, 0 // version needed to extract
}; };
// I do not know why memcpy is not working here // I do not know why memcpy is not working here
//memcpy(buffer, head, sizeof(head)); //memcpy(buffer, head, sizeof(head));
memmove(buffer, head, sizeof(head)); memmove(buffer, head, sizeof(head));
buffer[ 10 ] = char(it.value()->encoding()); // compression method buffer[ 10 ] = char(it.value()->encoding()); // compression
buffer[ 11 ] = char(it.value()->encoding() >> 8); method
buffer[ 11 ] = char(it.value()->encoding() >> 8);
transformToMsDos( it.value()->datetime(), &buffer[ 12 ] ); transformToMsDos( it.value()->datetime(), &buffer[ 12 ] );
uLong mycrc = it.value()->crc32(); uLong mycrc = it.value()->crc32();
buffer[ 16 ] = char(mycrc); // crc checksum buffer[ 16 ] = char(mycrc); // crc checksum
buffer[ 17 ] = char(mycrc >> 8); buffer[ 17 ] = char(mycrc >> 8);
buffer[ 18 ] = char(mycrc >> 16); buffer[ 18 ] = char(mycrc >> 16);
buffer[ 19 ] = char(mycrc >> 24); buffer[ 19 ] = char(mycrc >> 24);
int mysize1 = it.value()->compressedSize(); int mysize1 = it.value()->compressedSize();
buffer[ 20 ] = char(mysize1); // compressed file size buffer[ 20 ] = char(mysize1); // compressed file size
buffer[ 21 ] = char(mysize1 >> 8); buffer[ 21 ] = char(mysize1 >> 8);
buffer[ 22 ] = char(mysize1 >> 16); buffer[ 22 ] = char(mysize1 >> 16);
buffer[ 23 ] = char(mysize1 >> 24); buffer[ 23 ] = char(mysize1 >> 24);
int mysize = it.value()->size(); int mysize = it.value()->size();
buffer[ 24 ] = char(mysize); // uncompressed file size buffer[ 24 ] = char(mysize); // uncompressed file size
buffer[ 25 ] = char(mysize >> 8); buffer[ 25 ] = char(mysize >> 8);
buffer[ 26 ] = char(mysize >> 16); buffer[ 26 ] = char(mysize >> 16);
buffer[ 27 ] = char(mysize >> 24); buffer[ 27 ] = char(mysize >> 24);
buffer[ 28 ] = char(it.value()->path().length()); // fileName lengt buffer[ 28 ] = char(it.value()->path().length()); // fileNam
h e length
buffer[ 29 ] = char(it.value()->path().length() >> 8); buffer[ 29 ] = char(it.value()->path().length() >> 8);
buffer[ 30 ] = char(extra_field_len); buffer[ 30 ] = char(extra_field_len);
buffer[ 31 ] = char(extra_field_len >> 8); buffer[ 31 ] = char(extra_field_len >> 8);
buffer[ 40 ] = char(it.value()->permissions()); buffer[ 40 ] = char(it.value()->permissions());
buffer[ 41 ] = char(it.value()->permissions() >> 8); buffer[ 41 ] = char(it.value()->permissions() >> 8);
int myhst = it.value()->headerStart(); int myhst = it.value()->headerStart();
buffer[ 42 ] = char(myhst); //relative offset of local header buffer[ 42 ] = char(myhst); //relative offset of local heade
buffer[ 43 ] = char(myhst >> 8); r
buffer[ 44 ] = char(myhst >> 16); buffer[ 43 ] = char(myhst >> 8);
buffer[ 45 ] = char(myhst >> 24); buffer[ 44 ] = char(myhst >> 16);
buffer[ 45 ] = char(myhst >> 24);
// file name // file name
strncpy( buffer + 46, path, path.length() ); strncpy( buffer + 46, path, path.length() );
//qDebug() << "closearchive length to write: " << bufferSize; //qDebug() << "closearchive length to write: " << bufferSize;
// extra field // extra field
char *extfield = buffer + 46 + path.length(); char *extfield = buffer + 46 + path.length();
extfield[0] = 'U'; extfield[0] = 'U';
extfield[1] = 'T'; extfield[1] = 'T';
extfield[2] = 5; extfield[2] = 5;
extfield[3] = 0; extfield[3] = 0;
extfield[4] = 1 | 2 | 4; // specify flags from local field extfield[4] = 1 | 2 | 4; // specify flags from local field
// (unless I misread the spec) // (unless I misread the spec)
// provide only modification time // provide only modification time
unsigned long time = (unsigned long)it.value()->date(); unsigned long time = (unsigned long)it.value()->date();
extfield[5] = char(time); extfield[5] = char(time);
extfield[6] = char(time >> 8); extfield[6] = char(time >> 8);
extfield[7] = char(time >> 16); extfield[7] = char(time >> 16);
extfield[8] = char(time >> 24); extfield[8] = char(time >> 24);
crc = crc32(crc, (Bytef *)buffer, bufferSize ); crc = crc32(crc, (Bytef *)buffer, bufferSize );
bool ok = ( device()->write( buffer, bufferSize ) == bufferSize ); bool ok = ( device()->write( buffer, bufferSize ) == bufferS
delete[] buffer; ize );
if ( !ok ) delete[] buffer;
return false; if ( !ok )
} return false;
qint64 centraldirendoffset = device()->pos(); }
//qDebug() << "closearchive: centraldirendoffset: " << centraldirendoff qint64 centraldirendoffset = device()->pos();
set; //qDebug() << "closearchive: centraldirendoffset: " << centraldirend
//qDebug() << "closearchive: device()->pos(): " << device()->pos(); offset;
//qDebug() << "closearchive: device()->pos(): " << device()->pos();
//write end of central dir record.
buffer[ 0 ] = 'P'; //end of central dir signature //write end of central dir record.
buffer[ 1 ] = 'K'; buffer[ 0 ] = 'P'; //end of central dir signature
buffer[ 2 ] = 5; buffer[ 1 ] = 'K';
buffer[ 3 ] = 6; buffer[ 2 ] = 5;
buffer[ 3 ] = 6;
buffer[ 4 ] = 0; // number of this disk
buffer[ 5 ] = 0; buffer[ 4 ] = 0; // number of this disk
buffer[ 5 ] = 0;
buffer[ 6 ] = 0; // number of disk with start of central dir
buffer[ 7 ] = 0; buffer[ 6 ] = 0; // number of disk with start of central dir
buffer[ 7 ] = 0;
int count = d->m_fileList.count();
//qDebug() << "number of files (count): " << count;
buffer[ 8 ] = char(count); // total number of entries in central dir of
buffer[ 9 ] = char(count >> 8); // this disk
buffer[ 10 ] = buffer[ 8 ]; // total number of entries in the central d
ir
buffer[ 11 ] = buffer[ 9 ];
int cdsize = centraldirendoffset - centraldiroffset;
buffer[ 12 ] = char(cdsize); // size of the central dir
buffer[ 13 ] = char(cdsize >> 8);
buffer[ 14 ] = char(cdsize >> 16);
buffer[ 15 ] = char(cdsize >> 24);
//qDebug() << "end : centraldiroffset: " << centraldiroffset;
//qDebug() << "end : centraldirsize: " << cdsize;
buffer[ 16 ] = char(centraldiroffset); // central dir offset
buffer[ 17 ] = char(centraldiroffset >> 8);
buffer[ 18 ] = char(centraldiroffset >> 16);
buffer[ 19 ] = char(centraldiroffset >> 24);
buffer[ 20 ] = 0; //zipfile comment length int count = d->m_fileList.count();
buffer[ 21 ] = 0; //qDebug() << "number of files (count): " << count;
if ( device()->write( buffer, 22 ) != 22 ) buffer[ 8 ] = char(count); // total number of entries in central dir
return false; of
buffer[ 9 ] = char(count >> 8); // this disk
return true; buffer[ 10 ] = buffer[ 8 ]; // total number of entries in the centra
l dir
buffer[ 11 ] = buffer[ 9 ];
int cdsize = centraldirendoffset - centraldiroffset;
buffer[ 12 ] = char(cdsize); // size of the central dir
buffer[ 13 ] = char(cdsize >> 8);
buffer[ 14 ] = char(cdsize >> 16);
buffer[ 15 ] = char(cdsize >> 24);
//qDebug() << "end : centraldiroffset: " << centraldiroffset;
//qDebug() << "end : centraldirsize: " << cdsize;
buffer[ 16 ] = char(centraldiroffset); // central dir offset
buffer[ 17 ] = char(centraldiroffset >> 8);
buffer[ 18 ] = char(centraldiroffset >> 16);
buffer[ 19 ] = char(centraldiroffset >> 24);
buffer[ 20 ] = 0; //zipfile comment length
buffer[ 21 ] = 0;
if ( device()->write( buffer, 22 ) != 22 )
return false;
return true;
} }
bool KZip::doWriteDir( const QString&, const QString&, const QString&, bool KZip::doWriteDir( const QString&, const QString&, const QString&,
mode_t, time_t, time_t, time_t ) { mode_t, time_t, time_t, time_t )
return true; {
return true;
} }
bool KZip::doPrepareWriting(const QString &name, const QString &user, bool KZip::doPrepareWriting(const QString &name, const QString &user,
const QString &group, qint64 /*size*/, mode_ const QString &gr
t perm, oup, qint64 /*size*/, mode_t perm,
time_t atime, time_t mtime, time_t ctime) { time_t atime, tim
//qDebug(); e_t mtime, time_t ctime) {
if ( !isOpen() ) //qDebug();
{ if ( !isOpen() )
qWarning( "KZip::writeFile: You must open the zip file before writi {
ng to it\n"); qWarning( "KZip::writeFile: You must open the zip file befor
return false; e writing to it\n");
} return false;
}
if ( ! ( mode() & QIODevice::WriteOnly ) ) // accept WriteOnly and Read
Write if ( ! ( mode() & QIODevice::WriteOnly ) ) // accept WriteOnly and R
{ eadWrite
qWarning( "KZip::writeFile: You must open the zip file for writing\ {
n"); qWarning( "KZip::writeFile: You must open the zip file for w
return false; riting\n");
} return false;
}
Q_ASSERT( device() );
Q_ASSERT( device() );
// set right offset in zip.
if ( !device()->seek( d->m_offset ) ) { // set right offset in zip.
qWarning() << "doPrepareWriting: cannot seek in ZIP file. Disk full if ( !device()->seek( d->m_offset ) ) {
?"; qWarning() << "doPrepareWriting: cannot seek in ZIP file. Di
return false; sk full?";
} return false;
}
// delete entries in the filelist with the same fileName as the one we
want // delete entries in the filelist with the same fileName as the one
// to save, so that we don't have duplicate file entries when viewing t we want
he zip // to save, so that we don't have duplicate file entries when viewin
// with konqi... g the zip
// CAUTION: the old file itself is still in the zip and won't be remove // with konqi...
d !!! // CAUTION: the old file itself is still in the zip and won't be rem
QMutableListIterator<KZipFileEntry*> it( d->m_fileList ); oved !!!
QMutableListIterator<KZipFileEntry*> it( d->m_fileList );
//qDebug() << "fileName to write: " << name; //qDebug() << "fileName to write: " << name;
while(it.hasNext()) while(it.hasNext())
{ {
it.next(); it.next();
//qDebug() << "prepfileName: " << it.current()->path(); //qDebug() << "prepfileName: " << it.current()->path();
if (name == it.value()->path() ) if (name == it.value()->path() )
{ {
//qDebug() << "removing following entry: " << it.current()-> //qDebug() << "removing following entry: " << it.cur
path(); rent()->path();
delete it.value(); delete it.value();
it.remove(); it.remove();
} }
} }
// Find or create parent dir // Find or create parent dir
KArchiveDirectory* parentDir = rootDir(); KArchiveDirectory* parentDir = rootDir();
QString fileName( name ); QString fileName( name );
int i = name.lastIndexOf( '/' ); int i = name.lastIndexOf( '/' );
if ( i != -1 ) if ( i != -1 )
{ {
QString dir = name.left( i ); QString dir = name.left( i );
fileName = name.mid( i + 1 ); fileName = name.mid( i + 1 );
//qDebug() << "ensuring" << dir << "exists. fileName=" << fileName; //qDebug() << "ensuring" << dir << "exists. fileName=" << fi
parentDir = findOrCreate( dir ); leName;
} parentDir = findOrCreate( dir );
}
// construct a KZipFileEntry and add it to list
KZipFileEntry * e = new KZipFileEntry( this, fileName, perm, mtime, use // construct a KZipFileEntry and add it to list
r, group, QString(), KZipFileEntry * e = new KZipFileEntry( this, fileName, perm, mtime,
name, device()->pos() + 30 + nam user, group, QString(),
e.length(), // start
0 /*size unknown yet*/, d->m_com name, device()->pos() + 30 + name.length(), // start
pression, 0 /*csize unknown yet*/ );
e->setHeaderStart( device()->pos() ); 0 /*size unknown yet*/, d->m_compression, 0 /*csize unknown yet*/ );
//qDebug() << "wrote file start: " << e->position() << " name: " << nam e->setHeaderStart( device()->pos() );
e; //qDebug() << "wrote file start: " << e->position() << " name: " <<
parentDir->addEntry( e ); name;
parentDir->addEntry( e );
d->m_currentFile = e;
d->m_fileList.append( e ); d->m_currentFile = e;
d->m_fileList.append( e );
int extra_field_len = 0;
if ( d->m_extraField == ModificationTime ) int extra_field_len = 0;
extra_field_len = 17; // value also used in finishWriting() if ( d->m_extraField == ModificationTime )
extra_field_len = 17; // value also used in finishWriting(
// write out zip header )
QByteArray encodedName = QFile::encodeName(name);
int bufferSize = extra_field_len + encodedName.length() + 30; // write out zip header
//qDebug() << "bufferSize=" << bufferSize; QByteArray encodedName = QFile::encodeName(name);
char* buffer = new char[ bufferSize ]; int bufferSize = extra_field_len + encodedName.length() + 30;
//qDebug() << "bufferSize=" << bufferSize;
buffer[ 0 ] = 'P'; //local file header signature char* buffer = new char[ bufferSize ];
buffer[ 1 ] = 'K';
buffer[ 2 ] = 3; buffer[ 0 ] = 'P'; //local file header signature
buffer[ 3 ] = 4; buffer[ 1 ] = 'K';
buffer[ 2 ] = 3;
buffer[ 4 ] = 0x14; // version needed to extract buffer[ 3 ] = 4;
buffer[ 5 ] = 0;
buffer[ 4 ] = 0x14; // version needed to extract
buffer[ 6 ] = 0; // general purpose bit flag buffer[ 5 ] = 0;
buffer[ 7 ] = 0;
buffer[ 6 ] = 0; // general purpose bit flag
buffer[ 8 ] = char(e->encoding()); // compression method buffer[ 7 ] = 0;
buffer[ 9 ] = char(e->encoding() >> 8);
buffer[ 8 ] = char(e->encoding()); // compression method
transformToMsDos( e->datetime(), &buffer[ 10 ] ); buffer[ 9 ] = char(e->encoding() >> 8);
buffer[ 14 ] = 'C'; //dummy crc transformToMsDos( e->datetime(), &buffer[ 10 ] );
buffer[ 15 ] = 'R';
buffer[ 16 ] = 'C'; buffer[ 14 ] = 'C'; //dummy crc
buffer[ 17 ] = 'q'; buffer[ 15 ] = 'R';
buffer[ 16 ] = 'C';
buffer[ 18 ] = 'C'; //compressed file size buffer[ 17 ] = 'q';
buffer[ 19 ] = 'S';
buffer[ 20 ] = 'I'; buffer[ 18 ] = 'C'; //compressed file size
buffer[ 21 ] = 'Z'; buffer[ 19 ] = 'S';
buffer[ 20 ] = 'I';
buffer[ 22 ] = 'U'; //uncompressed file size buffer[ 21 ] = 'Z';
buffer[ 23 ] = 'S';
buffer[ 24 ] = 'I'; buffer[ 22 ] = 'U'; //uncompressed file size
buffer[ 25 ] = 'Z'; buffer[ 23 ] = 'S';
buffer[ 24 ] = 'I';
buffer[ 26 ] = (uchar)(encodedName.length()); //fileName length buffer[ 25 ] = 'Z';
buffer[ 27 ] = (uchar)(encodedName.length() >> 8);
buffer[ 26 ] = (uchar)(encodedName.length()); //fileName length
buffer[ 28 ] = (uchar)(extra_field_len); // extra field length buffer[ 27 ] = (uchar)(encodedName.length() >> 8);
buffer[ 29 ] = (uchar)(extra_field_len >> 8);
buffer[ 28 ] = (uchar)(extra_field_len); // extra field length
// file name buffer[ 29 ] = (uchar)(extra_field_len >> 8);
strncpy( buffer + 30, encodedName, encodedName.length() );
// file name
// extra field strncpy( buffer + 30, encodedName, encodedName.length() );
if ( d->m_extraField == ModificationTime )
{ // extra field
char *extfield = buffer + 30 + encodedName.length(); if ( d->m_extraField == ModificationTime )
// "Extended timestamp" header (0x5455) {
extfield[0] = 'U'; char *extfield = buffer + 30 + encodedName.length();
extfield[1] = 'T'; // "Extended timestamp" header (0x5455)
extfield[2] = 13; // data size extfield[0] = 'U';
extfield[3] = 0; extfield[1] = 'T';
extfield[4] = 1 | 2 | 4; // contains mtime, atime, ctime extfield[2] = 13; // data size
extfield[3] = 0;
extfield[5] = char(mtime); extfield[4] = 1 | 2 | 4; // contains mtime, atime, ct
extfield[6] = char(mtime >> 8); ime
extfield[7] = char(mtime >> 16);
extfield[8] = char(mtime >> 24); extfield[5] = char(mtime);
extfield[6] = char(mtime >> 8);
extfield[9] = char(atime); extfield[7] = char(mtime >> 16);
extfield[10] = char(atime >> 8); extfield[8] = char(mtime >> 24);
extfield[11] = char(atime >> 16);
extfield[12] = char(atime >> 24); extfield[9] = char(atime);
extfield[10] = char(atime >> 8);
extfield[13] = char(ctime); extfield[11] = char(atime >> 16);
extfield[14] = char(ctime >> 8); extfield[12] = char(atime >> 24);
extfield[15] = char(ctime >> 16);
extfield[16] = char(ctime >> 24); extfield[13] = char(ctime);
} extfield[14] = char(ctime >> 8);
extfield[15] = char(ctime >> 16);
// Write header extfield[16] = char(ctime >> 24);
bool b = (device()->write( buffer, bufferSize ) == bufferSize ); }
d->m_crc = 0L;
delete[] buffer; // Write header
bool b = (device()->write( buffer, bufferSize ) == bufferSize );
Q_ASSERT( b ); d->m_crc = 0L;
if (!b) { delete[] buffer;
return false;
} Q_ASSERT( b );
if (!b) {
// Prepare device for writing the data return false;
// Either device() if no compression, or a KFilterDev to compress }
if ( d->m_compression == 0 ) {
d->m_currentDev = device(); // Prepare device for writing the data
return true; // Either device() if no compression, or a KFilterDev to compress
} if ( d->m_compression == 0 ) {
d->m_currentDev = device();
d->m_currentDev = KFilterDev::device( device(), "application/x-gzip", f return true;
alse ); }
Q_ASSERT( d->m_currentDev );
if ( !d->m_currentDev ) { d->m_currentDev = KFilterDev::device( device(), "application/x-gzip"
return false; // ouch , false );
} Q_ASSERT( d->m_currentDev );
static_cast<KFilterDev *>(d->m_currentDev)->setSkipHeaders(); // Just z if ( !d->m_currentDev ) {
lib, not gzip return false; // ouch
}
b = d->m_currentDev->open( QIODevice::WriteOnly ); static_cast<KFilterDev *>(d->m_currentDev)->setSkipHeaders(); // Jus
Q_ASSERT( b ); t zlib, not gzip
return b;
b = d->m_currentDev->open( QIODevice::WriteOnly );
Q_ASSERT( b );
return b;
} }
bool KZip::doFinishWriting( qint64 size ) bool KZip::doFinishWriting( qint64 size )
{ {
if ( d->m_currentFile->encoding() == 8 ) { if ( d->m_currentFile->encoding() == 8 ) {
// Finish // Finish
(void)d->m_currentDev->write( 0, 0 ); (void)d->m_currentDev->write( 0, 0 );
delete d->m_currentDev; delete d->m_currentDev;
} }
// If 0, d->m_currentDev was device() - don't delete ;) // If 0, d->m_currentDev was device() - don't delete ;)
d->m_currentDev = 0L; d->m_currentDev = 0L;
Q_ASSERT( d->m_currentFile ); Q_ASSERT( d->m_currentFile );
//qDebug() << "fileName: " << d->m_currentFile->path(); //qDebug() << "fileName: " << d->m_currentFile->path();
//qDebug() << "getpos (at): " << device()->pos(); //qDebug() << "getpos (at): " << device()->pos();
d->m_currentFile->setSize(size); d->m_currentFile->setSize(size);
int extra_field_len = 0; int extra_field_len = 0;
if ( d->m_extraField == ModificationTime ) if ( d->m_extraField == ModificationTime )
extra_field_len = 17; // value also used in finishWriting() extra_field_len = 17; // value also used in finishWriting(
)
int csize = device()->pos() - int csize = device()->pos() -
d->m_currentFile->headerStart() - 30 - d->m_currentFile->headerStart() - 30 -
d->m_currentFile->path().length() - extra_field_len; d->m_currentFile->path().length() - extra_field_len;
d->m_currentFile->setCompressedSize(csize); d->m_currentFile->setCompressedSize(csize);
//qDebug() << "usize: " << d->m_currentFile->size(); //qDebug() << "usize: " << d->m_currentFile->size();
//qDebug() << "csize: " << d->m_currentFile->compressedSize(); //qDebug() << "csize: " << d->m_currentFile->compressedSize();
//qDebug() << "headerstart: " << d->m_currentFile->headerStart(); //qDebug() << "headerstart: " << d->m_currentFile->headerStart();
//qDebug() << "crc: " << d->m_crc; //qDebug() << "crc: " << d->m_crc;
d->m_currentFile->setCRC32( d->m_crc ); d->m_currentFile->setCRC32( d->m_crc );
d->m_currentFile = 0L; d->m_currentFile = 0L;
// update saved offset for appending new files // update saved offset for appending new files
d->m_offset = device()->pos(); d->m_offset = device()->pos();
return true; return true;
} }
bool KZip::doWriteSymLink(const QString &name, const QString &target, bool KZip::doWriteSymLink(const QString &name, const QString &target,
const QString &user, const QString &group, const QString &user, const
mode_t perm, time_t atime, time_t mtime, time_t c QString &group,
time) { mode_t perm, time_t atime,
time_t mtime, time_t ctime) {
// reassure that symlink flag is set, otherwise strange things happen on // reassure that symlink flag is set, otherwise strange things happen on
// extraction // extraction
perm |= S_IFLNK; perm |= S_IFLNK;
Compression c = compression(); Compression c = compression();
setCompression(NoCompression); // link targets are never compressed setCompression(NoCompression); // link targets are never compressed
if (!doPrepareWriting(name, user, group, 0, perm, atime, mtime, ctime)) { if (!doPrepareWriting(name, user, group, 0, perm, atime, mtime, ctime)) {
qWarning() << "prepareWriting failed"; qWarning() << "prepareWriting failed";
setCompression(c); setCompression(c);
return false; return false;
} }
QByteArray symlink_target = QFile::encodeName(target); QByteArray symlink_target = QFile::encodeName(target);
if (!writeData(symlink_target, symlink_target.length())) { if (!writeData(symlink_target, symlink_target.length())) {
qWarning() << "writeData failed"; qWarning() << "writeData failed";
setCompression(c); setCompression(c);
return false; return false;
} }
if (!finishWriting(symlink_target.length())) { if (!finishWriting(symlink_target.length())) {
qWarning() << "finishWriting failed"; qWarning() << "finishWriting failed";
setCompression(c); setCompression(c);
return false; return false;
} }
setCompression(c); setCompression(c);
return true; return true;
} }
void KZip::virtual_hook( int id, void* data ) void KZip::virtual_hook( int id, void* data )
{ {
KArchive::virtual_hook( id, data ); KArchive::virtual_hook( id, data );
} }
bool KZip::writeData(const char * data, qint64 size) bool KZip::writeData(const char * data, qint64 size)
{ {
Q_ASSERT( d->m_currentFile ); Q_ASSERT( d->m_currentFile );
Q_ASSERT( d->m_currentDev ); Q_ASSERT( d->m_currentDev );
if (!d->m_currentFile || !d->m_currentDev) { if (!d->m_currentFile || !d->m_currentDev) {
return false; return false;
} }
// crc to be calculated over uncompressed stuff... // crc to be calculated over uncompressed stuff...
// and they didn't mention it in their docs... // and they didn't mention it in their docs...
d->m_crc = crc32(d->m_crc, (const Bytef *) data , size); d->m_crc = crc32(d->m_crc, (const Bytef *) data , size);
qint64 written = d->m_currentDev->write( data, size ); qint64 written = d->m_currentDev->write( data, size );
//qDebug() << "wrote" << size << "bytes."; //qDebug() << "wrote" << size << "bytes.";
return written == size; return written == size;
} }
void KZip::setCompression( Compression c ) void KZip::setCompression( Compression c )
{ {
d->m_compression = ( c == NoCompression ) ? 0 : 8; d->m_compression = ( c == NoCompression ) ? 0 : 8;
} }
KZip::Compression KZip::compression() const KZip::Compression KZip::compression() const
{ {
return ( d->m_compression == 8 ) ? DeflateCompression : NoCompression; return ( d->m_compression == 8 ) ? DeflateCompression : NoCompression;
} }
void KZip::setExtraField( ExtraField ef ) void KZip::setExtraField( ExtraField ef )
{ {
d->m_extraField = ef; d->m_extraField = ef;
} }
KZip::ExtraField KZip::extraField() const KZip::ExtraField KZip::extraField() const
{ {
return d->m_extraField; return d->m_extraField;
} }
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
////////////////////// KZipFileEntry//////////////////////////////////// ////////////////////// KZipFileEntry////////////////////////////////////
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
class KZipFileEntry::KZipFileEntryPrivate class KZipFileEntry::KZipFileEntryPrivate
{ {
public: public:
KZipFileEntryPrivate() KZipFileEntryPrivate()
: crc(0), : crc(0),
compressedSize(0), compressedSize(0),
headerStart(0), headerStart(0),
encoding(0) encoding(0)
{} {}
unsigned long crc; unsigned long crc;
qint64 compressedSize; qint64 compressedSize;
qint64 headerStart; qint64 headerStart;
int encoding; int encoding;
QString path; QString path;
}; };
KZipFileEntry::KZipFileEntry(KZip* zip, const QString& name, int access, in t date, KZipFileEntry::KZipFileEntry(KZip* zip, const QString& name, int access, in t date,
const QString& user, const QString& group, con const QString& user
st QString& symlink, , const QString& group, const QString& symlink,
const QString& path, qint64 start, qint64 unco const QString& path
mpressedSize, , qint64 start, qint64 uncompressedSize,
int encoding, qint64 compressedSize) int encoding, qint6
4 compressedSize)
: KArchiveFile(zip, name, access, date, user, group, symlink, start, uncom pressedSize ), : KArchiveFile(zip, name, access, date, user, group, symlink, start, uncom pressedSize ),
d(new KZipFileEntryPrivate) d(new KZipFileEntryPrivate)
{ {
d->path = path; d->path = path;
d->encoding = encoding; d->encoding = encoding;
d->compressedSize = compressedSize; d->compressedSize = compressedSize;
} }
KZipFileEntry::~KZipFileEntry() KZipFileEntry::~KZipFileEntry()
{ {
delete d; delete d;
} }
int KZipFileEntry::encoding() const int KZipFileEntry::encoding() const
{ {
return d->encoding; return d->encoding;
} }
qint64 KZipFileEntry::compressedSize() const qint64 KZipFileEntry::compressedSize() const
{ {
return d->compressedSize; return d->compressedSize;
} }
void KZipFileEntry::setCompressedSize(qint64 compressedSize) void KZipFileEntry::setCompressedSize(qint64 compressedSize)
{ {
d->compressedSize = compressedSize; d->compressedSize = compressedSize;
} }
void KZipFileEntry::setHeaderStart(qint64 headerstart) void KZipFileEntry::setHeaderStart(qint64 headerstart)
{ {
d->headerStart = headerstart; d->headerStart = headerstart;
} }
qint64 KZipFileEntry::headerStart() const qint64 KZipFileEntry::headerStart() const
{ {
return d->headerStart; return d->headerStart;
} }
unsigned long KZipFileEntry::crc32() const unsigned long KZipFileEntry::crc32() const
{ {
return d->crc; return d->crc;
} }
void KZipFileEntry::setCRC32(unsigned long crc32) void KZipFileEntry::setCRC32(unsigned long crc32)
{ {
d->crc=crc32; d->crc=crc32;
} }
const QString &KZipFileEntry::path() const const QString &KZipFileEntry::path() const
{ {
return d->path; return d->path;
} }
QByteArray KZipFileEntry::data() const QByteArray KZipFileEntry::data() const
{ {
QIODevice* dev = createDevice(); QIODevice* dev = createDevice();
QByteArray arr; QByteArray arr;
if ( dev ) { if ( dev ) {
arr = dev->readAll(); arr = dev->readAll();
delete dev; delete dev;
} }
return arr; return arr;
} }
QIODevice* KZipFileEntry::createDevice() const QIODevice* KZipFileEntry::createDevice() const
{ {
//qDebug() << "creating iodevice limited to pos=" << position() << ", c //qDebug() << "creating iodevice limited to pos=" << position() << "
size=" << compressedSize(); , csize=" << compressedSize();
// Limit the reading to the appropriate part of the underlying device ( // Limit the reading to the appropriate part of the underlying devic
e.g. file) e (e.g. file)
KLimitedIODevice* limitedDev = new KLimitedIODevice( archive()->device( KLimitedIODevice* limitedDev = new KLimitedIODevice( archive()->devi
), position(), compressedSize() ); ce(), position(), compressedSize() );
if ( encoding() == 0 || compressedSize() == 0 ) // no compression (or e if ( encoding() == 0 || compressedSize() == 0 ) // no compression (o
ven no data) r even no data)
return limitedDev; return limitedDev;
if ( encoding() == 8 ) if ( encoding() == 8 )
{ {
// On top of that, create a device that uncompresses the zlib data // On top of that, create a device that uncompresses the zli
QIODevice* filterDev = KFilterDev::device( limitedDev, "application b data
/x-gzip" ); QIODevice* filterDev = KFilterDev::device( limitedDev, "appl
if ( !filterDev ) ication/x-gzip" );
return 0L; // ouch if ( !filterDev )
static_cast<KFilterDev *>(filterDev)->setSkipHeaders(); // Just zli return 0L; // ouch
b, not gzip static_cast<KFilterDev *>(filterDev)->setSkipHeaders(); // J
bool b = filterDev->open( QIODevice::ReadOnly ); ust zlib, not gzip
bool b = filterDev->open( QIODevice::ReadOnly );
b = b; // annoying unused variable warning b = b; // annoying unused variable warning
Q_ASSERT( b ); Q_ASSERT( b );
return filterDev; return filterDev;
} }
qWarning() << "This zip file contains files compressed with method" qWarning() << "This zip file contains files compressed with method"
<< encoding() << ", this method is currently not supported by << encoding() << ", this method is currently not s
KZip," upported by KZip,"
<< "please use a command-line tool to handle this file."; << "please use a command-line tool to handle this
return 0L; file.";
return 0L;
} }
 End of changes. 114 change blocks. 
1020 lines changed or deleted 1072 lines changed or added

This html diff was produced by rfcdiff 1.41. The latest version is available from http://tools.ietf.org/tools/rfcdiff/