예제 #1
0
void QbsRunConfiguration::setBaseWorkingDirectory(const QString &wd)
{
    const QString &oldWorkingDirectory = workingDirectory();

    m_userWorkingDirectory = wd;

    const QString &newWorkingDirectory = workingDirectory();
    if (oldWorkingDirectory != newWorkingDirectory)
        emit baseWorkingDirectoryChanged(newWorkingDirectory);
}
예제 #2
0
void GitEditor::applyDiffChunk(const VcsBase::DiffChunk& chunk, bool revert)
{
    VcsBase::VcsBaseOutputWindow *outwin = VcsBase::VcsBaseOutputWindow::instance();
    QTemporaryFile patchFile;
    if (!patchFile.open())
        return;

    const QString baseDir = workingDirectory();
    patchFile.write(chunk.header);
    patchFile.write(chunk.chunk);
    patchFile.close();

    GitClient *client = GitPlugin::instance()->gitClient();
    QStringList args = QStringList() << QLatin1String("--cached");
    if (revert)
        args << QLatin1String("--reverse");
    QString errorMessage;
    if (client->synchronousApplyPatch(baseDir, patchFile.fileName(), &errorMessage, args)) {
        if (errorMessage.isEmpty())
            outwin->append(tr("Chunk successfully staged"));
        else
            outwin->append(errorMessage);
        if (revert)
            emit diffChunkReverted(chunk);
        else
            emit diffChunkApplied(chunk);
    } else {
        outwin->appendError(errorMessage);
    }
}
예제 #3
0
파일: kprocess.cpp 프로젝트: vasi/kdelibs
int KProcess::startDetached()
{
    Q_D(KProcess);

    qint64 pid;
    if (!QProcess::startDetached(d->prog, d->args, workingDirectory(), &pid))
        return 0;
    return (int) pid;
}
예제 #4
0
Path GetPhysFSWorkingDirectory()
{
	std::string workingDirStr = PHYSFS_getBaseDir();
	Path workingDirectory(workingDirStr);

	if (workingDirectory.has_filename())
		workingDirectory = workingDirectory.parent_path();

	return workingDirectory;
}
예제 #5
0
	void DrumKitTest::RunTest()
	{


		std::string workingDirectory("/home/jeremy/Desktop/Prog/RaspiDrums/Data/");
		std::string kitLocation(workingDirectory + "Kits/default.xml");


		DrumKit::Kit kit;

		DrumKit::Module module(workingDirectory);
		module.LoadKit(kitLocation, kit);


		std::string xmlFileLoc(workingDirectory + "alsaConfig.xml");

		Sound::AlsaParams aParams;
		Sound::Alsa::ReadXmlConfig(aParams, xmlFileLoc);


		Sound::Mixer mixer(module.soundParameters, aParams);
		Sound::Alsa  alsa(aParams, mixer);

		std::string sensorFile(workingDirectory + "../out.raw");

		char channel = 0;
		IO::Sensor sensor(channel);

		DrumKit::Trigger snareTrigger(kit.drum[0], mixer);

		alsa.Start();

		high_resolution_clock::time_point tStart = high_resolution_clock::now();
		unsigned long long dt = 0;


		while(dt < 10*1000)
		{

			high_resolution_clock::time_point t = high_resolution_clock::now();
			dt = (unsigned long long) duration<double, std::milli>(t - tStart).count();


			short value = sensor.GetOutput();
			snareTrigger.Trig(value);

		}


		alsa.Stop();


		return;
	}
