Exemplo n.º 1
0
void TestAusmt::testExternalRemoved()
{
    prepareSimple();
    GET_DIR;
    GET_FILES_DIR;

    // Test when external source applied or unapplied your patch

    // Perform a false apply (copy file from patched)
    QVERIFY(QFile::remove(filesDir.absoluteFilePath("simple.qml")));
    QVERIFY(QFile::copy(":/patched/simple-patch1.qml", filesDir.absoluteFilePath("simple.qml")));
    QFile destFileApply (filesDir.absoluteFilePath("simple.qml"));
    QVERIFY(destFileApply.exists());
    destFileApply.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser);

    // Apply
    QCOMPARE(QProcess::execute(dir.absoluteFilePath(AUSMT_INSTALL), QStringList() << "simple-patch1"), 0);
    checkSimple1Applied();

    // Perform a false unapply (copy file from original)
    QVERIFY(QFile::remove(filesDir.absoluteFilePath("simple.qml")));
    QVERIFY(QFile::copy(":/files/simple.qml", filesDir.absoluteFilePath("simple.qml")));
    QFile destFileUnapply (filesDir.absoluteFilePath("simple.qml"));
    QVERIFY(destFileUnapply.exists());
    destFileUnapply.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser);

    // Unapply
    QCOMPARE(QProcess::execute(dir.absoluteFilePath(AUSMT_REMOVE), QStringList() << "simple-patch1"), 0);
    checkUnapplied();
}
Exemplo n.º 2
0
void TestAusmt::testOTAModify()
{
    prepareSimple();
    GET_DIR;
    GET_FILES_DIR;

    // An OTA update happened, modifying a patched file

    // Apply
    QCOMPARE(QProcess::execute(dir.absoluteFilePath(AUSMT_INSTALL), QStringList() << "simple-patch1"), 0);
    checkSimple1Applied();

    // Copy the OTA file, and regen md5sums, to simulate the effect of an update
    QVERIFY(QFile::remove(filesDir.absoluteFilePath("simple.qml")));
    QVERIFY(QFile::copy(":/files/simple-ota.qml", filesDir.absoluteFilePath("simple.qml")));
    QFile destFile (filesDir.absoluteFilePath("simple.qml"));
    QVERIFY(destFile.exists());
    destFile.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser);
    generateFileMd5sums();

    // Unapply
    QCOMPARE(QProcess::execute(dir.absoluteFilePath(AUSMT_REMOVE), QStringList() << "simple-patch1"), 0);

    // Check files
    QFile file (filesDir.absoluteFilePath("simple.qml"));
    QFile original (":/files/simple-ota.qml");
    QVERIFY(file.open(QIODevice::ReadOnly));
    QVERIFY(original.open(QIODevice::ReadOnly));
    QCOMPARE(file.readAll(), original.readAll());
    file.close();
    original.close();

    checkUnappliedMeta();
}
Exemplo n.º 3
0
void TestAusmt::prepareSimple()
{
    GET_DIR;
    GET_VAR_DIR;
    GET_FILES_DIR;

    if (varDir.exists()) {
        QVERIFY(varDir.removeRecursively());
    }

    if (filesDir.exists()) {
        QVERIFY(filesDir.removeRecursively());
    }

    QVERIFY(QDir::root().mkpath(varDir.absolutePath()));
    QVERIFY(QDir::root().mkpath(filesDir.absolutePath()));

    QDir filesResDir (":/files");
    foreach (const QString &fileName, filesResDir.entryList(QDir::Files))  {
        QFile file (filesResDir.absoluteFilePath(fileName));
        if (filesDir.exists(fileName)) {
            QVERIFY(QFileInfo(filesDir.absoluteFilePath(fileName)).isFile());
            QVERIFY(filesDir.remove(fileName));
        }
        QVERIFY(file.copy(filesDir.absoluteFilePath(fileName)));
        QFile destFile (filesDir.absoluteFilePath(fileName));
        QVERIFY(destFile.exists());
        destFile.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser);
    }

    generateFileMd5sums();
}
Exemplo n.º 4
0
void CSMonitorClient::slot_checkFile()
{
	ClientLogger->AddLog(QString::fromLocal8Bit("下载版本比较文件成功"));
	QString path = QApplication::applicationDirPath() + "/autoCheckVersionFile.tmp";
	QString strSvrVersion;
	QFile file;
	file.setFileName(path);
	if(file.open(QIODevice::ReadWrite))
	{
		//设置文件共享打开
		file.setPermissions(QFileDevice::ReadOther | QFileDevice::ExeOther | QFileDevice::WriteOther);
		strSvrVersion = file.readAll().constData();
		strSvrVersion = strSvrVersion.trimmed();
		file.close();
	}
	else
	{
		ClientLogger->AddLog(QString::fromLocal8Bit("版本比较文件无法打开[%1]").arg(path));
		QFile::remove(path);
		return;
	}

	QFile::remove(path);

	ClientLogger->AddLog(QString::fromLocal8Bit("最新的软件版本号为[%1] 本地软件版本号为[%2]").arg(strSvrVersion).arg(MessageDataMediator->m_strClientVersion));

	bool bNeedUpdate = CMisc::IsNeedUpdate(MessageDataMediator->m_strClientVersion, strSvrVersion);
	emit sig_showIndependentItem("SMonitorClient", strSvrVersion, bNeedUpdate);
}
Exemplo n.º 5
0
bool tiBackupService::install(const QString &path)
{
    qDebug() << "tiBackupService::install()";

    QFile *tiServicePath = new QFile(path);
    if(!tiServicePath->open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream out(tiServicePath);

    QFile *tiServiceTemplate = new QFile(":/init/tibackup");
    if(!tiServiceTemplate->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        tiServicePath->close();
        tiServicePath->deleteLater();
        return false;
    }
    QTextStream in(tiServiceTemplate);

    out << in.readAll();
    out.flush();

    tiServicePath->setPermissions(QFile::ReadOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::ExeGroup | QFile::ReadOther);
    tiServicePath->close();
    tiServiceTemplate->close();

    tiServicePath->deleteLater();
    tiServiceTemplate->deleteLater();

    emit serviceInstalled();
    return true;
}
void Updater::downloadFinished(QNetworkReply* reply)
{
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if (statusCode.isValid() && statusCode.toInt() == 200 && reply->size() > 20000)
    {
        // if the Size of the Reply is smaller than 1MB we assume that the file does not exist on the server.
        // if your File should be smaller than 1MB, change the number
        QFile *file = new QFile("/Applications/RemoteControlServer2.app");
        if (file->open(QIODevice::WriteOnly))
        {
            file->write(reply->readAll());
        }
        file->setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner
                             | QFileDevice::ReadGroup | QFileDevice::ExeGroup
                             | QFileDevice::ReadOther | QFileDevice::ExeOther);

        QString appPath = "/Applications/RemoteControlServer.app";
        QFile::remove(appPath);
        file->rename(appPath);
        file->close();

        std::cout << "Update finished - Have fun using the new version of the Remote Control Server.\n";
    }
    else
    {
        std::cout << "Update failed - The Download of the new Version of the Remote Control Server failed. The Updater is finishing now.\n";
    }

    emit finished();
}
Exemplo n.º 7
0
bool Gcc::run(QString filename)
{
	if(!compile(filename))
		return false;

	QString outputString;
	QFileInfo outputFileInfo(m_outputFileName);
	QFile scriptFile;

#ifdef Q_OS_WIN32
	scriptFile.setFileName(QDir::temp().absoluteFilePath("kiprBatchFile.cmd"));
	outputString += "@echo off\n";
	outputString += "\"" + QDir::toNativeSeparators(outputFileInfo.absolutePath()) + "\\" + outputFileInfo.fileName() + "\"\n";
	outputString +=  "pause\n";
#else
	scriptFile.setFileName(QDir::temp().absoluteFilePath("kiprScript.sh"));
	outputString += "#!/bin/bash\n";
	outputString += "cd \"" + outputFileInfo.absolutePath() + "\"\n";
	outputString += "\"./" + outputFileInfo.fileName() + "\"\n";
#endif

	if(!scriptFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
		qWarning("Gcc::run() Unable to open temp file for writing");
		return false;
	}

	scriptFile.setPermissions(scriptFile.permissions() | QFile::ExeOwner);
	scriptFile.write(outputString.toLocal8Bit());
	scriptFile.close();

	QStringList args;
	QFileInfo scriptInfo(scriptFile);

	m_outputBinary.setWorkingDirectory(outputFileInfo.absolutePath());

#ifdef Q_OS_WIN32
	QString startLine = "start \"" + m_outputFileName + "\" \"cmd /c " +
						scriptInfo.absoluteFilePath() + "\"\n";
	args << "/k";
	m_outputBinary.start("cmd", args);
	m_outputBinary.write(startLine.toLocal8Bit());
	m_outputBinary.write("exit\n");
#elif defined(Q_OS_MAC)
	args << "-a" << "/Applications/Utilities/Terminal.app" << scriptInfo.absoluteFilePath();
	m_outputBinary.start("open", args);
#else
	args << "-e" << scriptInfo.absoluteFilePath() + " && echo \"\nQuitting in 5 secs...\" && sleep 5";
	m_outputBinary.start("xterm", args);
#endif

	return true;

}
Exemplo n.º 8
0
/**OK
 * Estrae il file fileName, contenuto nell'oggetto zip, con il nome fileDest.
 * Se la funzione fallisce restituisce false e cancella il file che si e tentato di estrarre.
 *
 * La funzione fallisce se:
 * * zip==NULL;
 * * l'oggetto zip e stato aperto in una modalita non compatibile con l'estrazione di file;
 * * non e possibile aprire il file all'interno dell'oggetto zip;
 * * non e possibile creare il file estratto;
 * * si e rilevato un errore nella copia dei dati (1);
 * * non e stato possibile chiudere il file all'interno dell'oggetto zip (1);
 *
 * (1): prima di uscire dalla funzione cancella il file estratto.
 */
