void DBusBackendWrapper::launch()
{
    Q_D(DBusBackendWrapper);

    if (identifier().isEmpty()) {
        setLastError("No identifier was set");
        setStatus(Invalid);
        return;
    }

    QByteArray object = QCryptographicHash::hash(identifier().toLocal8Bit(),
                                                 QCryptographicHash::Md5);
    QString dbusIdentifier = QString::fromLocal8Bit(object.toHex());

    // Register to DBus
    d->dbusObjectPath = DBUS_BACKEND_PATH_PREFIX;
    d->dbusObjectPath.append(dbusIdentifier);

    new Pt2Adaptor(this);
    if (!QDBusConnection::sessionBus().registerObject(d->dbusObjectPath, this)) {
        setLastError(QString("Failed to register object on path %1").arg(d->dbusObjectPath));
        setStatus(Invalid);
        return;
    }

    // Launch the backend
    setStatus(Launching);
    d->process->setWorkingDirectory(APPLICATION_FOLDER);
    QString trueExecutable = executable();
    trueExecutable.replace("$PROVIDER", QString(PROVIDER_PATH) + " --plugin ");
    trueExecutable.append(QString(" --identifier %1 ").arg(dbusIdentifier));

    debug("dbus-backend-wrapper") << "starting" << trueExecutable;

    d->process->start(trueExecutable);
}
Example #2
0
void EmbeddedFilesDock::fillInfo()
{
    m_table->setHorizontalHeaderLabels(
        QStringList() << tr("Name") << tr("Description") << tr("Size") << tr("Creation date")
        << tr("Modification date") << tr("Checksum"));
    if (!document()->hasEmbeddedFiles()) {
        m_table->setItem(0, 0, new QTableWidgetItem(tr("No files")));
        return;
    }

    const QList<Poppler::EmbeddedFile*> files = document()->embeddedFiles();
    m_table->setRowCount(files.count());
    int i = 0;
    Q_FOREACH(Poppler::EmbeddedFile *file, files) {
        m_table->setItem(i, 0, new QTableWidgetItem(file->name()));
        m_table->setItem(i, 1, new QTableWidgetItem(file->description()));
        m_table->setItem(i, 2, new QTableWidgetItem(QString::number(file->size())));
        m_table->setItem(i, 3, new QTableWidgetItem(file->createDate().toString(Qt::SystemLocaleDate)));
        m_table->setItem(i, 4, new QTableWidgetItem(file->modDate().toString(Qt::SystemLocaleDate)));
        const QByteArray checksum = file->checksum();
        const QString checksumString = !checksum.isEmpty() ? QString::fromAscii(checksum.toHex()) : QString::fromLatin1("n/a");
        m_table->setItem(i, 5, new QTableWidgetItem(checksumString));
        ++i;
    }
Example #3
0
void Settings::save()
{
	QSettings settings;
	settings.setValue("settings/configFileName", m_configFileName);
	settings.setValue("settings/multipleconfig", m_multipleConfigs);

	if ( multipleConfigs() && !configFileName().isEmpty() )
	{
		QByteArray hash = QCryptographicHash::hash( configFileName().toLocal8Bit(), QCryptographicHash::Md5 );
		settings.beginGroup( hash.toHex() );
	}

	settings.setValue("buildPath", m_buildPath);
	settings.setValue("includePath", m_includePath);
	settings.setValue("installPath", m_installPath);
	settings.setValue("sourceDirectory", m_sourceDir);
	settings.setValue("applicationDirectory", m_appDir);
	settings.setValue("targetPlatform", m_targetPlatform);
	settings.setValue("toolPath", m_toolPath);
	settings.setValue("programmer", m_programmer);
	settings.setValue("absolutePathInSamples", m_absolutePathInSamples);
	settings.setValue("clearLogBeforeBuild", m_clearLogBeforeBuild);
	settings.setValue("verboseBuild", m_verboseBuild);
}
Example #4
0
QString TDownlad::CalcSha1(QString Path)
{
        QFile FileToHash(Path);
        QByteArray ba;
        QString HashOutput;
        QCryptographicHash CPU(QCryptographicHash::Sha1);
        if (FileToHash.open(QIODevice::ReadOnly))
        {
                while (!FileToHash.atEnd())
                {
                        ba = FileToHash.read(1024);
                        CPU.addData(ba);
                }
                FileToHash.close();
                ba = CPU.result();
                HashOutput = ba.toHex();
                return HashOutput;
        }
        else
        {
                HashOutput = "ERR";
                return HashOutput;
        }
}
Example #5
0
Ztamp::Ztamp(QByteArray const& ztampID)
{
	// Check ztamps folder
	QDir ztampsDir = QDir(QCoreApplication::applicationDirPath());
	if (!ztampsDir.cd("ztamps"))
	{
		if (!ztampsDir.mkdir("ztamps"))
		{
			LogError("Unable to create ztamps directory !\n");
			exit(-1);
		}
		ztampsDir.cd("ztamps");
	}
	id = ztampID;
	configFileName = ztampsDir.absoluteFilePath(ztampID.toHex()+".dat");

	// Check if config file exists and load it
	if (QFile::exists(configFileName))
		LoadConfig();

	saveTimer = new QTimer(this);
	connect(saveTimer, SIGNAL(timeout()), this, SLOT(SaveConfig()));
	saveTimer->start(5*60*1000); // 5min
}
void PacketTable::insert_row_in_table(QByteArray data)
{
    bool isOk;
    int i, length;
    QString mac_dst, mac_src, stream;

    qDebug() << "[data]" << data.toHex();

    if (data.size() <= 14)
        return;

    int row = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(row);

    mac_dst = QString::number(data.mid(0,6).toHex().toLongLong(&isOk,16), 16).toUpper();
    qDebug() << mac_dst;
    mac_src = QString::number(data.mid(6,6).toHex().toLongLong(&isOk,16), 16).toUpper();
    qDebug() << mac_src;
    length = data.mid(12,2).toHex().toInt(&isOk,16);
    qDebug() << length;
    for(i = 14; (i < 14 + length) && (i<data.size()); i++ )
      stream.append(QString::number((uchar)data[i], 16));

    qDebug() << stream;
    QTableWidgetItem *newItem = new QTableWidgetItem(mac_dst);
    ui->tableWidget->setItem(row, 0, newItem);

    newItem = new QTableWidgetItem(mac_src);
    ui->tableWidget->setItem(row, 1, newItem);

    newItem = new QTableWidgetItem(QString::number(length));
    ui->tableWidget->setItem(row, 2, newItem);

    newItem = new QTableWidgetItem(stream);
    ui->tableWidget->setItem(row, 3, newItem);
}
Example #7
0
static QString variantToTextValue(const QVariant &value, const QString &typeNs, const QString &type)
{
    switch (value.userType()) {
    case QVariant::Char:
    // fall-through
    case QVariant::String:
        return value.toString();
    case QVariant::Url:
        // xmlpatterns/data/qatomicvalue.cpp says to do this:
        return value.toUrl().toString();
    case QVariant::ByteArray: {
        const QByteArray data = value.toByteArray();
        if (typeNs == KDSoapNamespaceManager::xmlSchema1999() || typeNs == KDSoapNamespaceManager::xmlSchema2001()) {
            if (type == QLatin1String("hexBinary")) {
                const QByteArray hb = data.toHex();
                return QString::fromLatin1(hb.constData(), hb.size());
            }
        }
        // default to base64Binary, like variantToXMLType() does.
        const QByteArray b64 = value.toByteArray().toBase64();
        return QString::fromLatin1(b64.constData(), b64.size());
    }
    case QVariant::Int:
    // fall-through
    case QVariant::LongLong:
    // fall-through
    case QVariant::UInt:
        return QString::number(value.toLongLong());
    case QVariant::ULongLong:
        return QString::number(value.toULongLong());
    case QVariant::Bool:
    case QMetaType::Float:
    case QVariant::Double:
        return value.toString();
    case QVariant::Time: {
        const QTime time = value.toTime();
        if (time.msec()) {
            // include milli-seconds
            return time.toString(QLatin1String("hh:mm:ss.zzz"));
        } else {
            return time.toString(Qt::ISODate);
        }
    }
    case QVariant::Date:
        return value.toDate().toString(Qt::ISODate);
    case QVariant::DateTime: // http://www.w3.org/TR/xmlschema-2/#dateTime
        return KDDateTime(value.toDateTime()).toDateString();
    case QVariant::Invalid:
        qDebug() << "ERROR: Got invalid QVariant in a KDSoapValue";
        return QString();
    default:
        if (value.canConvert<KDDateTime>()) {
            return value.value<KDDateTime>().toDateString();
        }

        if (value.userType() == qMetaTypeId<float>()) {
            return QString::number(value.value<float>());
        }

        qDebug() << QString::fromLatin1("QVariants of type %1 are not supported in "
                                        "KDSoap, see the documentation").arg(QLatin1String(value.typeName()));
        return value.toString();
    }
}
Example #8
0
void TCS34725Driver::getID()
{
    QByteArray result = writeThenRead(TCS34725Address_, ID, 1);
    qDebug() << QString(result.toHex());
}
void FastoHexEdit::paintEvent(QPaintEvent *event) {
  if (mode_ == HEX_MODE) {
    QPainter painter(viewport());

    QSize areaSize = viewport()->size();
    QSize widgetSize = fullSize();

    const int charW = charWidth();
    const int charH = charHeight();

    int firstLineIdx = verticalScrollBar()->value();
    int lastLineIdx = firstLineIdx + areaSize.height() / charH;

    const QRect rect = stableRect(event->rect());
    const int yPosStart = rect.top();
    const int xPosStart = rect.left();
    const int yPosEnd = rect.bottom();
    const int xPosEnd = rect.right();

    const int wid = xPosEnd - xPosStart;
    const int height = yPosEnd - yPosStart;
    const int widchars = wid - TextMarginXY * 2;
    const int acharInLine = asciiCharInLine(widchars);
    if (acharInLine <= 0) {
      return;
    }

    const int xPosAscii = widchars/4 * 3;  // line pos
    const int xPosAsciiStart = xPosAscii + TextMarginXY;

    int indexCount = data_.size() / acharInLine;
    if (lastLineIdx > indexCount) {
      lastLineIdx = indexCount;
      if (data_.size() % acharInLine) {
        lastLineIdx++;
      }
    }
    verticalScrollBar()->setPageStep(areaSize.height() / charH);
    verticalScrollBar()->setRange(0, (widgetSize.height() - areaSize.height()) / charH + 1);

    painter.setPen(Qt::gray);
    painter.drawLine(xPosAscii, yPosStart, xPosAscii, yPosEnd);

    painter.setPen(Qt::black);

    int size = data_.size();
    for (int lineIdx = firstLineIdx, yPos = yPosStart;
         lineIdx < lastLineIdx; lineIdx += 1, yPos += charH) {
      QByteArray part = data_.begin() + (lineIdx * acharInLine);
      int part_size = size / acharInLine ? acharInLine : size % acharInLine;
      part.resize(part_size);
      size -= part_size;
      QByteArray hex = part.toHex();

      painter.setBackgroundMode(Qt::OpaqueMode);
      for (int xPos = xPosStart, i = 0; i < hex.size(); i++, xPos += 3 * charW) {
        QString val = hex.mid(i * 2, 2);
        QRect hexrect(xPos, yPos, 3 * charW, charH);
        painter.drawText(hexrect, Qt::AlignLeft, val);
        char ch = part[i];
        if ((ch < 0x20) || (ch > 0x7e)) {
          part[i] = '.';
        }
      }

      painter.setBackgroundMode(Qt::TransparentMode);
      QRect asciirect(xPosAsciiStart, yPos, acharInLine * charW, charH);
      painter.drawText(asciirect, Qt::AlignLeft, part);
    }
  } else {
    base_class::paintEvent(event);
  }
}
Example #10
0
 /* md5 of string */
 inline QString md5( const QByteArray& src )
 {
   QByteArray const digest = QCryptographicHash::hash( src, QCryptographicHash::Md5 );
   return QString::fromLatin1( digest.toHex() ).rightJustified( 32, '0' ).toLower();
 }
Example #11
0
void WebSocketWorker::ProcessFrames(QTcpSocket *socket)
{
    while (m_isRunning && socket && socket->bytesAvailable() >= 2) // No header? Return and wait for more
    {
        uint8_t headerSize = 2; // Smallest possible header size is 2 bytes, greatest is 14 bytes

        QByteArray header = socket->peek(headerSize); // Read header to establish validity and size of frame

        WebSocketFrame frame;
        // FIN
        frame.finalFrame = (bool)(header[0] & 0x80);
        // Reserved bits
        if (header.at(0) & 0x70)
        {
            LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessFrames() "
                                     "- Invalid data in reserved fields");
            SendClose(kCloseProtocolError, "Invalid data in reserved fields");
            return;
        }
        // Operation code
        uint8_t opCode = (header.at(0) & 0xF);
        if ((opCode > WebSocketFrame::kOpBinaryFrame &&
             opCode < WebSocketFrame::kOpClose) ||
             (opCode > WebSocketFrame::kOpPong))
        {
            LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessFrames() "
                                             "- Invalid OpCode (%1)")
                                            .arg(QString::number(opCode, 16)));
            SendClose(kCloseProtocolError, "Invalid OpCode");
            return;
        }
        frame.opCode = (WebSocketFrame::OpCode)opCode;
        frame.isMasked = (header.at(1) >> 7) & 0xFE;

        if (frame.isMasked)
            headerSize += 4; // Add 4 bytes for the mask

        frame.payloadSize = (header.at(1) & 0x7F);
        // Handle 16 or 64bit payload size headers
        if (frame.payloadSize >= 126)
        {
            uint8_t payloadHeaderSize = 2; // 16bit payload size
            if (frame.payloadSize == 127)
                payloadHeaderSize = 8; // 64bit payload size

            headerSize += payloadHeaderSize; // Add bytes for extended payload size

            if (socket->bytesAvailable() < headerSize)
                return; // Return and wait for more

            header = socket->peek(headerSize); // Peek the entire header
            QByteArray payloadHeader = header.mid(2,payloadHeaderSize);
            frame.payloadSize = 0;
            for (int i = 0; i < payloadHeaderSize; i++)
            {
                frame.payloadSize |= ((uint8_t)payloadHeader.at(i) << ((payloadHeaderSize - (i + 1)) * 8));
            }
        }
        else
        {
            if (socket->bytesAvailable() < headerSize)
                return; // Return and wait for more
            header = socket->peek(headerSize); // Peek the entire header including mask
        }

        while ((uint64_t)socket->bytesAvailable() < (frame.payloadSize + header.length()))
        {
            if (!socket->waitForReadyRead(2000)) // Wait 2 seconds for the next chunk of the frame
            {

                m_errorCount++;

                if (m_errorCount == 5)
                {
                    LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessFrames() - Timed out waiting for rest of frame to arrive.");
                    SendClose(kCloseBadData);
                }
                return;
            }
        }

        if (frame.opCode == WebSocketFrame::kOpContinuation)
             m_readFrame.payloadSize += frame.payloadSize;

        LOG(VB_HTTP, LOG_DEBUG, QString("Read Header: %1").arg(QString(header.toHex())));
        LOG(VB_HTTP, LOG_DEBUG, QString("Final Frame: %1").arg(frame.finalFrame ? "Yes" : "No"));
        LOG(VB_HTTP, LOG_DEBUG, QString("Op Code: %1").arg(QString::number(frame.opCode)));
        LOG(VB_HTTP, LOG_DEBUG, QString("Payload Size: %1 Bytes").arg(QString::number(frame.payloadSize)));
        LOG(VB_HTTP, LOG_DEBUG, QString("Total Payload Size: %1 Bytes").arg(QString::number( m_readFrame.payloadSize)));

        if (!m_fuzzTesting &&
            frame.payloadSize > qPow(2,20)) // Set 1MB limit on payload per frame
        {
            LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessFrames() - Frame payload larger than limit of 1MB");
            SendClose(kCloseTooLarge, "Frame payload larger than limit of 1MB");
            return;
        }

        if (!m_fuzzTesting &&
            m_readFrame.payloadSize > qPow(2,22)) // Set 4MB limit on total payload
        {
            LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessFrames() - Total payload larger than limit of 4MB");
            SendClose(kCloseTooLarge, "Total payload larger than limit of 4MB");
            return;
        }

        socket->read(headerSize); // Discard header from read buffer

        frame.payload = socket->read(frame.payloadSize);

        // Unmask payload
        if (frame.isMasked)
        {
            frame.mask = header.right(4);
            for (uint i = 0; i < frame.payloadSize; i++)
                frame.payload[i] = frame.payload.at(i) ^ frame.mask[i % 4];
        }

        if (m_readFrame.fragmented && frame.opCode > WebSocketFrame::kOpContinuation && frame.opCode < WebSocketFrame::kOpClose)
        {
            LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Incomplete multi-part frame? Expected continuation.");
            SendClose(kCloseProtocolError, "Incomplete multi-part frame? Expected continuation.");
            return;
        }

        // Check control frame validity
        if (frame.opCode >= 0x08)
        {
            if (!frame.finalFrame)
            {
                SendClose(kCloseProtocolError, "Control frames MUST NOT be fragmented");
                return;
            }
            else if (frame.payloadSize > 125)
            {
                SendClose(kCloseProtocolError, "Control frames MUST NOT have payload greater than 125 bytes");
                return;
            }
        }

        switch (frame.opCode)
        {
            case WebSocketFrame::kOpContinuation:
                if (!m_readFrame.fragmented)
                {
                    LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Received Continuation Frame out of sequence");
                    SendClose(kCloseProtocolError, "Received Continuation Frame out of sequence");
                    return;
                }

                m_readFrame.payload.append(frame.payload);

                if (m_readFrame.fragmented && frame.finalFrame)
                {
                    m_readFrame.finalFrame = true;
                    frame = m_readFrame;
                    // Fall through to appropriate handler for complete payload
                }
                else
                    break;
                [[clang::fallthrough]];
            case WebSocketFrame::kOpTextFrame:
            case WebSocketFrame::kOpBinaryFrame:
                HandleDataFrame(frame);
                break;
            case WebSocketFrame::kOpPing:
                SendPong(frame.payload);
                break;
            case WebSocketFrame::kOpPong:
                break;
            case WebSocketFrame::kOpClose:
                if (!frame.finalFrame)
                    SendClose(kCloseProtocolError, "Control frames MUST NOT be fragmented");
                else
                    HandleCloseConnection(frame.payload);
                break;
            default:
                LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Received Unknown Frame Type");
                break;
        }

        frame.reset();
    }
}
void NfcWorker::doIso7816Test(const QVariant &aid, const QVariant &hex_cla, const QVariant &hex_ins, const QVariant &hexp1p2, const QVariant &hex_lc,
		const QVariant &hex_command, const QVariant &hex_le) {
	emit message(QString("ISO7816-4 test starts"));

	QString _aid = aid.toString();
	QString _hex_cla = hex_cla.toString();
	QString _hex_ins = hex_ins.toString();
	QString _hex_p1p2 = hexp1p2.toString();
	QString _hex_lc = hex_lc.toString();
	QString _hex_command = hex_command.toString();
	QString _hex_le = hex_le.toString();

	emit message(QString("Le: '%1'").arg(_hex_le));
	emit message(QString("COMMAND: '%1'").arg(_hex_command));
	emit message(QString("Lc: '%1'").arg(_hex_lc));
	emit message(QString("P1 P2: '%1'").arg(_hex_p1p2));
	emit message(QString("INS: '%1'").arg(_hex_ins));
	emit message(QString("CLA: '%1'").arg(_hex_cla));
	emit message(QString("AID: '%1'").arg(_aid));
	emit message(QString("ISO7816-4 request APDU:"));

	// variables for handles
	uint32_t hSESession;
	uint32_t seChannel;
	uint32_t uiccSeReaderID;

	// variables for retrieving the Readers, holders of possible secure elements
	uint32_t numberOfReaders = 0;
	uint32_t *phReaders = NULL;
	static int DEF_LEN = 10;
	char readerName[DEF_LEN];
	uint32_t len = 10;

	//variables for opening and exchanging data
	fcp_type_t fcpResponseType;
	int32_t openResponseLen;
	uint32_t exchangeResponseLen;
	uint32_t nReceiveAPDUBufferSize;
	uint8_t* result;

	QByteArray hex_encoded = QByteArray(aid.toByteArray());
	QByteArray the_aid = QByteArray::fromHex(hex_encoded);

	uint8_t fixed_aid[14] = { 0xA0, 0x00, 0x00, 0x00, 0x18, 0x30, 0x80, 0x05, 0x00, 0x65, 0x63, 0x68, 0x6F, 0x00 };
	uint8_t command_apdu_len = 5;
	uint8_t command_apdu[5] = { 0x10, 0x41, 0x11, 0x22, 0x00 };

	// loop variable
	uint32_t i;

	// Call nfc_se_service_get_num_readers() with the handle acquired in previous step to get the number of available Readers in the system
	CHECK(nfc_se_service_get_num_readers(&numberOfReaders));
	emit message(QString("number of readers=%1").arg(numberOfReaders));

	// Allocate space for the readers
	phReaders = (uint32_t*) malloc(sizeof(uint32_t) * numberOfReaders);
	emit message(QString("space allocated for readers"));

	// get the handles for the readers
	CHECK(nfc_se_service_get_readers(phReaders, &numberOfReaders));
	emit message(QString("got handles for readers"));

	// Iterate through the readers to find the SIM reader.
	for (i = 0; i < numberOfReaders; i++) {
		len = 10;
		CHECK(nfc_se_reader_get_name(phReaders[i], readerName, &len));
		if ((len == 3) && (strcmp(readerName, "SIM") == 0)) {
			uiccSeReaderID = phReaders[i];
			emit message(QString("got handle to UICC SE reader"));
			break;
		}
	}

	// Deallocate the array for holding the readers.
	free(phReaders);
	emit message(QString("deallocated space allocated for readers"));

	// Open a session with the SIM Reader
	// Note: You may hold onto this session for the lifetime
	// of you application.
	CHECK(nfc_se_reader_open_session( uiccSeReaderID,&hSESession ));
	emit message(QString("opened session with UICC reader"));

	// Open a channel to AID
	fcpResponseType = OPEN_NO_FCP_INFO;
	openResponseLen = 0;

//	uint8_t[] aid_as_int = reinterpret_cast<unsigned char*>(the_aid.data());
	CHECK(nfc_se_session_open_logical_channel(hSESession, fixed_aid, 12, fcpResponseType, &seChannel, &openResponseLen));
	emit message(QString("opened logical channel"));

	// send APDU command
	QByteArray apduBytes = QByteArray::fromRawData(reinterpret_cast<const char *>(command_apdu), command_apdu_len);
	QString apduBytesAsHex = QString::fromAscii(apduBytes.toHex());
	emit message(QString("transmit:%1").arg(apduBytesAsHex));

	CHECK(nfc_se_channel_transmit_apdu( seChannel, command_apdu, command_apdu_len, &exchangeResponseLen ));

	// response length not working on Dev Alpha at present
	// so hard coding length which should be 7 for my test SIM (temporary code)
	exchangeResponseLen = 7;

	// uint8_t is an 8 bit unsigned type
	result = (uint8_t*) malloc(sizeof(uint8_t) * exchangeResponseLen);
	//get the response of the open call

	nReceiveAPDUBufferSize = exchangeResponseLen;

	if (exchangeResponseLen >= 2) {
		CHECK(nfc_se_channel_get_transmit_data(seChannel, &result[0], &nReceiveAPDUBufferSize));
		emit message(QString("got response APDU. Len=%1").arg(nReceiveAPDUBufferSize));
		QByteArray responseData = QByteArray::fromRawData(reinterpret_cast<const char *>(result), nReceiveAPDUBufferSize);
		QString responseAsHex = QString::fromAscii(responseData.toHex());
		emit message(QString("APDU response: %1").arg(responseAsHex));
	}

	free(result);

	// Close the channel
	if (NFC_RESULT_SUCCESS != nfc_se_channel_close_channel(seChannel)) {
		emit message(QString("nfc_se_channel_close_channel failed"));
		return;
	}
	emit message(QString("ISO7816-4 test ends"));

}
Example #13
0
void HexDump::dump(QByteArray* raw, const char* func, int line)
{
    qDebug() << func << line << "RawDump: BEGIN";
	//qDebug() << raw->size() << raw->toHex();

	unsigned int size = raw->size();

	int ze = 0;
	while(size!=0 && ze < 8)
	{
		size /= 10;
		ze++;
	}

	int lines = ceil(raw->size()/8.0);
	//qDebug() << lines;
	int pos=0;

	QByteArray part;
	QString out;

	for( int i=0 ; i<lines ; i++ )
	{
		out.clear();
		part.clear();
		part = raw->mid(pos, 8);

		out.append("0x");
		out.append(QString("%1").arg(pos,ze,16,QChar('0')));
		out.append(" / ");
		out.append(QString("%1").arg(pos,ze,10,QChar('0')));
		out.append(" - ");
		out.append(part.toHex());

		if(part.size() != 8)
		{
			int padd = 8-part.size();
			while(padd!=0)
			{
				out.append("  ");
				padd--;
			}
		}

		out.append(" - ");

		for( int p=0 ; p<part.size() ; p++ )
		{
			char c = part[p];
			if(c >= 0x20 && c <= 0x7E)
			{
				out.append(c);
			}
			else
			{
				out.append(' ');

			}
		}

		//qDebug() << out << part.toHex();
		qDebug() << out;
		pos +=8;
	}

	qDebug() << func << line << "RawDump: END";
}
Example #14
0
void UdpManager::readUDP()
{
    QByteArray Temp;
    Temp.resize(socket->pendingDatagramSize());

    QHostAddress sender;
    quint16 senderPort;
    socket->readDatagram(Temp.data(),Temp.size(),&sender,&senderPort);

    QString debugMessage = "Got \"" + QString(Temp.data()) + "\" from " + sender.toString() + ":"+ QString::number(senderPort) + " (UDP)";
    emit updateClientGUIConsole(debugMessage);

    QString compareString = "BLENDER";
    QString message;
    if(Temp.data() == compareString)
    {
        if (workerIsBusy)
            message = "BLENDER0";       //is busy
        else{
            if (isGPUWorker)
                message = "BLENDER2";   // is available GPU-Worker
            else
                message = "BLENDER1";   // is available CPU-Worker
        }
        writeUDP(message, sender);
    }
    else if( QString(Temp.data()).at(0) == '#' && !workerIsBusy )
    {
        message = "";

        QString filepathToBlend = QDir::currentPath() + "/awesome.blend";

        QByteArray fileData;

        QFile file( filepathToBlend ); //e.g.: /.../build/awesome.blend
        if( file.open(QIODevice::ReadOnly) )
        {
            fileData = file.readAll();
            file.close();

            //Generate MD5 Hash
            QByteArray hashData = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
            file_hash = hashData.toHex();

            qDebug() << "Hex-Hash: " << hashData.toHex();

        }
        else
        {
            //Error
            file_hash = "Th15I5Th3DummymD5HasH0fGSORF.0RG";
        }

        //Send UDP Response
        writeUDP( "#" + file_hash, sender );
        if(file_hash==QString(Temp.data()).remove('#') )
        {
            emit setFileCached(true);
        }
        else
        {
            emit setFileCached(false);
        }
    }
    else if( QString(Temp.data()).startsWith("killall"))
    {
    qDebug()<<"Bye Bye Blender";
    QProcess *myProcess = new QProcess(this);
    myProcess->start("killall blender");
    myProcess->waitForFinished();
    }


    emit setServerAddress(sender);

}
Example #15
0
	coex::typeOS detectOS(QString inputFolder)
	{
		QList<fileos> listfiles;
		QList<fileos> checkfiles;

		// Windows XP
		listfiles << fileos( coex::ceWindowsXP, "5.1.2600.5512", "/WINDOWS/system32/kernel32.dll", "d612ee36f95da6d1179f7567b2b77d77");
		listfiles << fileos( coex::ceWindowsXP, "5.1.2600.5512", "/WINDOWS/system32/kernel32.dll", "800937D2446728367B713F5AC0B9BAC0"); // ??
		listfiles << fileos( coex::ceWindowsXP, "5.1.2600.5781", "/WINDOWS/system32/kernel32.dll", "E1E261C6D29F87FAFCC88F94952ED8D5");
		listfiles << fileos( coex::ceWindowsXP, "5.1.2600.6293", "/WINDOWS/system32/kernel32.dll", "9CB5C708CFBD8B007BE2C8A44A3DDE25");
		listfiles << fileos( coex::ceWindowsXP, "5.1.2600.6293", "/WINDOWS/system32/kernel32.dll", "D056B67FCC32221681438A6240DB3E1A");
		listfiles << fileos( coex::ceWindowsXP, "5.2.3790.4480", "/WINDOWS/system32/kernel32.dll", "43301E4453581691B791855934BFF7C5");
		listfiles << fileos( coex::ceWindowsXP, "5.2.3790.4480", "/WINDOWS/system32/kernel32.dll", "B4B82A9E888B1A8964D136AD227C6428");
		listfiles << fileos( coex::ceWindowsXP, "5.2.3790.5069", "/WINDOWS/system32/kernel32.dll", "23A6C522DF754CAD344D737AA45CBD03");
		listfiles << fileos( coex::ceWindowsXP, "5.2.3790.5069", "/WINDOWS/system32/kernel32.dll", "B6D45BB7311512B268064C1A203C003E");
		listfiles << fileos( coex::ceWindowsXP, "5.2.3790.5069", "/WINDOWS/system32/kernel32.dll", "2836EF1A4A12D5149D085833AC84A006");
		
		// Windows Vista
		listfiles << fileos( coex::ceWindowsVista , "6.0.6002.18704", "/Windows/system32/kernel32.dll", "A02EB771DAE80667E3C877CF19E3F6EE");		
		listfiles << fileos( coex::ceWindowsVista , "6.0.6002.18449", "/Windows/system32/KERNEL32.dll", "2299078C1E59FE69ADDF49897D6A373A");
		listfiles << fileos( coex::ceWindowsVista , "6.0.6002.18449", "/Windows/syswow64/kernel32.dll", "7F4CAEAC24592FA9F574E1F8CD1D0604");
		listfiles << fileos( coex::ceWindowsVista , "6.0.6002.18740", "/Windows/system32/kernel32.dll", "14EED915B63F7AB64A1E367BCB6973D0");
		listfiles << fileos( coex::ceWindowsVista , "6.0.6002.18740", "/Windows/system32/kernel32.dll", "12A16A6E0883D403FA78D1D825BB9824");
		listfiles << fileos( coex::ceWindowsVista , "6.0.6002.18740", "/Windows/system32/kernel32.dll", "A8EAB98AC1E987C925EF518E6065A36C");

		// Windows 7
		listfiles << fileos( coex::ceWindows7 , "6.1.7600.16385", "/Windows/system32/kernel32.dll", "5b4b379ad10deda4eda01b8c6961b193");
		listfiles << fileos( coex::ceWindows7 , "6.1.7600.16385", "/Windows/SYSTEM32/kernel32.dll", "4605F7EE9805F7E1C98D6C959DD2949C"); // ?? HW32.Laneul.xkyw
		listfiles << fileos( coex::ceWindows7 , "6.1.7600.16385", "/Windows/SysWOW64/kernel32.dll", "606ECB76A424CC535407E7A24E2A34BC");
		listfiles << fileos( coex::ceWindows7 , "6.1.7600.16850", "/Windows/system32/kernel32.dll", "DDBD24DC04DA5FD0EDF45CF72B7C01E2");
		listfiles << fileos( coex::ceWindows7 , "6.1.7600.17206", "/Windows/system32/kernel32.dll", "43DB3433F141F01E53D1C5AA0F434098");
		listfiles << fileos( coex::ceWindows7 , "6.1.7600.17206", "/Windows/SysWOW64/kernel32.dll", "385BE92E3106491BBB542F8F1C06C606");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.17514", "/Windows/system32/kernel32.dll", "7A6326D96D53048FDEC542DF23D875A0");		
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.17514", "/Windows/SysWOW64/kernel32.dll", "e80758cf485db142fca1ee03a34ead05");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.17651", "/Windows/system32/kernel32.dll", "B9B42A302325537D7B9DC52D47F33A73");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.17651", "/Windows/SysWOW64/kernel32.dll", "99C3F8E9CC59D95666EB8D8A8B4C2BEB");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.17932", "/Windows/system32/kernel32.dll", "EAF41CFBA5281834CBC383C710AC7965");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.17932", "/Windows/SysWOW64/kernel32.dll", "9B98D47916EAD4F69EF51B56B0C2323C");		
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.17965", "/Windows/system32/kernel32.dll", "1DC3504CA4C57900F1557E9A3F01D272");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.17965", "/Windows/SysWOW64/kernel32.dll", "D4F3176082566CEFA633B4945802D4C4");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.18015", "/Windows/system32/kernel32.dll", "65C113214F7B05820F6D8A65B1485196");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.18015", "/Windows/system32/kernel32.dll", "AE09B85158C66E2C154C5C9B3C0027B3"); // HW32.Laneul.gqke
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.18015", "/Windows/SysWOW64/kernel32.dll", "AC0B6F41882FC6ED186962D770EBF1D2");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.18229", "/Windows/system32/kernel32.dll", "D8973E71F1B35CD3F3DEA7C12D49D0F0");
		listfiles << fileos( coex::ceWindows7 , "6.1.7601.18229", "/Windows/SysWOW64/kernel32.dll", "365A5034093AD9E04F433046C4CDF6AB");
		
		// windows 8
		listfiles << fileos( coex::ceWindows8 , "6.2.9200.16384", "/Windows/System32/kernel32.dll", "3C6933B638BB812F4084CF44AE698704");
		listfiles << fileos( coex::ceWindows8 , "6.2.9200.16384", "/Windows/System32/kernel32.dll", "744B34F13E730805E63076622418CCB8");
		listfiles << fileos( coex::ceWindows8 , "6.2.9200.16384", "/Windows/SysWOW64/kernel32.dll", "1C5F50F98291B7545391BB57C406E615");		
		listfiles << fileos( coex::ceWindows8 , "6.2.9200.16627", "/Windows/System32/kernel32.dll", "e1ff9d65e6b86f7ebb531ae36c5af635");

		for(int i = 0; i < listfiles.size(); i++)
		{
			QFileInfo fi(inputFolder + listfiles[i].filePath);
			if(fi.exists())
			{
				QFile file(fi.absoluteFilePath());
				if (file.open(QIODevice::ReadOnly)) 
				{
					QByteArray fileData = file.readAll();
					QByteArray hashData = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
					QString str = hashData.toHex();
							 
					if(str.toLower() == listfiles[i].hash.toLower())
						checkfiles << listfiles[i];
				}
			}
		}

		if(checkfiles.size() == 0)
			return coex::ceUnknown;


		coex::typeOS os_result = coex::ceUnknown;
		// check on conflicts
		{
			int nCounter = 0;
			for(int x = 0; x < checkfiles.size()-1; x++)
				for(int y = x+1; y < checkfiles.size(); y++)
				{
					if(checkfiles[x].os != checkfiles[y].os)
					{
						std::cout << " conflict between: \n\t " 
						<< checkfiles[x].toString().toStdString() 
						<< "\n\t and " << checkfiles[y].toString().toStdString() << "\n";
						nCounter++;
					};
				};
			if(nCounter == 0) 
			{
				std::cout << "\n  OS was detected";
				std::cout << checkfiles[0].toBigString().toStdString() << "\n";
				os_result = checkfiles[0].os;
			}
		};

    return os_result;
  };  
