-rw-r--r-- | pwmanager/pwmanager/pwmdoc.cpp | 15 | ||||
-rw-r--r-- | pwmanager/pwmanager/pwmprefs.cpp | 1 | ||||
-rw-r--r-- | pwmanager/pwmanager/pwmprefs.h | 4 | ||||
-rw-r--r-- | pwmanager/pwmanager/pwmviewstyle.cpp | 32 | ||||
-rw-r--r-- | pwmanager/pwmanager/pwmviewstyle_0.cpp | 21 | ||||
-rw-r--r-- | pwmanager/pwmanager/pwmviewstyle_0.h | 6 | ||||
-rw-r--r-- | pwmanager/pwmanager/pwmviewstyle_1.cpp | 20 | ||||
-rw-r--r-- | pwmanager/pwmanager/pwmviewstyle_1.h | 5 | ||||
-rw-r--r-- | pwmanager/pwmanager/serializer.cpp | 34 |
9 files changed, 107 insertions, 31 deletions
diff --git a/pwmanager/pwmanager/pwmdoc.cpp b/pwmanager/pwmanager/pwmdoc.cpp index 9fe4809..c167c2c 100644 --- a/pwmanager/pwmanager/pwmdoc.cpp +++ b/pwmanager/pwmanager/pwmdoc.cpp @@ -1,563 +1,565 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 2.0 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmdoc.h" #include "pwmview.h" #include "blowfish.h" #include "sha1.h" #include "globalstuff.h" #include "gpasmanfile.h" #include "serializer.h" #include "compressgzip.h" #include "compressbzip2.h" #include "randomizer.h" #include "pwminit.h" #ifndef PWM_EMBEDDED //US #include "libgryptif.h" #else #include "pwmprefs.h" #include "kglobal.h" #endif #ifdef CONFIG_KWALLETIF # include "kwalletemu.h" #endif // CONFIG_KWALLETIF #include <qdatetime.h> #include <qsize.h> #include <qfileinfo.h> #include <qfile.h> +#define __USE_GNU +#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> -#include <iostream> +//US#include <iostream> #include <algorithm> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdint.h> //TODO: reset to its normal value. #define META_CHECK_TIMER_INTERVAL 10/*300*/ /* sek */ using namespace std; void PwMDocList::add(PwMDoc *doc, const string &id) { #ifdef PWM_DEBUG // check for existance of object in debug mode only. vector<listItem>::iterator begin = docList.begin(), end = docList.end(), i = begin; while (i != end) { if (i->doc == doc) { BUG(); return; } ++i; } #endif listItem newItem; newItem.doc = doc; newItem.docId = id; docList.push_back(newItem); } void PwMDocList::edit(PwMDoc *doc, const string &newId) { vector<listItem>::iterator begin = docList.begin(), end = docList.end(), i = begin; while (i != end) { if (i->doc == doc) { i->docId = newId; return; } ++i; } } void PwMDocList::del(PwMDoc *doc) { vector<listItem>::iterator begin = docList.begin(), end = docList.end(), i = begin; while (i != end) { if (i->doc == doc) { docList.erase(i); return; } ++i; } } bool PwMDocList::find(const string &id, listItem *ret) { vector<listItem>::iterator begin = docList.begin(), end = docList.end(), i = begin; while (i != end) { if (i->docId == id) { if (ret) *ret = *i; return true; } ++i; } return false; } DocTimer::DocTimer(PwMDoc *_doc) : doc (_doc) , mpwLock (0) , autoLockLock (0) , metaCheckLock (0) { mpwTimer = new QTimer; autoLockTimer = new QTimer; metaCheckTimer = new QTimer; connect(mpwTimer, SIGNAL(timeout()), this, SLOT(mpwTimeout())); connect(autoLockTimer, SIGNAL(timeout()), this, SLOT(autoLockTimeout())); connect(metaCheckTimer, SIGNAL(timeout()), this, SLOT(metaCheckTimeout())); } DocTimer::~DocTimer() { delete mpwTimer; delete autoLockTimer; delete metaCheckTimer; } void DocTimer::start(TimerIDs timer) { switch (timer) { case id_mpwTimer: if (mpwTimer->isActive()) mpwTimer->stop(); doc->setDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW); mpwTimer->start(conf()->confGlobPwTimeout() * 1000, true); break; case id_autoLockTimer: if (autoLockTimer->isActive()) autoLockTimer->stop(); if (conf()->confGlobLockTimeout() > 0) autoLockTimer->start(conf()->confGlobLockTimeout() * 1000, true); break; case id_metaCheckTimer: if (metaCheckTimer->isActive()) metaCheckTimer->stop(); metaCheckTimer->start(META_CHECK_TIMER_INTERVAL * 1000, true); break; } } void DocTimer::stop(TimerIDs timer) { switch (timer) { case id_mpwTimer: mpwTimer->stop(); break; case id_autoLockTimer: autoLockTimer->stop(); break; case id_metaCheckTimer: metaCheckTimer->stop(); break; } } void DocTimer::getLock(TimerIDs timer) { switch (timer) { case id_mpwTimer: ++mpwLock; break; case id_autoLockTimer: ++autoLockLock; break; case id_metaCheckTimer: ++metaCheckLock; break; } } void DocTimer::putLock(TimerIDs timer) { switch (timer) { case id_mpwTimer: if (mpwLock) --mpwLock; break; case id_autoLockTimer: if (autoLockLock) --autoLockLock; break; case id_metaCheckTimer: if (metaCheckLock) --metaCheckLock; break; } } void DocTimer::mpwTimeout() { if (mpwLock) { mpwTimer->start(1000, true); return; } doc->unsetDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW); } void DocTimer::autoLockTimeout() { if (autoLockLock) { autoLockTimer->start(1000, true); return; } if (conf()->confGlobAutoDeepLock() && doc->filename != QString::null && doc->filename != "") { doc->deepLock(true); } else { doc->lockAll(true); } } void DocTimer::metaCheckTimeout() { if (metaCheckLock) { // check again in one second. metaCheckTimer->start(1000, true); return; } if (doc->isDeepLocked()) { metaCheckTimer->start(META_CHECK_TIMER_INTERVAL * 1000, true); return; } if (doc->isDocEmpty()) { metaCheckTimer->start(META_CHECK_TIMER_INTERVAL * 1000, true); return; } #ifdef CONFIG_KWALLETIF KWalletEmu *kwlEmu = doc->init->kwalletEmu(); if (kwlEmu) kwlEmu->suspendDocSignals(); #endif // CONFIG_KWALLETIF /* We simply trigger all views to update their * displayed values. This way they have a chance * to get notified when some meta changes over time. * (for example an entry expired). * The _view_ is responsive for not updating its * contents if nothing really changed! */ emit doc->dataChanged(doc); #ifdef CONFIG_KWALLETIF if (kwlEmu) kwlEmu->resumeDocSignals(); #endif // CONFIG_KWALLETIF metaCheckTimer->start(META_CHECK_TIMER_INTERVAL * 1000, true); } PwMDocList PwMDoc::openDocList; unsigned int PwMDocList::unnamedDocCnt = 1; PwMDoc::PwMDoc(QObject *parent, const char *name) : PwMDocUi(parent, name) , dataChangedLock (0) { deleted = false; unnamedNum = 0; getOpenDocList()->add(this, getTitle().latin1()); curDocStat = 0; setMaxNumEntries(); _timer = new DocTimer(this); timer()->start(DocTimer::id_mpwTimer); timer()->start(DocTimer::id_autoLockTimer); timer()->start(DocTimer::id_metaCheckTimer); addCategory(DEFAULT_CATEGORY, 0, false); listView = 0; emit docCreated(this); } PwMDoc::~PwMDoc() { emit docClosed(this); getOpenDocList()->del(this); delete _timer; } PwMerror PwMDoc::saveDoc(char compress, const QString *file) { PwMerror ret, e; if (!file) { if (filename == "") return e_filename; } else { if (*file == "" && filename == "") return e_filename; if (*file != "") filename = *file; } bool wasDeepLocked = isDeepLocked(); if (wasDeepLocked) { if (deepLock(false) != e_success) return e_noPw; } if (!isPwAvailable()) { /* password is not available. This means, the * document wasn't saved, yet. */ bool useChipcard = getDocStatFlag(DOC_STAT_USE_CHIPCARD); QString pw(requestNewMpw(&useChipcard)); if (pw != "") { currentPw = pw; } else { return e_noPw; } if (useChipcard) { setDocStatFlag(DOC_STAT_USE_CHIPCARD); } else { unsetDocStatFlag(DOC_STAT_USE_CHIPCARD); } } #ifndef PWM_EMBEDDED int _cryptAlgo = conf()->confGlobCryptAlgo(); int _hashAlgo = conf()->confGlobHashAlgo(); #else int _cryptAlgo = PWM_CRYPT_BLOWFISH; int _hashAlgo = PWM_HASH_SHA1; #endif // sanity check for the selected algorithms if (_cryptAlgo < PWM_CRYPT_BLOWFISH || _cryptAlgo > PWM_CRYPT_TWOFISH128) { printWarn("Invalid Crypto-Algorithm selected! " "Config-file seems to be corrupt. " "Falling back to Blowfish."); _cryptAlgo = PWM_CRYPT_BLOWFISH; } if (_hashAlgo < PWM_HASH_SHA1 || _hashAlgo > PWM_HASH_TIGER) { printWarn("Invalid Hash-Algorithm selected! " "Config-file seems to be corrupt. " "Falling back to SHA1."); _hashAlgo = PWM_HASH_SHA1; } char cryptAlgo = static_cast<char>(_cryptAlgo); char hashAlgo = static_cast<char>(_hashAlgo); if (conf()->confGlobMakeFileBackup()) { if (!backupFile(filename)) return e_fileBackup; } QString tmpFileMoved(QString::null); if (QFile::exists(filename)) { /* Move the existing file to some tmp file. * When saving file succeeds, delete tmp file. Otherwise * move tmp file back. See below. */ Randomizer *rnd = Randomizer::obj(); char rnd_buf[5]; sprintf(rnd_buf, "%X%X%X%X", rnd->genRndChar() & 0xFF, rnd->genRndChar() & 0xFF, rnd->genRndChar() & 0xFF, rnd->genRndChar() & 0xFF); tmpFileMoved = filename + "." + rnd_buf + ".mv"; if (!copyFile(filename, tmpFileMoved)) return e_openFile; if (!QFile::remove(filename)) { printWarn(string("removing orig file ") + filename.latin1() + " failed!"); } } QFile f(filename); string serialized; if (!f.open(IO_ReadWrite)) { ret = e_openFile; goto out_moveback; } e = writeFileHeader(hashAlgo, hashAlgo, cryptAlgo, compress, ¤tPw, &f); if (e == e_hashNotImpl) { printDebug("PwMDoc::saveDoc(): writeFileHeader() failed: e_hashNotImpl"); f.close(); ret = e_hashNotImpl; goto out_moveback; } else if (e != e_success) { printDebug("PwMDoc::saveDoc(): writeFileHeader() failed"); f.close(); ret = e_writeHeader; goto out_moveback; } if (!serializeDta(&serialized)) { printDebug("PwMDoc::saveDoc(): serializeDta() failed"); f.close(); ret = e_serializeDta; goto out_moveback; } e = writeDataHash(hashAlgo, &serialized, &f); if (e == e_hashNotImpl) { printDebug("PwMDoc::saveDoc(): writeDataHash() failed: e_hashNotImpl"); f.close(); ret = e_hashNotImpl; goto out_moveback; } else if (e != e_success) { printDebug("PwMDoc::saveDoc(): writeDataHash() failed"); f.close(); ret = e_writeHeader; goto out_moveback; } if (!compressDta(&serialized, compress)) { printDebug("PwMDoc::saveDoc(): compressDta() failed"); f.close(); ret = e_enc; goto out_moveback; } e = encrypt(&serialized, ¤tPw, &f, cryptAlgo); if (e == e_weakPw) { printDebug("PwMDoc::saveDoc(): encrypt() failed: e_weakPw"); f.close(); ret = e_weakPw; goto out_moveback; } else if (e == e_cryptNotImpl) { printDebug("PwMDoc::saveDoc(): encrypt() failed: e_cryptNotImpl"); f.close(); ret = e_cryptNotImpl; goto out_moveback; } else if (e != e_success) { printDebug("PwMDoc::saveDoc(): encrypt() failed"); f.close(); ret = e_enc; goto out_moveback; } unsetDocStatFlag(DOC_STAT_DISK_DIRTY); f.close(); if (chmod(filename.latin1(), conf()->confGlobFilePermissions())) { printWarn(string("chmod failed: ") + strerror(errno)); } openDocList.edit(this, getTitle().latin1()); if (wasDeepLocked) deepLock(true); if (tmpFileMoved != QString::null) { // now remove the moved file. if (!QFile::remove(tmpFileMoved)) { printWarn(string("removing file ") + tmpFileMoved.latin1() + " failed!"); } } ret = e_success; printDebug(string("writing file { compress: ") + tostr(static_cast<int>(compress)) + " cryptAlgo: " + tostr(static_cast<int>(cryptAlgo)) + " hashAlgo: " + tostr(static_cast<int>(hashAlgo)) + " }"); goto out; out_moveback: if (tmpFileMoved != QString::null) { if (copyFile(tmpFileMoved, filename)) { if (!QFile::remove(tmpFileMoved)) { printWarn(string("removing tmp file ") + filename.latin1() + " failed!"); } } else { printWarn(string("couldn't copy file ") + tmpFileMoved.latin1() + " back to " + filename.latin1()); } } out: return ret; } PwMerror PwMDoc::openDoc(const QString *file, int openLocked) { PWM_ASSERT(file); PWM_ASSERT(openLocked == 0 || openLocked == 1 || openLocked == 2); string decrypted, dataHash; PwMerror ret; char cryptAlgo, dataHashType, compress; unsigned int headerLen; if (*file == "") return e_readFile; filename = *file; /* check if this file is already open. * This does not catch symlinks! */ if (!isDeepLocked()) { if (getOpenDocList()->find(filename.latin1())) return e_alreadyOpen; } QFile f(filename); if (openLocked == 2) { // open deep-locked if (!QFile::exists(filename)) return e_openFile; if (deepLock(true, false) != e_success) return e_openFile; goto out_success; } if (!f.open(IO_ReadOnly)) return e_openFile; ret = checkHeader(&cryptAlgo, ¤tPw, &compress, &headerLen, &dataHashType, &dataHash, &f); if (ret != e_success) { printDebug("PwMDoc::openDoc(): checkHeader() failed"); f.close(); if (ret == e_wrongPw) { wrongMpwMsgBox(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); return ret; } else if (ret == e_noPw || ret == e_fileVer || ret == e_fileFormat || ret == e_hashNotImpl) { return ret; } else return e_readFile; } ret = decrypt(&decrypted, headerLen, ¤tPw, cryptAlgo, &f); if (ret == e_cryptNotImpl) { printDebug("PwMDoc::openDoc(): decrypt() failed: e_cryptNotImpl"); f.close(); return e_cryptNotImpl; } else if (ret != e_success) { printDebug("PwMDoc::openDoc(): decrypt() failed"); f.close(); return e_readFile; } if (!decompressDta(&decrypted, compress)) { @@ -645,1032 +647,1043 @@ PwMerror PwMDoc::writeFileHeader(char keyHash, char dataHash, char crypt, char c #ifndef PWM_EMBEDDED case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *buf; size_t hashLen; err = gc.hash(&buf, &hashLen, reinterpret_cast<const unsigned char *>(pw->latin1()), pw->length(), keyHash); if (err != e_success) return e_hashNotImpl; if (f->writeBlock(reinterpret_cast<const char *>(buf), hashLen) != static_cast<Q_LONG>(hashLen)) { delete [] buf; return e_hashNotImpl; } delete [] buf; break; } #endif default: { return e_hashNotImpl; } } return e_success; } PwMerror PwMDoc::checkHeader(char *cryptAlgo, QString *pw, char *compress, unsigned int *headerLength, char *dataHashType, string *dataHash, QFile *f) { PWM_ASSERT(cryptAlgo); PWM_ASSERT(pw); PWM_ASSERT(headerLength); PWM_ASSERT(dataHashType); PWM_ASSERT(dataHash); PWM_ASSERT(f); int tmpRet; // check "magic" header const char magicHdr[] = FILE_ID_HEADER; const int hdrLen = array_size(magicHdr) - 1; char tmp[hdrLen]; if (f->readBlock(tmp, hdrLen) != hdrLen) return e_readFile; if (memcmp(tmp, magicHdr, hdrLen) != 0) return e_fileFormat; // read and check file ver int fileV = f->getch(); if (fileV == -1) return e_fileFormat; if (fileV != PWM_FILE_VER) return e_fileVer; // read hash hash type int keyHash = f->getch(); if (keyHash == -1) return e_fileFormat; // read data hash type tmpRet = f->getch(); if (tmpRet == -1) return e_fileFormat; *dataHashType = tmpRet; // read crypt algo tmpRet = f->getch(); if (tmpRet == -1) return e_fileFormat; *cryptAlgo = tmpRet; // get compression-algo tmpRet = f->getch(); if (tmpRet == -1) return e_fileFormat; *compress = tmpRet; // get the MPW-flag int mpw_flag = f->getch(); if (mpw_flag == -1) return e_fileFormat; if (mpw_flag == 0x01) setDocStatFlag(DOC_STAT_USE_CHIPCARD); else unsetDocStatFlag(DOC_STAT_USE_CHIPCARD); // skip the "RESERVED"-bytes if (!(f->at(f->at() + 64))) return e_fileFormat; *pw = requestMpw(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); if (*pw == "") { /* the user didn't give a master-password * or didn't insert a chipcard */ return e_noPw; } // verify key-hash switch (keyHash) { case PWM_HASH_SHA1: { // read hash from header const int hashLen = SHA1_HASH_LEN_BYTE; string readHash; int i; for (i = 0; i < hashLen; ++i) readHash.push_back(f->getch()); Sha1 hash; hash.sha1_write(reinterpret_cast<const byte *>(pw->latin1()), pw->length()); string ret = hash.sha1_read(); if (ret != readHash) return e_wrongPw; // hash doesn't match (wrong key) break; } #ifndef PWM_EMBEDDED case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *buf; size_t hashLen; err = gc.hash(&buf, &hashLen, reinterpret_cast<const unsigned char *>(pw->latin1()), pw->length(), keyHash); if (err != e_success) return e_hashNotImpl; string calcHash(reinterpret_cast<const char *>(buf), static_cast<string::size_type>(hashLen)); delete [] buf; // read hash from header string readHash; size_t i; for (i = 0; i < hashLen; ++i) readHash.push_back(f->getch()); if (calcHash != readHash) return e_wrongPw; // hash doesn't match (wrong key) break; } #endif default: { return e_hashNotImpl; } } // read the data-hash from the file unsigned int hashLen, i; switch (*dataHashType) { case PWM_HASH_SHA1: hashLen = SHA1_HASH_LEN_BYTE; break; #ifndef PWM_EMBEDDED case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; hashLen = gc.hashLength(*dataHashType); if (hashLen == 0) return e_hashNotImpl; break; } #endif default: return e_hashNotImpl; } *dataHash = ""; for (i = 0; i < hashLen; ++i) { tmpRet = f->getch(); if (tmpRet == -1) return e_fileFormat; dataHash->push_back(static_cast<char>(tmpRet)); } *headerLength = f->at(); #ifndef PWM_EMBEDDED printDebug(string("opening file { compress: ") + tostr(static_cast<int>(*compress)) + " cryptAlgo: " + tostr(static_cast<int>(*cryptAlgo)) + " keyHashAlgo: " + tostr(static_cast<int>(keyHash)) + " }"); #else printDebug(string("opening file { compress: ") + tostr((int)(*compress)) + " cryptAlgo: " + tostr((int)(*cryptAlgo)) + " keyHashAlgo: " + tostr((int)(keyHash)) + " }"); #endif return e_success; } PwMerror PwMDoc::writeDataHash(char dataHash, string *d, QFile *f) { PWM_ASSERT(d); PWM_ASSERT(f); switch (dataHash) { case PWM_HASH_SHA1: { const int hashLen = SHA1_HASH_LEN_BYTE; Sha1 h; h.sha1_write(reinterpret_cast<const byte *>(d->c_str()), d->size()); string hRet = h.sha1_read(); if (f->writeBlock(hRet.c_str(), hashLen) != hashLen) return e_writeFile; break; } #ifndef PWM_EMBEDDED case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *buf; size_t hashLen; err = gc.hash(&buf, &hashLen, reinterpret_cast<const unsigned char *>(d->c_str()), d->size(), dataHash); if (err != e_success) return e_hashNotImpl; if (f->writeBlock(reinterpret_cast<const char *>(buf), hashLen) != static_cast<Q_LONG>(hashLen)) { delete [] buf; return e_hashNotImpl; } delete [] buf; break; } #endif default: { return e_hashNotImpl; } } return e_success; } bool PwMDoc::backupFile(const QString &filePath) { QFileInfo fi(filePath); if (!fi.exists()) return true; // Yes, true is correct. QString pathOnly(fi.dirPath(true)); QString nameOnly(fi.fileName()); QString backupPath = pathOnly + "/~" + nameOnly + ".backup"; return copyFile(filePath, backupPath); } bool PwMDoc::copyFile(const QString &src, const QString &dst) { QFileInfo fi(src); if (!fi.exists()) return false; if (QFile::exists(dst)) { if (!QFile::remove(dst)) return false; } QFile srcFd(src); if (!srcFd.open(IO_ReadOnly)) return false; QFile dstFd(dst); if (!dstFd.open(IO_ReadWrite)) { srcFd.close(); return false; } const int tmpBuf_size = 512; char tmpBuf[tmpBuf_size]; #ifndef PWM_EMBEDDED Q_LONG bytesRead, bytesWritten; #else long bytesRead, bytesWritten; #endif while (!srcFd.atEnd()) { #ifndef PWM_EMBEDDED bytesRead = srcFd.readBlock(tmpBuf, static_cast<Q_ULONG>(tmpBuf_size)); #else bytesRead = srcFd.readBlock(tmpBuf, (unsigned long)(tmpBuf_size)); #endif if (bytesRead == -1) { srcFd.close(); dstFd.close(); return false; } #ifndef PWM_EMBEDDED bytesWritten = dstFd.writeBlock(tmpBuf, static_cast<Q_ULONG>(bytesRead)); #else bytesWritten = dstFd.writeBlock(tmpBuf, (unsigned long)(bytesRead)); #endif if (bytesWritten != bytesRead) { srcFd.close(); dstFd.close(); return false; } } srcFd.close(); dstFd.close(); return true; } PwMerror PwMDoc::addEntry(const QString &category, PwMDataItem *d, bool dontFlagDirty, bool updateMeta) { PWM_ASSERT(d); unsigned int cat = 0; if (isDeepLocked()) { PwMerror ret; ret = deepLock(false); if (ret != e_success) return e_lock; } addCategory(category, &cat); if (numEntries(category) >= maxEntries) return e_maxAllowedEntr; vector<unsigned int> foundPositions; /* historically this was: * const int searchIn = SEARCH_IN_DESC | SEARCH_IN_NAME | * SEARCH_IN_URL | SEARCH_IN_LAUNCHER; * But for now we only search in desc. * That's a tweak to be KWallet compatible. But it should not add * usability-drop onto PwManager, does it? * (And yes, "int" was a bug. Correct is "unsigned int") */ const unsigned int searchIn = SEARCH_IN_DESC; findEntry(cat, *d, searchIn, &foundPositions, true); if (foundPositions.size()) { // DOH! We found this entry. return e_entryExists; } d->listViewPos = -1; d->lockStat = conf()->confGlobNewEntrLockStat(); if (updateMeta) { d->meta.create = QDateTime::currentDateTime(); d->meta.update = d->meta.create; } dta[cat].d.push_back(*d); delAllEmptyCat(true); if (!dontFlagDirty) flagDirty(); return e_success; } PwMerror PwMDoc::addCategory(const QString &category, unsigned int *categoryIndex, bool checkIfExist) { if (isDeepLocked()) { PwMerror ret; ret = deepLock(false); if (ret != e_success) return e_lock; } if (checkIfExist) { if (findCategory(category, categoryIndex)) return e_categoryExists; } PwMCategoryItem item; item.name = category.latin1(); dta.push_back(item); if (categoryIndex) *categoryIndex = dta.size() - 1; return e_success; } bool PwMDoc::delEntry(const QString &category, unsigned int index, bool dontFlagDirty) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return false; } return delEntry(cat, index, dontFlagDirty); } bool PwMDoc::delEntry(unsigned int category, unsigned int index, bool dontFlagDirty) { if (isDeepLocked()) return false; if (index > dta[category].d.size() - 1) return false; getDataChangedLock(); if (!lockAt(category, index, false)) { putDataChangedLock(); return false; } putDataChangedLock(); int lvPos = dta[category].d[index].listViewPos; // delete entry dta[category].d.erase(dta[category].d.begin() + index); unsigned int i, entries = numEntries(category); if (!entries) { // no more entries in this category, so // we can delete it, too. BUG_ON(!delCategory(category)); // delCategory() flags it dirty, so we need not to do so. return true; } for (i = 0; i < entries; ++i) { // decrement all listViewPositions that are greater than the deleted. if (dta[category].d[i].listViewPos > lvPos) --dta[category].d[i].listViewPos; } if (!dontFlagDirty) flagDirty(); return true; } bool PwMDoc::editEntry(const QString &oldCategory, const QString &newCategory, unsigned int index, PwMDataItem *d, bool updateMeta) { PWM_ASSERT(d); unsigned int oldCat = 0; if (!findCategory(oldCategory, &oldCat)) { BUG(); return false; } return editEntry(oldCat, newCategory, index, d, updateMeta); } bool PwMDoc::editEntry(unsigned int oldCategory, const QString &newCategory, unsigned int index, PwMDataItem *d, bool updateMeta) { if (isDeepLocked()) return false; if (updateMeta) { d->meta.update = QDateTime::currentDateTime(); if (d->meta.create.isNull()) { d->meta.create = d->meta.update; } } if (dta[oldCategory].name != newCategory.latin1()) { // the user changed the category. PwMerror ret; d->rev = 0; ret = addEntry(newCategory, d, true, false); if (ret != e_success) return false; if (!delEntry(oldCategory, index, true)) return false; } else { d->rev = dta[oldCategory].d[index].rev + 1; // increment revision counter. dta[oldCategory].d[index] = *d; } flagDirty(); return true; } unsigned int PwMDoc::numEntries(const QString &category) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return 0; } return numEntries(cat); } bool PwMDoc::serializeDta(string *d) { PWM_ASSERT(d); Serializer ser; if (!ser.serialize(dta)) return false; d->assign(ser.getXml()); if (!d->size()) return false; return true; } bool PwMDoc::deSerializeDta(const string *d, bool entriesLocked) { PWM_ASSERT(d); +#ifndef PWM_EMBEDDED try { + Serializer ser(d->c_str()); ser.setDefaultLockStat(entriesLocked); if (!ser.deSerialize(&dta)) return false; } catch (PwMException) { return false; } +#else + Serializer ser(d->c_str()); + ser.setDefaultLockStat(entriesLocked); + if (!ser.deSerialize(&dta)) + return false; + else + return false; +#endif + emitDataChanged(this); return true; } bool PwMDoc::getEntry(const QString &category, unsigned int index, PwMDataItem * d, bool unlockIfLocked) { PWM_ASSERT(d); unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return false; } return getEntry(cat, index, d, unlockIfLocked); } bool PwMDoc::getEntry(unsigned int category, unsigned int index, PwMDataItem *d, bool unlockIfLocked) { if (index > dta[category].d.size() - 1) return false; bool locked = isLocked(category, index); if (locked) { /* this entry is locked. We don't return a password, * until it's unlocked by the user by inserting * chipcard or entering the mpw */ if (unlockIfLocked) { if (!lockAt(category, index, false)) { return false; } locked = false; } } *d = dta[category].d[index]; if (locked) d->pw = LOCKED_STRING.latin1(); return true; } PwMerror PwMDoc::getCommentByLvp(const QString &category, int listViewPos, string *foundComment) { PWM_ASSERT(foundComment); unsigned int cat = 0; if (!findCategory(category, &cat)) return e_invalidArg; unsigned int i, entries = numEntries(cat); for (i = 0; i < entries; ++i) { if (dta[cat].d[i].listViewPos == listViewPos) { *foundComment = dta[cat].d[i].comment; if (dta[cat].d[i].binary) return e_binEntry; return e_normalEntry; } } BUG(); return e_generic; } bool PwMDoc::compressDta(string *d, char algo) { PWM_ASSERT(d); switch (algo) { case PWM_COMPRESS_GZIP: { CompressGzip comp; return comp.compress(d); } case PWM_COMPRESS_BZIP2: { CompressBzip2 comp; return comp.compress(d); } case PWM_COMPRESS_NONE: { return true; } default: { BUG(); } } return false; } bool PwMDoc::decompressDta(string *d, char algo) { PWM_ASSERT(d); switch (algo) { case PWM_COMPRESS_GZIP: { CompressGzip comp; return comp.decompress(d); } case PWM_COMPRESS_BZIP2: { CompressBzip2 comp; return comp.decompress(d); } case PWM_COMPRESS_NONE: { return true; } } return false; } PwMerror PwMDoc::encrypt(string *d, const QString *pw, QFile *f, char algo) { PWM_ASSERT(d); PWM_ASSERT(pw); PWM_ASSERT(f); size_t encSize; byte *encrypted = 0; switch (algo) { case PWM_CRYPT_BLOWFISH: { Blowfish::padNull(d); encSize = d->length(); encrypted = new byte[encSize]; Blowfish bf; if (bf.bf_setkey((byte *) pw->latin1(), pw->length())) { delete [] encrypted; return e_weakPw; } bf.bf_encrypt((byte *) encrypted, (byte *) d->c_str(), encSize); break; } #ifndef PWM_EMBEDDED case PWM_CRYPT_AES128: /*... fall through */ case PWM_CRYPT_AES192: case PWM_CRYPT_AES256: case PWM_CRYPT_3DES: case PWM_CRYPT_TWOFISH: case PWM_CRYPT_TWOFISH128: { if (!LibGCryptIf::available()) return e_cryptNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *plain = new unsigned char[d->length() + 1024]; memcpy(plain, d->c_str(), d->length()); err = gc.encrypt(&encrypted, &encSize, plain, d->length(), reinterpret_cast<const unsigned char *>(pw->latin1()), pw->length(), algo); delete [] plain; if (err != e_success) return e_cryptNotImpl; break; } #endif default: { delete_ifnot_null_array(encrypted); return e_cryptNotImpl; } } // write encrypted data to file #ifndef PWM_EMBEDDED if (f->writeBlock(reinterpret_cast<const char *>(encrypted), static_cast<Q_ULONG>(encSize)) != static_cast<Q_LONG>(encSize)) { delete_ifnot_null_array(encrypted); return e_writeFile; } #else if (f->writeBlock((const char *)(encrypted), (unsigned long)(encSize)) != (long)(encSize)) { delete_ifnot_null_array(encrypted); return e_writeFile; } #endif delete_ifnot_null_array(encrypted); return e_success; } PwMerror PwMDoc::decrypt(string *d, unsigned int pos, const QString *pw, char algo, QFile *f) { PWM_ASSERT(d); PWM_ASSERT(pw); PWM_ASSERT(f); unsigned int cryptLen = f->size() - pos; byte *encrypted = new byte[cryptLen]; byte *decrypted = new byte[cryptLen]; f->at(pos); #ifndef PWM_EMBEDDED if (f->readBlock(reinterpret_cast<char *>(encrypted), static_cast<Q_ULONG>(cryptLen)) != static_cast<Q_LONG>(cryptLen)) { delete [] encrypted; delete [] decrypted; return e_readFile; } #else if (f->readBlock((char *)(encrypted), (unsigned long)(cryptLen)) != (long)(cryptLen)) { delete [] encrypted; delete [] decrypted; return e_readFile; } #endif switch (algo) { case PWM_CRYPT_BLOWFISH: { Blowfish bf; bf.bf_setkey((byte *) pw->latin1(), pw->length()); bf.bf_decrypt(decrypted, encrypted, cryptLen); break; } #ifndef PWM_EMBEDDED case PWM_CRYPT_AES128: /*... fall through */ case PWM_CRYPT_AES192: case PWM_CRYPT_AES256: case PWM_CRYPT_3DES: case PWM_CRYPT_TWOFISH: case PWM_CRYPT_TWOFISH128: { if (!LibGCryptIf::available()) return e_cryptNotImpl; LibGCryptIf gc; PwMerror err; err = gc.decrypt(&decrypted, &cryptLen, encrypted, cryptLen, reinterpret_cast<const unsigned char *>(pw->latin1()), pw->length(), algo); if (err != e_success) { delete [] encrypted; delete [] decrypted; return e_cryptNotImpl; } break; } #endif default: { delete [] encrypted; delete [] decrypted; return e_cryptNotImpl; } } delete [] encrypted; #ifndef PWM_EMBEDDED d->assign(reinterpret_cast<const char *>(decrypted), static_cast<string::size_type>(cryptLen)); #else d->assign((const char *)(decrypted), (string::size_type)(cryptLen)); #endif delete [] decrypted; if (algo == PWM_CRYPT_BLOWFISH) { if (!Blowfish::unpadNull(d)) { BUG(); return e_readFile; } } return e_success; } PwMerror PwMDoc::checkDataHash(char dataHashType, const string *dataHash, const string *dataStream) { PWM_ASSERT(dataHash); PWM_ASSERT(dataStream); switch(dataHashType) { case PWM_HASH_SHA1: { Sha1 hash; hash.sha1_write((byte*)dataStream->c_str(), dataStream->length()); string ret = hash.sha1_read(); if (ret != *dataHash) return e_fileCorrupt; break; } #ifndef PWM_EMBEDDED case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *buf; size_t hashLen; err = gc.hash(&buf, &hashLen, reinterpret_cast<const unsigned char *>(dataStream->c_str()), dataStream->length(), dataHashType); if (err != e_success) return e_hashNotImpl; string calcHash(reinterpret_cast<const char *>(buf), static_cast<string::size_type>(hashLen)); delete [] buf; if (calcHash != *dataHash) return e_fileCorrupt; break; } #endif default: return e_hashNotImpl; } return e_success; } bool PwMDoc::lockAt(unsigned int category, unsigned int index, bool lock) { if (index >= numEntries(category)) { BUG(); return false; } if (lock == dta[category].d[index].lockStat) return true; if (!lock && currentPw != "") { // "unlocking" and "password is already set" if (!getDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW)) { // unlocking without pw not allowed QString pw; pw = requestMpw(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); if (pw != "") { if (pw != currentPw) { wrongMpwMsgBox(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); return false; } else { timer()->start(DocTimer::id_mpwTimer); } } else { return false; } } else { timer()->start(DocTimer::id_mpwTimer); } } dta[category].d[index].lockStat = lock; dta[category].d[index].rev++; // increment revision counter. emitDataChanged(this); if (!lock) timer()->start(DocTimer::id_autoLockTimer); return true; } bool PwMDoc::lockAt(const QString &category,unsigned int index, bool lock) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return false; } return lockAt(cat, index, lock); } bool PwMDoc::lockAll(bool lock) { if (!lock && isDeepLocked()) { PwMerror ret; ret = deepLock(false); if (ret != e_success) return false; return true; } if (isDocEmpty()) { return true; } if (!lock && currentPw != "") { // unlocking and password is already set if (!getDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW)) { // unlocking without pw not allowed QString pw; pw = requestMpw(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); if (pw != "") { if (pw != currentPw) { wrongMpwMsgBox(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); return false; } else { timer()->start(DocTimer::id_mpwTimer); } } else { return false; } } else { timer()->start(DocTimer::id_mpwTimer); } } vector<PwMCategoryItem>::iterator catBegin = dta.begin(), catEnd = dta.end(), catI = catBegin; vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; while (catI != catEnd) { entrBegin = catI->d.begin(); entrEnd = catI->d.end(); entrI = entrBegin; while (entrI != entrEnd) { entrI->lockStat = lock; entrI->rev++; // increment revision counter. ++entrI; } ++catI; } emitDataChanged(this); if (lock) timer()->stop(DocTimer::id_autoLockTimer); else timer()->start(DocTimer::id_autoLockTimer); return true; } bool PwMDoc::isLocked(const QString &category, unsigned int index) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return false; } return isLocked(cat, index); } bool PwMDoc::unlockAll_tempoary(bool revert) { static vector< vector<bool> > *oldLockStates = 0; static bool wasDeepLocked; if (revert) { // revert the unlocking if (oldLockStates) { /* we actually _have_ unlocked something, because * we have allocated space for the oldLockStates. * So, go on and revert them! */ if (wasDeepLocked) { PwMerror ret = deepLock(true); if (ret == e_success) { /* deep-lock succeed. We are save. * (but if it failed, just go on * lock them normally) */ delete_and_null(oldLockStates); timer()->start(DocTimer::id_autoLockTimer); printDebug("tempoary unlocking of dta " "reverted by deep-locking."); return true; } printDebug("deep-lock failed while reverting! " "Falling back to normal-lock."); } if (unlikely(!wasDeepLocked && numCategories() != oldLockStates->size())) { /* DOH! We have modified "dta" while * it was unlocked tempoary. DON'T DO THIS! */ BUG(); delete_and_null(oldLockStates); timer()->start(DocTimer::id_autoLockTimer); return false; } vector<PwMCategoryItem>::iterator catBegin = dta.begin(), catEnd = dta.end(), catI = catBegin; vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; vector< vector<bool> >::iterator oldCatStatI = oldLockStates->begin(); vector<bool>::iterator oldEntrStatBegin, oldEntrStatEnd, oldEntrStatI; while (catI != catEnd) { entrBegin = catI->d.begin(); entrEnd = catI->d.end(); entrI = entrBegin; if (likely(!wasDeepLocked)) { oldEntrStatBegin = oldCatStatI->begin(); oldEntrStatEnd = oldCatStatI->end(); oldEntrStatI = oldEntrStatBegin; if (unlikely(catI->d.size() != oldCatStatI->size())) { /* DOH! We have modified "dta" while * it was unlocked tempoary. DON'T DO THIS! */ BUG(); delete_and_null(oldLockStates); timer()->start(DocTimer::id_autoLockTimer); return false; } } while (entrI != entrEnd) { if (wasDeepLocked) { /* this is an error-fallback if * deeplock didn't succeed */ entrI->lockStat = true; } else { entrI->lockStat = *oldEntrStatI; } ++entrI; if (likely(!wasDeepLocked)) ++oldEntrStatI; diff --git a/pwmanager/pwmanager/pwmprefs.cpp b/pwmanager/pwmanager/pwmprefs.cpp index 5779ecc..d3847f6 100644 --- a/pwmanager/pwmanager/pwmprefs.cpp +++ b/pwmanager/pwmanager/pwmprefs.cpp @@ -1,299 +1,300 @@ /* This file is part of PwManager/Pi Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #include <kconfig.h> #include <klocale.h> #include <kstaticdeleter.h> #include "pwmprefs.h" PWMPrefs *PWMPrefs::sInstance = 0; static KStaticDeleter<PWMPrefs> staticDeleter; PWMPrefs::PWMPrefs() : KPimPrefs("pwmanagerrc") { KPrefs::setCurrentGroup( "Global" ); addItemString( "autoStart", &mAutoStart, "" ); addItemString( "browserCommand", &mBrowserCommand, "" ); addItemString( "xtermCommand", &mXTermCommand, CONF_DEFAULT_XTERMCOMMAND); addItemFont( "entryFont", &mEntryFont); addItemInt( "pwTimeout", &mPwTimeout, CONF_DEFAULT_PWTIMEOUT ); addItemInt( "lockTimeout", &mLockTimeout, CONF_DEFAULT_LOCKTIMEOUT ); addItemInt( "compression", &mCompression, CONF_DEFAULT_COMPRESSION ); addItemInt( "filePermissions", &mFilePermissions, CONF_DEFAULT_FILEPERMISSIONS ); addItemInt( "minimizeLock", &mMinimizeLock, CONF_DEFAULT_MINIMIZELOCK ); addItemBool( "unlockOnOpen", &mUnlockOnOpen, CONF_DEFAULT_UNLOCKONOPEN ); addItemBool( "tray", &mTray, CONF_DEFAULT_TRAY ); addItemBool( "makeFileBackup", &mMakeFileBackup, CONF_DEFAULT_MAKEFILEBACKUP ); addItemBool( "autostartDeepLocked", &mAutostartDeeplocked, CONF_DEFAULT_AUTOSTART_DEEPL ); addItemBool( "autoDeepLock", &mAutoDeeplock, CONF_DEFAULT_AUTODEEPLOCK ); addItemBool( "kwalletEmu", &mKWalletEmu, CONF_DEFAULT_KWALLETEMU ); addItemBool( "newEntrLockStat", &mNewEntrLockStat, CONF_DEFAULT_NEWENTRLOCKSTAT ); KPrefs::setCurrentGroup( "Wnd" ); addItemSize( "MainWndSize", &mMainWndSize); addItemInt( "MainViewStyle", &mMainViewStyle, CONF_DEFAULT_MAINVIEWSTYLE ); addItemBool( "autoMinimizeOnStart", &mAutoMinimizeOnStart, CONF_DEFAULT_AUTOMINIMIZE ); addItemBool( "close", &mClose, CONF_DEFAULT_WNDCLOSE ); + addItemIntList( "CommentSplitter", &mCommentSplitter ); } PWMPrefs::~PWMPrefs() { } PWMPrefs *PWMPrefs::instance() { if ( !sInstance ) { #ifdef PWM_EMBEDDED sInstance = staticDeleter.setObject( new PWMPrefs() ); #else //PWM_EMBEDDED //US the following line has changed ???. Why staticDeleter.setObject( sInstance, new PWMPrefs() ); #endif //KAB_EMBEDDED sInstance->readConfig(); } return sInstance; } // US introduce a nonconst way to return the config object. KConfig* PWMPrefs::getConfig() { return config(); } /******************************************************************* * functions for reading the configuration settings *******************************************************************/ QString PWMPrefs::confGlobAutoStart() { return mAutoStart; } QString PWMPrefs::confGlobBrowserCommand() { return mBrowserCommand; } QString PWMPrefs::confGlobXtermCommand() { return mXTermCommand; } QFont PWMPrefs::confGlobEntryFont() { return mEntryFont; } int PWMPrefs::confGlobPwTimeout() { return mPwTimeout; } int PWMPrefs::confGlobLockTimeout() { return mLockTimeout; } int PWMPrefs::confGlobCompression() { return mCompression; } int PWMPrefs::confGlobFilePermissions() { return mFilePermissions; } int PWMPrefs::confGlobMinimizeLock() { return mMinimizeLock; } bool PWMPrefs::confGlobUnlockOnOpen() { return mUnlockOnOpen; } bool PWMPrefs::confGlobTray() { return mTray; } bool PWMPrefs::confGlobMakeFileBackup() { return mMakeFileBackup; } bool PWMPrefs::confGlobAutostartDeepLocked() { return mAutostartDeeplocked; } bool PWMPrefs::confGlobAutoDeepLock() { return mAutoDeeplock; } bool PWMPrefs::confGlobKwalletEmu() { return mKWalletEmu; } bool PWMPrefs::confGlobNewEntrLockStat() { return mNewEntrLockStat; } QSize PWMPrefs::confWndMainWndSize() { return mMainWndSize; } int PWMPrefs::confWndMainViewStyle() { return mMainViewStyle; } bool PWMPrefs::confWndAutoMinimizeOnStart() { return mAutoMinimizeOnStart; } bool PWMPrefs::confWndClose() { return mClose; } /******************************************************************* * functions for writing the configuration settings *******************************************************************/ void PWMPrefs::confGlobAutoStart(const QString &e) { mAutoStart = e; } void PWMPrefs::confGlobBrowserCommand(const QString &e) { mBrowserCommand = e; } void PWMPrefs::confGlobXtermCommand(const QString &e) { mXTermCommand = e; } void PWMPrefs::confGlobEntryFont(const QFont &e) { mEntryFont = e; } void PWMPrefs::confGlobPwTimeout(int e) { mPwTimeout = e; } void PWMPrefs::confGlobLockTimeout(int e) { mLockTimeout = e; } void PWMPrefs::confGlobCompression(int e) { mCompression = e; } void PWMPrefs::confGlobFilePermissions(int e) { mFilePermissions = e; } void PWMPrefs::confGlobMinimizeLock(int e) { mMinimizeLock = e; } void PWMPrefs::confGlobUnlockOnOpen(bool e) { mUnlockOnOpen = e; } void PWMPrefs::confGlobTray(bool e) { mTray = e; } void PWMPrefs::confGlobMakeFileBackup(bool e) { mMakeFileBackup = e; } void PWMPrefs::confGlobAutostartDeepLocked(bool e) { mAutostartDeeplocked = e; } void PWMPrefs::confGlobAutoDeepLock(bool e) { mAutoDeeplock = e; } void PWMPrefs::confGlobKwalletEmu(bool e) { mKWalletEmu = e; } void PWMPrefs::confGlobNewEntrLockStat(bool e) { mNewEntrLockStat = e; } void PWMPrefs::confWndMainWndSize(const QSize &e) { mMainWndSize = e; } void PWMPrefs::confWndMainViewStyle(int e) { mMainViewStyle = e; } void PWMPrefs::confWndAutoMinimizeOnStart(bool e) { mAutoMinimizeOnStart = e; } void PWMPrefs::confWndClose(bool e) { mClose = e; } diff --git a/pwmanager/pwmanager/pwmprefs.h b/pwmanager/pwmanager/pwmprefs.h index bf7d8b1..6a89d10 100644 --- a/pwmanager/pwmanager/pwmprefs.h +++ b/pwmanager/pwmanager/pwmprefs.h @@ -1,146 +1,150 @@ /* This file is part of PwManager/Pi Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #ifndef PWMPREFS_H #define PWMPREFS_H #include <qstringlist.h> #include <qsize.h> #include <kpimprefs.h> class KConfig; #define conf() PWMPrefs::instance() #define CONF_DEFAULT_PWTIMEOUT 10 /* 10 sec */ #define CONF_DEFAULT_LOCKTIMEOUT 0 /* 0 == disable */ #define CONF_DEFAULT_TRAY true #define CONF_DEFAULT_UNLOCKONOPEN false #define CONF_DEFAULT_MAINVIEWSTYLE 0 #define CONF_DEFAULT_COMPRESSION 0x01 /* gzip */ #define CONF_DEFAULT_AUTOMINIMIZE false #define CONF_DEFAULT_BROWSERCOMMAND "" #define CONF_DEFAULT_XTERMCOMMAND "konsole -e" #define CONF_DEFAULT_FILEPERMISSIONS 0600 #define CONF_DEFAULT_MAKEFILEBACKUP false #define CONF_DEFAULT_AUTOSTART_DEEPL true #define CONF_DEFAULT_AUTODEEPLOCK true #define CONF_DEFAULT_KWALLETEMU true #define CONF_DEFAULT_MINIMIZELOCK 2 /* deep-lock */ #define CONF_DEFAULT_NEWENTRLOCKSTAT true /* locked */ #define CONF_DEFAULT_WNDCLOSE true /* don't minimize to tray */ class PWMPrefs : public KPimPrefs { public: virtual ~PWMPrefs(); static PWMPrefs *instance(); public: /* functions for reading the configuration settings */ /* GLOBAL */ QString confGlobAutoStart(); QString confGlobBrowserCommand(); QString confGlobXtermCommand(); QFont confGlobEntryFont(); int confGlobPwTimeout(); int confGlobLockTimeout(); int confGlobCompression(); int confGlobFilePermissions(); int confGlobMinimizeLock(); bool confGlobUnlockOnOpen(); bool confGlobTray(); bool confGlobMakeFileBackup(); bool confGlobAutostartDeepLocked(); bool confGlobAutoDeepLock(); bool confGlobKwalletEmu(); bool confGlobNewEntrLockStat(); /* WND */ QSize confWndMainWndSize(); int confWndMainViewStyle(); bool confWndAutoMinimizeOnStart(); bool confWndClose(); public: /* functions for writing the configuration settings */ /* GLOBAL */ void confGlobAutoStart(const QString &e); void confGlobBrowserCommand(const QString &e); void confGlobXtermCommand(const QString &e); void confGlobEntryFont(const QFont &e); void confGlobPwTimeout(int e); void confGlobLockTimeout(int e); void confGlobCompression(int e); void confGlobFilePermissions(int e); void confGlobMinimizeLock(int e); void confGlobUnlockOnOpen(bool e); void confGlobTray(bool e); void confGlobMakeFileBackup(bool e); void confGlobAutostartDeepLocked(bool e); void confGlobAutoDeepLock(bool e); void confGlobKwalletEmu(bool e); void confGlobNewEntrLockStat(bool e); /* WND */ void confWndMainWndSize(const QSize &e); void confWndMainViewStyle(int e); void confWndAutoMinimizeOnStart(bool e); void confWndClose(bool e); QString mAutoStart; QString mBrowserCommand; QString mXTermCommand; QFont mEntryFont; int mPwTimeout; int mLockTimeout; int mCompression; int mFilePermissions; int mMinimizeLock; bool mUnlockOnOpen; bool mTray; bool mMakeFileBackup; bool mAutostartDeeplocked; bool mAutoDeeplock; bool mKWalletEmu; bool mNewEntrLockStat; QSize mMainWndSize; int mMainViewStyle; bool mAutoMinimizeOnStart; bool mClose; + //US ENH + QValueList<int> mCommentSplitter; + + // US introduce a nonconst way to return the config object. KConfig* getConfig(); private: PWMPrefs(); static PWMPrefs *sInstance; }; #endif diff --git a/pwmanager/pwmanager/pwmviewstyle.cpp b/pwmanager/pwmanager/pwmviewstyle.cpp index 51d8f6c..9704615 100644 --- a/pwmanager/pwmanager/pwmviewstyle.cpp +++ b/pwmanager/pwmanager/pwmviewstyle.cpp @@ -1,217 +1,239 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmviewstyle.h" #include "pwmexception.h" #include "pwmviewstyle_0.h" #include "pwmviewstyle_1.h" #include "listviewpwm.h" #include "pwmview.h" #include "commentbox.h" #ifndef PWM_EMBEDDED #include "configuration.h" #else #include "pwmprefs.h" #endif PwMViewStyle::PwMViewStyle(QWidget *parent, const char *name) : QWidget(parent, name) { curStyle = style_notset; s0 = 0; s1 = 0; } PwMViewStyle::~PwMViewStyle() { - //US ENH : load and store the size of the listviewcolumns - lv->saveLayout(conf()->getConfig(), "listview"); - conf()->getConfig()->sync(); + //US ENH : store the size of the listviewcolumns + switch (curStyle) + { + case style_0: + s0->saveSettings(PWMPrefs::instance()); + break; + case style_1: + s1->saveSettings(PWMPrefs::instance()); + break; + default: + BUG(); + } + + + PWMPrefs::instance()->getConfig()->sync(); delete_ifnot_null(s0); delete_ifnot_null(s1); } void PwMViewStyle::initStyle(style_t style) { printDebug(string("initializing style ") + tostr(style)); bool wasMaximized = v->isMaximized(); if (v->isVisible()) v->hide(); switch (style) { case style_0: delete_ifnot_null(s0); delete_ifnot_null(s1); s0 = new PwMViewStyle_0(v); lv = s0->getLv(); commentBox = s0->getCommentBox(); break; case style_1: delete_ifnot_null(s0); delete_ifnot_null(s1); s1 = new PwMViewStyle_1(v); lv = s1->getLv(); commentBox = s1->getCommentBox(); break; default: BUG(); return; } curStyle = style; connect(lv, SIGNAL(pressed(QListViewItem *)), v, SLOT(handleToggle(QListViewItem *))); connect(lv, SIGNAL(rightButtonClicked(QListViewItem *, const QPoint &, int)), v, SLOT(handleRightClick(QListViewItem *, const QPoint &, int))); connect(lv, SIGNAL(clicked(QListViewItem *)), v, SLOT(refreshCommentTextEdit(QListViewItem *))); lv->addColumn(i18n("Description"), 180); lv->addColumn(i18n("Username"), 150); lv->addColumn(i18n("Password"), 150); lv->addColumn(i18n("URL"), 180); lv->addColumn(i18n("Launcher"), 120); v->tmpReEnableSort(); - //US ENH : load and store the size of the listviewcolumns - lv->restoreLayout(conf()->getConfig(), "listview"); + //US ENH : load the size of the listviewcolumns + switch (style) + { + case style_0: + s0->restoreSettings(PWMPrefs::instance()); + break; + case style_1: + s1->restoreSettings(PWMPrefs::instance()); + break; + default: + BUG(); + } resizeView(v->size()); v->updateView(); if (wasMaximized) { v->showMaximized(); } else { v->show(); } connect(lv, SIGNAL(layoutChanged()), v, SLOT(reorgLp())); } void PwMViewStyle::resizeView(const QSize &size) { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->resize(size); return; case style_1: PWM_ASSERT(s1); s1->resize(size); return; default: BUG(); } } QString PwMViewStyle::getCurrentCategory() { switch (curStyle) { case style_0: PWM_ASSERT(s0); return s0->getCurrentCategory(); case style_1: PWM_ASSERT(s1); return s1->getCurrentCategory(); default: BUG(); } return ""; } void PwMViewStyle::addCategory(const QString &cat) { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->addCategory(cat); return; case style_1: PWM_ASSERT(s1); s1->addCategory(cat); return; default: BUG(); } } void PwMViewStyle::delCategory(const QString &cat) { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->delCategory(cat); return; case style_1: PWM_ASSERT(s1); s1->delCategory(cat); return; default: BUG(); } } void PwMViewStyle::delAllCategories() { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->delAllCategories(); return; case style_1: PWM_ASSERT(s1); s1->delAllCategories(); return; default: BUG(); } } void PwMViewStyle::selectCategory(const QString &cat) { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->selectCategory(cat); return; case style_1: PWM_ASSERT(s1); s1->selectCategory(cat); return; default: BUG(); } } int PwMViewStyle::numCategories() { switch (curStyle) { case style_0: PWM_ASSERT(s0); return s0->numCategories(); case style_1: PWM_ASSERT(s1); return s1->numCategories(); default: BUG(); } return 0; } #ifndef PWM_EMBEDDED #include "pwmviewstyle.moc" #endif diff --git a/pwmanager/pwmanager/pwmviewstyle_0.cpp b/pwmanager/pwmanager/pwmviewstyle_0.cpp index 6d46ac6..7262684 100644 --- a/pwmanager/pwmanager/pwmviewstyle_0.cpp +++ b/pwmanager/pwmanager/pwmviewstyle_0.cpp @@ -1,93 +1,112 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmviewstyle_0.h" #include "pwmview.h" #include "listviewpwm.h" #include "commentbox.h" #include <klocale.h> - +#include "pwmprefs.h" PwMViewStyle_0::PwMViewStyle_0(PwMView *view) : QObject() { vbox1 = new QVBox(view); vbox1->setSpacing(3); hbox1 = new QHBox(vbox1); hbox1->setSpacing(10); categoriesTitle = new QLabel(hbox1); categoriesTitle->setText(i18n("Categories:")); categoriesCombo = new QComboBox(hbox1); renCatButton = new QPushButton(i18n("&Rename"), hbox1); delCatButton = new QPushButton(i18n("&Delete"), hbox1); #ifndef PWM_EMBEDDED splitter1 = new QSplitter(vbox1); splitter1->setOrientation(Qt::Vertical); #else splitter1 = new KDGanttMinimizeSplitter( Qt::Vertical, vbox1); splitter1->setMinimizeDirection ( KDGanttMinimizeSplitter::Up ); //US topLayout->addWidget(mMiniSplitter ); #endif lv = new ListViewPwM(splitter1); commentBox = new CommentBox(splitter1); // set sizes and styles commentBox->resize(commentBox->size().width(), 60); categoriesTitle->setAlignment(Qt::AlignVCenter | Qt::AlignRight); // connections connect(categoriesCombo, SIGNAL(activated(int)), view, SLOT(shiftToView())); connect(renCatButton, SIGNAL(clicked()), view, SLOT(renCatButton_slot())); connect(delCatButton, SIGNAL(clicked()), view, SLOT(delCatButton_slot())); } PwMViewStyle_0::~PwMViewStyle_0() { delete vbox1; } void PwMViewStyle_0::delCategory(const QString &cat) { PWM_ASSERT(categoriesCombo); int i, count = categoriesCombo->count(); for (i = 0; i < count; ++i) { if (categoriesCombo->text(i) == cat) { categoriesCombo->removeItem(i); return; } } BUG(); } void PwMViewStyle_0::selectCategory(const QString &cat) { PWM_ASSERT(categoriesCombo); int i, count = categoriesCombo->count(); for (i = 0; i < count; ++i) { if (categoriesCombo->text(i) == cat) { categoriesCombo->setCurrentItem(i); return; } } // fall back to 0 categoriesCombo->setCurrentItem(0); } + + +//US ENH: I need a place to load the view dependend settings. Eg. splittersize +void PwMViewStyle_0::restoreSettings(PWMPrefs* prefs) +{ + //load and store the size of the listviewcolumns + lv->restoreLayout(prefs->getConfig(), "listview"); + splitter1->setSizes( prefs->mCommentSplitter ); + +} + +//US ENH: I need a place to load the view dependend settings. Eg. splittersize +void PwMViewStyle_0::saveSettings(PWMPrefs* prefs) +{ + //store the size of the listviewcolumns + lv->saveLayout(prefs->getConfig(), "listview"); + prefs->mCommentSplitter = splitter1->sizes(); + +} diff --git a/pwmanager/pwmanager/pwmviewstyle_0.h b/pwmanager/pwmanager/pwmviewstyle_0.h index cc564c3..bd93c06 100644 --- a/pwmanager/pwmanager/pwmviewstyle_0.h +++ b/pwmanager/pwmanager/pwmviewstyle_0.h @@ -1,99 +1,105 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef PWMVIEWSTYLE_0_H #define PWMVIEWSTYLE_0_H #include <qhbox.h> #include <qvbox.h> #include <qpushbutton.h> #ifndef PWM_EMBEDDED #include <qtextedit.h> #include <qsplitter.h> #else #include <qmultilineedit.h> #include <KDGanttMinimizeSplitter.h> #endif #include <qlabel.h> #include <qcombobox.h> class PwMView; class ListViewPwM; class CommentBox; +class PWMPrefs; class PwMViewStyle_0 : public QObject { public: PwMViewStyle_0(PwMView *view); ~PwMViewStyle_0(); ListViewPwM * getLv() { return lv; } CommentBox * getCommentBox() { return commentBox; } /** returns the currently selected category */ QString getCurrentCategory() { return categoriesCombo->currentText(); } /** add Category to the view */ void addCategory(const QString &cat) { categoriesCombo->insertItem(cat); } /** delete Category from view */ void delCategory(const QString &cat); /** delete all categories from view */ void delAllCategories() { categoriesCombo->clear(); } /** select the specified category */ void selectCategory(const QString &cat); /** returns the number of categories in this view. * This value dosn't say anything about the number of * categories in the document. */ int numCategories() { return categoriesCombo->count(); } /** resize the view */ void resize(const QSize &size) { vbox1->resize(size); } + //US ENH: I need a place to load the view dependend settings. Eg. splittersize + void restoreSettings(PWMPrefs* prefs); + void saveSettings(PWMPrefs* prefs); + + protected: /** main list view */ ListViewPwM *lv; /** categories combo-box */ QComboBox *categoriesCombo; /** title string for the categories combo or list box */ QLabel *categoriesTitle; /** hbox1 for widget style */ QHBox *hbox1; /** vbox1 for widget style */ QVBox *vbox1; /** splitter for commentTextEdit */ #ifndef PWM_EMBEDDED QSplitter *splitter1; #else KDGanttMinimizeSplitter * splitter1; #endif /** push button to change the category name */ QPushButton *renCatButton; /** push button to delete the category */ QPushButton *delCatButton; /** comment box */ CommentBox *commentBox; }; #endif diff --git a/pwmanager/pwmanager/pwmviewstyle_1.cpp b/pwmanager/pwmanager/pwmviewstyle_1.cpp index 4c24bc4..8b2d6d3 100644 --- a/pwmanager/pwmanager/pwmviewstyle_1.cpp +++ b/pwmanager/pwmanager/pwmviewstyle_1.cpp @@ -1,130 +1,150 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmviewstyle_1.h" #include "pwmview.h" #include "listviewpwm.h" #include "commentbox.h" #include <klocale.h> +#include "pwmprefs.h" #define INITIAL_CATEGORIES_WIDTH 100 PwMViewStyle_1::PwMViewStyle_1(PwMView *view) : QObject() { #ifndef PWM_EMBEDDED splitter = new QSplitter(view); #else splitter = new KDGanttMinimizeSplitter( Qt::Horizontal, view); splitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Right ); //US topLayout->addWidget(mMiniSplitter ); #endif vbox1 = new QVBox(splitter); categoriesTitle = new QLabel(vbox1); categoriesList = new QListBox(vbox1); #ifndef PWM_EMBEDDED splitter2 = new QSplitter(splitter); splitter2->setOrientation(Qt::Vertical); #else splitter2 = new KDGanttMinimizeSplitter( Qt::Vertical, splitter); splitter2->setMinimizeDirection ( KDGanttMinimizeSplitter::Right ); //US topLayout->addWidget(mMiniSplitter ); #endif lv = new ListViewPwM(splitter2); commentBox = new CommentBox(splitter2); // set sizes and styles commentBox->resize(commentBox->size().width(), 60); QValueList<int> sizes; #ifndef PWM_EMBEDDED sizes.push_back(INITIAL_CATEGORIES_WIDTH); sizes.push_back(view->height() - INITIAL_CATEGORIES_WIDTH); #else sizes.append(INITIAL_CATEGORIES_WIDTH); sizes.append(view->height() - INITIAL_CATEGORIES_WIDTH); #endif splitter->setSizes(sizes); categoriesTitle->setAlignment(Qt::AlignHCenter); #ifndef PWM_EMBEDDED categoriesTitle->setFrameShape(QFrame::MenuBarPanel); #else categoriesTitle->setFrameShape(QFrame::StyledPanel); #endif categoriesTitle->setText(i18n("Categories:")); catCtxMenu = new QPopupMenu(view); catCtxMenu->insertItem(i18n("&Rename"), view, SLOT(renCatButton_slot())); catCtxMenu->insertItem(i18n("&Delete"), view, SLOT(delCatButton_slot())); // connections connect(categoriesList, SIGNAL(highlighted(int)), view, SLOT(shiftToView())); connect(categoriesList, SIGNAL(rightButtonClicked(QListBoxItem *, const QPoint &)), this, SLOT(catRightClick(QListBoxItem *, const QPoint &))); } PwMViewStyle_1::~PwMViewStyle_1() { delete catCtxMenu; delete splitter; } void PwMViewStyle_1::catRightClick(QListBoxItem *item, const QPoint &point) { if (!item) return; catCtxMenu->move(point); catCtxMenu->show(); } void PwMViewStyle_1::delCategory(const QString &cat) { PWM_ASSERT(categoriesList); int i, count = categoriesList->count(); for (i = 0; i < count; ++i) { if (categoriesList->text(i) == cat) { categoriesList->removeItem(i); return; } } BUG(); } void PwMViewStyle_1::selectCategory(const QString &cat) { PWM_ASSERT(categoriesList); int i, count = categoriesList->count(); for (i = 0; i < count; ++i) { if (categoriesList->text(i) == cat) { categoriesList->setCurrentItem(i); return; } } // fall back to 0 categoriesList->setCurrentItem(0); } +//US ENH: I need a place to load the view dependend settings. Eg. splittersize +void PwMViewStyle_1::restoreSettings(PWMPrefs* prefs) +{ + //load and store the size of the listviewcolumns + lv->restoreLayout(prefs->getConfig(), "listview"); + splitter2->setSizes( prefs->mCommentSplitter ); + +} + +//US ENH: I need a place to load the view dependend settings. Eg. splittersize +void PwMViewStyle_1::saveSettings(PWMPrefs* prefs) +{ + //store the size of the listviewcolumns + lv->saveLayout(prefs->getConfig(), "listview"); + prefs->mCommentSplitter = splitter2->sizes(); + +} + + #ifndef PWM_EMBEDDED #include "pwmviewstyle_1.moc" #endif diff --git a/pwmanager/pwmanager/pwmviewstyle_1.h b/pwmanager/pwmanager/pwmviewstyle_1.h index a50f587..a7f100c 100644 --- a/pwmanager/pwmanager/pwmviewstyle_1.h +++ b/pwmanager/pwmanager/pwmviewstyle_1.h @@ -1,107 +1,112 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef PWMVIEWSTYLE_1_H #define PWMVIEWSTYLE_1_H #include <qvbox.h> #ifndef PWM_EMBEDDED #include <qtextedit.h> #include <qsplitter.h> #else #include <qmultilineedit.h> #include <KDGanttMinimizeSplitter.h> #endif #include <qlabel.h> #include <qlistbox.h> #include <qpopupmenu.h> class PwMView; class ListViewPwM; class CommentBox; +class PWMPrefs; class PwMViewStyle_1 : public QObject { Q_OBJECT public: PwMViewStyle_1(PwMView *view); ~PwMViewStyle_1(); ListViewPwM * getLv() { return lv; } CommentBox * getCommentBox() { return commentBox; } /** returns the currently selected category */ QString getCurrentCategory() { return categoriesList->currentText(); } /** add Category to the view */ void addCategory(const QString &cat) { categoriesList->insertItem(cat); } /** delete Category from view */ void delCategory(const QString &cat); /** delete all categories from view */ void delAllCategories() { categoriesList->clear(); } /** select the specified category */ void selectCategory(const QString &cat); /** returns the number of categories in this view. * This value dosn't say anything about the number of * categories in the document. */ int numCategories() { return categoriesList->count(); } /** resize the view */ void resize(const QSize &size) { splitter->resize(size); } + //US ENH: I need a place to load the view dependend settings. Eg. splittersize + void restoreSettings(PWMPrefs* prefs); + void saveSettings(PWMPrefs* prefs); + protected slots: /** user clicked right button in category list */ void catRightClick(QListBoxItem *item, const QPoint &point); protected: /** main list view */ ListViewPwM *lv; #ifndef PWM_EMBEDDED /** main splitter widget */ QSplitter *splitter; /** commentTextEdit splitter */ QSplitter *splitter2; #else /** main splitter widget */ KDGanttMinimizeSplitter *splitter; /** commentTextEdit splitter */ KDGanttMinimizeSplitter *splitter2; #endif /** categories list-box */ QListBox *categoriesList; /** title string for the categories combo or list box */ QLabel *categoriesTitle; /** hbox1 for widget style */ QVBox *vbox1; /** text-edit to display the comment */ CommentBox *commentBox; /** category list context menu */ QPopupMenu *catCtxMenu; }; #endif diff --git a/pwmanager/pwmanager/serializer.cpp b/pwmanager/pwmanager/serializer.cpp index 9377e3d..a54ba8a 100644 --- a/pwmanager/pwmanager/serializer.cpp +++ b/pwmanager/pwmanager/serializer.cpp @@ -1,677 +1,663 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 2.0 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "serializer.h" #include "pwmexception.h" #ifdef PWM_EMBEDDED #include <kglobal.h> #include <klocale.h> #endif /* enable/disable serializer debugging (0/1) */ #define SERIALIZER_DEBUG 1 /* use the old xml tags for writing (0/1) */ #define USE_OLD_TAGS 0 /* write a CDATA section (0/1) */ #define WRITE_CDATA_SEC 0 #define META_CREATE_DATE "c" #define META_VALID_DATE "v" #define META_EXPIRE_DATE "e" #define META_UPDATE_DATE "u" #define META_UPDATE_INT "i" //US ENH : uniqueid #define META_UNIQUEID "n" /* This is compatibility stuff. * The names of the entries have changed and here are the * new and old ones */ #define ROOT_MAGIC_OLD "PwM-xml-dat" #define VER_STR_OLD "ver" #define COMPAT_VER_OLD "0x02" #define CAT_ROOT_OLD "categories" #define CAT_PREFIX_OLD "cat_" #define CAT_NAME_OLD "name" #define ENTRY_PREFIX_OLD "entry_" #define ENTRY_DESC_OLD "desc" #define ENTRY_NAME_OLD "name" #define ENTRY_PW_OLD "pw" #define ENTRY_COMMENT_OLD "comment" #define ENTRY_URL_OLD "url" #define ENTRY_LAUNCHER_OLD "launcher" #define ENTRY_LVP_OLD "listViewPos" #define ENTRY_BIN_OLD "b" #define ENTRY_META_OLD "m" #define ROOT_MAGIC_NEW "P" #define VER_STR_NEW "v" #define COMPAT_VER_NEW "2" #define CAT_ROOT_NEW "c" #define CAT_PREFIX_NEW "c" #define CAT_NAME_NEW "n" #define ENTRY_PREFIX_NEW "e" #define ENTRY_DESC_NEW "d" #define ENTRY_NAME_NEW "n" #define ENTRY_PW_NEW "p" #define ENTRY_COMMENT_NEW "c" #define ENTRY_URL_NEW "u" #define ENTRY_LAUNCHER_NEW "l" #define ENTRY_LVP_NEW "v" #define ENTRY_BIN_NEW ENTRY_BIN_OLD #define ENTRY_META_NEW ENTRY_META_OLD #if USE_OLD_TAGS != 0 # define ROOT_MAGIC_WR ROOT_MAGIC_OLD # define VER_STR_WR VER_STR_OLD # define COMPAT_VER_WR COMPAT_VER_OLD # define CAT_ROOT_WR CAT_ROOT_OLD # define CAT_PREFIX_WR CAT_PREFIX_OLD # define CAT_NAME_WR CAT_NAME_OLD # define ENTRY_PREFIX_WR ENTRY_PREFIX_OLD # define ENTRY_DESC_WR ENTRY_DESC_OLD # define ENTRY_NAME_WR ENTRY_NAME_OLD # define ENTRY_PW_WR ENTRY_PW_OLD # define ENTRY_COMMENT_WR ENTRY_COMMENT_OLD # define ENTRY_URL_WR ENTRY_URL_OLD # define ENTRY_LAUNCHER_WR ENTRY_LAUNCHER_OLD # define ENTRY_LVP_WR ENTRY_LVP_OLD # define ENTRY_BIN_WR ENTRY_BIN_OLD # define ENTRY_META_WR ENTRY_META_OLD #else # define ROOT_MAGIC_WR ROOT_MAGIC_NEW # define VER_STR_WR VER_STR_NEW # define COMPAT_VER_WR COMPAT_VER_NEW # define CAT_ROOT_WR CAT_ROOT_NEW # define CAT_PREFIX_WR CAT_PREFIX_NEW # define CAT_NAME_WR CAT_NAME_NEW # define ENTRY_PREFIX_WR ENTRY_PREFIX_NEW # define ENTRY_DESC_WR ENTRY_DESC_NEW # define ENTRY_NAME_WR ENTRY_NAME_NEW # define ENTRY_PW_WR ENTRY_PW_NEW # define ENTRY_COMMENT_WR ENTRY_COMMENT_NEW # define ENTRY_URL_WR ENTRY_URL_NEW # define ENTRY_LAUNCHER_WR ENTRY_LAUNCHER_NEW # define ENTRY_LVP_WR ENTRY_LVP_NEW # define ENTRY_BIN_WR ENTRY_BIN_NEW # define ENTRY_META_WR ENTRY_META_NEW #endif Serializer::Serializer() { defaultLockStat = true; //US BUG: I needed to specify a document name. Otherwise impl will not be created for serializing #ifndef PWM_EMBEDDED domDoc = new QDomDocument; #else domDoc = new QDomDocument("mydoc"); #endif } Serializer::Serializer(const QCString &buffer) { defaultLockStat = true; //US BUG: I needed to specify a document name. Otherwise impl will not be created for serializing #ifndef PWM_EMBEDDED domDoc = new QDomDocument; #else domDoc = new QDomDocument("mydoc"); #endif if (!parseXml(buffer)) { delete domDoc; #ifndef PWM_EMBEDDED throw PwMException(PwMException::EX_PARSE); #else qDebug("Serializer::Serializer : Parse Exception "); #endif } } Serializer::~Serializer() { delete_ifnot_null(domDoc); } void Serializer::clear() { delete_ifnot_null(domDoc); domDoc = new QDomDocument; } bool Serializer::parseXml(const QCString &buffer) { PWM_ASSERT(domDoc); #ifndef PWM_EMBEDDED if (!domDoc->setContent(buffer, true)) return false; #else if (!domDoc->setContent(buffer)) return false; #endif if (!checkValid()) return false; return true; } QCString Serializer::getXml() { PWM_ASSERT(domDoc); #ifndef PWM_EMBEDDED #if defined(PWM_DEBUG) && SERIALIZER_DEBUG != 0 QCString tmp(domDoc->toCString(8)); printDebug("<BEGIN Serializer::getXml() dump>\n"); cout << tmp << endl; printDebug("<END Serializer::getXml() dump>"); #endif // DEBUG QCString ret(domDoc->toCString(0)); ret.replace('\n', ""); return ret; #else #if defined(PWM_DEBUG) && SERIALIZER_DEBUG != 0 QCString tmp(" " + domDoc->toCString()); printDebug("<BEGIN Serializer::getXml() dump>\n"); qDebug(tmp); cout << tmp << endl; printDebug("<END Serializer::getXml() dump>"); #endif // DEBUG QCString ret(domDoc->toCString()); ret.replace(QRegExp("\n"), ""); return ret; #endif } bool Serializer::serialize(const vector<PwMCategoryItem> &dta) { PWM_ASSERT(domDoc); QDomElement root(genNewRoot()); QDomElement catNode(domDoc->createElement(CAT_ROOT_WR)); root.appendChild(catNode); if (!addCategories(&catNode, dta)) return false; return true; } bool Serializer::deSerialize(vector<PwMCategoryItem> *dta) { PWM_ASSERT(domDoc); PWM_ASSERT(dta); QDomElement root(domDoc->documentElement()); QDomNode n; dta->clear(); for (n = root.firstChild(); !n.isNull(); n = n.nextSibling()) { // find <categories> ... </categories> // <c> ... </c> if (n.nodeName() == CAT_ROOT_NEW || n.nodeName() == CAT_ROOT_OLD) { if (!readCategories(n, dta)) { return false; } /* NOTE: We can stop processing here, as we * don't have more nodes in root, yet. */ return true; } } return false; } bool Serializer::readCategories(const QDomNode &n, vector<PwMCategoryItem> *dta) { QDomNodeList nl(n.childNodes()); QDomNode cur; QString name; unsigned int numCat = nl.count(), i; PwMCategoryItem curCat; vector<PwMDataItem> curEntr; if (!numCat) { printDebug("Serializer::readCategories(): empty"); return false; } for (i = 0; i < numCat; ++i) { cur = nl.item(i); if (cur.nodeName().left(1) == CAT_PREFIX_NEW || cur.nodeName().left(4) == CAT_PREFIX_OLD) { name = cur.toElement().attribute(CAT_NAME_NEW); if (name == QString::null) name = cur.toElement().attribute(CAT_NAME_OLD); PWM_ASSERT(name != QString::null); PWM_ASSERT(name != ""); curCat.clear(); curCat.name = name.latin1(); if (!readEntries(cur, &curEntr)) { dta->clear(); return false; } curCat.d = curEntr; dta->push_back(curCat); } else { printDebug("Serializer::readCategories(): uh? not a category?"); } } return true; } bool Serializer::readEntries(const QDomNode &n, vector<PwMDataItem> *dta) { QDomNodeList nl(n.childNodes()); QDomNode cur; unsigned int numEntr = nl.count(), i; PwMDataItem curEntr; dta->clear(); for (i = 0; i < numEntr; ++i) { cur = nl.item(i); if (cur.nodeName().left(1) == ENTRY_PREFIX_NEW || cur.nodeName().left(6) == ENTRY_PREFIX_OLD) { if (!extractEntry(cur, &curEntr)) { return false; } dta->push_back(curEntr); } else { printDebug("Serializer::readEntries(): hm? not an entry?"); } } return true; } bool Serializer::extractEntry(const QDomNode &n, PwMDataItem *dta) { QDomNodeList nl(n.childNodes()); QDomNode cur, cdata; unsigned int cnt = nl.count(), i; QString name, text; if (!cnt) { printDebug("Serializer::extractEntry(): empty"); return false; } dta->clear(); for (i = 0; i < cnt; ++i) { cur = nl.item(i); name = cur.nodeName(); cdata = cur.firstChild(); if (unlikely(cdata.isCDATASection())) { text = cdata.toCDATASection().data(); } else if (likely(cur.isElement())) { text = cur.toElement().text(); } else { printDebug("Serializer::extractEntry(): neither CDATA nor element."); return false; } if (text == " ") text = ""; // for backward compatibility. if (name == ENTRY_DESC_NEW || name == ENTRY_DESC_OLD) { dta->desc = unescapeEntryData(text).latin1(); } else if (name == ENTRY_NAME_NEW || name == ENTRY_NAME_OLD) { dta->name = unescapeEntryData(text).latin1(); } else if (name == ENTRY_PW_NEW || name == ENTRY_PW_OLD) { dta->pw = unescapeEntryData(text).latin1(); } else if (name == ENTRY_COMMENT_NEW || name == ENTRY_COMMENT_OLD) { dta->comment = unescapeEntryData(text).latin1(); } else if (name == ENTRY_URL_NEW || name == ENTRY_URL_OLD) { dta->url = unescapeEntryData(text).latin1(); } else if (name == ENTRY_LAUNCHER_NEW || name == ENTRY_LAUNCHER_OLD) { dta->launcher = unescapeEntryData(text).latin1(); } else if (name == ENTRY_LVP_NEW || name == ENTRY_LVP_OLD) { dta->listViewPos = strtol(text.latin1(), 0, 10); } else if (name == ENTRY_BIN_NEW) { // ENTRY_BIN_NEW == ENTRY_BIN_OLD if (text == "0") { dta->binary = false; } else { dta->binary = true; } } else if (name == ENTRY_META_NEW) { // ENTRY_META_NEW == ENTRY_META_OLD if (!extractMeta(cur, &dta->meta)) return false; } else { printDebug(string("Serializer::extractEntry(): invalid: ") + name.latin1()); } } dta->lockStat = defaultLockStat; return true; } bool Serializer::extractMeta(const QDomNode &n, PwMMetaData *dta) { QDomNode cur(n.firstChild()); QString name, val; while (!cur.isNull()) { name = cur.nodeName(); val = cur.toElement().text(); if (val == "") { cur = cur.nextSibling(); continue; } #ifndef PWM_EMBEDDED if (name == META_CREATE_DATE) { dta->create = QDateTime::fromString(val, Qt::ISODate); } else if (name == META_VALID_DATE) { dta->valid = QDateTime::fromString(val, Qt::ISODate); } else if (name == META_EXPIRE_DATE) { dta->expire = QDateTime::fromString(val, Qt::ISODate); } else if (name == META_UPDATE_DATE) { dta->update = QDateTime::fromString(val, Qt::ISODate); } else if (name == META_UPDATE_INT) { dta->updateInt = strtoul(val.latin1(), 0, 10); } else if (name == META_UNIQUEID) { dta->uniqueid = unescapeEntryData(val).latin1(); } else { printDebug(string("extractMeta(): invalid: ") + name.latin1()); } #else - QDateTime m_dt; - - if ((name == META_CREATE_DATE) || - (name == META_VALID_DATE) || - (name == META_EXPIRE_DATE) || - (name == META_UPDATE_DATE)) - { - int pos = val.find("T"); - QString date = val.left(pos); - QString time = val.mid(pos+1); - qDebug("Serializer::extractMeta from %s to date=%s ,time=%s",val.latin1(), date.latin1(), time.latin1() ); - bool ok1, ok2; - - QDate m_date = KGlobal::locale()->readDate(date, &ok1); - QTime m_time = KGlobal::locale()->readTime(time, &ok2); - if ((ok1 == false) || (ok2 == false)) - qDebug("Serializer::extractMeta invalid date or time !!!!!!!!!!!!!"); - m_dt.setDate(m_date); - m_dt.setTime(m_time); - } + bool ok = true; if (name == META_CREATE_DATE) { - dta->create = m_dt; + dta->create = KGlobal::locale()->readDateTime(val, KLocale::ISODate, &ok); } else if (name == META_VALID_DATE) { - dta->valid = m_dt; + dta->valid = KGlobal::locale()->readDateTime(val, KLocale::ISODate, &ok); } else if (name == META_EXPIRE_DATE) { - dta->expire = m_dt; + dta->expire = KGlobal::locale()->readDateTime(val, KLocale::ISODate, &ok); } else if (name == META_UPDATE_DATE) { - dta->update = m_dt; + dta->update = KGlobal::locale()->readDateTime(val, KLocale::ISODate, &ok); } else if (name == META_UPDATE_INT) { dta->updateInt = strtoul(val.latin1(), 0, 10); } else if (name == META_UNIQUEID) { dta->uniqueid = unescapeEntryData(val).latin1(); } else { printDebug(string("extractMeta(): invalid: ") + name.latin1()); } + + if (ok == false) + qDebug("Serializer::extractMeta invalid date or time !!!!!!!!!!!!!"); + + #endif cur = cur.nextSibling(); } return true; } bool Serializer::checkValid() { PWM_ASSERT(domDoc); QDomElement root(domDoc->documentElement()); if (root.nodeName() != ROOT_MAGIC_NEW && root.nodeName() != ROOT_MAGIC_OLD) { printDebug("Serializer: wrong magic"); return false; } if (root.attribute(VER_STR_NEW) != COMPAT_VER_NEW && root.attribute(VER_STR_OLD) != COMPAT_VER_OLD) { printDebug("Serializer: wrong version"); return false; } return true; } QDomElement Serializer::genNewRoot() { PWM_ASSERT(domDoc); QDomElement root(domDoc->createElement(ROOT_MAGIC_WR)); root.setAttribute(VER_STR_WR, COMPAT_VER_WR); domDoc->appendChild(root); return root; } bool Serializer::addCategories(QDomElement *e, const vector<PwMCategoryItem> &dta) { unsigned int numCat = dta.size(), i; QString curId, curName; QDomElement curCat; for (i = 0; i < numCat; ++i) { curId = CAT_PREFIX_WR; curId += tostr(i).c_str(); curName = dta[i].name.c_str(); curCat = domDoc->createElement(curId); curCat.setAttribute(CAT_NAME_WR, curName); if (!addEntries(&curCat, dta[i].d)) { return false; } e->appendChild(curCat); } return true; } bool Serializer::addEntries(QDomElement *e, const vector<PwMDataItem> &dta) { unsigned int numEntr = dta.size(), i; QString curId; QDomElement curEntr; for (i = 0; i < numEntr; ++i) { curId = ENTRY_PREFIX_WR; curId += tostr(i).c_str(); curEntr = domDoc->createElement(curId); if (!writeEntry(&curEntr, dta[i])) { return false; } e->appendChild(curEntr); } return true; } bool Serializer::writeEntry(QDomElement *e, const PwMDataItem &_dta) { #if WRITE_CDATA_SEC != 0 # define new_text(x) domDoc->createCDATASection(x) QDomCDATASection curText; #else # define new_text(x) domDoc->createTextNode(x) QDomText curText; #endif QDomText plainText; QDomElement tag; // begin -- This is for compatibility with the old serializer PwMDataItem dta = _dta; if (!dta.desc.size()) dta.desc = " "; if (!dta.name.size()) dta.name = " "; if (!dta.pw.size()) dta.pw = " "; if (!dta.comment.size()) dta.comment = " "; if (!dta.url.size()) dta.url = " "; if (!dta.launcher.size()) dta.launcher = " "; // end -- This is for compatibility with the old serializer tag = domDoc->createElement(ENTRY_DESC_WR); curText = new_text(escapeEntryData(dta.desc.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_NAME_WR); curText = new_text(escapeEntryData(dta.name.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_PW_WR); curText = new_text(escapeEntryData(dta.pw.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_COMMENT_WR); curText = new_text(escapeEntryData(dta.comment.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_URL_WR); curText = new_text(escapeEntryData(dta.url.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_LAUNCHER_WR); curText = new_text(escapeEntryData(dta.launcher.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_LVP_WR); plainText = domDoc->createTextNode(tostr(dta.listViewPos).c_str()); tag.appendChild(plainText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_BIN_WR); if (dta.binary) plainText = domDoc->createTextNode("1"); else plainText = domDoc->createTextNode("0"); tag.appendChild(plainText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_META_WR); if (!writeMeta(&tag, dta.meta)) return false; e->appendChild(tag); #undef new_text return true; } bool Serializer::writeMeta(QDomElement *e, const PwMMetaData &dta) { QDomText text; QDomElement tag; tag = domDoc->createElement(META_CREATE_DATE); #ifndef PWM_EMBEDDED text = domDoc->createTextNode(dta.create.toString(Qt::ISODate)); #else text = domDoc->createTextNode(KGlobal::locale()->formatDateTime(dta.create, KLocale::ISODate)); #endif tag.appendChild(text); e->appendChild(tag); tag = domDoc->createElement(META_VALID_DATE); #ifndef PWM_EMBEDDED text = domDoc->createTextNode(dta.valid.toString(Qt::ISODate)); #else text = domDoc->createTextNode(KGlobal::locale()->formatDateTime(dta.valid, KLocale::ISODate)); #endif tag.appendChild(text); e->appendChild(tag); tag = domDoc->createElement(META_EXPIRE_DATE); #ifndef PWM_EMBEDDED text = domDoc->createTextNode(dta.expire.toString(Qt::ISODate)); #else text = domDoc->createTextNode(KGlobal::locale()->formatDateTime(dta.expire, KLocale::ISODate)); #endif tag.appendChild(text); e->appendChild(tag); tag = domDoc->createElement(META_UPDATE_DATE); #ifndef PWM_EMBEDDED text = domDoc->createTextNode(dta.update.toString(Qt::ISODate)); #else text = domDoc->createTextNode(KGlobal::locale()->formatDateTime(dta.update, KLocale::ISODate)); #endif tag.appendChild(text); e->appendChild(tag); tag = domDoc->createElement(META_UPDATE_INT); text = domDoc->createTextNode(tostr(dta.updateInt).c_str()); tag.appendChild(text); e->appendChild(tag); tag = domDoc->createElement(META_UNIQUEID); text = domDoc->createTextNode(escapeEntryData(dta.uniqueid)); tag.appendChild(text); e->appendChild(tag); #undef new_text return true; } QString Serializer::escapeEntryData(QString dta) { #ifndef PWM_EMBEDDED dta.replace('\n', "$>--endl--<$"); dta.replace("]]>", "||>"); #else dta.replace(QRegExp("\n"), "$>--endl--<$"); dta.replace(QRegExp("]]>"), "||>"); #endif return dta; } QString Serializer::unescapeEntryData(QString dta) { #ifndef PWM_EMBEDDED dta.replace("$>--endl--<$", "\n"); dta.replace("||>", "]]>"); #else dta.replace(QRegExp("$>--endl--<$"), "\n"); dta.replace(QRegExp("||>"), "]]>"); #endif return dta; } |