bool JlCompress::extractFile(QuaZip* zip, QString fileName, QString fileDest) {
    // zip: oggetto dove aggiungere il file
    // filename: nome del file reale
    // fileincompress: nome del file all'interno del file compresso

    // Controllo l'apertura dello zip
    if (!zip) return false;
    if (zip->getMode()!=QuaZip::mdUnzip) return false;

    // Apro il file compresso
    if (!fileName.isEmpty())
        zip->setCurrentFile(fileName);
    QuaZipFile inFile(zip);
    if(!inFile.open(QIODevice::ReadOnly) || inFile.getZipError()!=UNZ_OK) return false;

    // Controllo esistenza cartella file risultato
    QDir curDir;
    if (!curDir.mkpath(QFileInfo(fileDest).absolutePath())) {
        return false;
    }

    QuaZipFileInfo info;
    if (!zip->getCurrentFileInfo(&info))
        return false;

    if (fileDest.endsWith('/') && QFileInfo(fileDest).isDir()) {
        return QFile(fileDest).setPermissions(info.getPermissions());
    }

    // Apro il file risultato
    QFile outFile;
    outFile.setFileName(fileDest);
    if(!outFile.open(QIODevice::WriteOnly)) return false;

    // Copio i dati
    if (!copyData(inFile, outFile) || inFile.getZipError()!=UNZ_OK) {
        outFile.close();
        removeFile(QStringList(fileDest));
        return false;
    }
    outFile.close();

    // Chiudo i file
    inFile.close();
    if (inFile.getZipError()!=UNZ_OK) {
        removeFile(QStringList(fileDest));
        return false;
    }

    return outFile.setPermissions(info.getPermissions());
}
Exemplo n.º 9
0
void TestAusmt::preparePatches()
{
    GET_DIR;
    GET_FILES_DIR;
    GET_PATCHES_DIR;

    // Dump patches
    QDir patchesResDir (":/patches/");
    foreach (const QString &fileName, patchesResDir.entryList(QDir::Files)) {
        QFile file (patchesResDir.absoluteFilePath(fileName));
        if (patchesDir.exists(fileName)) {
            QVERIFY(QFileInfo(patchesDir.absoluteFilePath(fileName)).isFile());
            QVERIFY(patchesDir.remove(fileName));
        }
        QVERIFY(file.copy(patchesDir.absoluteFilePath(fileName)));
    }

    foreach (const QString &dirName, patchesResDir.entryList(QDir::Dirs)) {
        if (patchesDir.exists(dirName)) {
            QVERIFY(QFileInfo(patchesDir.absoluteFilePath(dirName)).isDir());
            QDir subDir (patchesDir);
            QVERIFY(subDir.cd(dirName));
            QVERIFY(subDir.removeRecursively());
        }

        patchesDir.mkdir(dirName);
        QDir patchesSubDir (patchesDir);
        QVERIFY(patchesSubDir.cd(dirName));

        QDir patchesResSubDir (patchesResDir);
        QVERIFY(patchesResSubDir.cd(dirName));

        foreach (const QString &fileName, patchesResSubDir.entryList(QDir::Files)) {
            QFile file (patchesResSubDir.absoluteFilePath(fileName));
            QVERIFY(file.copy(patchesSubDir.absoluteFilePath(fileName)));
        }
    }

    // Update patches
    QString makePatchName = patchesDir.absoluteFilePath(MAKE_PATCH_SH);
    QFile makePatch (makePatchName);
    QVERIFY(makePatch.exists());
    QVERIFY(makePatch.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser | QFileDevice::ExeUser));
    QProcess makePatchProcess;
    makePatchProcess.setWorkingDirectory(patchesDir.absolutePath());
    makePatchProcess.start(patchesDir.absoluteFilePath(MAKE_PATCH_SH),
                           QStringList() << filesDir.absolutePath());
    makePatchProcess.waitForFinished(-1);
    QCOMPARE(makePatchProcess.exitCode(), 0);
}
Exemplo n.º 10
0
/*!
 * \qmlsignal FileWriter::changePermissions()
 * used in QML to change the permissions of a file.  This is a signal that needs to be called.
 */