Example #16
0
QPCSCReader::Result QPCSCReader::transferCTL(const QByteArray &apdu, bool verify,
	quint16 lang, quint8 minlen, quint8 newPINOffset, bool requestCurrentPIN) const
{
	bool display = false;
	QHash<DRIVER_FEATURES,quint32> features = d->features();
	if( DWORD ioctl = features.value(FEATURE_IFD_PIN_PROPERTIES) )
	{
		DWORD size = 0;
		BYTE recv[256];
		LONG rv = SC(Control, d->card, ioctl, nullptr, 0u, recv, DWORD(sizeof(recv)), &size);
		if( rv == SCARD_S_SUCCESS )
		{
			PIN_PROPERTIES_STRUCTURE *caps = (PIN_PROPERTIES_STRUCTURE *)recv;
			display = caps->wLcdLayout > 0;
		}
	}

	quint8 PINFrameOffset = 0, PINLengthOffset = 0;
	#define SET() \
		data->bTimerOut = 30; \
		data->bTimerOut2 = 30; \
		data->bmFormatString = FormatASCII|AlignLeft|quint8(PINFrameOffset << 4)|PINFrameOffsetUnitBits; \
		data->bmPINBlockString = PINLengthNone << 5|PINFrameSizeAuto; \
		data->bmPINLengthFormat = PINLengthOffsetUnitBits|PINLengthOffset; \
		data->wPINMaxExtraDigit = quint16(minlen << 8) | 12; \
		data->bEntryValidationCondition = ValidOnKeyPressed; \
		data->wLangId = lang; \
		data->bTeoPrologue[0] = 0x00; \
		data->bTeoPrologue[1] = 0x00; \
		data->bTeoPrologue[2] = 0x00; \
		data->ulDataLength = quint32(apdu.size())

	QByteArray cmd( 255, 0 );
	if( verify )
	{
		PIN_VERIFY_STRUCTURE *data = (PIN_VERIFY_STRUCTURE*)cmd.data();
		SET();
		data->bNumberMessage = display ? CCIDDefaultInvitationMessage : NoInvitationMessage;
		data->bMsgIndex = NoInvitationMessage;
		cmd.resize( sizeof(PIN_VERIFY_STRUCTURE) - 1 );
	}
	else
	{
		PIN_MODIFY_STRUCTURE *data = (PIN_MODIFY_STRUCTURE*)cmd.data();
		SET();
		data->bNumberMessage = display ? ThreeInvitationMessage : NoInvitationMessage;
		data->bInsertionOffsetOld = 0x00;
		data->bInsertionOffsetNew = newPINOffset;
		data->bConfirmPIN = ConfirmNewPin;
		if(requestCurrentPIN)
		{
			data->bConfirmPIN |= RequestCurrentPin;
			data->bMsgIndex1 = NoInvitationMessage;
			data->bMsgIndex2 = OneInvitationMessage;
			data->bMsgIndex3 = TwoInvitationMessage;
		}
		else
		{
			data->bMsgIndex1 = OneInvitationMessage;
			data->bMsgIndex2 = TwoInvitationMessage;
			data->bMsgIndex3 = ThreeInvitationMessage;
		}
		cmd.resize( sizeof(PIN_MODIFY_STRUCTURE) - 1 );
	}
	cmd += apdu;

	DWORD ioctl = features.value( verify ? FEATURE_VERIFY_PIN_START : FEATURE_MODIFY_PIN_START );
	if( !ioctl )
		ioctl = features.value( verify ? FEATURE_VERIFY_PIN_DIRECT : FEATURE_MODIFY_PIN_DIRECT );

	qCDebug(APDU).nospace() << 'T' << d->proto - 1 << "> " << apdu.toHex().constData();
	qCDebug(APDU).nospace() << "CTL" << "> " << cmd.toHex().constData();
	QByteArray data( 255 + 3, 0 );
	DWORD size = DWORD(data.size());
	LONG err = SC(Control, d->card, ioctl, cmd.constData(), DWORD(cmd.size()), LPVOID(data.data()), DWORD(data.size()), &size);

	if( DWORD finish = features.value( verify ? FEATURE_VERIFY_PIN_FINISH : FEATURE_MODIFY_PIN_FINISH ) )
	{
		size = DWORD(data.size());
		err = SC(Control, d->card, finish, nullptr, 0u, LPVOID(data.data()), DWORD(data.size()), &size);
	}

	Result result = { data.mid(int(size - 2), 2), data.left(int(size - 2)), quint32(err) };
	qCDebug(APDU).nospace() << 'T' << d->proto - 1 << "< " << result.SW.toHex().constData();
	if(!result.data.isEmpty()) qCDebug(APDU).nospace() << data.left(int(size)).toHex().constData();
	return result;
}
void MainServeur::ProcessData()
{
    QDataStream in(m_Client);

    if(taillePacket == 0)
    {
        if(m_Client->bytesAvailable() < (int)sizeof(quint16))
            return;

        in >> taillePacket;
    }
    if(m_Client->bytesAvailable() < taillePacket)
        return;

    quint8 header;
    in >> header;

    emit message(tr("Données reçues pour Header(%1) et pour taille(%2)").arg(QString::number(header), QString::number(taillePacket)));
    bool Authentified = m_Authentification->State() == AuthentificationSystem::Accepted;
    switch(header)
    {
        case CMSG_MESSAGE_LEGER:
        {
            QString messageRecu;
            in >> messageRecu;
            QString messageSecondRecu;
            in >> messageSecondRecu;

            QByteArray encryptedPassword;
            in >> encryptedPassword;

            emit message(tr("Message léger reçu depuis un client : %1\n%2\n%3").arg(messageRecu, messageSecondRecu, encryptedPassword.toHex()));
            break;
        }
        case CMSG_MESSAGE_CUSTOM:
        {
            /** Créer un comportement de test. **/
            break;
        }
        case CMSG_PING:
        {
            if(Authentified)
                emit message(tr("Ping reçu de %1.").arg(m_Authentification->GetUserName()));
            else
                emit message(tr("Ping reçu d'un client non authentifié."));

            Reponse(SMSG_PONG);
            break;
        }
        case CMSG_PONG:
        {
            if(Authentified)
                emit message(tr("Pong! Reçu de %1").arg(m_Authentification->GetUserName()));
            else
                emit message(tr("Pong! Reçu d'un client non authentifié."));
            break;
        }
        case CMSG_MESSAGE_AUTH:
        {
            QString userName;
            in >> userName;

            QByteArray password;
            in >> password;

            m_Authentification = AuthentificationSystem::Authentificate(userName, password);

            if(m_Authentification->Error() == AuthentificationSystem::NoError)
            {
                emit message(tr("Tentative d'authentification de %1 réussi !").arg(userName));
                emit newClient(m_Authentification->GetUserName(), m_Authentification->GetClasse());

                Reponse(SMSG_AUTHENTIFICATION_SUCCESS);
            }
            else if(m_Authentification->Error() == AuthentificationSystem::Double_Account_Detected)
            {
                emit message(tr("Tentative d'authentification de %1 raté car double compte détectée.").arg(userName));
                Reponse(SMSG_AUTHENTIFICATION_FAILED);
                // Kick("AuthentificationSystem: another account is already connected.");
            }
            else if(m_Authentification->Error() == AuthentificationSystem::Password_Incorrect)
            {
                emit message(tr("Tentative d'authentification de %1 raté car le mot de passe est incorrecte.").arg(userName));
                Reponse(SMSG_AUTHENTIFICATION_FAILED);
            }
            else if(m_Authentification->Error() == AuthentificationSystem::UserName_Not_Available)
            {
                emit message(tr("Tentative d'authentification de %1 raté car le nom de compte n'existe pas.").arg(userName));
                Reponse(SMSG_AUTHENTIFICATION_FAILED);
            }
            else
            {
                emit message(tr("Tentative d'authentification de %1 raté, raison inconnue !").arg(userName));
                Reponse(SMSG_AUTHENTIFICATION_FAILED);
            }

            break;
        }
        case CMSG_MESSAGE_HOMEWORKFOR:
        {
            if(!Authentified)
            {
                Reponse(SMSG_YOU_ARE_NOT_AUTHENTIFIED);
                emit message(tr("Demande de devoir de la part d'un client non authentifié !! (Refusé)"));
                break;
            }
            QString matiere = tr("all");
            bool needOnlyMatiere;
            in >> needOnlyMatiere;

            if(needOnlyMatiere)
                in >> matiere;

            emit message(tr("Demande de devoir reçu de la part de %1 en classe de %2").arg(m_Authentification->GetUserName(), m_Authentification->GetClasse()));

            QList<Devoir> devoirs = SQLServerSupervisor::GetInstance()->LoadHomeworks(m_Authentification, matiere);
            SendHomeworks(devoirs);
            break;
        }
        case CMSG_MESSAGE_LISTMATIERE:
        {
            if(Authentified)
            {
                QStringList listMatiere = SQLServerSupervisor::GetInstance()->GetAllMatiereFromClasse(m_Authentification);
                emit message(tr("Demande des matières disponibles pour la classe %1 de %2").arg(m_Authentification->GetClasse(), m_Authentification->GetUserName()));
                SendMatieres(listMatiere);
            }
            else
            {
                emit message(tr("Demande des matières disponibles d'un utilisateur inconnu."));
            }

            break;
        }
        default:
        {
            emit message(tr("Header inconnu détecté : 0x%1").arg(QString::number(header, 16).toUpper()));
            break;
        }
    }

    taillePacket = 0;
}
Example #18
0
QString hash(const QString& string)
{
	QByteArray data = string.toUtf8();
	QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5);
	return hash.toHex();
}
Example #19
0
void PacketsSplitter::addReadedBytes(const QByteArray &bytes)
{
#ifdef DEBUG0
    qDebug() << "!!\n!!" << bytes.toHex() << "!!\n!!";
#endif
    switch (m_byteIndex) {
    case 0:
    case 1:
        if(bytes.at(0) == 0xFF - 0x100) {
            ++m_byteIndex;
            m_packet.append(bytes);
        } else {
            m_byteIndex = 0;
            m_packet.clear();
        }
        break;
    case 2:
        if(bytes.at(0) == 0x16) {
            ++m_byteIndex;
            m_packet.append(bytes);
        } else {
            m_byteIndex = 0;
            m_packet.clear();
        }
        break;
    case 3:
        ++m_byteIndex;
        m_packetLength = bytes.at(0);
        m_packet.append(bytes);
        break;
    case 4:
        if(bytes.at(0) == 0x04) {
            ++m_byteIndex;
            m_packet.append(bytes);
        } else {
            m_byteIndex = 0;
            m_packet.clear();
        }
        break;
    default:
        if(m_byteIndex == m_packetLength - 1) {
#ifdef DEBUG0
            qDebug() << QString("pas #%1").arg(QString::number(m_byteIndex));
#endif
            m_byteIndex = 0;
            m_packet.append(bytes);
            char checkSum = 0;
            for(int i = 0; i < m_packetLength - 1; ++i) {
                checkSum += m_packet.at(i);
            }
#ifdef DEBUG
            qDebug() << "Calculated checksum:" << (int)checkSum;
            qDebug() << "Received checksum:" << (int)m_packet.at(m_packetLength - 1);
#endif
            if(checkSum == m_packet.at(m_packetLength - 1)) {
#ifdef DEBUG
                qDebug() << "Readed packet" << m_packet.toHex().toUpper();
#endif                
                emit packetIsReaded(true);
                emit readedPacket(m_packet);
            } else {
                emit packetIsReaded(false);
            }
            m_packet.clear();
            m_packetLength = 0;
        } else {
#ifdef DEBUG0
            qDebug() << QString("pas #%1").arg(QString::number(m_byteIndex));
#endif
            ++m_byteIndex;
            m_packet.append(bytes);
        }
        break;
    }
}
Example #20
0
void CDataParser::DataMayRead()
{
    Sleep( 4 );

    int nMinLen = 8;
    Win_QextSerialPort& winSerial = *( Win_QextSerialPort* ) sender( );
    int nValided = winSerial.bytesAvailable( );
    if ( nMinLen > nValided ) {
#ifndef QT_NO_DEBUG
        qDebug( ) << QString( " Data Length less than 8 ( %1 )") .arg( nValided )  << endl;
#endif
         return;
    }

#ifndef QT_NO_DEBUG
        qDebug( ) << "Time " << QDateTime::currentDateTime( ).toMSecsSinceEpoch( ) << endl;
#endif
        QByteArray byData = winSerial.readAll( );

#ifndef QT_NO_DEBUG
        QString strData( byData.toHex( ) );
        qDebug( ) << "Read Serial Port Cmd : " << strData << endl;
#endif

        if ( byData.count( ) < nMinLen ) {
            return;
        }

        char cEnd = 0x55;
        char cStart = 0xAA;
        int nIndex = -1;
        QByteArray bySingle;
        int nDataLen = 0;

        do {
            nIndex = byData.indexOf( cStart );
            if ( -1 == nIndex ) { // No 0xAA
                break;
            } else if ( 0 < nIndex ) { // First 0xAA
                byData.remove( 0, nIndex );
                if ( nMinLen > byData.count( ) ) {
                    break;
                }
            }

            nDataLen = ( BYTE ) byData[ 1 ] + ( ( ( BYTE ) byData[ 2 ]  ) << 8 );
            nDataLen += 4;

            if ( nDataLen >= byData.count( ) ) {
                break;
            }

            if ( cEnd != byData[ nDataLen ] ) {
                nDataLen += 1;
                byData.remove( 0, nDataLen );
                continue;
            }

            nDataLen += 1;
            bySingle = byData.left( nDataLen  );
            byData.remove( 0, nDataLen );

            ParseSerialData( bySingle );
        } while ( nMinLen <= byData.count( ) );
}
void ClientHeavyLoad::askLogin(const quint8 &query_id,const QString &login,const QByteArray &hash)
{
    if(player_informations->isFake)
    {
        askLoginBot(query_id);
        return;
    }
    QString queryText;
    switch(GlobalServerData::serverSettings.database.type)
    {
        default:
        case ServerSettings::Database::DatabaseType_Mysql:
            queryText=QString("SELECT id,pseudo,skin,position_x,position_y,orientation,map_name,type,clan,cash,rescue_map,rescue_x,rescue_y,rescue_orientation FROM player WHERE login=\"%1\" AND password=\"%2\"")
                .arg(SqlFunction::quoteSqlVariable(login))
                .arg(SqlFunction::quoteSqlVariable(QString(hash.toHex())));
        break;
        case ServerSettings::Database::DatabaseType_SQLite:
            queryText=QString("SELECT id,pseudo,skin,position_x,position_y,orientation,map_name,type,clan,cash,rescue_map,rescue_x,rescue_y,rescue_orientation FROM player WHERE login=\"%1\" AND password=\"%2\"")
                .arg(SqlFunction::quoteSqlVariable(login))
                .arg(SqlFunction::quoteSqlVariable(QString(hash.toHex())));
        break;
    }
    QSqlQuery loginQuery(queryText);
    if(loginQuery.size()==0)
        loginIsWrong(query_id,"Bad login","Bad login for: "+login+", hash: "+hash.toHex());
    else
    {
        if(!loginQuery.next())
            loginIsWrong(query_id,"Wrong login/pass",QString("No login/pass found into the db, login: \"%1\", pass: \"%2\"").arg(login).arg(QString(hash.toHex())));
        else if(GlobalServerData::serverPrivateVariables.connected_players_id_list.contains(loginQuery.value(0).toUInt()))
            loginIsWrong(query_id,"Already logged","Already logged");
        else if(simplifiedIdList.size()<=0)
            loginIsWrong(query_id,"Not free id to login","Not free id to login");
        else
        {
            bool ok;
            player_informations->public_and_private_informations.public_informations.clan=loginQuery.value(8).toUInt(&ok);
            if(!ok)
            {
                emit message(QString("clan id is not an number, clan disabled"));
                player_informations->public_and_private_informations.public_informations.clan=0;//no clan
            }
            player_informations->id=loginQuery.value(0).toUInt(&ok);
            if(!ok)
            {
                loginIsWrong(query_id,"Wrong account data",QString("Player is is not a number: %1").arg(loginQuery.value(0).toString()));
                return;
            }
            player_informations->public_and_private_informations.public_informations.pseudo=loginQuery.value(1).toString();
            QString skinString=loginQuery.value(2).toString();
            if(GlobalServerData::serverPrivateVariables.skinList.contains(skinString))
                player_informations->public_and_private_informations.public_informations.skinId=GlobalServerData::serverPrivateVariables.skinList[skinString];
            else
            {
                emit message(QString("Skin not found, or out of the 255 first folder, default of the first by order alphabetic if have"));
                player_informations->public_and_private_informations.public_informations.skinId=0;
            }
            QString type=loginQuery.value(7).toString();
            if(type=="normal")
                player_informations->public_and_private_informations.public_informations.type=Player_type_normal;
            else if(type=="premium")
                player_informations->public_and_private_informations.public_informations.type=Player_type_premium;
            else if(type=="gm")
                player_informations->public_and_private_informations.public_informations.type=Player_type_gm;
            else if(type=="dev")
                player_informations->public_and_private_informations.public_informations.type=Player_type_dev;
            else
            {
                emit message(QString("Mysql wrong type value").arg(type));
                player_informations->public_and_private_informations.public_informations.type=Player_type_normal;
            }
            player_informations->public_and_private_informations.cash=loginQuery.value(9).toUInt(&ok);
            if(!ok)
            {
                emit message(QString("cash id is not an number, cash set to 0"));
                player_informations->public_and_private_informations.cash=0;
            }

            player_informations->public_and_private_informations.public_informations.speed=CATCHCHALLENGER_SERVER_NORMAL_SPEED;
            if(!loadTheRawUTF8String())
            {
                loginIsWrong(query_id,"Convert into utf8 have wrong size","Convert into utf8 have wrong size");
                return;
            }
            QString orientationString=loginQuery.value(5).toString();
            Orientation orentation;
            if(orientationString=="top")
                orentation=Orientation_top;
            else if(orientationString=="bottom")
                orentation=Orientation_bottom;
            else if(orientationString=="left")
                orentation=Orientation_left;
            else if(orientationString=="right")
                orentation=Orientation_right;
            else
            {
                orentation=Orientation_bottom;
                emit message(QString("Wrong orientation corrected with bottom"));
            }
            //id(0),login(1),skin(2),position_x(3),position_y(4),orientation(5),map_name(6),type(7),clan(8),cash(9),rescue_map(10),rescue_x(11),rescue_y(12),rescue_orientation(13)
            //all is rights
            if(GlobalServerData::serverPrivateVariables.map_list.contains(loginQuery.value(6).toString()))
            {
                quint8 x=loginQuery.value(3).toUInt(&ok);
                if(!ok)
                {
                    loginIsWrong(query_id,"Wrong account data","x coord is not a number");
                    return;
                }
                quint8 y=loginQuery.value(4).toUInt(&ok);
                if(!ok)
                {
                    loginIsWrong(query_id,"Wrong account data","y coord is not a number");
                    return;
                }
                if(x>=GlobalServerData::serverPrivateVariables.map_list[loginQuery.value(6).toString()]->width)
                {
                    loginIsWrong(query_id,"Wrong account data","x to out of map");
                    return;
                }
                if(y>=GlobalServerData::serverPrivateVariables.map_list[loginQuery.value(6).toString()]->height)
                {
                    loginIsWrong(query_id,"Wrong account data","y to out of map");
                    return;
                }
                loginIsRightWithRescue(query_id,
                    player_informations->id,
                    GlobalServerData::serverPrivateVariables.map_list[loginQuery.value(6).toString()],
                    x,
                    y,
                    (Orientation)orentation,
                    loginQuery.value(10),
                    loginQuery.value(11),
                    loginQuery.value(12),
                    loginQuery.value(13)
                );
            }
            else
                loginIsWrong(query_id,"Map not found","Map not found: "+loginQuery.value(6).toString());

        }
    }
}
Example #22
0
const QByteArray Auth::calculateAuthKey()
{
    QSqlDatabase db = QSqlDatabase::database ( m_db );

    bool ok = false;
    QSqlQuery query(db);

    ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_SECRET'") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: error getting zm_auth_hash_secret from db %s", qPrintable(query.lastError().text()));
        return QByteArray();
    }

    QString auth_key = query.value(0).toString(); // HASH Secret

    ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_IPS'") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: error getting zm_auth_hash_ips from db %s", qPrintable(query.lastError().text()));
        return QByteArray();
    }

    bool use_remote_addr = query.value(0).toBool(); // Include remote addr?

    ok = query.exec( QString("SELECT now()") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: Can not read Server Time. now() function doesn't work %s",
               qPrintable(query.lastError().text()));
        return QByteArray();
    }

    QDateTime dateTime = query.value(0).toDateTime();

    auth_key += m_userName;
    auth_key += m_hashPassword;

    if ( use_remote_addr )
    {
        QTcpSocket socket;
        socket.connectToHost( db.hostName(), ConnectionManager::connectionWebPort( m_db ), QIODevice::ReadOnly );
        //if we can get ip address from the socket in 3000 ms
        if ( socket.waitForConnected( 3000 ) ){
            auth_key += socket.localAddress().toString();
        } else {
            //else try with HostInfo
            QHostInfo hinfo = QHostInfo::fromName ( QHostInfo::localHostName()  );
            QHostInfo checkLocalHost = QHostInfo::fromName ( db.hostName()  );
            if ( ! checkLocalHost.addresses().isEmpty() )
                if ( checkLocalHost.addresses().first().toString() == "127.0.0.1" ) hinfo = checkLocalHost;

            if ( !hinfo.addresses().isEmpty() )
            {
                //TODO: fix this. Use the correct interface address and not the first
                QHostAddress address = hinfo.addresses().first();
                auth_key += address.toString();
            }
        }
    }

    dateTime = dateTime.toTimeSpec( Qt::LocalTime );
    auth_key += QString::number( dateTime.time().hour() ); //hour
    auth_key += QString::number( dateTime.date().day() ); //day of month
    auth_key += QString::number( dateTime.date().month() -1 ); //month
    auth_key += QString::number( dateTime.date().year() - 1900 ); //years since 1900

    qDebug ( qPrintable("authkey: " + auth_key) );

    QByteArray ret = QCryptographicHash::hash( auth_key.toUtf8(), QCryptographicHash::Md5 );
    //qDebug ( qPrintable(QString (auth_key.toUtf8())) );
    qDebug ( qPrintable("authkey hex: " + ret.toHex()) );

    m_authKey = ret.toHex();
    return m_authKey;
}
Example #23
0
//==============================================================================
void GameServer::HandlePutPlayer_(const QVariantMap& request, QVariantMap& response)
{
  if (!testingStageActive_)
  {
    WriteResult_(response, EFEMPResult::BAD_ACTION);
    return;
  }

  if (!request["x"].toFloat() || !request["y"].toFloat())
  {
    WriteResult_(response, EFEMPResult::BAD_PLACING);
    return;
  }

  float x = request["x"].toFloat();
  float y = request["y"].toFloat();

  Player* player = CreateActor_<Player>();
  SetActorPosition_(player, Vector2(x, y));

  if (IsPositionWrong(x, y, player))
  {
    KillActor_(player);
    WriteResult_(response, EFEMPResult::BAD_PLACING);
    return;
  }

  auto inventory = request["inventory"].toList();
  for (auto elem: inventory)
  {
    Item* item = CreateActor_<Item>();
    SetItemDescription(elem.toMap(), item);
    item->SetOnTheGround(false);
    player->items_.push_back(item);
    actors_.erase(std::remove(actors_.begin(), actors_.end(), item), actors_.end());
    //idToActor_.erase(item->GetId());
  }

  auto stats = request["stats"].toMap();
  for (auto s = stats.begin(); s != stats.end(); s++)
  {
    EStatConst stat = StringToStat[s.key()];
    QVariant val = s.value();
    player->SetStat(stat, val.toFloat());
  }

  if (stats.size() == 0)
  {
    player->SetSpeed(playerVelocity_);
  }

  QVariantList items;
  for (auto& elem: player->items_)
  {
    QVariantMap item;
    item["id"] = elem->GetId();
    item["name"] = elem->Getname();
    item["type"] = elem->GetTypeItem();
    item["class"] = elem->GetClass();
    item["subtype"] = elem->GetSubtype();
    item["weight"] = elem->GetWeight();
    items << item;
  }
  response["inventory"] = items;

  auto slot = request["slots"].toMap();
  QVariantMap id_slot;
  for (auto i = SlotToString.begin(); i != SlotToString.end(); i++)
  {
    if (slot.find(i.key()) != slot.end())
    {
      Item* item = CreateActor_<Item>();
      SetItemDescription(slot[i.key()].toMap(), item);
      player->items_.push_back(item);
      player->SetSlot(i.value(), item);
      player->SetStat(true, item);
      id_slot[i.key()] = item->GetId();
    }
  }
  response["slots"] = id_slot;
  response["id"] = player->GetId();

  QByteArray sid;
  do
  {
    QByteArray id = QString::number(qrand()).toLatin1();
    sid = QCryptographicHash::hash(id, QCryptographicHash::Sha1);

  } while (sidToPlayer_.find(sid) != sidToPlayer_.end());
  sid = sid.toHex();

  sidToPlayer_.insert(sid, player);
  response["sid"] = sid;
  response["fistId"] = FistId_;
}
Example #24
0
/*
 * Given a buffer containing what is hopefully a MIDI message,
 * return a string describing the MIDI message.
 */