void QDesignerFormBuilder::createResources(DomResources *resources)
{
    if (m_ignoreCreateResources)
        return;
    QStringList paths;
    if (resources != 0) {
        const QList<DomResource*> dom_include = resources->elementInclude();
        foreach (DomResource *res, dom_include) {
            QString path = QDir::cleanPath(workingDirectory().absoluteFilePath(res->attributeLocation()));
            paths << path;
        }
    }
예제 #7
0
/*!
 * \brief MainWindow::getMatchedFiles - get matched file list filtered by the file name pattern
 * \param fileNamePattern - the pattern of the file name
 * \param directoryName - the directory where the files located
 * \return a list of string contains matched file names
 */
QStringList MainWindow::getMatchedFiles(const QString& fileNamePattern, const QString& directoryName) {
    QStringList files;
    QFileInfo directory(directoryName);
    if ( directory.isDir() && directory.exists() ) {
        QRegExp filenameExpression(fileNamePattern, Qt::CaseInsensitive, QRegExp::RegExp2);
        QDir workingDirectory(directoryName);
        QFileInfoList fileInfoList = workingDirectory.entryInfoList(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);

        for ( QFileInfo& file : fileInfoList ) {
            QString filename = file.fileName();
            if ( filenameExpression.indexIn(filename) != -1 ) {
                files.append(filename);
            }
        }
    }
    return files;
}
예제 #8
0
	void DrumKit_HddTest::RunTest()
	{


		std::string workingDirectory("/home/jeremy/Desktop/Prog/RaspiDrums/Data/");
		std::string kitLocation(workingDirectory + "Kits/default.xml");


		DrumKit::Kit kit;

		DrumKit::Module module(workingDirectory);
		module.LoadKit(kitLocation, kit);


		std::string xmlFileLoc(workingDirectory + "alsaConfig.xml");

		Sound::AlsaParams aParams;
		Sound::Alsa::ReadXmlConfig(aParams, xmlFileLoc);


		Sound::Mixer mixer(module.soundParameters, aParams);
		Sound::Alsa  alsa(aParams, mixer);

		std::string sensorFile(workingDirectory + "../out.raw");

		IO::HddSensor hddSensor(sensorFile);
		DrumKit::Trigger snareTrigger(kit.drum[0], mixer);

		alsa.Start();

		int N = hddSensor.GetDataLength();

		for(int i = 0; i < N; i++)
		{

			short value = hddSensor.GetOutput();
			snareTrigger.Trig(value);

		}

		alsa.Stop();


		return;
	}
예제 #9
0
void ChangeSelectionDialog::recalculateCompletion()
{
    const QString workingDir = workingDirectory();
    if (workingDir == m_oldWorkingDir)
        return;
    m_oldWorkingDir = workingDir;

    if (!workingDir.isEmpty()) {
        GitClient *client = GitPlugin::instance()->client();
        QStringList args;
        args << QLatin1String("--format=%(refname:short)");
        QString output;
        if (client->synchronousForEachRefCmd(workingDir, args, &output)) {
            m_changeModel->setStringList(output.split(QLatin1Char('\n')));
            return;
        }
    }
    m_changeModel->setStringList(QStringList());
}
예제 #10
0
파일: Tracker.cpp 프로젝트: Ithamar/cosmoe
void
TTracker::ArgvReceived(int32 argc, char **argv)
{
	BMessage *message = CurrentMessage();
	const char *currentWorkingDirectoryPath = NULL;
	entry_ref ref;

	if (message->FindString("cwd", &currentWorkingDirectoryPath) == B_OK) {
		BDirectory workingDirectory(currentWorkingDirectoryPath);
		for (int32 index = 1; index < argc; index++) {
			BEntry entry;
			if (entry.SetTo(&workingDirectory, argv[index]) == B_OK
				&& entry.GetRef(&ref) == B_OK) 
				OpenRef(&ref);
			else if (get_ref_for_path(argv[index], &ref) == B_OK)
				OpenRef(&ref);
		}
	}
}
예제 #11
0
void ChangeSelectionDialog::selectCommitFromRecentHistory()
{
    QString workingDir = workingDirectory();
    if (workingDir.isEmpty())
        return;

    QString commit = change();
    int tilde = commit.indexOf(QLatin1Char('~'));
    if (tilde != -1)
        commit.truncate(tilde);
    LogChangeDialog dialog(false, this);
    dialog.setWindowTitle(tr("Select Commit"));

    dialog.runDialog(workingDir, commit, LogChangeWidget::IncludeRemotes);

    if (dialog.result() == QDialog::Rejected || dialog.commitIndex() == -1)
        return;

    m_ui->changeNumberEdit->setText(dialog.commit());
}
예제 #12
0
void ChangeSelectionDialog::recalculateDetails()
{
    terminateProcess();
    enableButtons(false);

    const QString workingDir = workingDirectory();
    QPalette palette = m_ui->workingDirectoryEdit->palette();
    Theme *theme = creatorTheme();
    if (workingDir.isEmpty()) {
        m_ui->detailsText->setPlainText(tr("Error: Bad working directory."));
        palette.setColor(QPalette::Text, theme->color(Theme::TextColorError));
        m_ui->workingDirectoryEdit->setPalette(palette);
        return;
    } else {
        palette.setColor(QPalette::Text, theme->color(Theme::TextColorNormal));
        m_ui->workingDirectoryEdit->setPalette(palette);
    }

    const QString ref = change();
    if (ref.isEmpty()) {
        m_ui->detailsText->clear();
        return;
    }

    QStringList args;
    args << QLatin1String("show") << QLatin1String("--stat=80") << ref;

    m_process = new QProcess(this);
    m_process->setWorkingDirectory(workingDir);
    m_process->setProcessEnvironment(m_gitEnvironment);

    connect(m_process, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
            this, &ChangeSelectionDialog::setDetails);

    m_process->start(m_gitExecutable.toString(), args);
    m_process->closeWriteChannel();
    if (!m_process->waitForStarted())
        m_ui->detailsText->setPlainText(tr("Error: Could not start Git."));
    else
        m_ui->detailsText->setPlainText(tr("Fetching commit data..."));
}
예제 #13
0
void VorbitalDlg::OnButtonBrowseFolderClick()
{
	QFileDialog fdialog( this, "Choose a directory", ".");
    QString dir = QFileDialog::getExistingDirectory(this, "Choose a directory", ".", QFileDialog::ShowDirsOnly);
    qDebug() << "Directory: " << dir << ".";
    QDir workingDirectory(dir);
    QStringList filters;
    filters << "*.wav" << "*.mp3" << "*.ogg" << "*.wv" << "*.snd" << "*.aif" << "*.aiff" /*<< "*.flac"*/;
    QFileInfoList files = workingDirectory.entryInfoList(filters, QDir::Files, QDir::Name);
	for( int i = 0; i < files.count(); i++ )
	{
        QListWidgetItem* item = new QListWidgetItem(files[i].baseName());
        item->setData(Qt::UserRole, QVariant(files[i].absoluteFilePath()));
        _lstPlaylist->addItem(item);
	}

	if( _lstPlaylist->currentRow() < 0 )
	{
		_lstPlaylist->setCurrentRow(0);
		_listPosition = 0;
	}
}
예제 #14
0
void ChangeSelectionDialog::recalculateDetails()
{
    if (m_process) {
        m_process->kill();
        m_process->waitForFinished();
        delete m_process;
        m_process = 0;
    }
    enableButtons(false);

    const QString workingDir = workingDirectory();
    QPalette palette = m_ui->workingDirectoryEdit->palette();
    if (workingDir.isEmpty()) {
        m_ui->detailsText->setPlainText(tr("Error: Bad working directory."));
        palette.setColor(QPalette::Text, Qt::red);
        m_ui->workingDirectoryEdit->setPalette(palette);
        return;
    } else {
        palette.setColor(QPalette::Text, Qt::black);
        m_ui->workingDirectoryEdit->setPalette(palette);
    }

    QStringList args;
    args << QLatin1String("log") << QLatin1String("-n1") << m_ui->changeNumberEdit->text();

    m_process = new QProcess(this);
    m_process->setWorkingDirectory(workingDir);
    m_process->setProcessEnvironment(m_gitEnvironment);

    connect(m_process, SIGNAL(finished(int)), this, SLOT(setDetails(int)));

    m_process->start(m_gitBinaryPath, args);
    m_process->closeWriteChannel();
    if (!m_process->waitForStarted())
        m_ui->detailsText->setPlainText(tr("Error: Could not start Git."));
    else
        m_ui->detailsText->setPlainText(tr("Fetching commit data..."));
}
예제 #15
0
void Q3IconViewExtraInfo::initializeQ3IconViewItems(const QList<DomItem *> &items)
{
    Q3IconView *iconView = qobject_cast<Q3IconView*>(widget());
    Q_ASSERT(iconView != 0);

    for (int i=0; i<items.size(); ++i) {
        DomItem *item = items.at(i);

        Q3IconViewItem *__item = new Q3IconViewItem(iconView);

        QList<DomProperty*> properties = item->elementProperty();
        for (int i=0; i<properties.size(); ++i) {
            DomProperty *p = properties.at(i);
            if (p->attributeName() == QLatin1String("text"))
                __item->setText(p->elementString()->text());

            if (p->attributeName() == QLatin1String("pixmap")) {
                DomResourcePixmap *pix = p->elementPixmap();
                QPixmap pixmap(core()->iconCache()->resolveQrcPath(pix->text(), pix->attributeResource(), workingDirectory()));
                __item->setPixmap(pixmap);
            }
        }
    }
}
예제 #16
0
void Command::run()
{
    // Check that the binary path is not empty
    if (binaryPath().trimmed().isEmpty()) {
        emit errorText(tr("Unable to start process, binary is empty"));
        return;
    }

    const unsigned processFlags = unixTerminalDisabled() ?
                unsigned(Utils::SynchronousProcess::UnixTerminalDisabled) :
                unsigned(0);
    const QSharedPointer<QProcess> process = Utils::SynchronousProcess::createProcess(processFlags);
    if (!workingDirectory().isEmpty())
        process->setWorkingDirectory(workingDirectory());

    process->setProcessEnvironment(processEnvironment());

    QByteArray stdOut;
    QByteArray stdErr;
    QString error;

    const int count = d->m_jobs.size();
    int exitCode = -1;
    bool ok = true;
    for (int j = 0; j < count; j++) {
        process->start(binaryPath(), d->m_jobs.at(j).arguments);
        if (!process->waitForStarted()) {
            ok = false;
            error += QString::fromLatin1("Error: \"%1\" could not be started: %2")
                    .arg(binaryPath(), process->errorString());
            break;
        }

        process->closeWriteChannel();
        const int timeOutSeconds = d->m_jobs.at(j).timeout;
        if (!Utils::SynchronousProcess::readDataFromProcess(*process, timeOutSeconds * 1000,
                                                            &stdOut, &stdErr, false)) {
            Utils::SynchronousProcess::stopProcess(*process);
            ok = false;
            error += msgTimeout(timeOutSeconds);
            break;
        }

        error += QString::fromLocal8Bit(stdErr);
        exitCode = process->exitCode();
        switch (reportTerminationMode()) {
        case NoReport:
            break;
        case ReportStdout:
            stdOut += msgTermination(exitCode, binaryPath(), d->m_jobs.at(j).arguments).toUtf8();
            break;
        case ReportStderr:
            error += msgTermination(exitCode, binaryPath(), d->m_jobs.at(j).arguments);
            break;
        }
    }

    // Special hack: Always produce output for diff
    if (ok && stdOut.isEmpty() && d->m_jobs.front().arguments.at(0) == QLatin1String("diff")) {
        stdOut += "No difference to HEAD";
    } else {
        // @TODO: Remove, see below
        if (ok && d->m_jobs.front().arguments.at(0) == QLatin1String("status"))
            removeColorCodes(&stdOut);
    }

    d->m_lastExecSuccess = ok;
    d->m_lastExecExitCode = exitCode;

    if (ok && !stdOut.isEmpty())
        emit outputData(stdOut);

    if (!error.isEmpty())
        emit errorText(error);

    emit finished(ok, exitCode, cookie());
    if (ok)
        emit success(cookie());
    // As it is used asynchronously, we need to delete ourselves
    this->deleteLater();
}
예제 #17
0
bool Q3ListBoxExtraInfo::loadWidgetExtraInfo(DomWidget *ui_widget)
{
    Q3ListBox *listBox = qobject_cast<Q3ListBox*>(widget());
    Q_ASSERT(listBox != 0);

    QList<DomItem *> items = ui_widget->elementItem();
    for (int i = 0; i < items.size(); ++i) {
        DomItem *item = items.at(i);

        QHash<QString, DomProperty*> properties = propertyMap(item->elementProperty());
        DomProperty *text = properties.value(QLatin1String("text"));
        DomProperty *pixmap = properties.value(QLatin1String("pixmap"));

        QString txt = text->elementString()->text();

        if (pixmap != 0) {
            DomResourcePixmap *pix = pixmap->elementPixmap();
            QPixmap pixmap(core()->iconCache()->resolveQrcPath(pix->text(), pix->attributeResource(), workingDirectory()));
            listBox->insertItem(pixmap, txt);
        } else {
            listBox->insertItem(txt);
        }
    }

    return true;
}
예제 #18
0
            emit processError(msgCannotWriteTempFile());
            delete d->m_tempFile;
            d->m_tempFile = 0;
            return false;
        }