void FileWriter::changePermissions(const QString &filename, const QString &permissions)
{
    QFile file;
    file.setFileName(filename);
    if (permissions == "+x" )
    {
        file.setPermissions(QFileDevice::ExeUser);
        file.setPermissions(QFileDevice::ExeGroup);
        file.setPermissions(QFileDevice::ExeOwner);
        file.setPermissions(QFileDevice::ExeOther);
    }
    else if (permissions == "+w")
    {
        file.setPermissions(QFileDevice::WriteUser);
        file.setPermissions(QFileDevice::WriteGroup);
        file.setPermissions(QFileDevice::WriteOwner);
        file.setPermissions(QFileDevice::WriteOther);
    }
    else if (permissions == "+r")
    {
        file.setPermissions(QFileDevice::ReadUser);
        file.setPermissions(QFileDevice::ReadGroup );
        file.setPermissions(QFileDevice::ReadOwner);
        file.setPermissions(QFileDevice::ReadOther);
    }
    else if(permissions ==  "o+r")
    {
        file.setPermissions(QFileDevice::ReadOwner);
    }
    else if(permissions == "o+r")
    {
        file.setPermissions(QFileDevice::WriteOwner);
    }
    else if(permissions == "o+x")
    {
        file.setPermissions(QFileDevice::ExeOwner);
    }
    else if (permissions == "u+r")
    {
        file.setPermissions(QFileDevice::ReadUser);
    }
    else if (permissions == "u+w")
    {
        file.setPermissions(QFileDevice::WriteUser);
    }
    else if(permissions == "u+e")
    {
        file.setPermissions(QFileDevice::ExeUser);
    }
    else if (permissions == "g+r")
    {
        file.setPermissions(QFileDevice::ReadGroup);
    }
    else if (permissions == "g+w")
    {
        file.setPermissions(QFileDevice::WriteGroup);
    }
    else if(permissions == "g+x")
    {
        file.setPermissions(QFileDevice::ExeGroup);
    }
    else if(permissions == "o+r")
    {
        file.setPermissions(QFileDevice::ReadOther);
    }
    else if(permissions == "o+w")
    {
        file.setPermissions(QFileDevice::WriteOther);
    }
    else if (permissions == "o+x")
    {
        file.setPermissions(QFileDevice::ExeOther);
    }
    else
    {
        qDebug() << "FILEWRITER Permission not allowed with the type of " <<  permissions;
    }
}
Exemplo n.º 11
0
void TestAusmt::initTestCase()
{
    // Dirs
    QDir srcDir (QStandardPaths::writableLocation(QStandardPaths::TempLocation));
    if (!srcDir.exists(AUSMTSRC_SUBDIR)) {
        QVERIFY(srcDir.mkdir(AUSMTSRC_SUBDIR));
    }
    QVERIFY(srcDir.cd(AUSMTSRC_SUBDIR));

    GET_DIR;
    GET_VAR_DIR;
    GET_FILES_DIR;
    GET_PATCHES_DIR;

    // Dump AUSMT into src dir
    QDir ausmtResDir (":/ausmtsrc/");
    foreach (const QString &fileName, ausmtResDir.entryList(QDir::Files)) {
        QFile file (ausmtResDir.absoluteFilePath(fileName));
        if (srcDir.exists(fileName)) {
            QVERIFY(QFileInfo(srcDir.absoluteFilePath(fileName)).isFile());
            QVERIFY(srcDir.remove(fileName));
        }
        QVERIFY(file.copy(srcDir.absoluteFilePath(fileName)));
    }

    QDir ausmtTestResDir (":/ausmtsrc-test/");
    foreach (const QString &fileName, ausmtTestResDir.entryList(QDir::Files)) {
        QFile file (ausmtTestResDir.absoluteFilePath(fileName));
        if (srcDir.exists(fileName)) {
            QVERIFY(QFileInfo(srcDir.absoluteFilePath(fileName)).isFile());
            QVERIFY(srcDir.remove(fileName));
        }
        QVERIFY(file.copy(srcDir.absoluteFilePath(fileName)));
    }

    // Make a better constants_root.sh
    QFile constantsRoot (srcDir.absoluteFilePath(CONSTANTS_ROOT_SH));
    QVERIFY(constantsRoot.open(QIODevice::WriteOnly));
    QTextStream constantsRootStream (&constantsRoot);
    constantsRootStream << QString("AUSMT_VAR_DIR=%1\n").arg(varDir.absolutePath());
    constantsRootStream << QString("PATCH_ROOT_DIR=%1\n").arg(patchesDir.absolutePath());
    constantsRootStream << QString("FILES_DIR=%1\n").arg(filesDir.absolutePath());
    constantsRootStream << QString("NOTIFY_WRAPPER_EXEC=echo\n");
    constantsRoot.close();

    // Build AUSMT
    QString buildName = srcDir.absoluteFilePath(BUILD_SH);
    QFile build (buildName);
    QVERIFY(build.exists());
    QVERIFY(build.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser | QFileDevice::ExeUser));
    QProcess buildProcess;
    buildProcess.setWorkingDirectory(srcDir.absolutePath());
    buildProcess.start(PYTHON, QStringList() << buildName);
    buildProcess.waitForFinished(-1);
    QCOMPARE(buildProcess.exitCode(), 0);

    foreach (const QString &fileName, dir.entryList(QDir::Files)) {
        QFile file (dir.absoluteFilePath(fileName));
        QVERIFY(file.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser | QFileDevice::ExeUser));
    }

    // Remove src
    QVERIFY(srcDir.removeRecursively());

    // Prepare patches
    preparePatches();
}
Exemplo n.º 12
0
void PlaylistDialog::newScript()
{

	Preferences *pPref = Preferences::get_instance();

	QString sDirectory = ( Preferences::get_instance()->getDataDirectory()  + "scripts/");
	QFileDialog fd(this);
	fd.setFileMode ( QFileDialog::AnyFile );
	fd.setFilter ( trUtf8 ( "Hydrogen Scripts (*.sh)" ) );
	fd.setAcceptMode ( QFileDialog::AcceptSave );
	fd.setWindowTitle ( trUtf8 ( "New Script" ) );
	fd.setDirectory ( sDirectory );

	QString defaultFilename;

	defaultFilename += ".sh";

	fd.selectFile ( defaultFilename );

	QString filename;
	if ( fd.exec() != QDialog::Accepted ) return;

	filename = fd.selectedFiles().first();

	if( filename.contains(" ", Qt::CaseInsensitive)){
		QMessageBox::information ( this, "Hydrogen", trUtf8 ( "Script name or path to the script contains whitespaces.\nIMPORTANT\nThe path to the script and the scriptname must without whitespaces.") );
		return;
	}

	QFile chngPerm ( filename );
	if (!chngPerm.open(QIODevice::WriteOnly | QIODevice::Text))
		return;

	QTextStream out(&chngPerm);
	out <<  "#!/bin/sh\n\n#have phun";
	chngPerm.close();

	if (chngPerm.exists() ) {
		chngPerm.setPermissions( QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner );
		QMessageBox::information ( this, "Hydrogen", trUtf8 ( "WARNING, the new file is executable by the owner of the file!" ) );
	}

	if( pPref->getDefaultEditor().isEmpty() ){
		QMessageBox::information ( this, "Hydrogen", trUtf8 ( "No Default Editor Set. Please set your Default Editor\nDo not use a console based Editor\nSorry, but this will not work for the moment." ) );

		static QString lastUsedDir = "/usr/bin/";

		QFileDialog fd(this);
		fd.setFileMode ( QFileDialog::ExistingFile );
		fd.setDirectory ( lastUsedDir );

		fd.setWindowTitle ( trUtf8 ( "Set your Default Editor" ) );

		QString filename;
		if ( fd.exec() == QDialog::Accepted ){
			filename = fd.selectedFiles().first();

			pPref->setDefaultEditor( filename );
		}
	}

	QString  openfile = pPref->getDefaultEditor() + " " + filename + "&";

	char *ofile;
	ofile = new char[openfile.length() + 1];
	strcpy(ofile, openfile.toAscii());
	int ret = std::system( ofile );
	delete [] ofile;
	return;
}
Exemplo n.º 13
0
void KSaveFileTest::test_ksavefile()
{
    QString targetFile;

    {
        //This will be the file we eventually write to. Yes, I know you
        //should never remove the temporaryfile and then expect the filename
        //to continue to be unique, but this is a test for crying out loud. :)
        KTemporaryFile file;
        file.setPrefix("ksavefiletest");
        QVERIFY( file.open() );
        targetFile = file.fileName();
    }

    {
        //Test basic functionality
        KSaveFile saveFile;
        saveFile.setFileName(targetFile);
        QVERIFY( saveFile.open() );
        QVERIFY( !QFile::exists(targetFile) );

        QTextStream ts ( &saveFile );
        ts << "This is test data one.\n";
        ts.flush();
        QCOMPARE( saveFile.error(), QFile::NoError );
        QVERIFY( !QFile::exists(targetFile) );

        QVERIFY( saveFile.finalize() );
        QVERIFY( QFile::exists(targetFile) );

        QFile::remove(targetFile);
        QVERIFY( !QFile::exists(targetFile) );
    }

    {
        //Make sure destructor does what it is supposed to do.
        {
            KSaveFile saveFile;
            saveFile.setFileName(targetFile);
            QVERIFY( saveFile.open() );
            QVERIFY( !QFile::exists(targetFile) );
        }

        QVERIFY( QFile::exists(targetFile) );
        QFile::remove(targetFile);
        QVERIFY( !QFile::exists(targetFile) );
    }

    {
        //Test some error conditions
        KSaveFile saveFile;
        QVERIFY( !saveFile.open() ); //no filename
        saveFile.setFileName(targetFile);
        QVERIFY( saveFile.open() );
        QVERIFY( !QFile::exists(targetFile) );
        QVERIFY( !saveFile.open() ); //already open

        QVERIFY( saveFile.finalize() );
        QVERIFY( QFile::exists(targetFile) );
        QVERIFY( !saveFile.finalize() ); //already finalized

        QFile::remove(targetFile);
        QVERIFY( !QFile::exists(targetFile) );
    }

    {
        //Do it again, aborting this time
        KSaveFile saveFile ( targetFile );
        QVERIFY( saveFile.open() );
        QVERIFY( !QFile::exists(targetFile) );

        QTextStream ts ( &saveFile );
        ts << "This is test data two.\n";
        ts.flush();
        QCOMPARE( saveFile.error(), QFile::NoError );
        QVERIFY( !QFile::exists(targetFile) );

        saveFile.abort();
        QVERIFY( !QFile::exists(targetFile) );
    }

    QFile file ( targetFile );
    QVERIFY( file.open(QIODevice::WriteOnly | QIODevice::Text) );
    QVERIFY( file.setPermissions( file.permissions() | QFile::ExeUser ) );
    file.close();

    {
        //Test how it works when the file already exists
        //Also check for special permissions
        KSaveFile saveFile ( targetFile );
        QVERIFY( saveFile.open() );

        QVERIFY( QFile::exists(targetFile) );
        QFileInfo fi ( targetFile );

#ifndef Q_WS_WIN
        // Windows: qt_ntfs_permission_lookup is not set by default in
        // qfsfileengine_win.cpp, could change in future Qt versions.
        QVERIFY( fi.permission( QFile::ExeUser ) );
#endif
        QVERIFY( fi.size() == 0 );

        QTextStream ts ( &saveFile );
        ts << "This is test data three.\n";
        ts.flush();

        fi.refresh();
        QVERIFY( fi.size() == 0 );
        QVERIFY( saveFile.finalize() );

        fi.refresh();
        QVERIFY( fi.size() != 0 );
#ifndef Q_WS_WIN
        QVERIFY( fi.permission( QFile::ExeUser ) );
#endif

        QFile::remove(targetFile);
    }

    {
        QFileInfo fi ( targetFile );
        targetFile = fi.fileName();
        QDir::setCurrent(fi.path());

        //one more time, this time with relative filenames
        KSaveFile saveFile ( targetFile );
        QVERIFY( saveFile.open() );
        QVERIFY( !QFile::exists(targetFile) );

        QTextStream ts ( &saveFile );
        ts << "This is test data four.\n";
        ts.flush();
        QCOMPARE( saveFile.error(), QFile::NoError );
        QVERIFY( !QFile::exists(targetFile) );

        QVERIFY( saveFile.finalize() );
        QVERIFY( QFile::exists(targetFile) );
        QFile::remove(targetFile);
    }

}
Exemplo n.º 14
0
void SMBSlave::smbCopyGet(const QUrl& ksrc, const QUrl& kdst, int permissions, KIO::JobFlags flags)
{
    qCDebug(KIO_SMB) << "src = " << ksrc << ", dest = " << kdst;

    // check if destination is ok ...
    const QString dstFile = kdst.toLocalFile();
    const QFileInfo dstInfo (dstFile);

    if(dstInfo.exists())  {
        if(dstInfo.isDir()) {
            error (ERR_IS_DIRECTORY, kdst.toDisplayString());
            return;
        }

        if(!(flags & KIO::Overwrite)) {
            error(ERR_FILE_ALREADY_EXIST, kdst.toDisplayString());
            return;
        }
    }

    bool bResume = false;
    const QFileInfo partInfo (dstFile + QLatin1String(".part"));
    const bool bPartExists = partInfo.exists();
    const bool bMarkPartial = config()->readEntry("MarkPartial", true);

    if (bMarkPartial && bPartExists && partInfo.size() > 0) {
      if (partInfo.isDir()) {
        error(ERR_IS_DIRECTORY, partInfo.absoluteFilePath());
        return;
      }
      bResume = canResume(partInfo.size());
    }

    if (bPartExists && !bResume)                  // get rid of an unwanted ".part" file
      QFile::remove(partInfo.absoluteFilePath());

    // open the output file...
    QFile::OpenMode mode;
    QString filename;
    if (bResume) {
        filename = partInfo.absoluteFilePath();
        mode = QFile::WriteOnly | QFile::Append;
    }
    else {
        filename = (bMarkPartial ? partInfo.absoluteFilePath() : dstFile);
        mode = QFile::WriteOnly | QFile::Truncate;
    }

    QFile file (filename);
    if (!bResume) {
        QFile::Permissions perms;
        if (permissions == -1) {
            perms = QFile::ReadOwner | QFile::WriteOwner;
        } else {
            perms = KIO::convertPermissions(permissions | QFile::WriteOwner);
        }
        file.setPermissions(perms);
    }

    if (!file.open(mode)) {
        qCDebug(KIO_SMB) << "could not write to" << dstFile;
        switch (file.error()) {
          case QFile::OpenError:
              if (bResume) {
                error (ERR_CANNOT_RESUME, kdst.toDisplayString());
              } else {
                error(ERR_CANNOT_OPEN_FOR_WRITING, kdst.toDisplayString());
              }
              break;
          case QFile::PermissionsError:
              error(ERR_WRITE_ACCESS_DENIED, kdst.toDisplayString());
              break;
          default:
              error(ERR_CANNOT_OPEN_FOR_WRITING, kdst.toDisplayString());
              break;
        }
        return;
    }

    // setup the source urls
    const SMBUrl src(ksrc);

    // Obtain information about source
    int errNum = cache_stat (src, &st);
    if (errNum != 0) {
        if (errNum == EACCES) {
            error (KIO::ERR_ACCESS_DENIED, src.toDisplayString());
        } else {
            error (KIO::ERR_DOES_NOT_EXIST, src.toDisplayString());
        }
        return;
    }

    if (S_ISDIR( st.st_mode )) {
        error (KIO::ERR_IS_DIRECTORY, src.toDisplayString());
        return;
    }
    totalSize(st.st_size);

    // Open the source file
    KIO::filesize_t processed_size = 0;
    int srcfd = smbc_open(src.toSmbcUrl(), O_RDONLY, 0);
    if (srcfd < 0){
        errNum = errno;
    } else {
        errNum = 0;
        if (bResume) {
            qCDebug(KIO_SMB) << "seeking to size" << partInfo.size();
            off_t offset = smbc_lseek(srcfd, partInfo.size(), SEEK_SET);
            if (offset == -1) {
                error(KIO::ERR_COULD_NOT_SEEK, src.toDisplayString());
                smbc_close(srcfd);
                return;
            } else {
                processed_size += offset;
            }
        }
    }

    if (srcfd < 0) {
        if(errNum == EACCES) {
            error( KIO::ERR_ACCESS_DENIED, src.toDisplayString() );
        } else {
            error( KIO::ERR_DOES_NOT_EXIST, src.toDisplayString() );
        }
        return;
    }

    // Perform the copy
    char buf[MAX_XFER_BUF_SIZE];
    bool isErr = false;

    while (1) {
        const ssize_t bytesRead = smbc_read(srcfd, buf, MAX_XFER_BUF_SIZE);
        if (bytesRead <= 0) {
            if (bytesRead < 0) {
                error( KIO::ERR_COULD_NOT_READ, src.toDisplayString());
                isErr = true;
            }
            break;
        }

        const qint64 bytesWritten = file.write(buf, bytesRead);
        if (bytesWritten == -1) {
            qCDebug(KIO_SMB) << "copy now KIO::ERR_COULD_NOT_WRITE";
            error( KIO::ERR_COULD_NOT_WRITE, kdst.toDisplayString());
            isErr = true;
            break;
        }

        processed_size += bytesWritten;
        processedSize(processed_size);
    }

    // FINISHED
    smbc_close(srcfd);

    // Handle error condition.
    if (isErr) {
        const QString sPart = partInfo.absoluteFilePath();
        if (bMarkPartial) {
            const int size = config()->readEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE);
            if (partInfo.size() <  size) {
                QFile::remove(sPart);
            }
        }
        return;
    }

    // Rename partial file to its original name.
    if (bMarkPartial) {
        const QString sPart = partInfo.absoluteFilePath();
        // Remove old dest file if it exists..
        if (dstInfo.exists()) {
            QFile::remove(dstFile);
        }
        if (!QFile::rename(sPart, dstFile)) {
            qCDebug(KIO_SMB) << "failed to rename" << sPart << "to" << dstFile;
            error(ERR_CANNOT_RENAME_PARTIAL, sPart);
            return;
        }
    }

    // Restore the mtime on the file.
    const QString mtimeStr = metaData("modified");
    qCDebug(KIO_SMB) << "modified:" << mtimeStr;
    if (!mtimeStr.isEmpty()) {
        QDateTime dt = QDateTime::fromString(mtimeStr, Qt::ISODate);
        if (dt.isValid()) {
            struct utimbuf utbuf;
            utbuf.actime = QFileInfo(file).lastRead().toTime_t(); // access time, unchanged
            utbuf.modtime = dt.toTime_t(); // modification time
            utime(QFile::encodeName(dstFile).constData(), &utbuf);
        }
    }

    finished();
}