QString Bridge::describeMIDI(QByteArray &buf)
{
    uint8_t msg = buf[0];
    uint8_t tag = msg & TAG_MASK;
    uint8_t channel = msg & CHANNEL_MASK;
    const char *desc= 0;

    // Work out what we have

    switch(tag) {
    case TAG_PROGRAM:
        desc = "Ch %1: Program change %2";
        break;
    case TAG_CHANNEL_PRESSURE:
        desc = "Ch %1: Pressure change %2";
        break;
    case TAG_NOTE_ON:
        desc = "Ch %1: Note %2 on  velocity %3";
        break;
    case TAG_NOTE_OFF:
        desc = "Ch %1: Note %2 off velocity %3";
        break;
    case TAG_KEY_PRESSURE:
        desc = "Ch %1: Note %2 pressure %3";
        break;
    case TAG_CONTROLLER:
        desc = "Ch %1: Controller %2 value %3";
        break;
    case TAG_PITCH_BEND:
        desc = "Ch %1: Pitch bend %2";
        break;
    case TAG_SPECIAL:
        if(msg == MSG_SYSEX_START) {
            QString res = "SysEx Message: ";
            for(int i = 1; i < buf.length(); i++) {
                uint8_t val = buf[i];
                if(val == MSG_SYSEX_END)
                    break;
                res.append(QString("0x%1 ").arg(val,0,16));
            }
            return res;
        }
        if(channel < 3) {
            desc = "System Message #%1: %2 %3";
        } else if (channel < 6) {
            desc = "System Message #%1: %2";
        } else {
            desc = "System Message #%1";
        }
        break;
    default:
        return QString("Unknown MIDI message %1").arg(QString(buf.toHex()));
    }

    // Format the output

    QString qdesc = QString(desc).arg((int) channel+(tag==TAG_SPECIAL?0:1));

    if(tag == TAG_PITCH_BEND && buf.length() == 3) { // recombine LSB/MSB for pitch bend
        return qdesc.arg((int) ((uint8_t)buf[1]) | ((uint8_t) buf[2])<<7 );
    }

    int i = 1;
    while(qdesc.contains("%") && i < buf.length()) {
      qdesc = qdesc.arg((int) buf[i++]);
    }
    return qdesc;
}
QString YandexmusicApi::getTrackUrl(const QString &storageDir)
{
  FileDownloader *fd = new FileDownloader(QUrl(QString("https://storage.mds.yandex.net/download-info/%1/2?format=json").arg(storageDir)));
  QJsonDocument jsonDoc = QJsonDocument::fromJson(fd->downloadedData());
  fd->~FileDownloader();

  QByteArray h = QCryptographicHash::hash("XGRlBW9FXlekgbPrRHuSiA" +
                                          jsonDoc.object().value("path").toString().mid(1).toUtf8() +
                                          jsonDoc.object().value("s").toString().toUtf8(), QCryptographicHash::Md5);


  return QString("https://") + jsonDoc.object().value("host").toString() + "/get-mp3/" + QString(h.toHex()) + QString("/") +
      jsonDoc.object().value("ts").toString() + jsonDoc.object().value("path").toString();
}
bool OwnUserInfoTask::take( Transfer* transfer )
{
	if ( forMe( transfer ) )
	{
		SnacTransfer* st = dynamic_cast<SnacTransfer*>( transfer );
		if ( !st )
			return false;
		
		Buffer* b = transfer->buffer();
		if ( st->snacSubtype() == 0x0F )
		{
			UserDetails ud;
			ud.fill( b );
			m_details = ud;
			emit gotInfo();
			setSuccess( 0, QString() );
			return true;
		}
		else
		{
			bool needUpload = false;
			Oscar::WORD infoType = b->getWord();
			if ( infoType == 0x0000 || infoType == 0x0001 )
			{
				Oscar::BYTE flags = b->getByte();
				if ( flags == 0x41 )  //we need to do a buddy upload when bit 8 = 1
					needUpload = true;
				
				QByteArray qba;
				if ( b->bytesAvailable() != 0 )
				{ //buffer might be empty if flags bit 8 = 1
					Oscar::BYTE checksumLength = b->getByte();
					qba = b->getBlock( checksumLength );
					kDebug(OSCAR_RAW_DEBUG) << "Self icon checksum: " << qba.toHex();
				}
				
				if ( needUpload )
				{
					kDebug(OSCAR_RAW_DEBUG) << "Buddy icon upload requested";
					emit buddyIconUploadRequested();
				}
				else
				{
					kDebug(OSCAR_RAW_DEBUG) << "no item for hash found";
				}
			}
			
			if ( infoType == 0x0002 )
			{
				QString availableMsg( b->getBSTR() );
				kDebug(OSCAR_RAW_DEBUG) << "self available message: ";
			}
			
			setSuccess( 0, QString() );
			return true;
		}
		
	}

	return false;
}
Example #27
0
void Options::set_opt ( const QString &opt, const QByteArray &val )
{
    QString         opt_str = option( opt );
    if ( settings_p )
        settings_p->setValue ( opt_str, QString::fromLatin1(val.toHex()) );
}
Example #28
0
QString ToString(const QByteArray &Hash) noexcept
   {
      return QString::fromLatin1(Hash.toHex());
   }
