Ejemplo n.º 1
0
bool CryptoDoc::isEncryptedWarning()
{
	if( isNull() )
		setLastError( tr("Container is not open") );
	if( isEncrypted() )
		setLastError( tr("Container is encrypted") );
	return isNull() || isEncrypted();
}
Ejemplo n.º 2
0
bool CryptoDoc::decrypt()
{
	if( isNull() )
	{
		setLastError( tr("Container is not open") );
		return false;
	}
	if( !isEncrypted() )
		return true;

	DEncEncryptedKey *key = 0;
	for( int i = 0; i < d->enc->nEncryptedKeys; ++i )
	{
		DEncEncryptedKey *tmp = d->enc->arrEncryptedKeys[i];
		if( qApp->poller()->token().cert() == SslCertificate::fromX509( Qt::HANDLE(tmp->pCert) ) )
		{
			key = tmp;
			break;
		}
	}
	if( !key )
	{
		setLastError( tr("You do not have the key to decrypt this document") );
		return false;
	}

	QByteArray in( (const char*)key->mbufTransportKey.pMem, key->mbufTransportKey.nLen ), out;
	bool decrypted = false;
	while( !decrypted )
	{
		switch( qApp->poller()->decrypt( in, out ) )
		{
		case Poller::DecryptOK: decrypted = true; break;
		case Poller::PinIncorrect: break;
		default: return false;
		}
	}

	ddocMemAssignData( &d->enc->mbufTransportKey, out.constData(), out.size() );
	d->enc->nKeyStatus = DENC_KEY_STATUS_INITIALIZED;

	CryptoDocThread dec( false, d );
	dec.waitForFinished();
	if( dec.err != ERR_OK )
		setLastError( dec.lastError.isEmpty() ? tr("Failed to decrypt data") : dec.lastError, dec.err );
	else if( !dec.lastError.isEmpty() )
		setLastError( dec.lastError );
	d->documents->revert();
	return !isEncrypted();
}
Ejemplo n.º 3
0
QList<CDocument> CryptoDoc::documents()
{
	QList<CDocument> list;
	if( isNull() )
		return list;

	if( isEncrypted() )
	{
		int count = dencOrigContent_count( m_enc );
		for( int i = 0; i < count; ++i )
		{
			char filename[255], size[255], mime[255], id[255];
			dencOrigContent_findByIndex( m_enc, i, filename, size, mime, id );
			CDocument doc;
			doc.filename = QString::fromUtf8( filename );
			doc.mime = QString::fromUtf8( mime );
			doc.size = QString::fromUtf8( size );
			list << doc;
		}
	}
	else if( m_doc )
	{
		for( int i = 0; i < m_doc->nDataFiles; ++i )
		{
			DataFile *data = m_doc->pDataFiles[i];
			CDocument doc;
			doc.path = QString::fromUtf8( data->szFileName );
			doc.filename = QFileInfo( QString::fromUtf8( data->szFileName ) ).fileName();
			doc.mime = QString::fromUtf8( data->szMimeType );
			doc.size = Common::fileSize( data->nSize );
			list << doc;
		}
	}
	return list;
}
Ejemplo n.º 4
0
void APC::encrypt() {
	if (isEncrypted()) {
		return;
	}
	int i;
	for (i = 0; i < data_len; i++) {
		data[i] = data[i] ^ key[i%keyLength];
	}
	setEncryptFlag();
}
/** Sets the unlock key of the modules and writes the key into the cofig file.*/
bool CSwordModuleInfo::unlock(const QString & unlockKey) {
	if (!isEncrypted()) {
		return false;
	}

	CBTConfig::setModuleEncryptionKey(name(), unlockKey);
	backend()->setCipherKey(m_module->Name(), unlockKey.toUtf8().constData());
	//TODO: write to Sword config as well

	return true;
}
Ejemplo n.º 6
0
void
incoming (struct client *client, struct email *msg)
{
// VERIFICATION HOOK
  int verificationHook_isEncrypted = isEncrypted (msg);
  printf ("incoming:\nisEncrypted = %i\nid = %i\n",
	  verificationHook_isEncrypted, msg->id);
// VERIFICATION HOOK END
  decrypt (client, msg);
  original (client, msg);
}
Ejemplo n.º 7
0
void CryptoDoc::save( const QString &filename )
{
	if( isNull() )
		return setLastError( tr("Container is not open") );
	if( !isEncrypted() )
		return setLastError( tr("Container is not crypted") );
	if( !filename.isEmpty() )
		d->fileName = filename;
	int err = dencGenEncryptedData_writeToFile( d->enc, d->fileName.toUtf8() );
	if( err != ERR_OK )
		setLastError( tr("Failed to save encrpyted file"), err );
}
/** This function returns true if this module is locked, otherwise return false. */
bool CSwordModuleInfo::isLocked() {
	//still works, but the cipherkey is stored in CBTConfig.
	//Works because it is set in sword on program startup.

	if (isEncrypted()) {
		if (unlockKeyIsValid()) {
			return false;
		}
		return true;
	}
	return false;
}
Ejemplo n.º 9
0
bool CryptoDoc::encrypt()
{
	if( isNull() )
	{
		setLastError( tr("Container is not open") );
		return false;
	}
	if( isEncrypted() )
		return true;
	if( d->enc->nEncryptedKeys < 1 )
	{
		setLastError( tr("No keys specified") );
		return false;
	}

	CryptoDocThread dec( true, d );
	dec.waitForFinished();
	if( dec.err != ERR_OK )
		setLastError( dec.lastError.isEmpty() ? tr("Failed to encrypt data") : dec.lastError, dec.err );
	else if( !dec.lastError.isEmpty() )
		setLastError( dec.lastError );
	d->documents->revert();
	return isEncrypted();
}
Ejemplo n.º 10
0
void CryptStream::_writeHeader () {
	assert (_mode == WRITE);
	assert (_file_bio); // Operate on _file_bio
	
	char buf[header_buf_size+1];
	// Write this header directly to the file, without encoding or encryption
	const int offset = header_buf_size;
	std::string hexIV = uc2hex((const unsigned char*)_iv.c_str(), _iv.length());
	int r = snprintf (buf, header_buf_size-1, "*167110* # v:%i # c:%.1i # e:%.1i # o:%i # ciph:%.30s # iv:%.256s # count:%i #",
						this->_version, isEncrypted(), isEncoded(), offset, EVP_CIPHER_name(_cipher),
						hexIV.c_str(), _pbkdfIterationCount);
	memset(buf+r, '*', header_buf_size-r-1);
	buf[header_buf_size-1] = '\n';
	BIO_write(_file_bio, buf, header_buf_size);
}
Ejemplo n.º 11
0
bool CSwordModuleInfo::unlock(const QString & unlockKey) {
    if (!isEncrypted())
        return false;

    bool unlocked = unlockKeyIsValid();

    btConfig().setModuleEncryptionKey(m_cachedName, unlockKey);

    /// \todo remove this comment once it is no longer needed
    /* There is currently a deficiency in sword 1.6.1 in that
       backend->setCipherKey() does not work correctly for modules from which
       data was already fetched. Therefore we have to reload the modules in
       bibletime.cpp */
    m_backend.setCipherKey(m_module.getName(), unlockKey.toUtf8().constData());

    /// \todo write to Sword config as well

    if (unlockKeyIsValid() != unlocked)
        emit unlockedChanged(!unlocked);
    return true;
}
QString CSwordModuleInfo::aboutText() const {
    QString text;
    text += "<table>";

    text += QString("<tr><td><b>%1</b></td><td>%2</td><tr>")
            .arg(tr("Version"))
            .arg(hasVersion() ? config(CSwordModuleInfo::ModuleVersion) : tr("unknown"));

    text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
            .arg(tr("Markup"))
            .arg(!QString(m_module->getConfigEntry("SourceType")).isEmpty() ? QString(m_module->
                    getConfigEntry("SourceType")) : tr("unknown"));

    text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
            .arg(tr("Location"))
            .arg(config(CSwordModuleInfo::AbsoluteDataPath));

    text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
            .arg(tr("Language"))
            .arg(language()->translatedName());

    if (m_module->getConfigEntry("Category"))
        text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
                .arg(tr("Category"))
                .arg(m_module->getConfigEntry("Category"));

    if (m_module->getConfigEntry("LCSH"))
        text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
                .arg(tr("LCSH"))
                .arg(m_module->getConfigEntry("LCSH"));

    text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
            .arg(tr("Writable"))
            .arg(isWritable() ? tr("yes") : tr("no"));

    if (isEncrypted())
        text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
                .arg(tr("Unlock key"))
                .arg(config(CSwordModuleInfo::CipherKey));

    QString options;

    unsigned int opts;

    for (opts = CSwordModuleInfo::filterTypesMIN; opts <= CSwordModuleInfo::filterTypesMAX; ++opts) {
        if (has(static_cast < CSwordModuleInfo::FilterTypes > (opts))) {
            if (!options.isEmpty()) {
                options += QString::fromLatin1(", ");
            }

            options += CSwordBackend::translatedOptionName(static_cast < CSwordModuleInfo::FilterTypes > (opts));
        }
    }

    if (!options.isEmpty()) {
        text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
                .arg(tr("Features"))
                .arg(options);
    }

    text += "</table><hr>";

    if (category() == Cult) //clearly say the module contains cult/questionable materials
        text += QString("<br/><b>%1</b><br/><br/>")
                .arg(tr("Take care, this work contains cult / questionable material!"));

    text += QString("<b>%1:</b><br/>%2</font>")
            .arg(tr("About"))
            .arg(config(AboutInformation));

    typedef QList<CSwordModuleInfo::ConfigEntry> ListConfigEntry;

    ListConfigEntry entries;

    entries.append(DistributionLicense);
    entries.append(DistributionSource);
    entries.append(DistributionNotes);
    entries.append(TextSource);
    entries.append(CopyrightNotes);
    entries.append(CopyrightHolder);
    entries.append(CopyrightDate);
    entries.append(CopyrightContactName);
    entries.append(CopyrightContactAddress);
    entries.append(CopyrightContactEmail);

    typedef QMap<CSwordModuleInfo::ConfigEntry, QString> MapConfigEntry;

    MapConfigEntry entryMap;

    entryMap[DistributionLicense] = tr("Distribution license");
    entryMap[DistributionSource] = tr("Distribution source");
    entryMap[DistributionNotes] = tr("Distribution notes");
    entryMap[TextSource] = tr("Text source");
    entryMap[CopyrightNotes] = tr("Copyright notes");
    entryMap[CopyrightHolder] = tr("Copyright holder");
    entryMap[CopyrightDate] = tr("Copyright date");
    entryMap[CopyrightContactName] = tr("Copyright contact name");
    entryMap[CopyrightContactAddress] = tr("Copyright contact address");
    entryMap[CopyrightContactEmail] = tr("Copyright contact email");

    text += ("<hr><table>");

    for (ListConfigEntry::iterator it(entries.begin()); it != entries.end(); ++it) {
        QString t( config(*it) );

        if (!t.isEmpty()) {
            text += QString("<tr><td><b>%1</b></td><td>%2</td></tr>")
                    .arg(entryMap[*it])
                    .arg(config(*it));
        }

    }

    text += "</table></font>";

    return text;
}
Ejemplo n.º 13
0
BOOL __RSPacketIsEncrypted(__RSPacket* packet)
{
    if (packet)
        return isEncrypted(packet);
    return NO;
}
Ejemplo n.º 14
0
bool CryptoDoc::encrypt()
{
	if( isNull() )
	{
		setLastError( tr("Container is not open") );
		return false;
	}
	if( isEncrypted() )
		return true;
	if( m_enc->nEncryptedKeys < 1 )
	{
		setLastError( tr("No keys specified") );
		return false;
	}

	int err = ERR_OK;

#if 0
	err = dencOrigContent_registerDigiDoc( m_enc, m_doc );
	if( err != ERR_OK )
	{
		setLastError( tr("Failed to encrypt data"), err );
		return false;
	}
#else // To avoid full file path
	err = dencEncryptedData_SetMimeType( m_enc, DENC_ENCDATA_TYPE_DDOC );
	for( int i = 0; i < m_doc->nDataFiles; ++i )
	{
		DataFile *data = m_doc->pDataFiles[i];
		QFileInfo file( QString::fromUtf8( data->szFileName ) );

		if( !file.exists() )
		{
			cleanProperties();
			setLastError( tr("Failed to encrypt data.<br />File does not exsist %1").arg( file.filePath() ) );
			return false;
		}

		int err = dencOrigContent_add( m_enc,
			QString("orig_file%1").arg(i).toUtf8(),
			file.fileName().toUtf8(),
			Common::fileSize( data->nSize ).toUtf8(),
			data->szMimeType,
			data->szId );

		if( err != ERR_OK )
		{
			cleanProperties();
			setLastError( tr("Failed to encrypt data"), err );
			return false;
		}
	}
#endif

	QFile f( QString( m_fileName ).append( ".ddoc" ) );
	err = createSignedDoc( m_doc, NULL, f.fileName().toUtf8() );
	if( err != ERR_OK )
	{
		cleanProperties();
		setLastError( tr("Failed to encrypt data"), err );
		return false;
	}

	if( !f.open( QIODevice::ReadOnly ) )
	{
		cleanProperties();
		setLastError( tr("Failed to encrypt data") );
		return false;
	}

	err = dencEncryptedData_AppendData( m_enc, f.readAll(), f.size() );
	if( err != ERR_OK )
	{
		cleanProperties();
		setLastError( tr("Failed to encrypt data"), err );
		return false;
	}
	f.close();
	f.remove();

	err = dencEncryptedData_encryptData( m_enc, DENC_COMPRESS_NEVER );
	if( err != ERR_OK )
	{
		cleanProperties();
		setLastError( tr("Failed to encrypt data"), err );
		return false;
	}

	deleteDDoc();
	return isEncrypted();
}
Ejemplo n.º 15
0
static int xmp_read(const char *path, char *buf, size_t size, off_t offset,
		    struct fuse_file_info *fi)
{
	fprintf(stderr, "In read\n");
	int fd;
	int res;
	//int action=DEC;
	FILE* inFile;
	//char* outFileStart;
	//size_t outFileSize;
	//FILE* outFile;