#endif
    }

    STARTUPINFO si;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    d->m_pid = new PROCESS_INFORMATION;
    ZeroMemory(d->m_pid, sizeof(PROCESS_INFORMATION));

    QString workDir = QDir::toNativeSeparators(workingDirectory());
    if (!workDir.isEmpty() && !workDir.endsWith('\\'))
        workDir.append('\\');

    QStringList stubArgs;
    stubArgs << modeOption(d->m_mode)
             << d->m_stubServer.fullServerName()
             << workDir
             << (d->m_tempFile ? d->m_tempFile->fileName() : 0)
             << createWinCommandline(pcmd, pargs)
             << msgPromptToClose();

    const QString cmdLine = createWinCommandline(
            QCoreApplication::applicationDirPath() + QLatin1String("/qtcreator_process_stub.exe"), stubArgs);

    bool success = CreateProcessW(0, (WCHAR*)cmdLine.utf16(),
예제 #19
0
bool Q3TableExtraInfo::loadWidgetExtraInfo(DomWidget *ui_widget)
{
    Q_UNUSED(ui_widget);

    Q3Table *table = qobject_cast<Q3Table*>(widget());
    Q_ASSERT(table != 0);

    Q3Header *hHeader = table->horizontalHeader();

    QList<DomColumn*> columns = ui_widget->elementColumn();
    for (int i=0; i<columns.size(); ++i) {
        DomColumn *column = columns.at(i);

        QHash<QString, DomProperty*> properties = propertyMap(column->elementProperty());
        DomProperty *text = properties.value(QLatin1String("text"));
        DomProperty *pixmap = properties.value(QLatin1String("pixmap"));

        QString txt = text->elementString()->text();

        if (pixmap != 0) {
            DomResourcePixmap *pix = pixmap->elementPixmap();
            QIcon icon(core()->iconCache()->resolveQrcPath(pix->text(), pix->attributeResource(), workingDirectory()));
            hHeader->setLabel(i, icon, txt);
        } else {
            hHeader->setLabel(i, txt);
        }
    }

    Q3Header *vHeader = table->verticalHeader();

    QList<DomRow*> rows = ui_widget->elementRow();
    for (int i=0; i<rows.size(); ++i) {
        DomRow *row = rows.at(i);

        QHash<QString, DomProperty*> properties = propertyMap(row->elementProperty());
        DomProperty *text = properties.value(QLatin1String("text"));
        DomProperty *pixmap = properties.value(QLatin1String("pixmap"));

        QString txt = text->elementString()->text();

        if (pixmap != 0) {
            DomResourcePixmap *pix = pixmap->elementPixmap();
            QIcon icon(core()->iconCache()->resolveQrcPath(pix->text(), pix->attributeResource(), workingDirectory()));
            vHeader->setLabel(i, icon, txt);
        } else {
            vHeader->setLabel(i, txt);
        }
    }

    return true;
}
예제 #20
0
Result<ExitCode> ProcessAsUser::Run(const Settings& settings, ProcessTracker& processTracker) const
{
	Trace trace(settings.GetLogLevel());
	trace < L"ProcessAsUser::Attempt to log a user on to the local computer";
	StringBuffer userName(settings.GetUserName());
	StringBuffer domain(settings.GetDomain());
	StringBuffer password(settings.GetPassword());
	StringBuffer workingDirectory(settings.GetWorkingDirectory());
	StringBuffer commandLine(settings.GetCommandLine());

	SecurityManager securityManager;
	auto setPrivilegesResult = securityManager.SetPrivileges(trace, { SE_TCB_NAME, SE_ASSIGNPRIMARYTOKEN_NAME }, true);
	if(setPrivilegesResult.HasError())
	{
		return setPrivilegesResult.GetError();
	}

	auto newUserSecurityTokenHandle = Handle(L"New user security token");
	unsigned long logonTypeCount = sizeof(allLogonTypes) / sizeof(allLogonTypes[0]);
	for (unsigned long logonTypeIndex = 0; logonTypeIndex < logonTypeCount; logonTypeIndex++)
	{
		auto logonType = allLogonTypes[logonTypeIndex];
		trace < L"::LogonUser using logon type ";
		switch (logonType)
		{
			case LOGON32_LOGON_INTERACTIVE:
				trace << L"LOGON32_LOGON_INTERACTIVE";
				break;

			case LOGON32_LOGON_NETWORK:
				trace << L"LOGON32_LOGON_NETWORK";
				break;

			case LOGON32_LOGON_BATCH:
				trace << L"LOGON32_LOGON_BATCH";
				break;

			case LOGON32_LOGON_SERVICE:
				trace << L"LOGON32_LOGON_SERVICE";
				break;
		}

		if (LogonUser(
			userName.GetPointer(),
			domain.GetPointer(),
			password.GetPointer(),
			logonType,
			LOGON32_PROVIDER_DEFAULT,
			&newUserSecurityTokenHandle))
		{
			break;
		}
		
		auto error = Error(L"LogonUser");
		trace << L" - ";
		trace << error.GetDescription();

		if(logonTypeIndex == logonTypeCount -1)
		{
			return error;
		}
	}

	trace < L"ProcessAsUser::InitializeConsoleRedirection a new security descriptor";
	trace < L"::InitializeSecurityDescriptor";
	SECURITY_DESCRIPTOR securityDescriptor = {};
	if (!InitializeSecurityDescriptor(
		&securityDescriptor,
		SECURITY_DESCRIPTOR_REVISION))
	{
		return Error(L"InitializeSecurityDescriptor");
	}

	trace < L"::SetSecurityDescriptorDacl";
	if (!SetSecurityDescriptorDacl(
		&securityDescriptor,
		true,
		nullptr,
		false))
	{
		return Error(L"SetSecurityDescriptorDacl");
	}

	trace < L"ProcessAsUser::Creates a new access primary token that duplicates new process's token";
	auto primaryNewUserSecurityTokenHandle = Handle(L"Primary new user security token");
	SECURITY_ATTRIBUTES processSecAttributes = {};
	processSecAttributes.lpSecurityDescriptor = &securityDescriptor;
	processSecAttributes.nLength = sizeof(SECURITY_DESCRIPTOR);
	processSecAttributes.bInheritHandle = true;
	trace < L"::DuplicateTokenEx";
	if (!DuplicateTokenEx(
		newUserSecurityTokenHandle,
		0, // MAXIMUM_ALLOWED
		&processSecAttributes,
		SecurityImpersonation,
		TokenPrimary,
		&primaryNewUserSecurityTokenHandle))
	{
		return Error(L"DuplicateTokenEx");
	}	

	SECURITY_ATTRIBUTES threadSecAttributes = {};
	threadSecAttributes.lpSecurityDescriptor = nullptr;
	threadSecAttributes.nLength = 0;
	threadSecAttributes.bInheritHandle = false;	
	STARTUPINFO startupInfo = {};	

	trace < L"ProcessTracker::InitializeConsoleRedirection";
	auto error = processTracker.InitializeConsoleRedirection(processSecAttributes, startupInfo);
	if(error.HasError())
	{
		return Result<ExitCode>(error.GetError());
	}

	trace < L"::LoadUserProfile";
	PROFILEINFO profileInfo = {};
	profileInfo.dwSize = sizeof(PROFILEINFO);
	profileInfo.lpUserName = userName.GetPointer();
	if (!LoadUserProfile(primaryNewUserSecurityTokenHandle, &profileInfo))
	{
		return Error(L"LoadUserProfile");
	}

	auto newProcessEnvironmentResult = GetEnvironment(settings, primaryNewUserSecurityTokenHandle, settings.GetInheritanceMode(), trace);
	if (newProcessEnvironmentResult.HasError())
	{
		UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
		return Result<ExitCode>(newProcessEnvironmentResult.GetError());
	}

	auto setIntegrityLevelResult = securityManager.SetIntegrityLevel(settings.GetIntegrityLevel(), primaryNewUserSecurityTokenHandle, trace);
	if (setIntegrityLevelResult.HasError())
	{
		return Result<ExitCode>(setIntegrityLevelResult.GetError());
	}

	trace < L"ProcessAsUser::Create a new process and its primary thread. The new process runs in the security context of the user represented by the specified token.";
	PROCESS_INFORMATION processInformation = {};
	startupInfo.dwFlags = STARTF_USESHOWWINDOW;
	startupInfo.wShowWindow = ShowModeConverter::ToShowWindowFlag(settings.GetShowMode());
	auto cmdLine = settings.GetCommandLine();
	trace < L"::CreateProcessAsUser";	
	if (!CreateProcessAsUser(
		primaryNewUserSecurityTokenHandle,
		nullptr,
		commandLine.GetPointer(),
		&processSecAttributes,
		&threadSecAttributes,
		true,
		CREATE_UNICODE_ENVIRONMENT,
		newProcessEnvironmentResult.GetResultValue().CreateEnvironment(),
		workingDirectory.GetPointer(),
		&startupInfo,
		&processInformation))
	{		
		auto result = Error(L"CreateProcessAsUser");
		UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
		return result;
	}

	// ReSharper disable CppInitializedValueIsAlwaysRewritten
	// ReSharper disable CppEntityAssignedButNoRead
	
	auto processHandle = Handle(L"Service Process");
	processHandle = processInformation.hProcess;
	
	auto threadHandle = Handle(L"Thread");
	threadHandle = processInformation.hThread;

	auto exitCode = processTracker.WaiteForExit(processInformation.hProcess, trace);
	UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);	

	return exitCode;
}
예제 #21
0
void Q3ListViewExtraInfo::initializeQ3ListViewItems(const QList<DomItem *> &items, Q3ListViewItem *parentItem)
{
    for (int i=0; i<items.size(); ++i) {
        DomItem *item = items.at(i);

        Q3ListViewItem *__item = 0;
        if (parentItem != 0)
            __item = new Q3ListViewItem(parentItem);
        else
            __item = new Q3ListViewItem(static_cast<Q3ListView*>(widget()));

        int textCount = 0, pixCount = 0;
        QList<DomProperty*> properties = item->elementProperty();
        for (int i=0; i<properties.size(); ++i) {
            DomProperty *p = properties.at(i);
            if (p->attributeName() == QLatin1String("text"))
                __item->setText(textCount++, p->elementString()->text());

            if (p->attributeName() == QLatin1String("pixmap")) {
                DomResourcePixmap *pix = p->elementPixmap();
                QPixmap pixmap(core()->iconCache()->resolveQrcPath(pix->text(), pix->attributeResource(), workingDirectory()));
                __item->setPixmap(pixCount++, pixmap);
            }
        }

        if (item->elementItem().size()) {
            __item->setOpen(true);
            initializeQ3ListViewItems(item->elementItem(), __item);
        }
    }
}
예제 #22
0
bool Q3ListViewExtraInfo::loadWidgetExtraInfo(DomWidget *ui_widget)
{
    Q3ListView *listView = qobject_cast<Q3ListView*>(widget());
    Q_ASSERT(listView != 0);

    Q3Header *header = listView->header();

    QList<DomColumn*> columns = ui_widget->elementColumn();
    for (int i=0; i<columns.size(); ++i) {
        DomColumn *column = columns.at(i);

        QHash<QString, DomProperty*> properties = propertyMap(column->elementProperty());
        DomProperty *text = properties.value(QLatin1String("text"));
        DomProperty *pixmap = properties.value(QLatin1String("pixmap"));
        DomProperty *clickable = properties.value(QLatin1String("clickable"));
        DomProperty *resizable = properties.value(QLatin1String("resizable"));

        QString txt = text->elementString()->text();

        if (pixmap != 0) {
            DomResourcePixmap *pix = pixmap->elementPixmap();
            QIcon icon(core()->iconCache()->resolveQrcPath(pix->text(), pix->attributeResource(), workingDirectory()));
            listView->addColumn(icon, txt);
        } else {
            listView->addColumn(txt);
        }

        if (clickable != 0) {
            header->setClickEnabled(clickable->elementBool() == QLatin1String("true"), header->count() - 1);
        }

        if (resizable != 0) {
            header->setResizeEnabled(resizable->elementBool() == QLatin1String("true"), header->count() - 1);
        }
    }

    if (ui_widget->elementItem().size()) {
        initializeQ3ListViewItems(ui_widget->elementItem());
    }

    return true;
}
예제 #23
0
Result<ExitCode> ProcessWithLogon::RunInternal(Trace& trace, const Settings& settings, ProcessTracker& processTracker, Environment& environment, bool changeIntegrityLevel) const
{
	SECURITY_ATTRIBUTES securityAttributes = {};
	securityAttributes.nLength = sizeof(SECURITY_DESCRIPTOR);
	securityAttributes.bInheritHandle = true;

	STARTUPINFO startupInfo = {};
	startupInfo.dwFlags = STARTF_USESHOWWINDOW;
	startupInfo.wShowWindow = ShowModeConverter::ToShowWindowFlag(settings.GetShowMode());	
	PROCESS_INFORMATION processInformation = {};

	trace < L"ProcessTracker::InitializeConsoleRedirection";
	processTracker.InitializeConsoleRedirection(securityAttributes, startupInfo);	

	StringBuffer userName(settings.GetUserName());
	StringBuffer domain(settings.GetDomain());
	StringBuffer password(settings.GetPassword());
	StringBuffer workingDirectory(settings.GetWorkingDirectory());
	StringBuffer commandLine(settings.GetCommandLine());

	if (changeIntegrityLevel)
	{
		trace < L"::LogonUser";
		auto newUserSecurityTokenHandle = Handle(L"New user security token");
		if (!LogonUser(
			userName.GetPointer(),
			domain.GetPointer(),
			password.GetPointer(),
			LOGON32_LOGON_BATCH,
			LOGON32_PROVIDER_DEFAULT,
			&newUserSecurityTokenHandle))
		{
			return Error(L"LogonUser");
		}

		trace < L"::LoadUserProfile";
		PROFILEINFO profileInfo = {};
		profileInfo.dwSize = sizeof(PROFILEINFO);
		profileInfo.lpUserName = userName.GetPointer();
		if (!LoadUserProfile(newUserSecurityTokenHandle, &profileInfo))
		{
			return Error(L"LoadUserProfile");
		}

		SecurityManager securityManager;
		auto setIntegrityLevelResult = securityManager.SetIntegrityLevel(settings.GetIntegrityLevel(), newUserSecurityTokenHandle, trace);
		if (setIntegrityLevelResult.HasError())
		{
			return Result<ExitCode>(setIntegrityLevelResult.GetError());
		}

		trace < L"::CreateProcessWithTokenW";		
		if (!CreateProcessWithTokenW(
			newUserSecurityTokenHandle,
			LOGON_WITH_PROFILE,
			nullptr,
			commandLine.GetPointer(),
			CREATE_UNICODE_ENVIRONMENT,
			environment.CreateEnvironment(),
			workingDirectory.GetPointer(),
			&startupInfo,
			&processInformation))
		{
			return Error(L"CreateProcessWithLogonW");
		}
	}
	else
	{
		trace < L"::CreateProcessWithLogonW";		
		if (!CreateProcessWithLogonW(
			userName.GetPointer(),
			domain.GetPointer(),
			password.GetPointer(),
			LOGON_WITH_PROFILE,
			nullptr,
			commandLine.GetPointer(),
			CREATE_UNICODE_ENVIRONMENT,
			environment.CreateEnvironment(),
			workingDirectory.GetPointer(),
			&startupInfo,
			&processInformation))
		{
			return Error(L"CreateProcessWithLogonW");
		}
	}

	// ReSharper disable once CppInitializedValueIsAlwaysRewritten
	auto processHandle = Handle(L"Process");
	processHandle = processInformation.hProcess;

	// ReSharper disable once CppInitializedValueIsAlwaysRewritten
	auto threadHandle = Handle(L"Thread");
	threadHandle = processInformation.hThread;

	return processTracker.WaiteForExit(processInformation.hProcess, trace);
}
예제 #24
0
void OutputExecuteJob::start()
{
    Q_ASSERT( d->m_status == JobNotStarted );
    d->m_status = JobRunning;

    const bool isBuilder = d->m_properties.testFlag( IsBuilderHint );

    const KUrl effectiveWorkingDirectory = workingDirectory();
    if( effectiveWorkingDirectory.isEmpty() ) {
        if( d->m_properties.testFlag( NeedWorkingDirectory ) ) {
            // A directory is not given, but we need it.
            setError( InvalidWorkingDirectoryError );
            if( isBuilder ) {
                setErrorText( i18n( "No build directory specified for a builder job." ) );
            } else {
                setErrorText( i18n( "No working directory specified for a process." ) );
            }
            return emitResult();
        }

        setModel( new OutputModel );
    } else {
        // Basic sanity checks.
        if( !effectiveWorkingDirectory.isValid() ) {
            setError( InvalidWorkingDirectoryError );
            if( isBuilder ) {
                setErrorText( i18n( "Invalid build directory '%1'", effectiveWorkingDirectory.prettyUrl() ) );
            } else {
                setErrorText( i18n( "Invalid working directory '%1'", effectiveWorkingDirectory.prettyUrl() ) );
            }
            return emitResult();
        } else if( !effectiveWorkingDirectory.isLocalFile() ) {
            setError( InvalidWorkingDirectoryError );
            if( isBuilder ) {
                setErrorText( i18n( "Build directory '%1' is not a local path", effectiveWorkingDirectory.prettyUrl() ) );
            } else {
                setErrorText( i18n( "Working directory '%1' is not a local path", effectiveWorkingDirectory.prettyUrl() ) );
            }
            return emitResult();
        }

        QFileInfo workingDirInfo( effectiveWorkingDirectory.toLocalFile() );
        if( !workingDirInfo.isDir() ) {
            // If a working directory does not actually exist, either bail out or create it empty,
            // depending on what we need by properties.
            // We use a dedicated bool variable since !isDir() may also mean that it exists,
            // but is not a directory, or a symlink to an inexistent object.
            bool successfullyCreated = false;
            if( !d->m_properties.testFlag( CheckWorkingDirectory ) ) {
                successfullyCreated = QDir( effectiveWorkingDirectory.directory() ).mkdir( effectiveWorkingDirectory.fileName() );
            }
            if( !successfullyCreated ) {
                setError( InvalidWorkingDirectoryError );
                if( isBuilder ) {
                    setErrorText( i18n( "Build directory '%1' does not exist or is not a directory", effectiveWorkingDirectory.prettyUrl() ) );
                } else {
                    setErrorText( i18n( "Working directory '%1' does not exist or is not a directory", effectiveWorkingDirectory.prettyUrl() ) );
                }
                return emitResult();
            }
        }

        setModel( new OutputModel( effectiveWorkingDirectory ) );
    }
    Q_ASSERT( model() );

    model()->setFilteringStrategy( d->m_filteringStrategy );
    setDelegate( new OutputDelegate );

    // Slots hasRawStdout() and hasRawStderr() are responsible
    // for feeding raw data to the line maker; so property-based channel filtering is implemented there.
    if( d->m_properties.testFlag( PostProcessOutput ) ) {
        connect( d->m_lineMaker, SIGNAL(receivedStdoutLines(QStringList)),
                 SLOT(postProcessStdout(QStringList)) );
        connect( d->m_lineMaker, SIGNAL(receivedStderrLines(QStringList)),
                 SLOT(postProcessStderr(QStringList)) );
    } else {
        connect( d->m_lineMaker, SIGNAL(receivedStdoutLines(QStringList)), model(),
                 SLOT(appendLines(QStringList)) );
        connect( d->m_lineMaker, SIGNAL(receivedStderrLines(QStringList)), model(),
                 SLOT(appendLines(QStringList)) );
    }

    if( !d->m_properties.testFlag( NoSilentOutput ) || verbosity() != Silent ) {
        d->m_outputStarted = true;
        startOutput();
    }

    const QString joinedCommandLine = d->joinCommandLine();
    QString headerLine;
    if( !effectiveWorkingDirectory.isEmpty() ) {
        headerLine = effectiveWorkingDirectory.toLocalFile( KUrl::RemoveTrailingSlash ) + "> " + joinedCommandLine;
    } else {
        headerLine = joinedCommandLine;
    }
    model()->appendLine( headerLine );

    if( !effectiveWorkingDirectory.isEmpty() ) {
        d->m_process->setWorkingDirectory( effectiveWorkingDirectory.toLocalFile() );
    }
    d->m_process->setProcessEnvironment( d->effectiveEnvironment() );
    d->m_process->setProgram( d->effectiveCommandLine() );
    d->m_process->start();
}