Example #29
0
bool Brut_Test::run(){
	
	QString sOrigHash = "81dc9bdb52d04dc20036dbd8313ed055";
    // QString sReverseHash0 = "c19173c3d173cc7e07cf5f19c28d0083";
    QString sReverseText = "6467756476606062606262606000404000000000000000001000000000220000000000002080000000000002002000004200140202515b";
    QByteArray text =  QByteArray::fromHex(sReverseText.toLatin1());
    // text = QString(text).toLatin1();

    QByteArray md5Text = QCryptographicHash::hash(text, QCryptographicHash::Md5);
    QString sMd5Text = QString(md5Text.toHex());

    int nPrevResult = BNACalculateBinDistance(BNAConvertHexToBin(sOrigHash), BNAConvertHexToBin(sMd5Text));
    std::cout << "Start: " << nPrevResult << "\n";

    // bool
    bool bExists = true;
    while(bExists){
        bExists = false;
        QByteArray textNew = BNATryBrutFast1(text, sOrigHash);
        textNew = BNATryBrutFast2(textNew, sOrigHash);

        QByteArray md5TextNew = QCryptographicHash::hash(textNew, QCryptographicHash::Md5);
        QString sMd5TextNew = QString(md5TextNew.toHex());

        QString sText_bin = BNAConvertHexToBin(sOrigHash);
        QString sTextNew_bin = BNAConvertHexToBin(sMd5TextNew);

        int nNewResult = BNACalculateBinDistance(sText_bin, sTextNew_bin);
        if(nNewResult > nPrevResult){
            bExists = true;
            text = QByteArray(textNew);
            nPrevResult = nNewResult;
            std::cout << "Distance: " << nPrevResult << "\n";
        }
    }

    text = QString(text).toLatin1();
    md5Text = QCryptographicHash::hash(text, QCryptographicHash::Md5);
    sMd5Text = QString(md5Text.toHex());

    nPrevResult = BNACalculateBinDistance(BNAConvertHexToBin(sOrigHash), BNAConvertHexToBin(sMd5Text));
    std::cout << "Start: " << nPrevResult << "\n";

    bExists = true;
    while(bExists){
        bExists = false;
        QByteArray textNew = BNATryBrutFast1(text, sOrigHash);
        textNew = BNATryBrutFast2(textNew, sOrigHash);

        QByteArray md5TextNew = QCryptographicHash::hash(textNew, QCryptographicHash::Md5);
        QString sMd5TextNew = QString(md5TextNew.toHex());

        QString sText_bin = BNAConvertHexToBin(sOrigHash);
        QString sTextNew_bin = BNAConvertHexToBin(sMd5TextNew);

        int nNewResult = BNACalculateBinDistance(sText_bin, sTextNew_bin);
        if(nNewResult > nPrevResult){
            bExists = true;
            text = QByteArray(textNew);
            nPrevResult = nNewResult;
            std::cout << "Distance: " << nPrevResult << "\n";
        }
    }

    std::cout << "Original: " << sReverseText.toStdString() << "\n";
    std::cout << "Reverted: " << QString(text.toHex()).toStdString() << "\n";

	return false;
}
Example #30
0
void BabyMEGClient::HescDisplay(double a)
{
    QByteArray data = QByteArray::fromRawData((char *)&a,8);
    qDebug() << data.toHex();
}