Exemple #1
0
void shmInfo(void) {
	int i;

	char *confShm;
	char thisLine[CONFIG_SPACE_SIZE];
	char thatLine[CONFIG_SPACE_SIZE];

	FILE *shmFile;

	struct stat newStat;

	if((confShm = configFetch("shm_file", &i)) != NULL) {
		snprintf(thisLine, sizeof(thisLine), "%s%c", confShm, 0);
	}
	else {
		snprintf(thisLine, sizeof(thisLine), "%s%c", CONFIG_DEFAULT_SHM, 0);
	}

	if(stat(thisLine, &newStat) == 0) {
		if(newStat.st_size > 0 && newStat.st_size < sizeof(thisLine)) {
			if((shmFile = fopen(thisLine, "r")) != NULL) {
				memset(thatLine, 0, sizeof(thatLine));

				if(fread(thatLine, newStat.st_size, 1, shmFile) == 1) {
					shmId = atoi(thatLine);

					statBuffer = NULL;

					if((statBuffer = shmat(shmId, NULL, 0)) == (void *) -1 || statBuffer == NULL) {
						warningMessage(ERROR_SLIGHT, "Error occurred while trying to attach to shared memory segment");

						return;
					}

					shmTell(statBuffer->telludEntrySize, statBuffer->telludWorkersAvailable, statBuffer->telludServerStarted, statBuffer->telludLastTask, statBuffer->telludTotalTasks, statBuffer->telludInfoTime, statBuffer->telludErrorTime, statBuffer->telludThreadTasks, statBuffer->telludInfoMessage, statBuffer->telludErrorMessage, "tellud");
					shmTell(statBuffer->telmondEntrySize, statBuffer->telmondWorkersAvailable, statBuffer->telmondServerStarted, statBuffer->telmondLastTask, statBuffer->telmondTotalTasks, statBuffer->telmondInfoTime, statBuffer->telmondErrorTime, statBuffer->telmondThreadTasks, statBuffer->telmondInfoMessage, statBuffer->telmondErrorMessage, "telmond");
					shmTell(statBuffer->telskindEntrySize, statBuffer->telskindWorkersAvailable, statBuffer->telskindServerStarted, statBuffer->telskindLastTask, statBuffer->telskindTotalTasks, statBuffer->telskindInfoTime, statBuffer->telskindErrorTime, statBuffer->telskindThreadTasks, statBuffer->telskindInfoMessage, statBuffer->telskindErrorMessage, "telskind");
				}

				if(fclose(shmFile) == -1) {
					warningMessage(ERROR_SLIGHT, "Error occurred while trying to close shared memory id file");
				}
			}
			else {
				warningMessage(ERROR_SLIGHT, "Error occurred while trying to open shared memory id file for reading");
			}
		}
		else {
			warningMessage(ERROR_SLIGHT, "Error occurred while trying to stat shared memory id file");
		}
	}
	else {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to stat shared memory id file");
	}
}
bool OscapScannerBase::tryToReadStdOutChar(QProcess& process)
{
    char readChar = '\0';
    if (!process.getChar(&readChar))
        return false;

    if (!mCapabilities.progressReporting())
        return true; // We did read something but it's not in a format we can parse.

    if (readChar == ':')
    {
        mLastRuleID = mReadBuffer;
        if (mReadingRuleID) // sanity check
        {
            emit progressReport(mLastRuleID, "processing");
        }
        else
        {
            emit warningMessage(QString(
                QObject::tr("Error when parsing scan progress output from stdout of the 'oscap' process. "
                "':' encountered while not reading rule ID, newline and/or rule result are missing! "
                "Read buffer is '%1'.")).arg(mReadBuffer));
        }
        mReadBuffer = "";
        mReadingRuleID = false;
    }
    else if (readChar == '\n')
    {
        if (!mReadingRuleID) // sanity check
        {
            emit progressReport(mLastRuleID, mReadBuffer);
        }
        else
        {
            emit warningMessage(QString(
                QObject::tr("Error when parsing scan progress output from stdout of the 'oscap' process. "
                "Newline encountered while reading rule ID, rule result and/or ':' are missing! "
                "Read buffer is '%1'.")).arg(mReadBuffer));
        }
        mReadBuffer = "";
        mReadingRuleID = true;
    }
    else
    {
        // we know for sure that buffer[0] can only contain ASCII characters
        // (IDs and special keywords regarding rule status)
        mReadBuffer.append(QChar::fromAscii(readChar));
    }

    return true;
}
void searchResult(UserInfo userInfo[], int num)
{
	int input;

	resultSound();

	while (1){
		topMessage("검색", "Search");
		messageBoxB("검색  ", "결과");

		printf("\n\n\t\t\t회원ID\t: %d \n\n", userInfo[num].userId);
		printf("\t\t\t이름\t: %s \n", userInfo[num].userName);
		printf("\t\t\t연락처\t: %s \n", userInfo[num].handphone);
		printf("\t\t\t주소\t: %s \n", userInfo[num].userAddress);

		puts("\n\n");
		BOT_COLOR;
		printf("\t\t\t\t\t\t\t\t\t        ");
		printf("\t\t\t\t 나가기 :  ESC \t\t\t\t\t   ");
		printf("\t\t\t\t\t\t\t\t\t        ");
		DEF_COLOR;

		input = getch();

		if (input == ESC_KEY){
			outSound();
			return;
		}
		else warningMessage(input - '0', 0, 0);
	}
}
Exemple #4
0
void TimeSync::getNTPTime()
{
    QUdpSocket sock;
    sock.connectToHost("0.pool.ntp.org",123);
    if(!sock.waitForConnected(1000))return;
    QByteArray data(48,char(0)); *(reinterpret_cast<qint32 *>(&data.data()[0]))=4194959577;
    if(sock.write(data)<0||!sock.waitForReadyRead(3000)||sock.bytesAvailable()!=48)return;
    data=sock.readAll();
    quint32 seconds=qToBigEndian(*(reinterpret_cast<quint32 *>(&data.data()[40])));
    quint32 fraction=qToBigEndian(*(reinterpret_cast<quint32 *>(&data.data()[44])));
    quint32 newTime=QDateTime::fromMSecsSinceEpoch(seconds*1000ll+fraction*1000ll/0x100000000ll-2208988800000ll).toTime_t();

    if(newTime<1451606400 || newTime>4000000000){
        QThread::msleep(500);
        emit startSync();
        return;
    }
    qint32 tempTimeShift=qint64(newTime)-qint64(QDateTime::currentDateTime().toTime_t());

    if(timeShift!=0)tempTimeShift=qint32((qint64(timeShift)+qint64(tempTimeShift))/2);

    if(tempTimeShift>3600 || tempTimeShift<-3600){
        static bool showMessage=true;
        if(showMessage)emit warningMessage(julyTr("TIME_SYNC_ERROR","Your clock is not set. Please close the Qt Bitcoin Trader and set the clock. Changing time at Qt Bitcoin Trader enabled can cause errors and damage the keys."));
        showMessage=false;
    }
    else
        timeShift.fetchAndStoreOrdered(tempTimeShift);

    getNTPTimeRetryCount++;
    if(getNTPTimeRetryCount<3)emit startSync();
}
void OscapScannerBase::watchStdErr(QProcess& process)
{
    process.setReadChannel(QProcess::StandardError);

    QString stdErrOutput("");

    // As readStdOut() is greedy and will continue reading for as long as there is output for it,
    // by the time we come to handle sdterr output there may be multiple warning and/or error messages.
    while (process.canReadLine())
    {
        // Trailing \n is returned by QProcess::readLine
        stdErrOutput = process.readLine();

        if (!stdErrOutput.isEmpty())
        {
            if (stdErrOutput.contains("WARNING: "))
            {
                QString guiMessage = guiFriendlyMessage(stdErrOutput);
                emit warningMessage(QObject::tr(guiMessage.toUtf8().constData()));
            }
            // Openscap >= 1.2.11 (60fb9f0c98eee) sends this message through stderr
            else if (stdErrOutput.contains(QRegExp("^Downloading: .+ \\.{3} \\w+\\n")))
            {
                emit infoMessage(stdErrOutput);
            }
            else
            {
                emit errorMessage(QObject::tr("The 'oscap' process has written the following content to stderr:\n"
                                            "%1").arg(stdErrOutput));
            }
        }

    }

}
Exemple #6
0
void pidRemove(void) {
	int i;
	int *confPort;

	char *confPid;
	char thisLine[CONFIG_SPACE_SIZE];

	struct stat newStat;

	if((confPort = configFetch("listen_port", &i)) != NULL) {
		if((confPid = configFetch("pid_file", &i)) != NULL) {
			snprintf(thisLine, sizeof(thisLine), "%s.%d%c", confPid, *confPort, 0);
		}
		else {
			snprintf(thisLine, sizeof(thisLine), "%s.%d%c", CONFIG_DEFAULT_PID, *confPort, 0);
		}
	}
	else {
		if((confPid = configFetch("pid_file", &i)) != NULL) {
			snprintf(thisLine, sizeof(thisLine), "%s.%d%c", confPid, CONFIG_DEFAULT_PORT, 0);
		}
		else {
			snprintf(thisLine, sizeof(thisLine), "%s.%d%c", CONFIG_DEFAULT_PID, CONFIG_DEFAULT_PORT, 0);
		}
	}

	if(stat(thisLine, &newStat) == 0) {
		if(unlink(thisLine) != 0) {
			warningMessage(ERROR_SLIGHT, "Error occurred while trying to remove file");
		}
	}
}
int Dialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QDialog::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: setInteger(); break;
        case 1: setDouble(); break;
        case 2: setItem(); break;
        case 3: setText(); break;
        case 4: setColor(); break;
        case 5: setFont(); break;
        case 6: setExistingDirectory(); break;
        case 7: setOpenFileName(); break;
        case 8: setOpenFileNames(); break;
        case 9: setSaveFileName(); break;
        case 10: criticalMessage(); break;
        case 11: informationMessage(); break;
        case 12: questionMessage(); break;
        case 13: warningMessage(); break;
        case 14: errorMessage(); break;
        default: ;
        }
        _id -= 15;
    }
    return _id;
}
void printList(UserInfo userInfo[])
{
	int input, page, k = 1, temp;
	int *ptr = &k;
	char search[OVERLAP_BUFFER];

	page = 1 + (count - 1) / 18;	//전체 페이지 계산

	while(1) {
		printListSub(userInfo, page, ptr, ON);

		input = getch();

		if (input == ARROW_BUFFER)
			input = getch();
		
		switch (input)
		{
		case LEFT_ARROW_KEY:	//좌측 방향키
			moveSound();
			if (k != 1) k--;
			break;
		case RIGHT_ARROW_KEY:	//우측 방향키
			moveSound();
			if (k != page) k++;
			break;
		case ENTER_KEY:		//enter키
			inSound();
			printListSub(userInfo, page, ptr, OFF);

			printf("페이지 검색: "); fgets(search, OVERLAP_BUFFER, stdin);
			temp = atoi(search);

			if (temp > 0 && temp <= page) k = temp;
			else warningMessage(0, 0, 0);

			break;
		case ESC_KEY:		//esc키
			outSound();
			return;
		default:
			warningMessage(input - '0', page, ptr);
			break;
		}
	}
}
bool Account::checkSupported()
{
    Settings &settings = Settings::instance();
    // Read user id, start/end dates, account type
    std::string userId, startDate, endDate, accountType("true"), sign;
    bool supported = settings.getBool("account/supported", false);
    if(!supported) {
        warningMessage(_("Account is not supported"));
        return false;
    }

    userId = settings.getString("account/user_id", "");
    startDate = settings.getString("account/start_date", "");
    endDate = settings.getString("account/end_date", "");
    sign = settings.getString("account/sign", "");

    std::string baMessage = userId + startDate + endDate + accountType;

    GByte *key = reinterpret_cast<GByte*>(CPLStrdup(sign.c_str()));
    int nLength = CPLBase64DecodeInPlace(key);
    std::string baSignature;
    baSignature.assign(reinterpret_cast<const char*>(key),
                       static_cast<size_t>(nLength));
    memset(key, 0, baSignature.size());
    CPLFree(key);

    bool verify = verifyRSASignature(
                reinterpret_cast<const unsigned char*>(baMessage.c_str()),
                static_cast<unsigned int>(baMessage.size()),
                reinterpret_cast<const unsigned char*>(baSignature.c_str()),
                static_cast<unsigned int>(baSignature.size()));
    if(!verify) {
        return false;
    }

    time_t current = time(nullptr);
    time_t start = timeFromString(startDate.c_str());
    time_t end = timeFromString(endDate.c_str());
    bool out = current >= start && current <= end;
    if(!out) {
        warningMessage(_("Account is supported. Verify success. Period expired."));
    }
    return out;
}
Exemple #10
0
void LinuxtrackGui::logsPackaged(int exitCode, QProcess::ExitStatus exitStatus)
{
  (void)exitCode;
  if((exitCode == 0) && (exitStatus == QProcess::NormalExit)){
    infoMessage(QString::fromUtf8("Package created successfully..."));
  }else{
    warningMessage(QString::fromUtf8("Couldn't create the package!\n"
    "Please check that you have write access to the destination directory!"));
  }
  ui.PackageLogsButton->setEnabled(true);
}
void searchMain(UserInfo userInfo[], int todo, char mess[], char top[])
{
	int input, menu = 1, num;
	int *ptr = &menu;
	char *menu_num2[MENU_NUM] = {
		{ "1. 회원ID로 검색" },
		{ "2. 이름으로 검색" },
		{ "3. 연락처로 검색" }
	};

	while (1) {
		topMessage(mess, top);
		messageBoxB("검색  ", "방법");
		menuSelectB(menu, 3, menu_num2);
		bottomMessageC();

		input = getch();

		if (input == ARROW_BUFFER)
			input = getch();

		switch (input)
		{
		case UP_ARROW_KEY:
			moveSound();
			if (menu > 1) menu--;
			break;
		case DOWN_ARROW_KEY:
			moveSound();
			if (menu < 3) menu++;
			break;
		case ENTER_KEY:
			inSound();
			num = searchUser(userInfo, menu);

			if (num){
				if (todo == _DELETE)
					deleteUser(userInfo, num);
				else if (todo == MODIFY)
					modifyUser(userInfo, num);
				else
					searchResult(userInfo, num);
			}
			break;
		case ESC_KEY:
			outSound();
			return;
		default:
			warningMessage(input - '0', 3, ptr);
			break;
		}
	}
}
Exemple #12
0
void ParserMixin::skipComments(const ParseContextSPtr& context, CommentSPtr pComment)
{
    if (!pComment)
        pComment = parseComment(context);
    while (pComment)
    {
        context->mMessageCollector->addMessage(
            warningMessage(context, Message::p_misplacedComment,
                           pComment->line(), pComment->column()));
        pComment = parseComment(context);
    }
}
Exemple #13
0
void timerStopThreads(int signalNumber) {
	int i;

	if(pMainMainInfo->timerThreadAccess == 0) {
		return;
	}

	warningMessage(ERROR_SLIGHT, "At least one thread refused to stop it's activity as requested, using force to terminate it");

	for(i = 0; i < THREAD_TELSKIND; i++) {
		threadKill(&threadPool[i]);
	}
}
void deleteUser(UserInfo userInfo[], int del)
{
	int input, menu = 1;

	while (del){
		topMessage("삭제", "Delete");

		printf("\n\n\n\n\t\t\t회원ID\t: %d \n\n", userInfo[del].userId);
		printf("\t\t\t이름\t: %s \n", userInfo[del].userName);
		printf("\t\t\t연락처\t: %s \n", userInfo[del].handphone);
		printf("\t\t\t주소\t: %s \n", userInfo[del].userAddress);

		puts("\n\n\n\t\t\t   정말로 삭제하시겠습니까? \n\n\n");
		bottomMessageB("삭제");

		input = getch();

		if (input == ENTER_KEY){
			inSound();
			/* 빈 메모리 공간이 많아지면 메모리 할당량 축소 */
			if (count < maxsize / 3){
				maxsize /= 2;
				userInfo = (UserInfo*)realloc(userInfo, sizeof(UserInfo)*maxsize);
			}
			/* 삭제 대상이 맨 마지막에 있다면, count를 하나 줄이는 것으로 끝 */
			if (del == count){
				centerMessage("삭제", "Delete");
				count--;
				return;
			}
			/* 나머지 경우는 한 칸씩 앞으로 덮어씌움 */
			else{
				for (int i = del + 1; i <= count; i++){
					userInfo[i - 1].userId = userInfo[i].userId;
					strcpy(userInfo[i - 1].userName, userInfo[i].userName);
					strcpy(userInfo[i - 1].userAddress, userInfo[i].userAddress);
					strcpy(userInfo[i - 1].handphone, userInfo[i].handphone);
				}
				centerMessage("삭제", "Delete");
				count--;
				return;
			}
		}
		else if (input == ESC_KEY){
			outSound();
			return;
		}
		else warningMessage(input - '0', 0, 0);
	}
	return;
}
int searchManyPrint(UserInfo userInfo[], int overlap[], int num)
{
	int input;

	resultSound();

	while (1) {
		topMessage("검색", "Search");

		BEAUTI2_COLOR; puts("\n\t\t\t      ◎  검색  결과  ◎");
		BEAUTI1_COLOR; puts("\t\t\t       ================");
		DEF_COLOR;

		for (int i = 1; i <= num; i++){
			printf("   %2d.  %d \t %s   \t%s  \t%s\n", i,
				userInfo[overlap[i]].userId, userInfo[overlap[i]].userName,
				userInfo[overlap[i]].handphone, userInfo[overlap[i]].userAddress);
		}

		for (int i = 1; i < OVERLAP_BUFFER - num; i++)
			puts(" ");	//공백 채우기

		if (num + 1 == OVERLAP_BUFFER){
			BEAUTI2_COLOR;
			puts("\n\t\t  검색 결과가 더 있으나 여기까지만 출력됩니다. ");
			puts("\t\t원하시는 결과가 없으면 다른 방법으로 검색해주세요.\n");
		}
		else puts("\n\n\n");

		BOT_COLOR;
		printf("\t\t\t\t\t\t\t\t\t        ");
		printf("\t 선택 :  해당 번호 입력 \t\t     나가기 :  ESC \t\t    ");
		printf("\t\t\t\t\t\t\t\t\t        ");
		DEF_COLOR;

		input = getch();
		input -= '0';	//아스키 값을 받기 때문에

		if (input + '0' == ESC_KEY){
			outSound();
			return 0;
		}
		else if (input > 0 && input <= num){
			inSound();
			return overlap[input];
		}
		else warningMessage(input - '0', 0, 0);
	}
}
Exemple #16
0
char *userGetInfo(struct paramInfo * pi) {
	int k;

	char *newBuffer;

	if((newBuffer = malloc(DATA_BLOCK_SIZE)) == NULL) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for user info buffer");

		return(NULL);
	}

	k = _snprintf(newBuffer, DATA_BLOCK_SIZE, "%s%c", nodeFetchUserLogin(), ITEM_SEPARATOR);
	k += _snprintf(newBuffer + k, DATA_BLOCK_SIZE - k, "%s%c", nodeFetchUserGroup(), ITEM_SEPARATOR);
	k += _snprintf(newBuffer + k, DATA_BLOCK_SIZE - k, "%s%c", nodeFetchUserName(), ITEM_SEPARATOR);
	k += _snprintf(newBuffer + k, DATA_BLOCK_SIZE - k, "%s%c", nodeFetchUserHome(), 0);

	return(newBuffer);
}
void OscapScannerRemoteSsh::removeRemoteFile(const QString& path, const QString& desc)
{
    SshSyncProcess proc(mSshConnection, this);
    proc.setCommand("rm");
    proc.setArguments(QStringList(path));
    proc.setCancelRequestSource(&mCancelRequested);
    proc.run();

    if (proc.getExitCode() != 0)
    {
        emit warningMessage(QString(
            QObject::tr("Failed to remove remote file %1. "
            "Diagnostic info: %2")).arg(desc).arg(proc.getDiagnosticInfo()));

        mCancelRequested = true;
        signalCompletion(mCancelRequested);
    }
}
void OscapScannerBase::watchStdErr(QProcess& process)
{
    process.setReadChannel(QProcess::StandardError);

    QString errorMessage("");

    while (process.canReadLine())
    {
        // Trailing \n is returned by QProcess::readLine
        errorMessage += process.readLine();
    }

    if (!errorMessage.isEmpty())
    {
        emit warningMessage(QObject::tr("The 'oscap' process has written the following content to stderr:\n"
                                        "%1").arg(errorMessage));
    }
}
bool ConnectionFactory::createRemoteConnection(const enum ngsCatalogObjectType type,
                                               const std::string &path,
                                               const Options &options)
{
    switch(type) {
    case CAT_CONTAINER_NGW:
    {
        std::string url = options.asString(KEY_URL);
        if(url.empty()) {
            return errorMessage(_("Missing required option 'url'"));
        }

        std::string login = options.asString(KEY_LOGIN);
        if(login.empty()) {
            login = "******";
        }
        else {
            std::string oldLogin(login);
            login = CPLString(login).Trim();
            if(!compare(oldLogin, login, true)) {
                warningMessage("Login was trimmed!");
            }
        }
        std::string password = options.asString(KEY_PASSWORD);
        bool isGuest = options.asBool(KEY_IS_GUEST);

        CPLJSONDocument connectionFile;
        CPLJSONObject root = connectionFile.GetRoot();
        root.Add(KEY_TYPE, type);
        root.Add(KEY_URL, url);
        root.Add(KEY_LOGIN, login);
        root.Add(KEY_IS_GUEST, isGuest);
        if(!password.empty()) {
            root.Add(KEY_PASSWORD, encrypt(password));
        }

        return connectionFile.Save(path);
    }
    default:
        return errorMessage(_("Unsupported connection type %d"), type);
    }
}
Exemple #20
0
char *machGetInfo(struct paramInfo * pi) {
	int k;

	char *newBuffer;

	if((newBuffer = malloc(DATA_BLOCK_SIZE)) == NULL) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for machine info buffer");

		return(NULL);
	}

	k = _snprintf(newBuffer, DATA_BLOCK_SIZE, "%s%c", nodeFetchNode(), ITEM_SEPARATOR);
	k += _snprintf(newBuffer + k, DATA_BLOCK_SIZE - k, "%s%c", nodeFetchDomain(), ITEM_SEPARATOR);
	k += _snprintf(newBuffer + k, DATA_BLOCK_SIZE - k, "%s%c", nodeFetchSystem(), ITEM_SEPARATOR);
	k += _snprintf(newBuffer + k, DATA_BLOCK_SIZE - k, "%s%c", nodeFetchRelease(), ITEM_SEPARATOR);
	k += _snprintf(newBuffer + k, DATA_BLOCK_SIZE - k, "%s%c", nodeFetchDistribution(), ITEM_SEPARATOR);
	k += _snprintf(newBuffer + k, DATA_BLOCK_SIZE - k, "%s%c", nodeFetchMachine(), 0);

	return(newBuffer);
}
int saveInfo(UserInfo userInfo[], FILE *writeFile)
{
	int input;

	while (1) {
		system("cls");

		TOP_COLOR;
		printf("Save  \t\t\t\t\t\t\t\t\t\t"); printf("\t\t\t\t\t\t\t\t\t        ");
		BOT_COLOR;
		printf("\t\t\t\t\t\t\t\t\t        ");
		printf("\t\t\t        변경 내용 저장\t\t\t\t\t ");
		printf("\t\t\t\t\t\t\t\t\t        ");
		DEF_COLOR;

		puts("\n\n\n\n\n\n\n\n\t\t\t    정말로 저장하시겠습니까? \n\n\n\n\n\n\n");
		bottomMessageB("저장");

		input = getch();

		if (input == ENTER_KEY){
			actionSound();
			writeFile = fopen("data.txt", "wt");	//writeFile open

			fprintf(writeFile, "%s\n", userInfo[0].userAddress);

			for (int i = 1; i <= count; i++)
				fprintf(writeFile, "%d\t%s\t%s\t%s\n",
				userInfo[i].userId, userInfo[i].userName, userInfo[i].userAddress, userInfo[i].handphone);

			fclose(writeFile);		//writeFile close
			return SAVE;
		}

		else if (input == ESC_KEY){
			outSound();
			return 0;
		}
		else warningMessage(input - '0', 0, 0);
	}
}
QString OscapScannerRemoteSsh::readRemoteFile(const QString& path, const QString& desc)
{
    SshSyncProcess proc(mSshConnection, this);
    proc.setCommand("cat");
    proc.setArguments(QStringList(path));
    proc.setCancelRequestSource(&mCancelRequested);
    proc.run();

    if (proc.getExitCode() != 0)
    {
        emit warningMessage(QString(
            QObject::tr("Failed to copy back %1. "
            "You will not be able to save this data! Diagnostic info: %2")).arg(desc).arg(proc.getDiagnosticInfo()));

        mCancelRequested = true;
        signalCompletion(mCancelRequested);
        return "";
    }

    return proc.getStdOutContents();
}
Exemple #23
0
Dialogs::Dialogs(QWidget *parent)
   : QWidget(parent), ui(new Ui::Dialogs)
{
   ui->setupUi(this);
   setWindowTitle(tr("Standard Dialogs"));

   ui->native_checkBox->setChecked(true);

   // signals
   connect(ui->integer_pushButton,    SIGNAL(clicked()), this, SLOT(setInteger()));
   connect(ui->double_pushButton,     SIGNAL(clicked()), this, SLOT(setDouble()));
   connect(ui->getItem_pushButton,    SIGNAL(clicked()), this, SLOT(setItem()));
   connect(ui->getText_pushButton,    SIGNAL(clicked()), this, SLOT(setText()));

   connect(ui->dir_pushButton,        SIGNAL(clicked()), this, SLOT(setExistingDirectory()));
   connect(ui->openFile_pushButton,   SIGNAL(clicked()), this, SLOT(setOpenFileName()));
   connect(ui->openFiles_pushButton,  SIGNAL(clicked()), this, SLOT(setOpenFileNames()));

   connect(ui->critical_pushButton,   SIGNAL(clicked()), this, SLOT(criticalMessage()));
   connect(ui->info_pushButton,       SIGNAL(clicked()), this, SLOT(informationMessage()));
   connect(ui->quest_pushButton,      SIGNAL(clicked()), this, SLOT(questionMessage()));
   connect(ui->warn_pushButton,       SIGNAL(clicked()), this, SLOT(warningMessage()));
   connect(ui->error_pushButton,      SIGNAL(clicked()), this, SLOT(errorMessage()));
}
Exemple #24
0
int main(int argc, char *argv[]) {
	int i, j;
	int thisSocket, thatSocket;
	int *confPort;
	unsigned int tmpSeconds;

	char *confConfig, *confEngine, *confPassword;
	char magicCookie[] = "TELLUTELLUTELLUTELLUTELLUTELLU";

	size_t s;

	uid_t *thisUid;
	gid_t *thisGid;

	/*
	 *
	 * Initialize default values.
	 *
	 */

	pMainMainInfo = &mainMainInfo;
	pMainThreadInfo = &mainThreadInfo;

	memset(pMainMainInfo, 0, sizeof(mainMainInfo));
	memset(pMainThreadInfo, 0, sizeof(mainThreadInfo));

	/*
	 *
	 * Read command line and parse configuration file.
	 *
	 */

	cmdRead(argv, argc);

	if((confConfig = configFetch("config_file", &i)) != NULL) {
		if(configRead(confConfig) != 0) {
			warningMessage(ERROR_SLIGHT, "Error occurred while trying to read configuration file");
		}
	}
	else {
		if(configRead(CONFIG_DEFAULT_FILE) != 0) {
			warningMessage(ERROR_SLIGHT, "Error occurred while trying to read configuration file");
		}
	}

	cmdRead(argv, argc);

	nodeInitNames();

	/*
	 *
	 * Initialize thread pool.
	 *
	 */

	if((threadPool = malloc(sizeof(struct threadInfo) * THREAD_TELSKIND)) == NULL) {
		warningMessage(ERROR_FATAL, "Error occurred while trying to allocate memory for thread pool");
	}

	memset(threadPool, 0, sizeof(struct threadInfo) * THREAD_TELSKIND);

	/*
	 *
	 * Initialize configurable subroutines.
	 *
	 */

	pMainThreadInfo->threadReady = 1;

	for(j = 0; j < THREAD_TELSKIND; j++) {
		threadPool[j].threadReady = 1;

		threadPool[j].magicCookie = magicCookie;
		threadPool[j].pMainInfo = pMainMainInfo;

		if((confEngine = configFetch("storage_engine", &i)) != NULL) {
			if(strncasecmp(confEngine, "plain", strlen(confEngine)) == 0) {
				threadPool[j].dbInfo.connect = plainConnect;
				threadPool[j].dbInfo.disconnect = plainDisconnect;
				threadPool[j].dbInfo.escape = plainEscape;
				threadPool[j].dbInfo.push = plainPush;
				threadPool[j].dbInfo.pull = plainPull;
				threadPool[j].dbInfo.round = plainRound;
				threadPool[j].dbInfo.free = plainFree;
				threadPool[j].dbInfo.expire = plainExpire;
				threadPool[j].dbInfo.cookie = plainCookie;
				threadPool[j].dbInfo.insert = plainInsert;
				threadPool[j].dbInfo.login = plainLogin;
				threadPool[j].dbInfo.logout = plainLogout;
				threadPool[j].dbInfo.session = plainSession;
				threadPool[j].dbInfo.permission = plainPermission;

				pMainThreadInfo->dbInfo.connect = plainConnect;
				pMainThreadInfo->dbInfo.disconnect = plainDisconnect;
				pMainThreadInfo->dbInfo.escape = plainEscape;
				pMainThreadInfo->dbInfo.push = plainPush;
				pMainThreadInfo->dbInfo.pull = plainPull;
				pMainThreadInfo->dbInfo.round = plainRound;
				pMainThreadInfo->dbInfo.free = plainFree;
				pMainThreadInfo->dbInfo.expire = plainExpire;
				pMainThreadInfo->dbInfo.cookie = plainCookie;
				pMainThreadInfo->dbInfo.insert = plainInsert;
				pMainThreadInfo->dbInfo.login = plainLogin;
				pMainThreadInfo->dbInfo.logout = plainLogout;
				pMainThreadInfo->dbInfo.session = plainSession;
				pMainThreadInfo->dbInfo.permission = plainPermission;

				continue;
			}
		}

		threadPool[j].dbInfo.connect = mysqlConnect;
		threadPool[j].dbInfo.disconnect = mysqlDisconnect;
		threadPool[j].dbInfo.escape = mysqlEscape;
		threadPool[j].dbInfo.push = mysqlPush;
		threadPool[j].dbInfo.pull = mysqlPull;
		threadPool[j].dbInfo.round = mysqlRound;
		threadPool[j].dbInfo.free = mysqlFree;
		threadPool[j].dbInfo.expire = mysqlExpire;
		threadPool[j].dbInfo.cookie = mysqlCookie;
		threadPool[j].dbInfo.insert = mysqlInsert;
		threadPool[j].dbInfo.login = mysqlLogin;
		threadPool[j].dbInfo.logout = mysqlLogout;
		threadPool[j].dbInfo.session = mysqlSession;
		threadPool[j].dbInfo.permission = mysqlPermission;

		pMainThreadInfo->dbInfo.connect = mysqlConnect;
		pMainThreadInfo->dbInfo.disconnect = mysqlDisconnect;
		pMainThreadInfo->dbInfo.escape = mysqlEscape;
		pMainThreadInfo->dbInfo.push = mysqlPush;
		pMainThreadInfo->dbInfo.pull = mysqlPull;
		pMainThreadInfo->dbInfo.round = mysqlRound;
		pMainThreadInfo->dbInfo.free = mysqlFree;
		pMainThreadInfo->dbInfo.expire = mysqlExpire;
		pMainThreadInfo->dbInfo.cookie = mysqlCookie;
		pMainThreadInfo->dbInfo.insert = mysqlInsert;
		pMainThreadInfo->dbInfo.login = mysqlLogin;
		pMainThreadInfo->dbInfo.logout = mysqlLogout;
		pMainThreadInfo->dbInfo.session = mysqlSession;
		pMainThreadInfo->dbInfo.permission = mysqlPermission;
	}

	/*
	 *
	 * Initialize magick cookie.
	 *
	 */

	if((confPassword = configFetch("agent_password", &i)) != NULL) {
		s = strlen(confPassword);

		if(s > DATA_COOKIE_SIZE) {
			s = DATA_COOKIE_SIZE;
		}

		strncpy(magicCookie, confPassword, s);
	}

	/*
	 *
	 * Initialize main thread.
	 *
	 */

	configSetUmask(0077);

	if(configSetLocale(CONFIG_DEFAULT_LOCALE) != 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to set default locale");
	}

	if(configChangeRoot(CONFIG_DEFAULT_ROOT) != 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to change root directory");
	}

	if(configCloseInput() != 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to close standard input");
	}

	if(configDaemonize() != 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to daemonize process");
	}

	threadStack(THREAD_TELSKIND);
	beginProcess(pMainThreadInfo);

	/*
	 *
	 * Initialize timer.
	 *
	 */

	if(timerInit(TIMER_RESOLUTION_STATUS, 0, timerStatThreads) != 0) {
		warningMessage(ERROR_FATAL, "Error occurred while trying to initialize timer");
	}

	/*
	 *
	 * Initialize worker threads.
	 *
	 */

	pMainMainInfo->allRunning = 0;
	pMainMainInfo->theEnd = 0;
	pMainMainInfo->threadEnd = 0;

	for(i = 0; i < THREAD_TELSKIND; i++) {
		if(threadInit(&threadPool[i], workerThread, &threadPool[i]) != 0) {
			warningMessage(ERROR_FATAL, "Error occurred while trying to initialize worker thread");
		}

		j = 0;

		while(threadPool[i].threadReady != 0) {
			timerWait(&tmpSeconds, 0, THREAD_AGAIN);

			if(j == 10000 || j == 20000 || j == 30000 || j == 40000 || j == 50000) {
				warningMessage(ERROR_SLIGHT, "Waiting for worker threads to start taking too long, still waiting");
			}
			else if(j >= 60000) {
				warningMessage(ERROR_FATAL, "Waiting for threads to start taking too long");
			}

			j++;
		}
	}

	/*
	 *
	 * Create socket to listen.
	 *
	 */

	if((confPort = configFetch("listen_port", &i)) != NULL) {
		thisSocket = netCreateListenSocket(*confPort);
	}
	else {
		thisSocket = netCreateListenSocket(CONFIG_DEFAULT_PORT);
	}

	/*
	 *
	 * Create process id, shm segment, switch user and group id's.
	 *
	 */

	pidCreate();
	shmCreate(DAEMON_TELSKIND, THREAD_TELSKIND);

	if((thisUid = configFetch("user_id", &i)) != NULL) {
		if(*thisUid != -1) {
			if(uidSwitch(*thisUid) != 0) {
				warningMessage(ERROR_SLIGHT, "Error occurred while trying to change user id");
			}
		}
	}

	if((thisGid = configFetch("group_id", &i)) != NULL) {
		if(*thisGid != -1) {
			if(gidSwitch(*thisGid) != 0) {
				warningMessage(ERROR_SLIGHT, "Error occurred while trying to change group id");
			}
		}
	}

	/*
	 *
	 * Serve connected clients.
	 *
	 */

	startProcess(THREAD_TELSKIND);

	pMainMainInfo->allRunning++;
	pMainMainInfo->rushThreadCounter = 0;

	while(pMainMainInfo->theEnd == 0) {
		thatSocket = netWaitConnection(thisSocket, pMainThreadInfo);

		if(pMainMainInfo->theEnd != 0) {
			break;
		}
mainLoop:
		for(i = 0; i < THREAD_TELSKIND; i++) {
			if(threadPool[i].threadReady == 0) {
				threadPool[i].threadReady++;
				threadPool[i].threadSocket = thatSocket;

				shmUpdate(i, DAEMON_TELSKIND);

				if(threadWake(&threadPool[i]) != 0) {
					netCloseSocket(threadPool[i].threadSocket);

					threadPool[i].threadReady = 0;
					threadPool[i].threadSocket = 0;

					warningMessage(ERROR_SLIGHT, "Error occurred while trying to start worker thread");
				}

				pMainMainInfo->rushThreadCounter = 0;

				break;
			}
		}

		if(i == THREAD_TELSKIND) {
			if(pMainMainInfo->rushThreadCounter > 1000) {
				pMainMainInfo->rushThreadCounter = 0;

				warningMessage(ERROR_SLIGHT, "No free worker thread available, dropping agent");

				netCloseSocket(thatSocket);
			}
			else {
				pMainMainInfo->rushThreadCounter++;

				if(pMainMainInfo->rushThreadCounter < 2) {
					warningMessage(ERROR_SLIGHT, "No free worker thread available, it may be necessary to enlarge the thread pool");
				}

				timerWait(&tmpSeconds, 0, THREAD_AGAIN);

				goto mainLoop;
			}
		}
	}

	/*
	 *
	 * Free allocated resources and terminate program.
	 *
	 */

	netCloseSocket(thisSocket);

	pMainMainInfo->threadEnd++;

	if(timerInit(TIMER_RESOLUTION_THREADSTOP, 0, timerStopThreads) == 0) {
		pMainMainInfo->timerThreadAccess = 1;

		for(i = 0; i < THREAD_TELSKIND; i++) {
			threadWake(&threadPool[i]);
		}

		pMainMainInfo->timerThreadAccess = 0;
	}
	else {
		for(i = 0; i < THREAD_TELSKIND; i++) {
			threadKill(&threadPool[i]);
		}
	}

	timesProcess(pMainThreadInfo);

	pidRemove();
	shmRemove(DAEMON_TELSKIND);

	free(threadPool);

	exitProcess(0);
	exit(0);
}
Exemple #25
0
char *softGetInstalled(struct paramInfo * pi) {
	unsigned int i, k;

	char *newBuffer, *tmpBuffer;

	size_t newBuflen, newBufcur, newBuffil;

	struct softwareStore newStore;

	DWORD newLength, newValue, newIndex;
	HKEY newKey, newSub;
	FILETIME newTime;
	TCHAR newString[CONFIG_SPACE_SIZE], newSubkey[CONFIG_SPACE_SIZE], newSubstring[CONFIG_SPACE_SIZE];

	memset(&newStore, 0, sizeof(newStore));

	newBuffil = 0;
	newBuflen = DATA_BLOCK_SIZE;

	if((newBuffer = malloc(newBuflen)) == NULL) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for software info buffer");

		return(NULL);
	}

	k = 0;
	newIndex = 0;

	if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", 0, KEY_ENUMERATE_SUB_KEYS, &newKey) == ERROR_SUCCESS) {
		for(i = 0; i < 10240; i++) {
			newLength = sizeof(newSubkey);

			if(RegEnumKeyEx(newKey, newIndex, (LPBYTE) &newSubkey, &newLength, NULL, NULL, NULL, &newTime) == ERROR_SUCCESS) {
				_snprintf(newSubstring, sizeof(newSubstring), "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\%s%c", newSubkey, 0);

				if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, newSubstring, 0, KEY_QUERY_VALUE, &newSub) == ERROR_SUCCESS) {
					newLength = sizeof(newString);

					if(RegQueryValueEx(newSub, "DisplayName", NULL, NULL, (LPBYTE) &newString, &newLength) == ERROR_SUCCESS) {
						_snprintf(newStore.name, sizeof(newStore.name), "%s%c", newString, 0);

						newLength = sizeof(newString);

						if(RegQueryValueEx(newSub, "DisplayVersion", NULL, NULL, (LPBYTE) &newString, &newLength) == ERROR_SUCCESS) {
							_snprintf(newStore.version, sizeof(newStore.version), "%s%c", newString, 0);
						}

						newLength = sizeof(newValue);

						if(RegQueryValueEx(newSub, "Size", NULL, NULL, (LPDWORD) &newValue, &newLength) == ERROR_SUCCESS) {
							newValue /= 1000;

							_snprintf(newStore.size, sizeof(newStore.size), "%lu%c", newValue, 0);
						}

						newLength = sizeof(newString);

						if(RegQueryValueEx(newSub, "HelpLink", NULL, NULL, (LPBYTE) &newString, &newLength) == ERROR_SUCCESS) {
							_snprintf(newStore.url, sizeof(newStore.url), "%s%c", newString, 0);
						}

						newBufcur = strlen(newStore.name) + strlen(newStore.version) + strlen(newStore.size) + strlen(newStore.url) + 64;

						if(newBuflen - newBuffil <= newBufcur) {
							newBuflen += DATA_BLOCK_SIZE;

							if((tmpBuffer = realloc(newBuffer, newBuflen)) == NULL) {
								free(newBuffer);

								warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for software info buffer");

								return(NULL);
							}

							newBuffer = tmpBuffer;
						}

						k += _snprintf(newBuffer + k, newBuflen, "%d%c%s%c%s%c%s%c%s%c", PACK_TYPE_MSI, ITEM_SEPARATOR, newStore.name, ITEM_SEPARATOR, newStore.version, ITEM_SEPARATOR, newStore.size, ITEM_SEPARATOR, newStore.url, ITEM_DELIMITER);

						newBuffil += newBufcur;
 					}

					RegCloseKey(newSub);
				}

				newIndex++;
 			}
			else {
				break;
			}
		}

		RegCloseKey(newKey);
	}

	if(k > 0) {
		k--;
	}

	newBuffer[k] = 0;

	return(newBuffer);
}
Exemple #26
0
void nodeInitNames(void) {
	int i;

	uid_t newUid;
	gid_t newGid;

	struct passwd *newPasswd;
	struct group *newGroup;
#if !defined(__sun__)
	struct utsname nodeNames;
#endif
	memset(&nodeData, 0, sizeof(nodeData));

	if(gethostname(nodeData.node, sizeof(nodeData.node)) != 0) {
#if defined(__sun__)
		if(sysinfo(SI_HOSTNAME, nodeData.node, sizeof(nodeData.node)) == -1) {
			nodeData.node[0] = 0;
		}
#else
		if(uname(&nodeNames) == 0) {
			if(nodeNames.nodename[0] == 0) {
				if(gethostname(nodeData.node, sizeof(nodeData.node)) != 0) {
					nodeData.node[0] = 0;
				}
			}
			else {
				snprintf(nodeData.node, sizeof(nodeData.node), "%s%c", nodeNames.nodename, 0);
			}
		}
		else {
			snprintf(nodeData.node, sizeof(nodeData.node), "%s%c", nodeNames.nodename, 0);
		}
#endif
	}
#if defined(__sun__)
	if(sysinfo(SI_SRPC_DOMAIN, nodeData.domain, sizeof(nodeData.domain)) == -1) {
		nodeData.domain[0] = 0;
	}
#else
 #ifdef _GNU_SOURCE
	if(nodeNames.domainname[0] == 0) {
		if(getdomainname(nodeData.domain, sizeof(nodeData.domain)) != 0) {
			nodeData.domain[0] = 0;
		}
	}
	else {
		snprintf(nodeData.domain, sizeof(nodeData.domain), "%s%c", nodeNames.domainname, 0);
	}
 #else
	if(getdomainname(nodeData.domain, sizeof(nodeData.domain)) != 0) {
		nodeData.domain[0] = 0;
	}
 #endif
#endif
#if defined(__sun__)
	if(sysinfo(SI_SYSNAME, nodeData.system, sizeof(nodeData.system)) == -1) {
		nodeData.system[0] = 0;
	}

	if(sysinfo(SI_RELEASE, nodeData.release, sizeof(nodeData.release)) == -1) {
		nodeData.release[0] = 0;
	}

	if(sysinfo(SI_MACHINE, nodeData.machine, sizeof(nodeData.machine)) == -1) {
		nodeData.machine[0] = 0;
	}
#else
	if(uname(&nodeNames) == 0) {
		if(nodeNames.sysname[0] == 0) {
			nodeData.system[0] = 0;
		}
		else {
			snprintf(nodeData.system, sizeof(nodeData.system), "%s%c", nodeNames.sysname, 0);
		}

		if(nodeNames.release[0] == 0) {
			nodeData.release[0] = 0;
		}
		else {
			snprintf(nodeData.release, sizeof(nodeData.release), "%s%c", nodeNames.release, 0);
		}

		if(nodeNames.machine[0] == 0) {
			nodeData.machine[0] = 0;
		}
		else {
			snprintf(nodeData.machine, sizeof(nodeData.machine), "%s%c", nodeNames.machine, 0);
		}
	}
#endif
	newUid = getuid();
	newGid = getgid();

	newPasswd = getpwuid(newUid);

	if(newPasswd != NULL) {
		if(newPasswd->pw_name[0] == 0) {
			nodeData.useruid[0] = 0;
		}
		else {
			snprintf(nodeData.useruid, sizeof(nodeData.useruid), "%s%c", newPasswd->pw_name, 0);
		}

		if(newPasswd->pw_gecos[0] == 0) {
			nodeData.usergecos[0] = 0;
		}
		else {
			snprintf(nodeData.usergecos, sizeof(nodeData.usergecos), "%s%c", newPasswd->pw_gecos, 0);
		}

		if(newPasswd->pw_dir[0] == 0) {
			nodeData.userhomedir[0] = 0;
		}
		else {
			snprintf(nodeData.userhomedir, sizeof(nodeData.userhomedir), "%s%c", newPasswd->pw_dir, 0);
		}
	}

	if(strlen(nodeData.usergecos) > 1) {
		for(i = strlen(nodeData.usergecos) - 1; i > 0; i--) {
			if(nodeData.usergecos[i] == ',') {
				nodeData.usergecos[i] = 0;
			}
			else {
				break;
			}
		}
	}

	if((newGroup = getgrgid(newGid)) != NULL) {
		if(newGroup->gr_name[0] == 0) {
			nodeData.usergrp[0] = 0;
		}
		else {
			snprintf(nodeData.usergrp, sizeof(nodeData.usergrp), "%s%c", newGroup->gr_name, 0);
		}
	}

	if(nodeData.node[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch local node name");
	}

	if(nodeData.domain[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch local domain name");
	}

	if(nodeData.system[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch local system name");
	}

	if(nodeData.release[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch local system release");
	}

	if(nodeData.machine[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch local system architecture");
	}

	if(nodeData.useruid[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch user unix name");
	}

	if(nodeData.usergecos[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch user real name");
	}

	if(nodeData.userhomedir[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch user home directory");
	}

	if(nodeData.usergrp[0] == 0) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch user primary group");
	}
}
bool OscapScannerBase::tryToReadStdOutChar(QProcess& process)
{
    char readChar = '\0';
    if (!process.getChar(&readChar))
        return false;

    if (!mCapabilities.progressReporting())
        return true; // We did read something but it's not in a format we can parse.

    if (readChar == ':')
    {
        switch (mReadingState)
        {
            case RS_READING_PREFIX:
                {
                    // Openscap <= 1.2.10 (60fb9f0c98eee) sends this message through stdout
                    if (mReadBuffer=="Downloading")
                    {
                         mReadingState = RS_READING_DOWNLOAD_FILE;
                    }
                    else
                    {
                        mLastRuleID = mReadBuffer;
                        emit progressReport(mLastRuleID, "processing");
                        mReadingState = RS_READING_RULE_RESULT;
                    }
                    mReadBuffer = "";
                }
                break;

            case RS_READING_RULE_RESULT:
                {
                    emit warningMessage(QString(
                                QObject::tr("Error when parsing scan progress output from stdout of the 'oscap' process. "
                                    "':' encountered while not reading rule ID, newline and/or rule result are missing! "
                                    "Read buffer is '%1'.")).arg(mReadBuffer));
                    mReadBuffer = "";
                }
                break;
            case RS_READING_DOWNLOAD_FILE:
                {
                    // When fetching remote content, openscap will inform scap-workbench about
                    // resources being downloaded. Keep any colon found in URL of file being downloaded.
                    mReadBuffer.append(QChar::fromAscii(readChar));
                }
                break;

            default:
                // noop
                break;
        }
    }
    else if (readChar == '\n')
    {
        switch(mReadingState)
        {
            case RS_READING_PREFIX:
                // If we found a '\n' while reading prefix, we might have received an error or
                // warning message through stdout.
                if (mReadBuffer.contains("--fetch-remote-resources"))
                {
                    // If message is about --fetch-remote-resources, emit a nice warning.
                    // This is needed for workbench to be able to handle messages from machines
                    // running older versions of openscap.
                    // From openscap version 1.2.11, this message is sent through stderr
                    // and therefore is handled accordingly by workbench.
                    emit warningMessage(guiFriendlyMessage(mReadBuffer));
                }
                else
                {
                    // No other error or warning messages are expected through stdout,
                    // so it is likely that a parsing error occured.
                    emit warningMessage(QString(
                                QObject::tr("Error when parsing scan progress output from stdout of the 'oscap' process. "
                                    "Newline encountered while reading rule ID, rule result and/or ':' are missing! "
                                    "Read buffer is '%1'.")).arg(mReadBuffer));
                }
                break;

            case RS_READING_RULE_RESULT:
                emit progressReport(mLastRuleID, mReadBuffer);
                break;

            case RS_READING_DOWNLOAD_FILE_STATUS:
                {
                    QString downloadStatus = mReadBuffer.mid(1);
                    if (downloadStatus == "ok")
                        emit infoMessage(QString("Downloading of \"%1\" finished: %2").arg(mLastDownloadingFile).arg(downloadStatus));
                    else
                        emit warningMessage(QString("Failed to download \"%1\"!").arg(mLastDownloadingFile));
                }
                break;
            default:
                // noop
                break;
        }
        mReadingState = RS_READING_PREFIX;
        mReadBuffer = "";
    }
    else if ( (readChar == '.') && (mReadingState == RS_READING_DOWNLOAD_FILE) && (mReadBuffer.endsWith(" ..")))
    {
        int urlLen = mReadBuffer.length();
        urlLen -= 1; // without first space
        urlLen -= 3; // without "progress dots"
        mLastDownloadingFile = mReadBuffer.mid(1, urlLen);

        emit infoMessage(QString("Downloading of \"%1\"...").arg(mLastDownloadingFile));

        mReadBuffer = "";
        mReadingState = RS_READING_DOWNLOAD_FILE_STATUS;
    }
    else
    {
        // we know for sure that buffer[0] can only contain ASCII characters
        // (IDs and special keywords regarding rule status)
        mReadBuffer.append(QChar::fromAscii(readChar));
    }

    return true;
}
Exemple #28
0
char *servGetProcesses(struct paramInfo * pi) {
	unsigned int i, k;

	char *newBuffer, *tmpBuffer;

	size_t newBuflen, newBufcur, newBuffil;

	FARPROC closeHandle, createSnapshot, processFirst, processNext, processInfo;
	HANDLE newSnapshot, newProcess;
	HMODULE modKernel, modPsapi;
	PROCESS_MEMORY_COUNTERS newCounter;
	PROCESSENTRY32 newEntry;
	SIZE_T vmPeak, vmSize;

	if((modKernel = LoadLibrary("kernel32.dll")) == NULL) {
		return(NULL);
	}

	closeHandle = GetProcAddress(modKernel, "CloseHandle");
	createSnapshot = GetProcAddress(modKernel, "CreateToolhelp32Snapshot");
	processFirst = GetProcAddress(modKernel, "Process32First");
	processNext = GetProcAddress(modKernel, "Process32Next");

	if(closeHandle == NULL || createSnapshot == NULL || processFirst == NULL || processNext == NULL) {
		FreeLibrary(modKernel);

		return(NULL);
	}

	if((newSnapshot = (HANDLE) (createSnapshot)(TH32CS_SNAPPROCESS, 0)) == INVALID_HANDLE_VALUE) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to create system snapshot");

		FreeLibrary(modKernel);

		return(NULL);
	}

	newBuffil = 0;
	newBuflen = DATA_BLOCK_SIZE;

	if((newBuffer = malloc(newBuflen)) == NULL) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for process info buffer");

		(closeHandle)(newSnapshot);

		FreeLibrary(modKernel);

		return(NULL);
	}

	modPsapi = NULL;
	processInfo = NULL;

	if((modPsapi = LoadLibrary("psapi.dll")) != NULL) {
		if((processInfo = GetProcAddress(modPsapi, "GetProcessMemoryInfo")) == NULL) {
			processInfo = GetProcAddress(modPsapi, "K32GetProcessMemoryInfo");
		}

		if(processInfo == NULL) {
			FreeLibrary(modPsapi);

			if((modPsapi = LoadLibrary("kernel32.dll")) != NULL) {
				if((processInfo = GetProcAddress(modPsapi, "GetProcessMemoryInfo")) == NULL) {
					processInfo = GetProcAddress(modPsapi, "K32GetProcessMemoryInfo");
				}
			}
		}
	}
	else {
		if((modPsapi = LoadLibrary("kernel32.dll")) != NULL) {
			if((processInfo = GetProcAddress(modPsapi, "GetProcessMemoryInfo")) == NULL) {
				processInfo = GetProcAddress(modPsapi, "K32GetProcessMemoryInfo");
			}
		}
	}

	k = 0;

	newEntry.dwSize = sizeof(newEntry);

	if((processFirst)(newSnapshot, &newEntry) == TRUE) {
		vmPeak = 0;
		vmSize = 0;

		if((newProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, newEntry.th32ProcessID)) != NULL) {
			if((processInfo)(newProcess, &newCounter, sizeof(newCounter)) != 0) {
				vmPeak = newCounter.PeakWorkingSetSize;
				vmSize = newCounter.WorkingSetSize;

				vmPeak /= 1000;
				vmSize /= 1000;
			}

			(closeHandle)(newProcess);
		}

		k += _snprintf(newBuffer + k, newBuflen, "%s%c%s%cS%c%lu%c%lu%c%lu%c0%c0%c0%c0%c%lu%c0%c0%c%lu%c0%c0%c0%c0%c0%c0%c0%c0%c0%c", newEntry.szExeFile, ITEM_SEPARATOR, newEntry.szExeFile, ITEM_SEPARATOR, ITEM_SEPARATOR, newEntry.th32ProcessID, ITEM_SEPARATOR, newEntry.th32ParentProcessID, ITEM_SEPARATOR, newEntry.cntThreads, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, vmPeak, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, vmSize, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_DELIMITER);

		for(i = 0; i < 65535; i++) {
			newEntry.dwSize = sizeof(newEntry);

			if((processNext)(newSnapshot, &newEntry) == TRUE) {
				vmPeak = 0;
				vmSize = 0;

				if((newProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, newEntry.th32ProcessID)) != NULL) {
					if((processInfo)(newProcess, &newCounter, sizeof(newCounter)) != 0) {
						vmPeak = newCounter.PeakWorkingSetSize;
						vmSize = newCounter.WorkingSetSize;

						vmPeak /= 1000;
						vmSize /= 1000;
					}

					(closeHandle)(newProcess);
				}

				newBufcur = strlen(newEntry.szExeFile) + 64;

				if(newBuflen - newBuffil <= newBufcur) {
					newBuflen += DATA_BLOCK_SIZE;

					if((tmpBuffer = realloc(newBuffer, newBuflen)) == NULL) {
						warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for process info buffer");

						free(newBuffer);

						(closeHandle)(newSnapshot);

						FreeLibrary(modKernel);

						if(modPsapi != NULL) {
							FreeLibrary(modPsapi);
						}

						return(NULL);
					}

					newBuffer = tmpBuffer;
				}

				k += _snprintf(newBuffer + k, newBuflen, "%s%c%s%cS%c%lu%c%lu%c%lu%c0%c0%c0%c0%c%lu%c0%c0%c%lu%c0%c0%c0%c0%c0%c0%c0%c0%c0%c", newEntry.szExeFile, ITEM_SEPARATOR, newEntry.szExeFile, ITEM_SEPARATOR, ITEM_SEPARATOR, newEntry.th32ProcessID, ITEM_SEPARATOR, newEntry.th32ParentProcessID, ITEM_SEPARATOR, newEntry.cntThreads, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, vmPeak, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, vmSize, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_DELIMITER);

				newBuffil += newBufcur;
			}
			else {
				break;
			}
		}
	}

	(closeHandle)(newSnapshot);

	FreeLibrary(modKernel);

	if(modPsapi != NULL) {
		FreeLibrary(modPsapi);
	}

	if(k > 0) {
		k--;
	}

	newBuffer[k] = 0;

	return(newBuffer);
}
Exemple #29
0
char *servGetServices(struct paramInfo * pi) {
	unsigned int i, k;

	char *newBuffer, *tmpBuffer;

	size_t newBuflen, newBufcur, newBuffil;

	DWORD newDummy, newNeeded, newReturned, newResume;
	FARPROC openManager, closeManager, enumServices;
	HMODULE modAdvapi;
	SC_HANDLE newKey;
	ENUM_SERVICE_STATUS newInfo;
	LPENUM_SERVICE_STATUS newArray;

	if((modAdvapi = LoadLibrary("advapi32.dll")) == NULL) {
		return(NULL);
	}

	openManager = GetProcAddress(modAdvapi, "OpenSCManagerA");
	closeManager = GetProcAddress(modAdvapi, "CloseServiceHandle");
	enumServices = GetProcAddress(modAdvapi, "EnumServicesStatusA");

	if(openManager == NULL || closeManager == NULL || enumServices == NULL) {
		FreeLibrary(modAdvapi);

		return(NULL);
	}

	if((newKey = (SC_HANDLE) (openManager)(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE)) == NULL) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to open service control manager");

		FreeLibrary(modAdvapi);

		return(NULL);
	}

	newBuffil = 0;
	newBuflen = DATA_BLOCK_SIZE;

	if((newBuffer = malloc(newBuflen)) == NULL) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for service info buffer");

		(closeManager)(newKey);

		FreeLibrary(modAdvapi);

		return(NULL);
	}

	k = 0;
	newResume = 0;

	if((enumServices)(newKey, SERVICE_WIN32, SERVICE_ACTIVE, &newInfo, 1, &newNeeded, &newReturned, &newResume) == 0) {
		if(GetLastError() == ERROR_MORE_DATA) {
			if((newArray = malloc(newNeeded)) != NULL) {
				newResume = 0;

				if((enumServices)(newKey, SERVICE_WIN32, SERVICE_ACTIVE, newArray, newNeeded, &newDummy, &newReturned, &newResume) == 0) {
					warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch running services");
				}
				else {
					for(i = 0; i < newReturned; i++) {
						if(newArray[i].lpDisplayName != NULL && newArray[i].lpDisplayName[0] != 0 && newArray[i].lpServiceName != NULL && newArray[i].lpServiceName[0] != 0) {
							newBufcur = strlen(newArray[i].lpDisplayName) + strlen(newArray[i].lpServiceName) + 64;

							if(newBuflen - newBuffil <= newBufcur) {
								newBuflen += DATA_BLOCK_SIZE;

								if((tmpBuffer = realloc(newBuffer, newBuflen)) == NULL) {
									warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for service info buffer");

									free(newArray);
									free(newBuffer);

									(closeManager)(newKey);

									FreeLibrary(modAdvapi);

									return(NULL);
								}

								newBuffer = tmpBuffer;
							}

							k += _snprintf(newBuffer + k, newBuflen, "%s%c%s%cA%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c", newArray[i].lpServiceName, ITEM_SEPARATOR, newArray[i].lpDisplayName, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_DELIMITER);

							newBuffil += newBufcur;
						}
					}
				}

				free(newArray);
			}
			else {
				warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for service info buffer");
			}
		}
		else {
			warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch running services");
		}
	}
	else {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch running services");
	}

	newResume = 0;

	if((enumServices)(newKey, SERVICE_WIN32, SERVICE_INACTIVE, &newInfo, 1, &newNeeded, &newReturned, &newResume) == 0) {
		if(GetLastError() == ERROR_MORE_DATA) {
			if((newArray = malloc(newNeeded)) != NULL) {
				newResume = 0;

				if((enumServices)(newKey, SERVICE_WIN32, SERVICE_INACTIVE, newArray, newNeeded, &newDummy, &newReturned, &newResume) == 0) {
					warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch running services");
				}
				else {
					for(i = 0; i < newReturned; i++) {
						if(newArray[i].lpDisplayName != NULL && newArray[i].lpDisplayName[0] != 0 && newArray[i].lpServiceName != NULL && newArray[i].lpServiceName[0] != 0) {
							newBufcur = strlen(newArray[i].lpDisplayName) + strlen(newArray[i].lpServiceName) + 64;

							if(newBuflen - newBuffil <= newBufcur) {
								newBuflen += DATA_BLOCK_SIZE;

								if((tmpBuffer = realloc(newBuffer, newBuflen)) == NULL) {
									warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for service info buffer");

									free(newArray);
									free(newBuffer);

									(closeManager)(newKey);

									FreeLibrary(modAdvapi);

									return(NULL);
								}

								newBuffer = tmpBuffer;
							}

							k += _snprintf(newBuffer + k, newBuflen, "%s%c%s%cS%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c0%c", newArray[i].lpServiceName, ITEM_SEPARATOR, newArray[i].lpDisplayName, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_SEPARATOR, ITEM_DELIMITER);

							newBuffil += newBufcur;
						}
					}
				}

				free(newArray);
			}
			else {
				warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for service info buffer");
			}
		}
		else {
			warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch running services");
		}
	}
	else {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to fetch running services");
	}

	(closeManager)(newKey);

	FreeLibrary(modAdvapi);

	if(k > 0) {
		k--;
	}

	newBuffer[k] = 0;

	return(newBuffer);
}
Exemple #30
0
char *servGetCount(struct paramInfo * pi) {
	unsigned int i, k, l;

	char *newBuffer;

	FARPROC closeHandle, createSnapshot, processFirst, processNext;
	HANDLE newSnapshot;
	HMODULE modKernel;
	PROCESSENTRY32 newEntry;

	if((modKernel = LoadLibrary("kernel32.dll")) == NULL) {
		return(NULL);
	}

	closeHandle = GetProcAddress(modKernel, "CloseHandle");
	createSnapshot = GetProcAddress(modKernel, "CreateToolhelp32Snapshot");
	processFirst = GetProcAddress(modKernel, "Process32First");
	processNext = GetProcAddress(modKernel, "Process32Next");

	if(closeHandle == NULL || createSnapshot == NULL || processFirst == NULL || processNext == NULL) {
		FreeLibrary(modKernel);

		return(NULL);
	}

	if((newSnapshot = (HANDLE) (createSnapshot)(TH32CS_SNAPPROCESS, 0)) == INVALID_HANDLE_VALUE) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to create system snapshot");

		FreeLibrary(modKernel);

		return(NULL);
	}

	k = 0;
	l = 0;

	newEntry.dwSize = sizeof(newEntry);

	if((processFirst)(newSnapshot, &newEntry) == TRUE) {
		l += newEntry.cntThreads;
		k++;

		for(i = 0; i < 65535; i++) {
			newEntry.dwSize = sizeof(newEntry);

			if((processNext)(newSnapshot, &newEntry) == TRUE) {
				l += newEntry.cntThreads;
				k++;
			}
			else {
				break;
			}
		}
	}

	(closeHandle)(newSnapshot);

	FreeLibrary(modKernel);

	if((newBuffer = malloc(DATA_STRING_SIZE)) == NULL) {
		warningMessage(ERROR_SLIGHT, "Error occurred while trying to allocate memory for process count buffer");

		return(NULL);
	}

	_snprintf(newBuffer, DATA_STRING_SIZE, "%lu%c%lu%c", k, ITEM_SEPARATOR, l, 0);

	return(newBuffer);
}