	//findif better way to do this
	char pathT[PATH_MAX];
	stopPath(pathT,"/tmpreadfile.txt");
	FILE *fileT;
	

	char fullPath[PATH_MAX];
	stopPath(fullPath, path);

	(void) fi;
	
	if(isEncrypted(fullPath)){
		//action=DEC;
		inFile=fopen(fullPath, "r");
		fileT=fopen(pathT,"w");
		do_crypt(inFile,fileT,DEC,key);
		fclose(inFile);
		fclose(fileT);
		fd=open(pathT,O_RDONLY);
		res=pread(fd,buf,size,offset);
		if(res==-1){
			res=-errno;
		}
		close(fd);
		remove(pathT);
		return res;

	}else{
		fd=open(fullPath,O_RDONLY);
		res=pread(fd,buf,size,offset);
		if(res==-1){
			res=-errno;
		}
		close(fd);
		remove(pathT);
		return res;
		
	}
/*
	inFile = fopen(fullPath, "r");
	fileT=fopen(pathT,"w");
	//outFile=open_memstream(&outFileStart,&outFileSize);//opens stream to be written t
	fprintf(stderr, "do_crypts is happening\n\n\n\n");
	if(!do_crypt(inFile,fileT,action,key)){
		fprintf(stderr, "do_cryptfailrd\n\n\n\n");
		
	}//come back to

	fclose(inFile);
	fclose(fileT);

	fd=open(tmpPath,O_RDONLY);


	//if (fd == -1)
		//return -errno;
	//fseek(fd,offset,SEEK_SET);
	res = pread(fd,buf,size,offset);
	if (res == -1)
		res = -errno;
	close(fd);
	remove(tmpPath);
	return res;//return number of bytes written*/
}
Ejemplo n.º 16
0
bool CryptoDoc::decrypt()
{
	if( isNull() )
	{
		setLastError( tr("Container is not open") );
		return false;
	}
	if( !isEncrypted() )
		return true;

	DEncEncryptedKey *key = 0;
	for( int i = 0; i < m_enc->nEncryptedKeys; ++i )
	{
		DEncEncryptedKey *tmp = m_enc->arrEncryptedKeys[i];
		if( qApp->poller()->token().cert() == SslCertificate::fromX509( Qt::HANDLE(tmp->pCert) ) )
		{
			key = tmp;
			break;
		}
	}
	if( !key )
	{
		setLastError( tr("You do not have the key to decrypt this document") );
		return false;
	}

	QByteArray in( (const char*)key->mbufTransportKey.pMem, key->mbufTransportKey.nLen ), out;
	bool decrypted = false;
	while( !decrypted )
	{
		switch( qApp->poller()->decrypt( in, out ) )
		{
		case Poller::DecryptOK: decrypted = true; break;
		case Poller::PinIncorrect: break;
		default: return false;
		}
	}

	ddocMemAssignData( &m_enc->mbufTransportKey, out.constData(), out.size() );
	m_enc->nKeyStatus = DENC_KEY_STATUS_INITIALIZED;
	int err = dencEncryptedData_decryptData( m_enc );
	if( err != ERR_OK )
	{
		setLastError( tr("Failed decrypt data"), err );
		return false;
	}

	DEncEncryptionProperty *prop = dencEncryptedData_FindEncryptionPropertyByName( m_enc, ENCPROP_ORIG_SIZE );
	if( prop && prop->szContent )
	{
		long size = QByteArray( prop->szContent ).toLong();
		if( size > 0 && size < m_enc->mbufEncryptedData.nLen )
			m_enc->mbufEncryptedData.nLen = size;
	}

	QString docName = QFileInfo( m_fileName ).fileName();
	m_ddocTemp = Common::tempFilename();
	removeFolder( m_ddocTemp );
	QDir().mkdir( m_ddocTemp );

	m_ddoc = QString( "%1/%2.ddoc" ).arg( m_ddocTemp ).arg( docName );
	QFile f( m_ddoc );
	if( !f.open( QIODevice::WriteOnly|QIODevice::Truncate ) )
	{
		setLastError( tr("Failed to create temporary files<br />%1").arg( f.errorString() ) );
		return false;
	}
	f.write( (const char*)m_enc->mbufEncryptedData.pMem, m_enc->mbufEncryptedData.nLen );
	f.close();
	ddocMemBuf_free( &m_enc->mbufEncryptedData );

	err = ddocSaxReadSignedDocFromFile( &m_doc, f.fileName().toUtf8(), 0, 0 );
	if( err != ERR_OK )
	{
		setLastError( tr("Failed to read decrypted data"), err );
		return false;
	}

	for( int i = 0; i < m_doc->nDataFiles; ++i )
	{
		QString file = QString( "%1/%2" ).arg( m_ddocTemp )
			.arg( QString::fromUtf8( m_doc->pDataFiles[i]->szFileName ) );
		if( QFile::exists( file ) )
			QFile::remove( file );
		err = ddocSaxExtractDataFile( m_doc, m_ddoc.toUtf8(),
			file.toUtf8(), m_doc->pDataFiles[i]->szId, CHARSET_UTF_8 );
		if( err == ERR_OK )
		{
			ddocMemAssignString( &m_doc->pDataFiles[i]->szFileName, file.toUtf8() );
			QFile::setPermissions( file, QFile::ReadOwner );
		}
		else
			setLastError( tr("Failed to save file '%1'").arg( file ), err );
	}

	cleanProperties();
	return !isEncrypted();
}
Ejemplo n.º 17
0
bool CSwordModuleInfo::isLocked() const {
    // still works, but the cipherkey is stored in BtConfig.
    // Works because it is set in sword on program startup.

    return isEncrypted() && !unlockKeyIsValid();
}
Ejemplo n.º 18
0
bool EncryptedStore::init(Mode mode, const QByteArray & appIdentification)
{
    Q_D(KOdfStore);
    bool checksumErrorShown = false;
    bool unreadableErrorShown = false;
    if (!KOdfStore::init(mode) || !d->good) {
        // This Store is already bad
        d->good = false;
        return false;
    }
    d->mode = mode;
    if (mode == Write) {
        d->good = KOdf::isEncryptionSupported();
        if (d->good) {
            if (!m_pZip->open(QIODevice::WriteOnly)) {
                d->good = false;
                return false;
            }
            m_pZip->setCompression(KZip::NoCompression);
            m_pZip->setExtraField(KZip::NoExtraField);
            // Write identification
            (void)m_pZip->writeFile("mimetype", "", "", appIdentification.data(), appIdentification.length());
            m_pZip->setCompression(KZip::DeflateCompression);
            // We don't need the extra field in KOffice - so we leave it as "no extra field".
        }
    } else {
        d->good = m_pZip->open(QIODevice::ReadOnly);
        d->good &= m_pZip->directory() != 0;
        if (!d->good) {
            return false;
        }

        // Read the manifest-file, so we can get the data we'll need to decrypt the other files in the store
        const KArchiveEntry* manifestArchiveEntry = m_pZip->directory()->entry(MANIFEST_FILE);
        if (!manifestArchiveEntry || !manifestArchiveEntry->isFile()) {
            // No manifest file? OK, *I* won't complain
            return true;
        }
        QIODevice *dev = (static_cast< const KArchiveFile* >(manifestArchiveEntry))->createDevice();

        KXmlDocument xmldoc;
        if (!xmldoc.setContent(dev)) {
            KMessage::message(KMessage::Warning, i18n("The manifest file seems to be corrupted. The document could not be opened."));
            dev->close();
            delete dev;
            m_pZip->close();
            d->good = false;
            return false;
        }
        KXmlElement xmlroot = xmldoc.documentElement();
        if (xmlroot.tagName() != "manifest:manifest") {
            KMessage::message(KMessage::Warning, i18n("The manifest file seems to be corrupted. The document could not be opened."));
            dev->close();
            delete dev;
            m_pZip->close();
            d->good = false;
            return false;
        }

        if (xmlroot.hasChildNodes()) {
            QCA::Base64 base64decoder(QCA::Decode);
            KXmlNode xmlnode = xmlroot.firstChild();
            while (!xmlnode.isNull()) {
                // Search for files
                if (!xmlnode.isElement() || xmlnode.toElement().tagName() != "manifest:file-entry" || !xmlnode.toElement().hasAttribute("manifest:full-path") || !xmlnode.hasChildNodes()) {
                    xmlnode = xmlnode.nextSibling();
                    continue;
                }

                // Build a structure to hold the data and fill it with defaults
                KoEncryptedStore_EncryptionData encData;
                encData.filesize = 0;
                encData.checksum = QCA::SecureArray();
                encData.checksumShort = false;
                encData.salt = QCA::SecureArray();
                encData.iterationCount = 0;
                encData.initVector = QCA::SecureArray();

                // Get some info about the file
                QString fullpath = xmlnode.toElement().attribute("manifest:full-path");
                if (xmlnode.toElement().hasAttribute("manifest:size")) {
                    encData.filesize = xmlnode.toElement().attribute("manifest:size").toUInt();
                }

                // Find the embedded encryption-data block
                KXmlNode xmlencnode = xmlnode.firstChild();
                while (!xmlencnode.isNull() && (!xmlencnode.isElement() || xmlencnode.toElement().tagName() != "manifest:encryption-data" || !xmlencnode.hasChildNodes())) {
                    xmlencnode = xmlencnode.nextSibling();
                }
                if (xmlencnode.isNull()) {
                    xmlnode = xmlnode.nextSibling();
                    continue;
                }

                // Find some things about the checksum
                if (xmlencnode.toElement().hasAttribute("manifest:checksum")) {
                    base64decoder.clear();
                    encData.checksum = base64decoder.decode(QCA::SecureArray(xmlencnode.toElement().attribute("manifest:checksum").toAscii()));
                    if (xmlencnode.toElement().hasAttribute("manifest:checksum-type")) {
                        QString checksumType = xmlencnode.toElement().attribute("manifest:checksum-type");
                        if (checksumType == "SHA1") {
                            encData.checksumShort = false;
                        }
                        // For this particual hash-type: check KoEncryptedStore_encryptionData.checksumShort
                        else if (checksumType == "SHA1/1K") {
                            encData.checksumShort = true;
                        } else {
                            // Checksum type unknown
                            if (!checksumErrorShown) {
                                KMessage::message(KMessage::Warning, i18n("This document contains an unknown checksum. When you give a password it might not be verified."));
                                checksumErrorShown = true;
                            }
                            encData.checksum = QCA::SecureArray();
                        }
                    } else {
                        encData.checksumShort = false;
                    }
                }

                KXmlNode xmlencattr = xmlencnode.firstChild();
                bool algorithmFound = false;
                bool keyDerivationFound = false;
                // Search all data about encrption
                while (!xmlencattr.isNull()) {
                    if (!xmlencattr.isElement()) {
                        xmlencattr = xmlencattr.nextSibling();
                        continue;
                    }

                    // Find some things about the encryption algorithm
                    if (xmlencattr.toElement().tagName() == "manifest:algorithm" && xmlencattr.toElement().hasAttribute("manifest:initialisation-vector")) {
                        algorithmFound = true;
                        encData.initVector = base64decoder.decode(QCA::SecureArray(xmlencattr.toElement().attribute("manifest:initialisation-vector").toAscii()));
                        if (xmlencattr.toElement().hasAttribute("manifest:algorithm-name") && xmlencattr.toElement().attribute("manifest:algorithm-name") != "Blowfish CFB") {
                            if (!unreadableErrorShown) {
                                KMessage::message(KMessage::Warning, i18n("This document contains an unknown encryption method. Some parts may be unreadable."));
                                unreadableErrorShown = true;
                            }
                            encData.initVector = QCA::SecureArray();
                        }
                    }

                    // Find some things about the key derivation
                    if (xmlencattr.toElement().tagName() == "manifest:key-derivation" && xmlencattr.toElement().hasAttribute("manifest:salt")) {
                        keyDerivationFound = true;
                        encData.salt = base64decoder.decode(QCA::SecureArray(xmlencattr.toElement().attribute("manifest:salt").toAscii()));
                        encData.iterationCount = 1024;
                        if (xmlencattr.toElement().hasAttribute("manifest:iteration-count")) {
                            encData.iterationCount = xmlencattr.toElement().attribute("manifest:iteration-count").toUInt();
                        }
                        if (xmlencattr.toElement().hasAttribute("manifest:key-derivation-name") && xmlencattr.toElement().attribute("manifest:key-derivation-name") != "PBKDF2") {
                            if (!unreadableErrorShown) {
                                KMessage::message(KMessage::Warning, i18n("This document contains an unknown encryption method. Some parts may be unreadable."));
                                unreadableErrorShown = true;
                            }
                            encData.salt = QCA::SecureArray();
                        }
                    }

                    xmlencattr = xmlencattr.nextSibling();
                }

                // Only use this encryption data if it makes sense to use it
                if (!(encData.salt.isEmpty() || encData.initVector.isEmpty())) {
                    m_encryptionData.insert(fullpath, encData);
                    if (!(algorithmFound && keyDerivationFound)) {
                        if (!unreadableErrorShown) {
                            KMessage::message(KMessage::Warning, i18n("This document contains incomplete encryption data. Some parts may be unreadable."));
                            unreadableErrorShown = true;
                        }
                    }
                }

                xmlnode = xmlnode.nextSibling();
            }
        }
        dev->close();
        delete dev;

        if (isEncrypted() && !(QCA::isSupported("sha1") && QCA::isSupported("pbkdf2(sha1)") && QCA::isSupported("blowfish-cfb"))) {
            d->good = false;
            KMessage::message(KMessage::Error, i18n("QCA has currently no support for SHA1 or PBKDF2 using SHA1. The document can not be opened."));
        }
    }

    return d->good;
}
Ejemplo n.º 19
0
static int xmp_write(const char *path, const char *buf, size_t size,
		     off_t offset, struct fuse_file_info *fi)
{
	fprintf(stderr, "in Write\n");
	int fd;
	int res;
	//size_t inFileSize;
	char fullPath[PATH_MAX];
	stopPath(fullPath, path);  
 	//int action=0;
	//int revAction=1;
	//char* inFileStart;

	FILE* inFile;
	//FILE* outFile;
	FILE* fileT;

	char pathT[PATH_MAX];
	stopPath(pathT,"/tmpFile");
	


	(void) fi;
	//inFile=fopen(fullPath,"r");
	 //fileT=fopen(pathT,"w");

	//outFile=fopen(fullPath,"r");
	
	//fd = open(path, O_WRONLY);
	//inFile=open_memstream(&inFileStart,&inFileSize);
	//fwrite(buf,size,sizeof(char),inFile);//write to the infile	
	//outFile= fopen(fullPath,"r");

	//res = pwrite(fd, buf, size, offset);
	if(isEncrypted(fullPath)){

		//action=DEC;
		//revAction=ENC;

		inFile = fopen(fullPath,"r");
		fileT = fopen(pathT,"w");

		do_crypt(inFile,fileT,DEC,key);
		//do_crypt(outFile,inFile,0,key);//come back to latter
		fclose(inFile);
		fclose(fileT);

		fd=open(pathT,O_WRONLY);
		//fd=open(fullPath,O_WRONLY);
		res = pwrite(fd, buf, size, offset);

		close(fd);

		inFile = fopen(fullPath,"w");
		fileT = fopen(pathT,"r");



		do_crypt(fileT,inFile,ENC,key);
		fclose(inFile);
		fclose(fileT);
		remove(pathT);
		return res;
		//fd=open(fullPath,O_WRONLY);
		
	}else{
		fd=open(fullPath,O_WRONLY);

		//fd=open(pathT,O_WRONLY);

		res =pwrite(fd,buf,size,offset);
		close(fd);
		remove(pathT);
		return res;
		//fd=open(fullPath, O_WRONLY);

	}
	fprintf(stderr, "do_crypts is happening\n\n\n\n");
	

	fclose(inFile);
	fclose(fileT);

	fd=open(pathT, O_WRONLY);

	//fseek(inFile,offset,SEEK_SET);
	//res=pwrite(fd,buf,size,offset);
	//res=fwrite(buf,1,size,inFile);
	//close(outFile);

	if (fd == -1)
		return -errno;

	//res=pwrite(fd,buf,size,offset);

	close(fd);
	//apend to doc
	inFile=fopen(fullPath,"w");
	 fileT=fopen(pathT,"r");
	if (res == -1)
		res = -errno;
	//fflush(inFile);

	//outFile=fopen(fullPath,"w");
	//fseek(inFile,0,SEEK_SET);
	fprintf(stderr, "do_crypts is happening\n\n\n\n");
	do_crypt(fileT,inFile,ENC, key);

	//fclose(outFile);
	fclose(inFile);
	fclose(fileT);
	remove(pathT);
	return res;
}
Ejemplo n.º 20
0
bool Medium::needDecryption() const
{
	return isEncrypted() && clearDeviceUdi().isEmpty();
}
Ejemplo n.º 21
0
static Bool set_cid_subfont(FONTinfo *fontInfo, OBJECT *dict)
{
  CID0_CACHE *cid_font ;
  OBJECT *theo;
  OMATRIX matrix ;

  enum { mch_subdict_Private, mch_subdict_FontMatrix, mch_subdict_dummy };
  static NAMETYPEMATCH mch_subdict[mch_subdict_dummy + 1] = {
    /* Use the enum above to index these */
    { NAME_Private,              1, { ODICTIONARY }},
    { NAME_FontMatrix,           2, { OARRAY, OPACKEDARRAY }},
    DUMMY_END_MATCH
  };

  enum { mch_private_Subrs, mch_private_SubrMapOffset, mch_private_SubrCount,
         mch_private_SDBytes, mch_private_RunInt, mch_private_dummy };
  static NAMETYPEMATCH mch_private[mch_private_dummy + 1] = {
    /* Use the enum above to index these */
    { NAME_Subrs | OOPTIONAL,         2, { OARRAY, OPACKEDARRAY }},
    { NAME_SubrMapOffset | OOPTIONAL, 1, { OINTEGER }},
    { NAME_SubrCount | OOPTIONAL,     1, { OINTEGER }},
    { NAME_SDBytes | OOPTIONAL,       1, { OINTEGER }},
    { NAME_RunInt | OOPTIONAL,        1, { ONAME }},
    DUMMY_END_MATCH
  };

  HQASSERT(fontInfo, "No font info") ;
  HQASSERT(dict, "No CID sub-dict") ;

  if ( (cid_font = cid0_set_font(fontInfo)) == NULL )
    return FALSE ;

  VERIFY_OBJECT(cid_font, CID0_CACHE_NAME) ;

  /* Extract the necessary font parameters */
  if ( !dictmatch(dict, mch_subdict) ||
       !dictmatch(mch_subdict[mch_subdict_Private].result, mch_private) )
    return error_handler(INVALIDFONT);

  if ( mch_private[mch_private_Subrs].result ) {
    cid_font->subrs = mch_private[mch_private_Subrs].result ;
    cid_font->subrcount = theLen(*cid_font->subrs) ;
    cid_font->subrmapoffset = cid_font->sdbytes = 0 ;
  } else {
    /* No Subrs, look for SubrMap details. We don't enforce requiring the
       offsets if there is no SubrCount or it is zero. */
    cid_font->subrs = NULL ;

    if ( (theo = mch_private[mch_private_SubrCount].result) != NULL ) {
      if ( oInteger(*theo) < 0 )
        return error_handler(INVALIDFONT) ;

      cid_font->subrcount = (uint32)oInteger(*theo) ;
    }

    if ( (theo = mch_private[mch_private_SDBytes].result) != NULL ) {
      if ( oInteger(*theo) < 0 || oInteger(*theo) > 4 )
        return error_handler(INVALIDFONT) ;

      cid_font->sdbytes = (uint32)oInteger(*theo) ;
    }

    if ( (theo = mch_private[mch_private_SubrMapOffset].result) != NULL ) {
      if ( oInteger(*theo) < 0 )
        return error_handler(INVALIDFONT) ;

      cid_font->subrmapoffset = (uint32)oInteger(*theo) ;
    }
 }

  /* No Encoding array. */
  theTags(theEncoding(*fontInfo)) = ONULL;

  /* No charstring dictionary. */
  theCharStrings(*fontInfo) = NULL;

  /* Metrics dictionary will be inherited from the top level CIDFont, so don't
     do anything with theMetrics and theMetrics2. */

  /* Test if it's a Morisawa or ATL encypted CID font */
  isEncrypted(*fontInfo) = PROTECTED_NONE ;
  theo = mch_private[mch_private_RunInt].result;
  if ( theo ) {
    if ( oName(*theo) == &system_names[ NAME_SpecialRun ] )
      isEncrypted(*fontInfo) = PROTECTED_MRSWA ;
    else if ( oName(*theo) == &system_names[ NAME_eCCRun ] )
      isEncrypted(*fontInfo) = PROTECTED_ATL ;
  }

  theSubsCount(*fontInfo) = 0;

  if ( !is_matrix(mch_subdict[mch_subdict_FontMatrix].result, &matrix) )
    return FALSE;

  /* Multiply this by the current fontmatrix to give a new one */
  matrix_mult(&matrix, &theFontMatrix(*fontInfo), &theFontMatrix(*fontInfo));
  matrix_mult(&matrix, &theFontCompositeMatrix(*fontInfo),
              &theFontCompositeMatrix(*fontInfo));

  /* gotFontMatrix is still set, from the set_font call preceding this. Leave
     theLookupFont set if it was already, since the FID in the parent
     dictionary is still valid. The matrix has changed though, so clear the
     lookup matrix. */
  theLookupMatrix(*fontInfo) = NULL ;

  /* Finally, install the FDArray subdict as the source for Private
     information */
  Copy(&fontInfo->subfont, dict) ;

  return TRUE;
}
Ejemplo n.º 22
0
STDMETHODIMP_(BOOL) CDataBase::GetContactSettingStr(HANDLE hContact, DBCONTACTGETSETTING *dbcgs)
{
	if ((dbcgs->pValue->type & DBVTF_VARIABLELENGTH) == 0)
	{
		FreeVariant(dbcgs->pValue);
		dbcgs->pValue->type = 0;
	}

	char namebuf[512];
	namebuf[0] = 0;
	if (dbcgs->szModule)
		strcpy_s(namebuf, dbcgs->szModule);
	strcat_s(namebuf, "/");
	if (dbcgs->szSetting)
		strcat_s(namebuf, dbcgs->szSetting);

	TDBTSettingDescriptor desc = {0,0,0,0,0,0,0,0};
	TDBTSetting set = {0,0,0,0};
	desc.cbSize = sizeof(desc);
	desc.Entity = (WPARAM)hContact;
	desc.pszSettingName = namebuf;

	set.cbSize = sizeof(set);
	set.Descriptor = &desc;

	switch (dbcgs->pValue->type) {
		case DBVT_ASCIIZ: set.Type = DBT_ST_ANSI; break;
		case DBVT_BLOB:   set.Type = DBT_ST_BLOB; break;
		case DBVT_UTF8:   set.Type = DBT_ST_UTF8; break;
		case DBVT_WCHAR:  set.Type = DBT_ST_WCHAR; break;
	}

	if (DBSettingRead(reinterpret_cast<WPARAM>(&set), 0) == DBT_INVALIDPARAM)
		return -1;

	switch (set.Type) {
	case DBT_ST_ANSI:
		dbcgs->pValue->type = DBVT_ASCIIZ;
		dbcgs->pValue->pszVal = set.Value.pAnsi;
		dbcgs->pValue->cchVal = set.Value.Length - 1;
		if (isEncrypted(dbcgs->szModule, dbcgs->szSetting))
			DecodeString(dbcgs->pValue->pszVal);
		break;
	case DBT_ST_UTF8:
		dbcgs->pValue->type = DBVT_UTF8;
		dbcgs->pValue->pszVal = set.Value.pUTF8;
		dbcgs->pValue->cchVal = set.Value.Length - 1;
		if (isEncrypted(dbcgs->szModule, dbcgs->szSetting))
			DecodeString(dbcgs->pValue->pszVal);
		break;
	case DBT_ST_WCHAR:
		if (dbcgs->pValue->type == DBVT_WCHAR) {
			dbcgs->pValue->pwszVal = set.Value.pWide;
			dbcgs->pValue->cchVal = set.Value.Length - 1;
		}
		else {
			dbcgs->pValue->type = DBVT_UTF8;
			dbcgs->pValue->pszVal = mir_utf8encodeW(set.Value.pWide);
			dbcgs->pValue->cchVal = static_cast<uint32_t>(strlen(dbcgs->pValue->pszVal));
			if (isEncrypted(dbcgs->szModule, dbcgs->szSetting))
				DecodeString(dbcgs->pValue->pszVal);
			mir_free(set.Value.pWide);
		}
		break;
	case DBT_ST_BLOB:
		dbcgs->pValue->type = DBVT_BLOB;
		dbcgs->pValue->pbVal = set.Value.pBlob;
		dbcgs->pValue->cpbVal = set.Value.Length;
		break;
	case DBT_ST_BOOL:
		dbcgs->pValue->type = DBVT_BYTE;
		dbcgs->pValue->bVal = (uint8_t)set.Value.Bool;
		break;
	case DBT_ST_BYTE: case DBT_ST_CHAR:
		dbcgs->pValue->type = DBVT_BYTE;
		dbcgs->pValue->bVal = set.Value.Byte;
		break;
	case DBT_ST_SHORT: case DBT_ST_WORD:
		dbcgs->pValue->type = DBVT_WORD;
		dbcgs->pValue->wVal = set.Value.Word;
		break;
	case DBT_ST_INT: case DBT_ST_DWORD:
		dbcgs->pValue->type = DBVT_DWORD;
		dbcgs->pValue->dVal = set.Value.DWord;
		break;
	case DBT_ST_INT64: case DBT_ST_QWORD:
	case DBT_ST_DOUBLE: case DBT_ST_FLOAT:
		dbcgs->pValue->type = DBVT_BLOB;
		dbcgs->pValue->cpbVal = sizeof(set.Value);
		dbcgs->pValue->pbVal = reinterpret_cast<BYTE*>(mir_alloc(sizeof(set.Value)));
		memcpy(dbcgs->pValue->pbVal, &set.Value, sizeof(set.Value));
		break;
	default:
		return -1;
	}

	return 0;
}
Ejemplo n.º 23
0
STDMETHODIMP_(BOOL) CDataBase::GetContactSettingStatic(HANDLE hContact, DBCONTACTGETSETTING *dbcgs)
{
	char namebuf[512];
	namebuf[0] = 0;
	if (dbcgs->szModule)
		strcpy_s(namebuf, dbcgs->szModule);
	strcat_s(namebuf, "/");
	if (dbcgs->szSetting)
		strcat_s(namebuf, dbcgs->szSetting);

	TDBTSettingDescriptor desc = {0,0,0,0,0,0,0,0};
	TDBTSetting set = {0,0,0,0};
	desc.cbSize = sizeof(desc);
	desc.Entity = (WPARAM)hContact;
	desc.pszSettingName = namebuf;

	set.cbSize = sizeof(set);
	set.Descriptor = &desc;

	if (DBSettingRead(reinterpret_cast<WPARAM>(&set), 0) == DBT_INVALIDPARAM)
		return -1;

	if ((set.Type & DBT_STF_VariableLength) ^ (dbcgs->pValue->type & DBVTF_VARIABLELENGTH))
	{
		if (set.Type & DBT_STF_VariableLength)
			mir_free(set.Value.pBlob);
		return -1;
	}

	switch (set.Type) {
	case DBT_ST_ANSI:
		if (dbcgs->pValue->cchVal < set.Value.Length) {
			memcpy(dbcgs->pValue->pszVal, set.Value.pAnsi, dbcgs->pValue->cchVal);
			dbcgs->pValue->pszVal[dbcgs->pValue->cchVal - 1] = 0;
		}
		else memcpy(dbcgs->pValue->pszVal, set.Value.pAnsi, set.Value.Length);

		dbcgs->pValue->type = DBVT_ASCIIZ;
		dbcgs->pValue->cchVal = set.Value.Length - 1;
		if (isEncrypted(dbcgs->szModule, dbcgs->szSetting))
			DecodeString(dbcgs->pValue->pszVal);

		mir_free(set.Value.pAnsi);
		break;
	case DBT_ST_UTF8:
		set.Value.pUTF8 = mir_utf8decode(set.Value.pUTF8, NULL);
		set.Value.Length = static_cast<uint32_t>(strlen(set.Value.pUTF8));

		if (dbcgs->pValue->cchVal < set.Value.Length) {
			memcpy(dbcgs->pValue->pszVal, set.Value.pUTF8, dbcgs->pValue->cchVal);
			dbcgs->pValue->pszVal[dbcgs->pValue->cchVal - 1] = 0;
		}
		else memcpy(dbcgs->pValue->pszVal, set.Value.pUTF8, set.Value.Length);

		dbcgs->pValue->type = DBVT_ASCIIZ;
		dbcgs->pValue->cchVal = set.Value.Length - 1;
		if (isEncrypted(dbcgs->szModule, dbcgs->szSetting))
			DecodeString(dbcgs->pValue->pszVal);

		mir_free(set.Value.pUTF8);
		break;
	case DBT_ST_WCHAR:
		{
			char *tmp = mir_u2a(set.Value.pWide);
			WORD l = static_cast<WORD>(strlen(tmp));
			mir_free(set.Value.pWide);

			if (dbcgs->pValue->cchVal < l + 1) {
				memcpy(dbcgs->pValue->pszVal, tmp, dbcgs->pValue->cchVal);
				dbcgs->pValue->pszVal[l] = 0;
			}
			else memcpy(dbcgs->pValue->pszVal, tmp, l + 1);

			dbcgs->pValue->type = DBVT_ASCIIZ;
			dbcgs->pValue->cchVal = l;
			if (isEncrypted(dbcgs->szModule, dbcgs->szSetting))
				DecodeString(dbcgs->pValue->pszVal);

			mir_free(tmp);
		}
		break;
	case DBT_ST_BLOB:
		if (dbcgs->pValue->cchVal < set.Value.Length)
			memcpy(dbcgs->pValue->pbVal, set.Value.pBlob, dbcgs->pValue->cchVal);
		else
			memcpy(dbcgs->pValue->pbVal, set.Value.pBlob, set.Value.Length);

		dbcgs->pValue->type = DBVT_BLOB;
		dbcgs->pValue->cchVal = set.Value.Length;
		mir_free(set.Value.pBlob);
		break;
	case DBT_ST_BOOL:
		dbcgs->pValue->type = DBVT_BYTE;
		dbcgs->pValue->bVal = set.Value.Bool ? TRUE : FALSE;
		break;
	case DBT_ST_BYTE: case DBT_ST_CHAR:
		dbcgs->pValue->type = DBVT_BYTE;
		dbcgs->pValue->bVal = set.Value.Byte;
		break;
	case DBT_ST_SHORT: case DBT_ST_WORD:
		dbcgs->pValue->type = DBVT_WORD;
		dbcgs->pValue->wVal = set.Value.Word;
		break;
	case DBT_ST_INT: case DBT_ST_DWORD:
		dbcgs->pValue->type = DBVT_DWORD;
		dbcgs->pValue->dVal = set.Value.DWord;
		break;
	default:
		return -1;
	}

	return 0;
}
Ejemplo n.º 24
0
STDMETHODIMP_(BOOL) CDataBase::WriteContactSetting(HANDLE hContact, DBCONTACTWRITESETTING *dbcws)
{
	char namebuf[512];
	namebuf[0] = 0;
	if (dbcws->szModule)
		strcpy_s(namebuf, dbcws->szModule);
	strcat_s(namebuf, "/");
	if (dbcws->szSetting)
		strcat_s(namebuf, dbcws->szSetting);

	TDBTSettingDescriptor desc = {0,0,0,0,0,0,0,0};
	TDBTSetting set = {0,0,0,0};
	desc.cbSize = sizeof(desc);
	desc.Entity = (WPARAM)hContact;
	desc.pszSettingName = namebuf;

	set.cbSize = sizeof(set);
	set.Descriptor = &desc;

	switch (dbcws->value.type) {
	case DBVT_ASCIIZ:
		set.Type = DBT_ST_ANSI;
		set.Value.pAnsi = dbcws->value.pszVal;
		if (isEncrypted(dbcws->szModule, dbcws->szSetting))
			EncodeString(dbcws->value.pszVal);
		break;
	case DBVT_UTF8:
		if (isEncrypted(dbcws->szModule, dbcws->szSetting))
			EncodeString(dbcws->value.pszVal);
		{
			wchar_t * tmp = mir_utf8decodeW(dbcws->value.pszVal);
			if (tmp == 0) {
				if (IsDebuggerPresent())
				{
					DebugBreak();
#ifdef _DEBUG
				}
				else {
					LOG(logWARNING, _T("Trying to write malformed UTF8 setting \"%hs\" in module \"%hs\""), dbcws->szSetting, dbcws->szModule);
					CLogger::Instance().ShowMessage();
#endif
				}
				return -1;
			}
			else mir_free(tmp);
		}

		set.Type = DBT_ST_UTF8;
		set.Value.pUTF8 = dbcws->value.pszVal;
		break;
	case DBVT_WCHAR:
		set.Type = DBT_ST_WCHAR;
		set.Value.pWide = dbcws->value.pwszVal;
		break;
	case DBVT_BLOB:
		set.Type = DBT_ST_BLOB;
		set.Value.pBlob = dbcws->value.pbVal;
		set.Value.Length = dbcws->value.cpbVal;
		break;
	case DBVT_BYTE:
		set.Type = DBT_ST_BYTE;
		set.Value.Byte = dbcws->value.bVal;
		break;
	case DBVT_WORD:
		set.Type = DBT_ST_WORD;
		set.Value.Word = dbcws->value.wVal;
		break;
	case DBVT_DWORD:
		set.Type = DBT_ST_DWORD;
		set.Value.DWord = dbcws->value.dVal;
		break;
	default:
		return -1;
	}

	if (DBSettingWrite(reinterpret_cast<WPARAM>(&set), 0) == DBT_INVALIDPARAM)
		return -1;

	if (dbcws->value.type == DBVT_WCHAR) {
		dbcws->value.type = DBVT_UTF8;
		wchar_t * tmp = dbcws->value.pwszVal;
		dbcws->value.pszVal = mir_utf8encodeW(dbcws->value.pwszVal);
		NotifyEventHooks(hSettingChangeEvent, (WPARAM)hContact, (LPARAM)dbcws);
		mir_free(dbcws->value.pszVal);
		dbcws->value.type = DBVT_WCHAR;
		dbcws->value.pwszVal = tmp;		
	}
	else NotifyEventHooks(hSettingChangeEvent, (WPARAM)hContact, (LPARAM)dbcws);

	return 0;
}
Ejemplo n.º 25
0
void Settings::setEncrypted(bool _encrypted) {
  if (isEncrypted() != _encrypted) {
    m_settings.insert("encrypted", _encrypted);
    saveSettings();
  }
}
Ejemplo n.º 26
0
qint32 cMediaInfo::writeFilename()
{
	QSqlQuery	query;

	query.prepare("SELECT id FROM file WHERE fileName=:fileName AND fileSize=:fileSize AND fileDate=:fileDate;");
	query.bindValue(":fileName", fileName());
	query.bindValue(":fileSize", fileSize());
	query.bindValue(":fileDate", fileDate());

	if(!query.exec())
	{
		myDebug << query.lastError().text();
		return(-1);
	}

	if(query.next())
		query.prepare("UPDATE file SET fileType=:fileType, length=:length, bitrate=:bitrate, sampleRate=:sampleRate, channels=:channels, bitsPerSample=:bitsPerSample, layer=:layer, version=:version, sampleWidth=:sampleWidth, sampleFrames=:sampleFrames, isEncrypted=:isEncrypted, trackGain=:trackGain, albumGain=:albumGain, trackPeak=:trackPeak, albumPeak=:albumPeak, protectionEnabled=:protectionEnabled, channelMode=:channelMode, isCopyrighted=:isCopyrighted, isOriginal=:isOriginal, album=:album, title=:title, copyright=:copyright, trackNumber=:trackNumber, contentGroupDescription=:contentGroupDescription, subTitle=:subTitle, originalAlbum=:originalAlbum, partOfSet=:partOfSet, subTitleOfSet=:subTitleOfSet, internationalStandardRecordingCode=:internationalStandardRecordingCode, leadArtist=:leadArtist, band=:band, conductor=:conductor, interpret=:interpret, originalArtist=:originalArtist, textWriter=:textWriter, originalTextWriter=:originalTextWriter, composer=:composer, encodedBy=:encodedBy, beatsPerMinute=:beatsPerMinute, language=:language, contentType=:contentType, mediaType=:mediaType, mood=:mood, producedNotice=:producedNotice, publisher=:publisher, fileOwner=:fileOwner, internetRadioStationName=:internetRadioStationName, internetRadioStationOwner=:internetRadioStationOwner, originalFilename=:originalFilename, playlistDelay=:playlistDelay, encodingTime=:encodingTime, originalReleaseTime=:originalReleaseTime, recordingTime=:recordingTime, releaseTime=:releaseTime, taggingTime=:taggingTime, swhwSettings=:swhwSettings, albumSortOrder=:albumSortOrder, performerSortOrder=:performerSortOrder, titleSortOrder=:titleSortOrder, synchronizedLyrics=:synchronizedLyrics, unsynchronizedLyrics=:unsynchronizedLyrics WHERE filename=:filename AND filesize=:filesize AND filedate=:filedate;");
	else
		query.prepare("INSERT INTO file (fileName, fileSize, fileDate, fileType, length, bitrate, sampleRate, channels, bitsPerSample, layer, version, sampleWidth, sampleFrames, isEncrypted, trackGain, albumGain, trackPeak, albumPeak, protectionEnabled, channelMode, isCopyrighted, isOriginal, album, title, copyright, trackNumber, contentGroupDescription, subTitle, originalAlbum, partOfSet, subTitleOfSet, internationalStandardRecordingCode, leadArtist, band, conductor, interpret, originalArtist, textWriter, originalTextWriter, composer, encodedBy, beatsPerMinute, language, contentType, mediaType, mood, producedNotice, publisher, fileOwner, internetRadioStationName, internetRadioStationOwner, originalFilename, playlistDelay, encodingTime, originalReleaseTime, recordingTime, releaseTime, taggingTime, swhwSettings, albumSortOrder, performerSortOrder, titleSortOrder, synchronizedLyrics, unsynchronizedLyrics) VALUES (:fileName, :fileSize, :fileDate, :fileType, :length, :bitrate, :sampleRate, :channels, :bitsPerSample, :layer, :version, :sampleWidth, :sampleFrames, :isEncrypted, :trackGain, :albumGain, :trackPeak, :albumPeak, :protectionEnabled, :channelMode, :isCopyrighted, :isOriginal, :album, :title, :copyright, :trackNumber, :contentGroupDescription, :subTitle, :originalAlbum, :partOfSet, :subTitleOfSet, :internationalStandardRecordingCode, :leadArtist, :band, :conductor, :interpret, :originalArtist, :textWriter, :originalTextWriter, :composer, :encodedBy, :beatsPerMinute, :language, :contentType, :mediaType, :mood, :producedNotice, :publisher, :fileOwner, :internetRadioStationName, :internetRadioStationOwner, :originalFilename, :playlistDelay, :encodingTime, :originalReleaseTime, :recordingTime, :releaseTime, :taggingTime, :swhwSettings, :albumSortOrder, :performerSortOrder, :titleSortOrder, :synchronizedLyrics, :unsynchronizedLyrics);");

	query.bindValue(":fileName", fileName());
	query.bindValue(":fileSize", fileSize());
	query.bindValue(":fileDate", fileDate());
	query.bindValue(":fileType", fileType());
	query.bindValue(":length", length());
	query.bindValue(":bitrate", bitrate());
	query.bindValue(":sampleRate", sampleRate());
	query.bindValue(":channels", channels());
	query.bindValue(":bitsPerSample", bitsPerSample());
	query.bindValue(":layer", layer());
	query.bindValue(":version", version());
	query.bindValue(":sampleWidth", sampleWidth());
	query.bindValue(":sampleFrames", sampleFrames());
	query.bindValue(":isEncrypted", isEncrypted());
	query.bindValue(":trackGain", trackGain());
	query.bindValue(":albumGain", albumGain());
	query.bindValue(":trackPeak", trackPeak());
	query.bindValue(":albumPeak", albumPeak());
	query.bindValue(":protectionEnabled", protectionEnabled());
	query.bindValue(":channelMode", channelMode());
	query.bindValue(":isCopyrighted", isCopyrighted());
	query.bindValue(":isOriginal", isOriginal());
	query.bindValue(":album", album());
	query.bindValue(":title", title());
	query.bindValue(":copyright", copyright());
	query.bindValue(":trackNumber", trackNumber());
	query.bindValue(":contentGroupDescription", contentGroupDescription());
	query.bindValue(":subTitle", subTitle());
	query.bindValue(":originalAlbum", originalAlbum());
	query.bindValue(":partOfSet", partOfSet());
	query.bindValue(":subTitleOfSet", subTitleOfSet());
	query.bindValue(":internationalStandardRecordingCode", internationalStandardRecordingCode());
	query.bindValue(":leadArtist", leadArtist());
	query.bindValue(":band", band());
	query.bindValue(":conductor", conductor());
	query.bindValue(":interpret", interpret().join(", "));
	query.bindValue(":originalArtist", originalArtist());
	query.bindValue(":textWriter", textWriter());
	query.bindValue(":originalTextWriter", originalTextWriter());
	query.bindValue(":composer", composer());
	query.bindValue(":encodedBy", encodedBy());
	query.bindValue(":beatsPerMinute", beatsPerMinute());
	query.bindValue(":language", language().join(", "));
	query.bindValue(":contentType", contentType().join(", "));
	query.bindValue(":mediaType", mediaType().join(", "));
	query.bindValue(":mood", mood());
	query.bindValue(":producedNotice", producedNotice());
	query.bindValue(":publisher", publisher());
	query.bindValue(":fileOwner", fileOwner());
	query.bindValue(":internetRadioStationName", internetRadioStationName());
	query.bindValue(":internetRadioStationOwner", internetRadioStationOwner());
	query.bindValue(":originalFilename", originalFilename());
	query.bindValue(":playlistDelay", playlistDelay());
	query.bindValue(":encodingTime", encodingTime());
	query.bindValue(":originalReleaseTime", originalReleaseTime());
	query.bindValue(":recordingTime", recordingTime());
	query.bindValue(":releaseTime", releaseTime());
	query.bindValue(":taggingTime", taggingTime());
	query.bindValue(":swhwSettings", swhwSettings().join(", "));
	query.bindValue(":albumSortOrder", albumSortOrder());
	query.bindValue(":performerSortOrder", performerSortOrder());
	query.bindValue(":titleSortOrder", titleSortOrder());
	query.bindValue(":synchronizedLyrics", synchronizedLyrics().join());
	query.bindValue(":unsynchronizedLyrics", unsynchronizedLyrics().join("||"));

	if(!query.exec())
	{
		myDebug << query.lastError().text();
		return(-1);
	}

	query.prepare("SELECT id FROM file WHERE fileName=:fileName AND fileSize=:fileSize AND fileDate=:fileDate;");
	query.bindValue(":fileName", fileName());
	query.bindValue(":fileSize", fileSize());
	query.bindValue(":fileDate", fileDate());

	if(!query.exec())
	{
		myDebug << query.lastError().text();
		return(-1);
	}

	if(query.next())
		return(query.value("id").toInt());

	return(-1);
}