void ProtocolController::onServerDataEvent(QByteArray &data)
{
    const QByteArray seperator("\r\n");

    if ( data.startsWith("MESSAGE:") ) {
        QByteArray preparedData = prepareRequest(data, QByteArrayLiteral("MESSAGE:"));

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

            QByteArray username = preparedData.left(seperatorIndex);
            QByteArray message = preparedData.mid(seperatorIndex + seperator.length());

            signalMessage(username, message);
        }
    }
    else if ( data.startsWith("STARTUP:") ) {
        QByteArray preparedData = prepareRequest(data, QByteArrayLiteral("STARTUP:"));

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

            QByteArray username = preparedData.left(seperatorIndex);
            QByteArray publicKey = preparedData.mid(seperatorIndex + seperator.length());

            signalStartup(username, publicKey);
        }
    }
    else if ( data.startsWith("ENCRYPT:") ) {
        QByteArray preparedData = prepareRequest(data, QByteArrayLiteral("ENCRYPT:"));

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

            QByteArray username = preparedData.left(seperatorIndex);
            QByteArray message = preparedData.mid(seperatorIndex + seperator.length());

            signalEncrypt(username, message);
        }
    }
    else if ( data.startsWith("IDENTITY-CHECK:") ) {
        QByteArray encryptedRandomString = stripRequest(data, QByteArrayLiteral("IDENTITY-CHECK:"));

        if ( encryptedRandomString.size() > 0 ) {
            signalIdentityCheck(encryptedRandomString);
        }
    }
    else if ( data.startsWith("AUTHENTICATION-ACCEPTED") ) {
        emit signalAuthenticationSucceded();
    }
    else if ( data.startsWith("NOTIFICATION:") ) {
        QByteArray notificationString = stripRequest(data, QByteArrayLiteral("NOTIFICATION:"));

        qDebug() << "Received notification: " << notificationString;

        if ( notificationString.startsWith("ONLINE") ) {
            int seperatorIndex = notificationString.indexOf(seperator);
            QByteArray username = notificationString.mid(seperatorIndex + seperator.length());

            qDebug() << "User " << username << " is online";

            emit signalUserOnline(username);
        }
    }
    else {
        qWarning() << "UNKNOWN ACTION";
        signalError(QByteArrayLiteral("UNKNOWN ACTION"));
    }
}
예제 #2
0
void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed)
{
    currentFilenames.push(filename);
    preprocessed.reserve(preprocessed.size() + symbols.size());
    while (hasNext()) {
        Token token = next();

        switch (token) {
        case PP_INCLUDE:
        {
            int lineNum = symbol().lineNum;
            QByteArray include;
            bool local = false;
            if (test(PP_STRING_LITERAL)) {
                local = lexem().startsWith('\"');
                include = unquotedLexem();
            } else
                continue;
            until(PP_NEWLINE);

            // #### stringery
            QFileInfo fi;
            if (local)
                fi.setFile(QFileInfo(QString::fromLocal8Bit(filename)).dir(), QString::fromLocal8Bit(include));
            for (int j = 0; j < Preprocessor::includes.size() && !fi.exists(); ++j) {
                const IncludePath &p = Preprocessor::includes.at(j);
                if (p.isFrameworkPath) {
                    const int slashPos = include.indexOf('/');
                    if (slashPos == -1)
                        continue;
                    QByteArray frameworkCandidate = include.left(slashPos);
                    frameworkCandidate.append(".framework/Headers/");
                    fi.setFile(QString::fromLocal8Bit(p.path + '/' + frameworkCandidate), QString::fromLocal8Bit(include.mid(slashPos + 1)));
                } else {
                    fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(include));
                }
                // try again, maybe there's a file later in the include paths with the same name
                // (186067)
                if (fi.isDir()) {
                    fi = QFileInfo();
                    continue;
                }
            }

            if (!fi.exists() || fi.isDir())
                continue;
            include = fi.canonicalFilePath().toLocal8Bit();

            if (Preprocessor::preprocessedIncludes.contains(include))
                continue;
            Preprocessor::preprocessedIncludes.insert(include);

            QFile file(QString::fromLocal8Bit(include));
            if (!file.open(QFile::ReadOnly))
                continue;

            QByteArray input = file.readAll();
            file.close();
            if (input.isEmpty())
                continue;

            Symbols saveSymbols = symbols;
            int saveIndex = index;

            // phase 1: get rid of backslash-newlines
            input = cleaned(input);

            // phase 2: tokenize for the preprocessor
            symbols = tokenize(input);
            input.clear();

            index = 0;

            // phase 3: preprocess conditions and substitute macros
            preprocessed += Symbol(0, MOC_INCLUDE_BEGIN, include);
            preprocess(include, preprocessed);
            preprocessed += Symbol(lineNum, MOC_INCLUDE_END, include);

            symbols = saveSymbols;
            index = saveIndex;
            continue;
        }
        case PP_DEFINE:
        {
            next(IDENTIFIER);
            QByteArray name = lexem();
            int start = index;
            until(PP_NEWLINE);
            Macro macro;
            macro.symbols.reserve(index - start - 1);
            for (int i = start; i < index - 1; ++i)
                macro.symbols += symbols.at(i);
            macros.insert(name, macro);
            continue;
        }
        case PP_UNDEF: {
            next(IDENTIFIER);
            QByteArray name = lexem();
            until(PP_NEWLINE);
            macros.remove(name);
            continue;
        }
        case PP_IDENTIFIER:
        {
//             if (macros.contains(symbol()))
//                 ;
        }
            // we _could_ easily substitute macros by the following
            // four lines, but we choose not to.
            /*
            if (macros.contains(sym.lexem())) {
                preprocessed += substitute(macros, symbols, i);
                continue;
            }
            */
            break;
        case PP_HASH:
            until(PP_NEWLINE);
            continue; // skip unknown preprocessor statement
        case PP_IFDEF:
        case PP_IFNDEF:
        case PP_IF:
            while (!evaluateCondition()) {
                if (!skipBranch())
                    break;
                if (test(PP_ELIF)) {
                } else {
                    until(PP_NEWLINE);
                    break;
                }
            }
            continue;
        case PP_ELIF:
        case PP_ELSE:
            skipUntilEndif();
            // fall through
        case PP_ENDIF:
            until(PP_NEWLINE);
            continue;
        case SIGNALS:
        case SLOTS: {
            Symbol sym = symbol();
            if (macros.contains("QT_NO_KEYWORDS"))
                sym.token = IDENTIFIER;
            else
                sym.token = (token == SIGNALS ? Q_SIGNALS_TOKEN : Q_SLOTS_TOKEN);
            preprocessed += sym;
        } continue;
        default:
            break;
        }
        preprocessed += symbol();
    }

    currentFilenames.pop();
}
bool QDeclarativeListModelParser::compileProperty(const QDeclarativeCustomParserProperty &prop, QList<ListInstruction> &instr, QByteArray &data)
{
    QList<QVariant> values = prop.assignedValues();
    for(int ii = 0; ii < values.count(); ++ii) {
        const QVariant &value = values.at(ii);

        if(value.userType() == qMetaTypeId<QDeclarativeCustomParserNode>()) {
            QDeclarativeCustomParserNode node =
                qvariant_cast<QDeclarativeCustomParserNode>(value);

            if (node.name() != listElementTypeName) {
                const QMetaObject *mo = resolveType(node.name());
                if (mo != &QDeclarativeListElement::staticMetaObject) {
                    error(node, QDeclarativeListModel::tr("ListElement: cannot contain nested elements"));
                    return false;
                }
                listElementTypeName = node.name(); // cache right name for next time
            }

            {
            ListInstruction li;
            li.type = ListInstruction::Push;
            li.dataIdx = -1;
            instr << li;
            }

            QList<QDeclarativeCustomParserProperty> props = node.properties();
            for(int jj = 0; jj < props.count(); ++jj) {
                const QDeclarativeCustomParserProperty &nodeProp = props.at(jj);
                if (nodeProp.name().isEmpty()) {
                    error(nodeProp, QDeclarativeListModel::tr("ListElement: cannot contain nested elements"));
                    return false;
                }
                if (nodeProp.name() == "id") {
                    error(nodeProp, QDeclarativeListModel::tr("ListElement: cannot use reserved \"id\" property"));
                    return false;
                }

                ListInstruction li;
                int ref = data.count();
                data.append(nodeProp.name());
                data.append('\0');
                li.type = ListInstruction::Set;
                li.dataIdx = ref;
                instr << li;

                if(!compileProperty(nodeProp, instr, data))
                    return false;

                li.type = ListInstruction::Pop;
                li.dataIdx = -1;
                instr << li;
            }

            {
            ListInstruction li;
            li.type = ListInstruction::Pop;
            li.dataIdx = -1;
            instr << li;
            }

        } else {

            QDeclarativeParser::Variant variant =
                qvariant_cast<QDeclarativeParser::Variant>(value);

            int ref = data.count();

            QByteArray d;
            d += char(variant.type()); // type tag
            if (variant.isString()) {
                d += variant.asString().toUtf8();
            } else if (variant.isNumber()) {
                double temp = variant.asNumber();
                d += QByteArray( reinterpret_cast<const char*>(&temp), sizeof(double));
            } else if (variant.isBoolean()) {
                d += char(variant.asBoolean());
            } else if (variant.isScript()) {
                if (definesEmptyList(variant.asScript())) {
                    d[0] = char(QDeclarativeParser::Variant::Invalid); // marks empty list
                } else {
                    QByteArray script = variant.asScript().toUtf8();
                    int v = evaluateEnum(script);
                    if (v<0) {
                        if (script.startsWith("QT_TR_NOOP(\"") && script.endsWith("\")")) {
                            d[0] = char(QDeclarativeParser::Variant::String);
                            d += script.mid(12,script.length()-14);
                        } else {
                            error(prop, QDeclarativeListModel::tr("ListElement: cannot use script for property value"));
                            return false;
                        }
                    } else {
                        d[0] = char(QDeclarativeParser::Variant::Number);
                        double temp = v;
                        d += QByteArray( reinterpret_cast<const char*>(&temp), sizeof(double));
                    }
                }
            }
            d.append('\0');
            data.append(d);

            ListInstruction li;
            li.type = ListInstruction::Value;
            li.dataIdx = ref;
            instr << li;
        }
    }

    return true;
}
예제 #4
0
int InboundAudioStream::parseData(const QByteArray& packet) {

    PacketType packetType = packetTypeForPacket(packet);
    QUuid senderUUID = uuidFromPacketHeader(packet);

    // parse header 
    int numBytesHeader = numBytesForPacketHeader(packet);
    const char* sequenceAt = packet.constData() + numBytesHeader;
    int readBytes = numBytesHeader;

    // parse sequence number and track it
    quint16 sequence = *(reinterpret_cast<const quint16*>(sequenceAt));
    readBytes += sizeof(quint16);
    SequenceNumberStats::ArrivalInfo arrivalInfo = _incomingSequenceNumberStats.sequenceNumberReceived(sequence, senderUUID);

    frameReceivedUpdateTimingStats();

    // TODO: handle generalized silent packet here?????

    // parse the info after the seq number and before the audio data.(the stream properties)
    int numAudioSamples;
    readBytes += parseStreamProperties(packetType, packet.mid(readBytes), numAudioSamples);

    // handle this packet based on its arrival status.
    // For now, late packets are ignored.  It may be good in the future to insert the late audio frame
    // into the ring buffer to fill in the missing frame if it hasn't been mixed yet.
    switch (arrivalInfo._status) {
        case SequenceNumberStats::Early: {
            int packetsDropped = arrivalInfo._seqDiffFromExpected;
            writeSamplesForDroppedPackets(packetsDropped * numAudioSamples);
            // fall through to OnTime case
        }
        case SequenceNumberStats::OnTime: {
            readBytes += parseAudioData(packetType, packet.mid(readBytes), numAudioSamples);
            break;
        }
        default: {
            break;
        }
    }

    int framesAvailable = _ringBuffer.framesAvailable();
    // if this stream was starved, check if we're still starved.
    if (_isStarved && framesAvailable >= _desiredJitterBufferFrames) {
        _isStarved = false;
    }
    // if the ringbuffer exceeds the desired size by more than the threshold specified,
    // drop the oldest frames so the ringbuffer is down to the desired size.
    if (framesAvailable > _desiredJitterBufferFrames + _maxFramesOverDesired) {
        int framesToDrop = framesAvailable - (_desiredJitterBufferFrames + DESIRED_JITTER_BUFFER_FRAMES_PADDING);
        _ringBuffer.shiftReadPosition(framesToDrop * _ringBuffer.getNumFrameSamples());
        
        _framesAvailableStat.reset();
        _currentJitterBufferFrames = 0;

        _oldFramesDropped += framesToDrop;
    }

    framesAvailableChanged();

    return readBytes;
}
예제 #5
0
/* the next two functions are implicitely thread safe,
   as they are only called by setup() which uses a mutex.
*/
static void setupLocaleMapper()
{
#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
    localeMapper = QTextCodec::codecForName("System");
#else

#ifndef QT_NO_ICONV
    localeMapper = QTextCodec::codecForName("System");
#endif

#if defined (_XOPEN_UNIX) && !defined(Q_OS_QNX) && !defined(Q_OS_OSF)
    if (!localeMapper) {
        char *charset = nl_langinfo (CODESET);
        if (charset)
            localeMapper = QTextCodec::codecForName(charset);
    }
#endif

    if (!localeMapper) {
        // Very poorly defined and followed standards causes lots of
        // code to try to get all the cases... This logic is
        // duplicated in QIconvCodec, so if you change it here, change
        // it there too.

        // Try to determine locale codeset from locale name assigned to
        // LC_CTYPE category.

        // First part is getting that locale name.  First try setlocale() which
        // definitely knows it, but since we cannot fully trust it, get ready
        // to fall back to environment variables.
#if !defined(QT_NO_SETLOCALE)
        const QByteArray ctype = setlocale(LC_CTYPE, 0);
#else
        const QByteArray ctype;
#endif

        // Get the first nonempty value from $LC_ALL, $LC_CTYPE, and $LANG
        // environment variables.
        QByteArray lang = qgetenv("LC_ALL");
        if (lang.isEmpty() || lang == "C") {
            lang = qgetenv("LC_CTYPE");
        }
        if (lang.isEmpty() || lang == "C") {
            lang = qgetenv("LANG");
        }

        // Now try these in order:
        // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)
        // 2. CODESET from lang if it contains a .CODESET part
        // 3. ctype (maybe the locale is named "ISO-8859-1" or something)
        // 4. locale (ditto)
        // 5. check for "@euro"
        // 6. guess locale from ctype unless ctype is "C"
        // 7. guess locale from lang

        // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)
        int indexOfDot = ctype.indexOf('.');
        if (indexOfDot != -1)
            localeMapper = checkForCodec( ctype.mid(indexOfDot + 1) );

        // 2. CODESET from lang if it contains a .CODESET part
        if (!localeMapper) {
            indexOfDot = lang.indexOf('.');
            if (indexOfDot != -1)
                localeMapper = checkForCodec( lang.mid(indexOfDot + 1) );
        }

        // 3. ctype (maybe the locale is named "ISO-8859-1" or something)
        if (!localeMapper && !ctype.isEmpty() && ctype != "C")
            localeMapper = checkForCodec(ctype);

        // 4. locale (ditto)
        if (!localeMapper && !lang.isEmpty())
            localeMapper = checkForCodec(lang);

        // 5. "@euro"
        if ((!localeMapper && ctype.contains("@euro")) || lang.contains("@euro"))
            localeMapper = checkForCodec("ISO 8859-15");

        // 6. guess locale from ctype unless ctype is "C"
        // 7. guess locale from lang
        const QByteArray &try_by_name = (!ctype.isEmpty() && ctype != "C") ? lang : ctype;

        // Now do the guessing.
        if (!lang.isEmpty() && !localeMapper && !try_by_name.isEmpty()) {
            if (try_locale_list(iso8859_15locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-15");
            else if (try_locale_list(iso8859_2locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-2");
            else if (try_locale_list(iso8859_3locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-3");
            else if (try_locale_list(iso8859_4locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-4");
            else if (try_locale_list(iso8859_5locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-5");
            else if (try_locale_list(iso8859_6locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-6");
            else if (try_locale_list(iso8859_7locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-7");
            else if (try_locale_list(iso8859_8locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-8-I");
            else if (try_locale_list(iso8859_9locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-9");
            else if (try_locale_list(iso8859_13locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-13");
            else if (try_locale_list(tis_620locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-11");
            else if (try_locale_list(koi8_ulocales, lang))
                localeMapper = QTextCodec::codecForName("KOI8-U");
            else if (try_locale_list(cp_1251locales, lang))
                localeMapper = QTextCodec::codecForName("CP 1251");
            else if (try_locale_list(pt_154locales, lang))
                localeMapper = QTextCodec::codecForName("PT 154");
            else if (try_locale_list(probably_koi8_rlocales, lang))
                localeMapper = ru_RU_hack(lang);
        }

    }

    // If everything failed, we default to 8859-1
    // We could perhaps default to 8859-15.
    if (!localeMapper)
        localeMapper = QTextCodec::codecForName("ISO 8859-1");
#endif
}
예제 #6
0
    void populateSettings(const QByteArray &xSettings)
    {
        if (xSettings.length() < 12)
            return;
        char byteOrder = xSettings.at(0);
        if (byteOrder != LSBFirst && byteOrder != MSBFirst) {
            qWarning("%s ByteOrder byte %d not 0 or 1", Q_FUNC_INFO , byteOrder);
            return;
        }

#define ADJUST_BO(b, t, x) \
        ((b == LSBFirst) ?                          \
         qFromLittleEndian<t>((const uchar *)(x)) : \
         qFromBigEndian<t>((const uchar *)(x)))
#define VALIDATE_LENGTH(x)    \
        if ((size_t)xSettings.length() < (offset + local_offset + 12 + x)) { \
            qWarning("%s Length %d runs past end of data", Q_FUNC_INFO , x); \
            return;                                                     \
        }

        uint number_of_settings = ADJUST_BO(byteOrder, quint32, xSettings.mid(8,4).constData());
        const char *data = xSettings.constData() + 12;
        size_t offset = 0;
        for (uint i = 0; i < number_of_settings; i++) {
            int local_offset = 0;
            VALIDATE_LENGTH(2);
            XSettingsType type = static_cast<XSettingsType>(*reinterpret_cast<const quint8 *>(data + offset));
            local_offset += 2;

            VALIDATE_LENGTH(2);
            quint16 name_len = ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
            local_offset += 2;

            VALIDATE_LENGTH(name_len);
            QByteArray name(data + offset + local_offset, name_len);
            local_offset += round_to_nearest_multiple_of_4(name_len);

            VALIDATE_LENGTH(4);
            int last_change_serial = ADJUST_BO(byteOrder, qint32, data + offset + local_offset);
            Q_UNUSED(last_change_serial);
            local_offset += 4;

            QVariant value;
            if (type == XSettingsTypeString) {
                VALIDATE_LENGTH(4);
                int value_length = ADJUST_BO(byteOrder, qint32, data + offset + local_offset);
                local_offset+=4;
                VALIDATE_LENGTH(value_length);
                QByteArray value_string(data + offset + local_offset, value_length);
                value.setValue(value_string);
                local_offset += round_to_nearest_multiple_of_4(value_length);
            } else if (type == XSettingsTypeInteger) {
                VALIDATE_LENGTH(4);
                int value_length = ADJUST_BO(byteOrder, qint32, data + offset + local_offset);
                local_offset += 4;
                value.setValue(value_length);
            } else if (type == XSettingsTypeColor) {
                VALIDATE_LENGTH(2*4);
                quint16 red = ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
                local_offset += 2;
                quint16 green = ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
                local_offset += 2;
                quint16 blue = ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
                local_offset += 2;
                quint16 alpha= ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
                local_offset += 2;
                QColor color_value(red,green,blue,alpha);
                value.setValue(color_value);
            }
            offset += local_offset;
            settings[name].updateValue(screen,name,value,last_change_serial);
        }

    }
예제 #7
0
QByteArray QxtMailMessage::rfc2822() const
{
    // Use quoted-printable if requested
	bool useQuotedPrintable = (extraHeader(QStringLiteral("Content-Transfer-Encoding")).toLower() == QLatin1String("quoted-printable"));
    // Use base64 if requested
	bool useBase64 = (extraHeader(QStringLiteral("Content-Transfer-Encoding")).toLower() == QLatin1String("base64"));
    // Check to see if plain text is ASCII-clean; assume it isn't if QP or base64 was requested
    QTextCodec* latin1 = QTextCodec::codecForName("latin1");
    bool bodyIsAscii = latin1->canEncode(body()) && !useQuotedPrintable && !useBase64;

    QHash<QString, QxtMailAttachment> attach = attachments();
    QByteArray rv;

	if (!sender().isEmpty() && !hasExtraHeader(QStringLiteral("From")))
    {
		rv += qxt_fold_mime_header(QStringLiteral("From"), sender(), latin1);
    }

    if (!qxt_d->rcptTo.isEmpty())
    {
		rv += qxt_fold_mime_header(QStringLiteral("To"), qxt_d->rcptTo.join(QStringLiteral(", ")), latin1);
    }

    if (!qxt_d->rcptCc.isEmpty())
    {
		rv += qxt_fold_mime_header(QStringLiteral("Cc"), qxt_d->rcptCc.join(QStringLiteral(", ")), latin1);
    }

    if (!subject().isEmpty())
    {
		rv += qxt_fold_mime_header(QStringLiteral("Subject"), subject(), latin1);
    }

    if (!bodyIsAscii)
    {
		if (!hasExtraHeader(QStringLiteral("MIME-Version")) && !attach.count())
            rv += "MIME-Version: 1.0\r\n";

        // If no transfer encoding has been requested, guess.
        // Heuristic: If >20% of the first 100 characters aren't
        // 7-bit clean, use base64, otherwise use Q-P.
        if(!bodyIsAscii && !useQuotedPrintable && !useBase64)
        {
            QString b = body();
            int nonAscii = 0;
            int ct = b.length();
            for (int i = 0; i < ct && i < 100; i++)
            {
				if (QXT_MUST_QP(b[i])) nonAscii++;
			}
            useQuotedPrintable = !(nonAscii > 20);
            useBase64 = !useQuotedPrintable;
        }
    }

    if (attach.count())
    {
        if (qxt_d->boundary.isEmpty())
            qxt_d->boundary = QUuid::createUuid().toString().toLatin1().replace("{", "").replace("}", "");
		if (!hasExtraHeader(QStringLiteral("MIME-Version")))
            rv += "MIME-Version: 1.0\r\n";
		if (!hasExtraHeader(QStringLiteral("Content-Type")))
            rv += "Content-Type: multipart/mixed; boundary=" + qxt_d->boundary + "\r\n";
    }
	else if (!bodyIsAscii && !hasExtraHeader(QStringLiteral("Content-Transfer-Encoding")))
    {
        if (!useQuotedPrintable)
        {
            // base64
            rv += "Content-Transfer-Encoding: base64\r\n";
        }
        else
        {
            // quoted-printable
            rv += "Content-Transfer-Encoding: quoted-printable\r\n";
        }
    }

    for(const QString& r: qxt_d->extraHeaders.keys())
    {
		if ((r.toLower() == QLatin1String("content-type") || r.toLower() == QLatin1String("content-transfer-encoding")) && attach.count())
        {
            // Since we're in multipart mode, we'll be outputting this later
            continue;
        }
		rv += qxt_fold_mime_header(r, extraHeader(r), latin1);
    }

    rv += "\r\n";

    if (attach.count())
    {
        // we're going to have attachments, so output the lead-in for the message body
        rv += "This is a message with multiple parts in MIME format.\r\n";
        rv += "--" + qxt_d->boundary + "\r\nContent-Type: ";
		if (hasExtraHeader(QStringLiteral("Content-Type")))
			rv += extraHeader(QStringLiteral("Content-Type")).toLatin1() + "\r\n";
        else
            rv += "text/plain; charset=UTF-8\r\n";
		if (hasExtraHeader(QStringLiteral("Content-Transfer-Encoding")))
        {
			rv += "Content-Transfer-Encoding: " + extraHeader(QStringLiteral("Content-Transfer-Encoding")).toLatin1() + "\r\n";
        }
        else if (!bodyIsAscii)
        {
            if (!useQuotedPrintable)
            {
                // base64
                rv += "Content-Transfer-Encoding: base64\r\n";
            }
            else
            {
                // quoted-printable
                rv += "Content-Transfer-Encoding: quoted-printable\r\n";
            }
        }
        rv += "\r\n";
    }

    if (bodyIsAscii)
    {
        QByteArray b = latin1->fromUnicode(body());
        int len = b.length();
        QByteArray line = "";
        QByteArray word = "";
        for (int i = 0; i < len; i++)
        {
            if (b[i] == '\n' || b[i] == '\r')
            {
                if (line.isEmpty()) 
                {
                    line = word;
                    word = "";
                }
                else if (line.length() + word.length() + 1 <= 78)
                {
                    line = line + ' ' + word;
                    word = "";
                }
                if(line[0] == '.')
                    rv += ".";
                rv += line + "\r\n";
                if ((b[i+1] == '\n' || b[i+1] == '\r') && b[i] != b[i+1])
                {
                    // If we're looking at a CRLF pair, skip the second half
                    i++;
                }
                line = word;
            }
            else if (b[i] == ' ')
            {
                if (line.length() + word.length() + 1 > 78)
                {
                    if(line[0] == '.')
                        rv += ".";
                    rv += line + "\r\n";
                    line = word;
                }
                else if (line.isEmpty())
                {
                    line = word;
                }
                else
                {
                    line = line + ' ' + word;
                }
                word = "";
            }
            else
            {
                word += b[i];
            }
        }
        if (line.length() + word.length() + 1 > 78)
        {
            if(line[0] == '.')
                rv += ".";
            rv += line + "\r\n";
            line = word;
        }
        else if (!word.isEmpty())
        {
            line += ' ' + word;
        }
        if(!line.isEmpty()) {
            if(line[0] == '.')
                rv += ".";
            rv += line + "\r\n";
        }
    }
    else if (useQuotedPrintable)
    {
        QByteArray b = body().toUtf8();
        int ct = b.length();
        QByteArray line;
        for (int i = 0; i < ct; i++)
        {
            if(b[i] == '\n' || b[i] == '\r')
            {
                if(line[0] == '.')
                    rv += ".";
                rv += line + "\r\n";
                line = "";
                if ((b[i+1] == '\n' || b[i+1] == '\r') && b[i] != b[i+1])
                {
                    // If we're looking at a CRLF pair, skip the second half
                    i++;
                }
            }
            else if (line.length() > 74)
            {
                rv += line + "=\r\n";
                line = "";
            }
            if (QXT_MUST_QP(b[i]))
            {
                line += "=" + b.mid(i, 1).toHex().toUpper();
            }
            else
            {
                line += b[i];
            }
        }
        if(!line.isEmpty()) {
            if(line[0] == '.')
                rv += ".";
            rv += line + "\r\n";
        }
    }
    else /* base64 */
    {
        QByteArray b = body().toUtf8().toBase64();
        int ct = b.length();
        for (int i = 0; i < ct; i += 78)
        {
            rv += b.mid(i, 78) + "\r\n";
        }
    }

    if (attach.count())
    {
        for(const QString& filename: attach.keys())
        {
            rv += "--" + qxt_d->boundary + "\r\n";
			rv += qxt_fold_mime_header(QStringLiteral("Content-Disposition"), QDir(filename).dirName(), latin1, "attachment; filename=");
            rv += attach[filename].mimeData();
        }
        rv += "--" + qxt_d->boundary + "--\r\n";
    }

    return rv;
}
예제 #8
0
	bool processHeaderData(const QByteArray &headerData)
	{
		QList<QByteArray> lines;
		int at = 0;
		while(at < headerData.size())
		{
			int end = headerData.indexOf("\n", at);
			assert(end != -1);

			if(end > at && headerData[end - 1] == '\r')
				lines += headerData.mid(at, end - at - 1);
			else
				lines += headerData.mid(at, end - at);
			at = end + 1;
		}

		if(lines.isEmpty())
			return false;

		QByteArray requestLine = lines[0];

		at = requestLine.indexOf(' ');
		if(at == -1)
			return false;

		method = QString::fromLatin1(requestLine.mid(0, at));
		if(method.isEmpty())
			return false;

		++at;
		int end = requestLine.indexOf(' ', at);
		if(end == -1)
			return false;

		uri = requestLine.mid(at, end - at);

		QByteArray versionStr = requestLine.mid(end + 1);
		if(versionStr == "HTTP/1.0")
			version1dot0 = true;

		for(int n = 1; n < lines.count(); ++n)
		{
			const QByteArray &line = lines[n];
			end = line.indexOf(':');
			if(end == -1)
				continue;

			// skip first space
			at = end + 1;
			if(at < line.length() && line[at] == ' ')
				++at;

			QByteArray name = line.mid(0, end);
			QByteArray val = line.mid(at);

			reqHeaders += HttpHeader(name, val);
		}

		//log_debug("httpserver: IN method=[%s] uri=[%s] 1.1=%s", qPrintable(method), uri.data(), version1dot0 ? "no" : "yes");
		//foreach(const HttpHeader &h, reqHeaders)
		//	log_debug("httpserver:   [%s] [%s]", h.first.data(), h.second.data());
		log_debug("httpserver: IN %s %s", qPrintable(method), uri.data());

		return true;
	}
예제 #9
0
Quest::Quest(QString path, Player *Owner)
{
    QFile file(path);
    if (!file.open(QFile::ReadOnly))
    {
        app.logError(QObject::tr("Error reading quest DB"));
        app.stopGameServer();
        throw std::exception();
    }

    QList<QString> lines = QString(file.readAll().replace('\r',"")).split('\n');

    owner = Owner;
    commands = new QList<QList<QString> >;
    name = new QString();
    descr = new QString();
    npc = new Pony(nullptr); // A NPC doesn't have an owner player !
    npc->id = 0;
    npc->netviewId = 0;
    id = 0;
    state = 0;
    eip = 0;

    // Parse the metadata, add everything else as quest commands
    for (int i=0; i<lines.size(); i++)
    {
        QList<QString> line = lines[i].split(" ", QString::SkipEmptyParts);
        if (!line.size() || lines[i][0]=='#')
            continue;
        if (line[0] == "name")
            if (line.size()>=2)
                npc->name = lines[i].mid(line[0].size()+1);
            else throw QString(QObject::tr("Quest::Quest: Error reading name, quest %1").arg(path));
        else if (line[0] == "scene")
            if (line.size()>=2)
                npc->sceneName = lines[i].mid(line[0].size()+1).toLower();
            else throw QString(QObject::tr("Quest::Quest: Error reading scene, quest %1").arg(path));
        else if (line[0] == "ponyData")
        {
            if (line.size()==2)
            {
                QByteArray ponyData = QByteArray::fromBase64(line[1].toLatin1());
                // Read the ponyData
                unsigned strlen;
                unsigned lensize=0;
                {
                    unsigned char num3; int num=0, num2=0;
                    do {
                        num3 = ponyData[lensize]; lensize++;
                        num |= (num3 & 0x7f) << num2;
                        num2 += 7;
                    } while ((num3 & 0x80) != 0);
                    strlen = (uint) num;
                }
                int nameSize = strlen + lensize;
                int ponyDataSize = ponyData.size() - nameSize;
                if (ponyDataSize == 43)
                {
                    app.logMessage(QString("Quest::Quest: PonyData of quest %1 is in old format, converting")
                                   .arg(path));
                    ponyData += uint32ToData(0); // Member ID
                    ponyData.insert(nameSize+17+3,ponyData.mid(nameSize+17,3)); // Hair color 2 (copy of color 1)
                }
                npc->ponyData = ponyData;
            }
            else throw QString(QObject::tr("Quest::Quest: Error reading ponyData, quest %1").arg(path));
        }
        else if (line[0] == "pos")
            if (line.size()==4)
            {
                bool ok1, ok2, ok3;
                npc->pos = UVector(line[1].toFloat(&ok1), line[2].toFloat(&ok2),
                                    line[3].toFloat(&ok3));
                if (!(ok1 && ok2 && ok3))
                    throw QString(QObject::tr("Quest::Quest: Error reading pos, quest %1").arg(path));
            }
            else throw QString(QObject::tr("Quest::Quest: Error reading pos, quest %1").arg(path));
        else if (line[0] == "rot")
            if (line.size()==5)
            {
                bool ok1, ok2, ok3, ok4;
                npc->rot = UQuaternion(line[1].toFloat(&ok1), line[2].toFloat(&ok2),
                                        line[3].toFloat(&ok3), line[4].toFloat(&ok4));
                if (!(ok1 && ok2 && ok3 && ok4))
                    throw QString(QObject::tr("Quest::Quest: Error reading rot, quest %1").arg(path));
            }
            else throw QString(QObject::tr("Quest::Quest: Error reading rot, quest %1").arg(path));
        else if (line[0] == "wear")
        {
            for (int i=1; i<line.size(); i++)
            {
                bool ok;
                int itemId = line[i].toInt(&ok);
                if (!ok)
                    throw QString(QObject::tr("Quest::Quest: Error reading wear, quest %1").arg(path));
                WearableItem item;
                item.id = itemId;
                item.index = wearablePositionsToSlot(wearablePositionsMap[itemId]);
                npc->worn << item;
            }
        }
        else if (line[0] == "shop")
        {
            for (int i=1; i<line.size(); i++)
            {
                bool ok;
                int itemId = line[i].toInt(&ok);
                if (!ok)
                    throw QString(QObject::tr("Quest::Quest: Error reading shop, quest %1").arg(path));
                InventoryItem item;
                item.id = itemId;
                item.index = i-1;
                item.amount = (quint32)-1;
                npc->inv << item;
            }
        }
        else if (line[0] == "questId")
            if (line.size()==2)
            {
                id = line[1].toInt();

                SceneEntity::lastIdMutex.lock();
                npc->id = 0;
                npc->netviewId = id;
                SceneEntity::lastIdMutex.unlock();
            }
            else throw QString(QObject::tr("Quest::Quest: Error reading questId, quest %1").arg(path));
        else if (line[0] == "questName")
            if (line.size()>=2)
                *name = lines[i].mid(line[0].size()+1);
            else throw QString(QObject::tr("Quest::Quest: Error reading questName, quest %1").arg(path));
        else if (line[0] == "questDescr")
            if (line.size()>=2)
                *descr = lines[i].mid(line[0].size()+1);
            else throw QString(QObject::tr("Quest::Quest: Error reading questDescr, quest %1").arg(path));
        else
            commands->append(line);
    }
}
예제 #10
0
void SettingsSerializer::readSerialized()
{
    QFile f(path);
    if (!f.open(QIODevice::ReadOnly))
    {
        qWarning() << "Couldn't open file";
        return;
    }
    QByteArray data = f.readAll();
    f.close();

    // Decrypt
    if (tox_is_data_encrypted((uint8_t*)data.data()))
    {
        if (password.isEmpty())
        {
            qCritical() << "The settings file is encrypted, but we don't have a password!";
            return;
        }

        Core* core = Nexus::getCore();

        uint8_t salt[TOX_PASS_SALT_LENGTH];
        tox_get_salt(reinterpret_cast<uint8_t *>(data.data()), salt);
        auto passkey = core->createPasskey(password, salt);

        data = core->decryptData(data, *passkey);
        if (data.isEmpty())
        {
            qCritical() << "Failed to decrypt the settings file";
            return;
        }
    }
    else
    {
        if (!password.isEmpty())
            qWarning() << "We have a password, but the settings file is not encrypted";
    }

    if (memcmp(data.data(), magic, 4))
    {
        qWarning() << "Bad magic!";
        return;
    }
    data = data.mid(4);

    QDataStream stream(&data, QIODevice::ReadOnly);
    stream.setVersion(QDataStream::Qt_5_0);

    while (!stream.atEnd())
    {
        RecordTag tag;
        readStream(stream, tag);
        if (tag == RecordTag::Value)
        {
            QByteArray key;
            QByteArray value;
            readStream(stream, key);
            readStream(stream, value);
            setValue(QString::fromUtf8(key), QVariant(QString::fromUtf8(value)));
        }
        else if (tag == RecordTag::GroupStart)
        {
            QByteArray prefix;
            readStream(stream, prefix);
            beginGroup(QString::fromUtf8(prefix));
        }
        else if (tag == RecordTag::ArrayStart)
        {
            QByteArray prefix;
            readStream(stream, prefix);
            beginReadArray(QString::fromUtf8(prefix));
            QByteArray sizeData;
            readStream(stream, sizeData);
            if (sizeData.isEmpty())
            {
                qWarning("The personal save file is corrupted!");
                return;
            }
            quint64 size = dataToVUint(sizeData);
            arrays[array].size = max(size, arrays[array].size);
        }
        else if (tag == RecordTag::ArrayValue)
        {
            QByteArray indexData;
            readStream(stream, indexData);
            if (indexData.isEmpty())
            {
                qWarning("The personal save file is corrupted!");
                return;
            }
            quint64 index = dataToVUint(indexData);
            setArrayIndex(index);
            QByteArray key;
            QByteArray value;
            readStream(stream, key);
            readStream(stream, value);
            setValue(QString::fromUtf8(key), QVariant(QString::fromUtf8(value)));
        }
        else if (tag == RecordTag::ArrayEnd)
        {
            endArray();
        }
    }

    group = array = -1;
}
예제 #11
0
void DevicePluginElro::radioData(const QList<int> &rawData)
{    
    // filter right here a wrong signal length
    if (rawData.length() != 49) {
        return;
    }

    int delay = rawData.first()/31;
    QByteArray binCode;
    
    // average 314
    if (delay > 290 && delay < 400) {
        // go trough all 48 timings (without sync signal)
        for (int i = 1; i <= 48; i+=2 ) {
            int div;
            int divNext;
            
            // if short
            if (rawData.at(i) <= 700) {
                div = 1;
            } else {
                div = 3;
            }
            // if long
            if (rawData.at(i+1) < 700) {
                divNext = 1;
            } else {
                divNext = 3;
            }

             //      _
             //     | |___   = 0 -> in 4 delays => 1000
             //         _
             //     ___| |   = 1 -> in 4 delays => 0001

            if (div == 1 && divNext == 3) {
                binCode.append('0');
            } else if(div == 3 && divNext == 1) {
                binCode.append('1');
            } else {
                return;
            }
        }
    } else {
        return;
    }

    qCDebug(dcElro) << "Understands this protocol: " << binCode;

    if (binCode.left(20) == "00000100000000000001") {
        if (binCode.right(4) == "0100") {
            qCDebug(dcElro) << "Motion Detector OFF";
        } else {
            qCDebug(dcElro) << "Motion Detector ON";
        }
    }

    // get the channel of the remote signal (5 channels, true=1, false=0)
    QList<bool> group;
    for (int i = 1; i < 10; i+=2) {
        if (binCode.at(i-1) == '0' && binCode.at(i) == '1') {
            group << false;
        } else if(binCode.at(i-1) == '0' && binCode.at(i) == '0') {
            group << true;
        } else {
            return;
        }
    }
    
    // get the button letter
    QString button;
    QByteArray buttonCode = binCode.mid(10,10);

    if (buttonCode == "0001010101") {
        button = "A";
    } else if (buttonCode == "0100010101") {
        button = "B";
    } else if (buttonCode == "0101000101") {
        button = "C";
    } else if(buttonCode == "0101010001") {
        button = "D";
    } else if(buttonCode == "0101010100") {
        button = "E";
    } else {
        return;
    }

    // get power status -> On = 0100, Off = 0001
    bool power;
    if (binCode.right(4).toInt(0,2) == 1) {
        power = true;
    } else if(binCode.right(4).toInt(0,2) == 4) {
        power = false;
    } else {
        return;
    }

    qCDebug(dcElro) << group << buttonCode << power;
}
예제 #12
0
void Profile::refreshModStatus()
{
  QFile file(getModlistFileName());
  if (!file.open(QIODevice::ReadOnly)) {
    throw MyException(tr("\"%1\" is missing or inaccessible").arg(getModlistFileName()));
  }

  bool modStatusModified = false;
  m_ModStatus.clear();
  m_ModStatus.resize(ModInfo::getNumMods());

  std::set<QString> namesRead;

  // load mods from file and update enabled state and priority for them
  int index = 0;
  while (!file.atEnd()) {
    QByteArray line = file.readLine().trimmed();
    bool enabled = true;
    QString modName;
    if (line.length() == 0) {
      // empty line
      continue;
    } else if (line.at(0) == '#') {
      // comment line
      continue;
    } else if (line.at(0) == '-') {
      enabled = false;
      modName = QString::fromUtf8(line.mid(1).trimmed().constData());
    } else if ((line.at(0) == '+')
               || (line.at(0) == '*')) {
      modName = QString::fromUtf8(line.mid(1).trimmed().constData());
    } else {
      modName = QString::fromUtf8(line.trimmed().constData());
    }
    if (modName.size() > 0) {
      QString lookupName = modName;
      if (namesRead.find(lookupName) != namesRead.end()) {
        continue;
      } else {
        namesRead.insert(lookupName);
      }
      unsigned int modIndex = ModInfo::getIndex(lookupName);
      if (modIndex != UINT_MAX) {
        ModInfo::Ptr info = ModInfo::getByIndex(modIndex);
        if ((modIndex < m_ModStatus.size())
            && (info->getFixedPriority() == INT_MIN)) {
          m_ModStatus[modIndex].m_Enabled = enabled;
          if (m_ModStatus[modIndex].m_Priority == -1) {
            if (static_cast<size_t>(index) >= m_ModStatus.size()) {
              throw MyException(tr("invalid index %1").arg(index));
            }
            m_ModStatus[modIndex].m_Priority = index++;
          }
        } else {
          qWarning("no mod state for \"%s\" (profile \"%s\")",
                   qPrintable(modName), m_Directory.path().toUtf8().constData());
          // need to rewrite the modlist to fix this
          modStatusModified = true;
        }
      } else {
        qDebug("mod \"%s\" (profile \"%s\") not found",
               qPrintable(modName), m_Directory.path().toUtf8().constData());
        // need to rewrite the modlist to fix this
        modStatusModified = true;
      }
    }
  }

  int numKnownMods = index;

  int topInsert = 0;

  // invert priority order to match that of the pluginlist. Also
  // give priorities to mods not referenced in the profile
  for (size_t i = 0; i < m_ModStatus.size(); ++i) {
    ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
    if (modInfo->alwaysEnabled()) {
      m_ModStatus[i].m_Enabled = true;
    }

    if (modInfo->getFixedPriority() == INT_MAX) {
      continue;
    }

    if (m_ModStatus[i].m_Priority != -1) {
      m_ModStatus[i].m_Priority = numKnownMods - m_ModStatus[i].m_Priority - 1;
    } else {
      if (static_cast<size_t>(index) >= m_ModStatus.size()) {
        throw MyException(tr("invalid index %1").arg(index));
      }
      if (modInfo->hasFlag(ModInfo::FLAG_FOREIGN)) {
        m_ModStatus[i].m_Priority = --topInsert;
      } else {
        m_ModStatus[i].m_Priority = index++;
      }
      // also, mark the mod-list as changed
      modStatusModified = true;
    }
  }
  // to support insertion of new mods at the top we may now have mods with negative priority. shift them all up
  // to align priority with 0
  if (topInsert < 0) {
    int offset = topInsert * -1;
    for (size_t i = 0; i < m_ModStatus.size(); ++i) {
      ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
      if (modInfo->getFixedPriority() == INT_MAX) {
        continue;
      }

      m_ModStatus[i].m_Priority += offset;
    }
  }

  file.close();
  updateIndices();
  if (modStatusModified) {
    m_ModListWriter.write();
  }
}
예제 #13
0
파일: hasher.cpp 프로젝트: jlaine/wilink
void stunHash()
{
    QString m_localUser = "******";
    QString m_remoteUser = "******";
    QString m_remotePassword = "******";

    QByteArray username = QString("%1:%2").arg(m_remoteUser, m_localUser).toUtf8();
    quint16 usernameSize = username.size();
    username += QByteArray::fromHex("e1c318");
//    username += QByteArray(4 * ((usernameSize + 3) / 4) - usernameSize, 0);
    quint32 priority = 1862270975;
    QByteArray unknown(8, 0);
    QByteArray key = m_remotePassword.toUtf8();

    QByteArray buffer;
    QDataStream stream(&buffer, QIODevice::WriteOnly);
    quint16 type = BindingRequest;
    quint16 length = 0;
    QByteArray id = QByteArray::fromHex("93be62deb6e5418f9f87b68b");
    stream << type;
    stream << length;
    stream << MAGIC_COOKIE;
    stream.writeRawData(id.data(), id.size());

    stream << quint16(Priority);
    stream << quint16(sizeof(priority));
    stream << priority;

    stream << quint16(Unknown);
    stream << quint16(unknown.size());
    stream.writeRawData(unknown.data(), unknown.size());

    stream << quint16(Username);
    stream << usernameSize;
    stream.writeRawData(username.data(), username.size());

    // integrity
    length = buffer.size() - 20 + 24;
    qint64 pos = stream.device()->pos();
    stream.device()->seek(2);
    stream << length;
    stream.device()->seek(pos);

    QByteArray integrity = QXmppUtils::generateHmacSha1(key, buffer);
    qDebug() << "integrity" << integrity.toHex();
    stream << quint16(MessageIntegrity);
    stream << quint16(integrity.size());
    stream.writeRawData(integrity.data(), integrity.size());

    // fingerprint
    length = buffer.size() - 20 + 8;
    pos = stream.device()->pos();
    stream.device()->seek(2);
    stream << length;
    stream.device()->seek(pos);

    quint32 fingerprint = QXmppUtils::generateCrc32(buffer) ^ 0x5354554eL;
    qDebug() << "fingerprint" << fingerprint;
    stream << quint16(Fingerprint);
    stream << quint16(sizeof(fingerprint));
    stream << fingerprint;

    // output
    buffer.prepend(QByteArray(10, 0));
    for (int i = 0; i < buffer.size(); i += 16)
    {
        QByteArray chunk = buffer.mid(i, 16);
        QString str;
        for (int j = 0; j < 16; j += 1)
            str += chunk.mid(j, 1).toHex() + " ";
        qDebug() << str;
    }

}
예제 #14
0
void Widget::tcpProcessPendingDatagrams()
{
    // Find who's sending
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == nullptr)
        return;

    QByteArray* recvBuffer=nullptr;
    for (auto pair : tcpClientsList)
    {
        if (pair.first == socket)
        {
            recvBuffer = pair.second;
            break;
        }
    }
    if (recvBuffer == nullptr)
    {
        logError(tr("TCP: Error fetching the socket's associated recv buffer"));
        return;
    }

    unsigned nTries = 0;

    // Acquire data
    while(socket->state()==QAbstractSocket::ConnectedState && nTries<3) // Exit if disconnected, too much retries, malformed HTTP request, or after all requests are processed
    {
        recvBuffer->append(socket->readAll());
        nTries++;

        if (!recvBuffer->size())
        {
#if DEBUG_LOG
            logMessage(tr("TCP: Nothing to read"));
#endif
            continue;
        }

        if (!recvBuffer->startsWith("POST") && !recvBuffer->startsWith("GET")) // Not HTTP, clear the buffer
        {
#if DEBUG_LOG
            logMessage(tr("TCP: Received non-HTTP request : ")+*recvBuffer->toHex());
#endif
            recvBuffer->clear();
            socket->close();
            return;
        }
        else if (recvBuffer->contains("Content-Length:")) // POST or GET request, wait for Content-Length header
        {
            QByteArray contentLength = *recvBuffer;
            contentLength = contentLength.right(contentLength.size() - contentLength.indexOf("Content-Length:") - 15);
            QList<QByteArray> lengthList = contentLength.trimmed().split('\n');
            if (lengthList.size()>1) // We want a number on this line and a next line to be sure we've got the full number
            {
                bool isNumeric;
                int length = lengthList[0].trimmed().toInt(&isNumeric);
                if (!isNumeric) // We've got something but it's not a number
                {
                    logError(tr("TCP: Error: Content-Length must be a (decimal) number !"));
                    recvBuffer->clear();
                    socket->close();
                    return;
                }

                // Detect and send data files if we need to
                QByteArray data = *recvBuffer;
#if DEBUG_LOG
                logMessage(tr("TCP: Got content-length request:")+data);
#endif
                // Get the payload only (remove headers)
                data = removeHTTPHeader(data, "POST ");
                data = removeHTTPHeader(data, "GET ");
                data = removeHTTPHeader(data, "User-Agent:");
                data = removeHTTPHeader(data, "Host:");
                data = removeHTTPHeader(data, "host:");
                data = removeHTTPHeader(data, "Accept:");
                data = removeHTTPHeader(data, "Content-Length:");
                data = removeHTTPHeader(data, "Content-Type:");
                data = removeHTTPHeader(data, "Server:");
                data = removeHTTPHeader(data, "Date:");
                data = removeHTTPHeader(data, "Transfert-Encoding:");
                data = removeHTTPHeader(data, "Connection:");
                data = removeHTTPHeader(data, "Vary:");
                data = removeHTTPHeader(data, "X-Powered-By:");
                data = removeHTTPHeader(data, "accept-encoding:");
                data = removeHTTPHeader(data, "if-modified-since:");

                if (data.size() >= length) // Wait until we have all the data, then process it all
                {
                    data.truncate(length);
                    tcpProcessData(data, socket);
                    *recvBuffer = recvBuffer->right(recvBuffer->size() - recvBuffer->indexOf(data) - data.size());
                    if (recvBuffer->isEmpty())
                        return;
                    nTries=0;
                }
            }
        }
        else if (recvBuffer->contains("\r\n\r\n")) // POST or GET request, without a Content-Length header
        {
            QByteArray data = *recvBuffer;
            data = data.left(data.indexOf("\r\n\r\n")+4);
            int dataSize = data.size();
#if DEBUG_LOG
            logMessage(tr("Got non-content length request:")+data);
#endif

            int i1=0;
            do
            {
                i1 = data.indexOf("GET");
                if (i1 != -1)
                {
                    int i2 = data.indexOf("HTTP")-1;
                    QString path = data.mid(i1 + 4, i2-i1-4);
                    if (path == "/log") // GET /log
                    {
                        data = removeHTTPHeader(data, "POST ");
                        data = removeHTTPHeader(data, "GET ");
                        data = removeHTTPHeader(data, "if-modified-since:");
                        data = removeHTTPHeader(data, "accept-encoding:");
                        data = removeHTTPHeader(data, "host:");
                        if (!enableGetlog)
                            continue;
                        QFile head(QString(NETDATAPATH)+"/dataTextHeader.bin");
                        head.open(QIODevice::ReadOnly);
                        if (!head.isOpen())
                        {
                            logError(tr("Can't open header : ","The header is a file")+head.errorString());
                            continue;
                        }
                        QByteArray logData = ui->log->toPlainText().toLatin1();
                        socket->write(head.readAll());
                        socket->write(QString("Content-Length: "+QString().setNum(logData.size())+"\r\n\r\n").toLocal8Bit());
                        socket->write(logData);
                        head.close();
                        logMessage(tr("Sent log to %1").arg(socket->peerAddress().toString()));
                        continue;
                    }
                    // Other GETs (not getlog)
                    data = removeHTTPHeader(data, "POST ");
                    data = removeHTTPHeader(data, "GET ");
                    logMessage(tr("TCP: Replying to HTTP GET %1").arg(path));
                    QFile head(QString(NETDATAPATH)+"/dataHeader.bin");
                    QFile res("data/"+path);
                    head.open(QIODevice::ReadOnly);
                    if (!head.isOpen())
                    {
                        logError(tr("TCP: Can't open header : ","The header is a file")+head.errorString());
                        continue;
                    }
                    res.open(QIODevice::ReadOnly);
                    if (!res.isOpen())
                    {
                        logError(tr("TCP: File not found"));
                        head.close();
                        QFile head404(QString(NETDATAPATH)+"/notmodified.bin");
                        head404.open(QIODevice::ReadOnly);
                        if (!head404.isOpen())
                        {
                            logError(tr("TCP: Can't open 304 Not Modified header : ","The header is a file")
                                       +head404.errorString());
                            continue;
                        }
                        socket->write(head404.readAll());
                        head404.close();
                        continue;
                    }
                    socket->write(head.readAll());
                    socket->write(QString("Content-Length: "+QString().setNum(res.size())+"\r\n\r\n").toLocal8Bit());
                    socket->write(res.readAll());
                    head.close();
                    res.close();
#if DEBUG_LOG
                    logMessage(tr("TCP: Sent %1 bytes").arg(res.size()+head.size()));
#endif
                }
            } while (i1 != -1);

            *recvBuffer = recvBuffer->mid(dataSize);
        }
    }
}
예제 #15
0
// This function goes through the entire byte array
// and tries to see whether this is a valid UTF-8 sequence.
// If it's valid, this is probably a UTF-8 string.
bool HTMLEncodingResolver::IsValidUtf8(const QByteArray &string)
{
    // This is an implementation of the Perl code written here:
    //   http://www.w3.org/International/questions/qa-forms-utf-8
    //
    // Basically, UTF-8 has a very specific byte-pattern. This function
    // checks if the sent byte-sequence conforms to this pattern.
    // If it does, chances are *very* high that this is UTF-8.
    //
    // This function is written to be fast, not pretty.
    if (string.isNull()) {
        return false;
    }

    int index = 0;

    while (index < string.size()) {
        QByteArray dword = string.mid(index, 4);

        if (dword.size() < 4) {
            dword = dword.leftJustified(4, '\0');
        }

        const unsigned char *bytes = (const unsigned char *) dword.constData();

        // ASCII
        if (bytes[0] == 0x09 ||
            bytes[0] == 0x0A ||
            bytes[0] == 0x0D ||
            (0x20 <= bytes[0] && bytes[0] <= 0x7E)
           ) {
            index += 1;
        }
        // non-overlong 2-byte
        else if ((0xC2 <= bytes[0] && bytes[0] <= 0xDF) &&
                 (0x80 <= bytes[1] && bytes[1] <= 0xBF)
                ) {
            index += 2;
        } else if ((bytes[0] == 0xE0                         &&              // excluding overlongs
                    (0xA0 <= bytes[1] && bytes[1] <= 0xBF) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF)) ||
                   (((0xE1 <= bytes[0] && bytes[0] <= 0xEC) ||               // straight 3-byte
                     bytes[0] == 0xEE                         ||
                     bytes[0] == 0xEF) &&
                    (0x80 <= bytes[1] && bytes[1] <= 0xBF)   &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF)) ||
                   (bytes[0] == 0xED                         &&              // excluding surrogates
                    (0x80 <= bytes[1] && bytes[1] <= 0x9F) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF))
                  ) {
            index += 3;
        } else if ((bytes[0] == 0xF0                         &&              // planes 1-3
                    (0x90 <= bytes[1] && bytes[1] <= 0xBF) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
                    (0x80 <= bytes[3] && bytes[3] <= 0xBF)) ||
                   ((0xF1 <= bytes[0] && bytes[0] <= 0xF3) &&              // planes 4-15
                    (0x80 <= bytes[1] && bytes[1] <= 0xBF) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
                    (0x80 <= bytes[3] && bytes[3] <= 0xBF)) ||
                   (bytes[0] == 0xF4                         &&            // plane 16
                    (0x80 <= bytes[1] && bytes[1] <= 0x8F) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
                    (0x80 <= bytes[3] && bytes[3] <= 0xBF))
                  ) {
            index += 4;
        } else {
            return false;
        }
    }

    return true;
}
예제 #16
0
Segment *SegmentNoaa::ReadSegmentInMemory()
{
    FILE*   f;
    BZFILE* b;
    int     nBuf;
    char    buf[ 11090 * 2 ];
    int     bzerror;

    quint16 val1_ch[5], val2_ch[5],tot_ch[5];
    QByteArray picture_line;

    int heightinsegment = 0;

    f = fopen ( this->fileInfo.absoluteFilePath().toLatin1(), "rb" );
    if ( !f ) {
        qDebug() << QString("file %1 not found ! ").arg(this->fileInfo.absoluteFilePath());
        segmentok = false;
        return this;
    }

    qDebug() << "Bz2 file " + this->fileInfo.absoluteFilePath() + " is open";

    if((b = BZ2_bzopen(this->fileInfo.absoluteFilePath().toLatin1(),"rb"))==NULL)
    {
        segmentok = false;
        qDebug() << "error in BZ2_bzopen";
    }

    bzerror = BZ_OK;
    while ( bzerror == BZ_OK )
    {
      nBuf = BZ2_bzRead ( &bzerror, b, buf, 11090 * 2 );
      if ( bzerror == BZ_OK || bzerror == BZ_STREAM_END)
      {
          QByteArray data = QByteArray::fromRawData(buf, sizeof(buf));
          picture_line = data.mid( 1500, 20480 );

          if ((data.at(0) & 0xFF) == 0x02 && (data.at(1) & 0xFF) == 0x84
              && (data.at(2) & 0xFF) == 0x01 && (data.at(3) & 0xFF) == 0x6f
              && (data.at(4) & 0xFF) == 0x03 && (data.at(5) & 0xFF) == 0x5c
              && (data.at(6) & 0xFF) == 0x01 && (data.at(7) & 0xFF) == 0x9d
              && (data.at(8) & 0xFF) == 0x02 && (data.at(9) & 0xFF) == 0x0f
              && (data.at(10) & 0xFF) == 0x00 && (data.at(11) & 0xFF) == 0x95)
          {

              for (int i=0, j = 0; i < 20471; i+=10, j++)
              {
                  for(int k = 0, l = 0; k < 5; k++)
                  {
                    val1_ch[k] = 0xFF & picture_line.at(i+l);
                    l++;
                    val2_ch[k] = 0xFF & picture_line.at(i+l);
                    l++;
                    tot_ch[k] = (val1_ch[k] <<= 8) | val2_ch[k];
                    *(this->ptrbaChannel[k].data() + heightinsegment * 2048 + j) = tot_ch[k];

                  }

                  for(int k = 0 ; k < 5; k++)
                  {
                      if (tot_ch[k] < stat_min_ch[k] )
                          stat_min_ch[k] = tot_ch[k];
                      if (tot_ch[k] > stat_max_ch[k] )
                          stat_max_ch[k] = tot_ch[k];
                  }
              }
              heightinsegment++;
          }
      }
    }

    //NbrOfLines = heightinsegment;
    BZ2_bzclose ( b );
    fclose(f);

    return this;

}
예제 #17
0
/*!
 * \brief Config::onNetwManagerFinished Qt slot to retrieve the content
 * \param reply a QNetworkReply containing the update data to parse
 */
void Updater::onNetwManagerFinished(QNetworkReply *reply)
{
    if (!m_URLs.remove(reply->url()))
        return;

    bool isReplyStable = reply->url().toString().contains("addons.teamspeak.com");
    if (reply->error() != QNetworkReply::NoError)
    {
        TSLogging::Log(reply->errorString(),LogLevel_WARNING);
    }
    else
    {
        QByteArray arr = reply->readAll();

        QVariant possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

        /* We'll deduct if the redirection is valid in the redirectUrl function */
        _urlRedirectedTo = this->redirectUrl(possibleRedirectUrl.toUrl(), _urlRedirectedTo);

        if(!_urlRedirectedTo.isEmpty()) /* If the URL is not empty, we're being redirected. */
        {
            TSLogging::Log(QString("%1: Update check forwarding to %2").arg(this->objectName()).arg(_urlRedirectedTo.toString()),LogLevel_INFO);
            CheckUpdate(_urlRedirectedTo);
            return;
        }

        int start = arr.indexOf((isReplyStable)?QString(ts3plugin_name()).append("_"):"Version",0);
        if (start == -1)
        {
            TSLogging::Log((this->objectName() + ": Did not find Version."),LogLevel_WARNING);
            return;
        }

        QString endStr = (isReplyStable)?".ts3_plugin":"Platforms";
        int end = arr.indexOf(endStr,start);
        if (end == -1)
        {
            TSLogging::Log((this->objectName() + ": Did not find %1.").arg(endStr),LogLevel_WARNING);
            return;
        }

        QString parse(arr.mid(start,end-start));
        QRegExp rx;
        if (isReplyStable)
            rx.setPattern("\\d+(?:\\_\\d+)+");
        else
            rx.setPattern("\\d+(?:\\.\\d+)+");

        int pos = rx.indexIn(parse);
        if (pos > -1)
            parse = rx.cap(0);

        if (isReplyStable)
        {
            parse.replace("_",".");
            m_VersionStable = parse;
        }
        else
            m_VersionBeta = parse;
    }

    reply->deleteLater();
    _urlRedirectedTo.clear();
    if (m_URLs.isEmpty())
    {
        m_netwManager->deleteLater();
        m_netwManager=NULL;
        CheckTriggerUpdateDialog();
    }
}
예제 #18
0
QT_USE_NAMESPACE

int main(int argc, char **argv)
{
    CoInitialize(0);

    enum State {
        Default = 0,
            OutOption
    } state;
    state = Default;
    
    QByteArray outname;
    QByteArray object;
    
    for (int a = 1; a < argc; ++a) {
        QByteArray arg(argv[a]);
        const char first = arg[0];
        switch(state) {
        case Default:
            if (first == '-' || first == '/') {
                arg = arg.mid(1);
                arg.toLower();
                if (arg == "o")
                    state = OutOption;
                else if (arg == "v") {
                    qWarning("dumpdoc: Version 1.0");
                    return 0;
                } else if (arg == "h") {
                    qWarning("dumpdoc Usage:\n\tdumpdoc object [-o <file>]"
                        "              \n\tobject   : object[/subobject]*"
                        "              \n\tsubobject: property\n"
                        "      \nexample:\n\tdumpdoc Outlook.Application/Session/CurrentUser -o outlook.html");
                    return 0;
                }
            } else {
                object = arg;
            }
            break;
        case OutOption:
            outname = arg;
            state = Default;
            break;
            
        default:
            break;
        }
    }
    
    if (object.isEmpty()) {
        qWarning("dumpdoc: No object name provided.\n"
            "         Use -h for help.");
        return -1;
    }
    QFile outfile;
    if (!outname.isEmpty()) {
        outfile.setFileName(QString::fromLatin1(outname.constData()));
        if (!outfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qWarning("dumpdoc: Could not open output file '%s'", outname.data());
        }
    } else {
        outfile.open(stdout, QIODevice::WriteOnly);
    }
    QTextStream out(&outfile);
    
    QByteArray subobject = object;
    int index = subobject.indexOf('/');
    if (index != -1)
        subobject = subobject.left(index);
    
    QAxObject topobject(QString::fromLatin1(subobject.constData()));
    
    if (topobject.isNull()) {
        qWarning("dumpdoc: Could not instantiate COM object '%s'", subobject.data());
        return -2;
    }
    
    QAxObject *axobject = &topobject;
    while (index != -1 && axobject) {
        index++;
        subobject = object.mid(index);
        if (object.indexOf('/', index) != -1) {
            int oldindex = index;
            index = object.indexOf('/', index);
            subobject = object.mid(oldindex, index-oldindex);	    
        } else {
            index = -1;
        }
        
        axobject = axobject->querySubObject(subobject);
    }
    if (!axobject || axobject->isNull()) {
        qWarning("dumpdoc: Subobject '%s' does not exist in '%s'", subobject.data(), object.data());
        return -3;
    }
    
    QString docu = axobject->generateDocumentation();
    out << docu;
    return 0;
}
예제 #19
0
void VideoDialog::readydata(QByteArray datagram)
{
    int find;
    int cnt = datagram.count('@');
    printf("cnt : %d\n", cnt);

    id1 = id2 = id3 = id4 = id5 = id6 = NULL;

    if(cnt>=1) id1 = datagram.mid(1, 3);
    if(cnt>=2) id2 = datagram.mid(4, 3);
    if(cnt>=3) id3 = datagram.mid(7, 3);
    if(cnt>=4) id4 = datagram.mid(10, 3);
    if(cnt>=5) id5 = datagram.mid(13, 3);
    if(cnt>=6) id6 = datagram.mid(16, 3);

    if(cnt>=1) time1 = datagram.mid(19, 4).insert(2, ':');
    if(cnt>=2) time2 = datagram.mid(23, 4).insert(2, ':');
    if(cnt>=3) time3 = datagram.mid(27, 4).insert(2, ':');
    if(cnt>=4) time4 = datagram.mid(31, 4).insert(2, ':');
    if(cnt>=5) time5 = datagram.mid(35, 4).insert(2, ':');
    if(cnt>=6) time6 = datagram.mid(39, 4).insert(2, ':');

    datagram = datagram.mid(43);
    if(cnt>=1)
    {
        find = datagram.indexOf('@', 0);
        name1 = datagram.left(find);
        datagram = datagram.mid(find+1);
    }
    if(cnt>=2)
    {
        find = datagram.indexOf('@', 0);
        name2 =  datagram.left(find);
        datagram = datagram.mid(find+1);
    }
    if(cnt>=3)
    {
        find = datagram.indexOf('@', 0);
        name3 =  datagram.left(find);
        datagram = datagram.mid(find+1);
    }
    if(cnt>=4)
    {
        find = datagram.indexOf('@', 0);
        name4 =  datagram.left(find);
        datagram = datagram.mid(find+1);
    }
    if(cnt>=5)
    {
        find = datagram.indexOf('@', 0);
        name5 =  datagram.left(find);
        datagram = datagram.mid(find+1);
    }
    if(cnt>=6)
    {
        find = datagram.indexOf('@', 0);
        name6 =  datagram.left(find);
        datagram = datagram.mid(find+1);
    }

    showlist();
}
예제 #20
0
void PDBFormat::PDBParser::parseAtom(BioStruct3D& biostruct, U2OpStatus&)
{
    /*
    Record Format

    COLUMNS     DEFINITION
    1 - 6       Record name "ATOM "
    7 - 11      Atom serial number.
    13 - 16     Atom name.
    17          Alternate location indicator.
    18 - 20     Residue name.
    22          Chain identifier.
    23 - 26     Residue sequence number.
    27          Code for insertion of residues.
    31 - 38     Orthogonal coordinates for X in Angstroms.
    39 - 46     Orthogonal coordinates for Y in Angstroms.
    47 - 54     Orthogonal coordinates for Z in Angstroms.
    55 - 60     Occupancy.
    61 - 66     Temperature factor.
    77 - 78     Element symbol, right-justified.
    79 - 80     Charge on the atom.
    */

    if (!flagAtomRecordPresent)
        flagAtomRecordPresent = true;

    bool isHetero = false;
    if (currentPDBLine.startsWith("HETATM")) {
        isHetero = true;
    }

    int id = currentPDBLine.mid(6,5).toInt();
    QByteArray atomName = currentPDBLine.mid(12,4).toLatin1().trimmed();
    QByteArray residueName = currentPDBLine.mid(17,3).toLatin1().trimmed();
    int resId = currentPDBLine.mid(22,4).toLatin1().toInt();
    char insCode = currentPDBLine.at(26).toLatin1();
    char residueAcronym = PDBFormat::getAcronymByName(residueName);
    char chainIdentifier = currentPDBLine.at(21).toLatin1();

    ResidueIndex residueIndex(resId,insCode);
    bool atomIsInChain = !isHetero || seqResContains(chainIdentifier, residueIndex.toInt(), residueAcronym);

    QByteArray elementName = currentPDBLine.mid(76,2).toLatin1().trimmed();

    QByteArray element = elementName.isEmpty() ? atomName.mid(0,1) : elementName;
    int atomicNumber = PDBFormat::getElementNumberByName(element);

    int chainIndex = chainIndexMap.contains(chainIdentifier) ? chainIndexMap.value(chainIdentifier) : currentChainIndex;

    if (currentModelIndex == 0 && atomIsInChain) {

        // Process residue

        if (!biostruct.moleculeMap.contains(chainIndex)) {
            createMolecule(chainIdentifier, biostruct, chainIndex);
        }

        SharedMolecule& mol = biostruct.moleculeMap[chainIndex];

        if (currentResidueIndex != residueIndex)  {
            SharedResidue residue(new ResidueData);
            residue->name = residueName;
            residue->acronym = residueAcronym;
            if (residue->acronym == 'X') {
                ioLog.details(tr("PDB warning: unknown residue name: %1").arg(residue->name.constData()));
            }
            residue->chainIndex = chainIndex;
            currentResidueIndex = residueIndex;
            residueOrder++;
            residueIndex.setOrder(residueOrder);
            mol->residueMap.insert(residueIndex, residue);
        }

    }

    // Process atom
    double x,y,z;
    x = currentPDBLine.mid(30,8).toDouble();
    y = currentPDBLine.mid(38,8).toDouble();
    z = currentPDBLine.mid(46,8).toDouble();
    double occupancy = currentPDBLine.mid(54,6).toDouble();
    double temperature = currentPDBLine.mid(60,6).toDouble();

    SharedAtom a(new AtomData);
    a->chainIndex = chainIndex;
    a->residueIndex = residueIndex;
    a->atomicNumber = atomicNumber;
    a->name = atomName;
    a->coord3d = Vector3D(x,y,z);
    a->occupancy = occupancy;
    a->temperature = temperature;

    biostruct.modelMap[currentModelIndex + 1].insert(id, a);

    if (atomIsInChain) {
        SharedMolecule& mol = biostruct.moleculeMap[chainIndex];
        Molecule3DModel& model3D = mol->models[currentModelIndex];
        model3D.atoms.insert(id, a);
    }

}
/*!
  Parses the MIME header \a header and returns the map of those headers.
  This function is for internal use only.
*/
QMap<QByteArray, QByteArray> TMimeHeader::parseHeaderParameter(const QByteArray &header)
{
    QMap<QByteArray, QByteArray> result;
    int pos = 0;
    
    for (;;) {
        pos = skipWhitespace(header, pos);
        if (pos >= header.length())
            return result;

        int semicol = header.indexOf(';', pos);
        if (semicol < 0) 
            semicol = header.length();

        QByteArray key;
        int equal = header.indexOf('=', pos);
        if (equal < 0 || equal > semicol) {
            key = header.mid(pos, semicol - pos).trimmed();
            if (!key.isEmpty()) {
                result.insert(key, QByteArray());
            }
            pos = semicol + 1;
            continue;
        }

        key = header.mid(pos,  equal - pos).trimmed();
        pos = equal + 1;        
        
        pos = skipWhitespace(header, pos);
        if (pos >= header.length())
            return result;

        QByteArray value;
        if (header[pos] == '"') {
            ++pos;
            while (pos < header.length()) {
                char c = header.at(pos);
                if (c == '"') {
                    // end of quoted text
                    break;
                } else if (c == '\\') {
                    ++pos;
                    if (pos >= header.length()) {
                        // broken header
                        return result;
                    }
                    c = header[pos];
                }
                
                value += c;
                ++pos;
            }
        } else {
            while (pos < header.length()) {
                char c = header.at(pos);
                if (c == ' ' || c == '\t' || c == '\r'
                    || c == '\n' || c == ';') {
                    break;
                }
                value += c;
                ++pos;
            }
        }

        result.insert(key, value);
    }
    return result;
}
예제 #22
0
//-------------------------------------------------------------------------------------------------
void ExchangeRate::slotReplyFin(QNetworkReply *netrep)
{
    if (netrep->error())
    {
        QMessageBox::warning(this, 0, tr("Connection error:") + ' ' + netrep->errorString());
        return;
    }

    const QByteArray baRead = netrep->readAll();
    int iSep = baRead.indexOf("<a href=\"/control/en/curmetal/detail/currency?period=daily\">", 40000);
    if (iSep > 0)
    {
        iSep = baRead.lastIndexOf("</td>", iSep);
        if (iSep > 0)
        {
            const QString strDate = baRead.mid(iSep-10, 10);        //[10 = "dd.MM.yyyy"]
            if (QDateTime::fromString(strDate, "dd.MM.yyyy").isValid())
            {
                iSep = baRead.indexOf("<td class=\"attribute\">100&nbsp;US Dollar</td>", iSep+70);
                if (iSep > 0)
                {
                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+45);
                    if (iSep > 0)
                    {
                        iSep += 34;
                        int iEnd = baRead.indexOf('\n', iSep);
                        if (iEnd > 0)
                        {
                            const double dPerUsd = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                            if (dPerUsd > 300.0 && dPerUsd < 8000.0)
                            {
                                iSep = baRead.indexOf("<td class=\"attribute\">100&nbsp;EURO</td>", iSep+100);
                                if (iSep > 0)
                                {
                                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+40);
                                    if (iSep > 0)
                                    {
                                        iSep += 34;
                                        iEnd = baRead.indexOf('\n', iSep);
                                        if (iEnd > 0)
                                        {
                                            const double dPerEur = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                                            if (dPerEur > 300.0 && dPerEur < 8000.0)
                                            {
                                                iSep = baRead.indexOf("<td class=\"attribute\">10&nbsp;Russian ruble</td>", iSep+100);
                                                if (iSep > 0)
                                                {
                                                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+48);
                                                    if (iSep > 0)
                                                    {
                                                        iSep += 34;
                                                        iEnd = baRead.indexOf('\n', iSep);
                                                        if (iEnd > 0)
                                                        {
                                                            const double dPerRub = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                                                            if (dPerRub > 1.0 && dPerRub < 10.0)
                                                            {
                                                                iSep = 0;
                                                                dUahPerUsd = dPerUsd/100.0;
                                                                dUahPerEur = dPerEur/100.0;
                                                                dUahPerRub = dPerRub/10.0;

                                                                const QString strUahPerUsd = QString::number(dUahPerUsd, 'f', 6),
                                                                        strUahPerEur = QString::number(dUahPerEur, 'f', 6),
                                                                        strUahPerRub = QString::number(dUahPerRub, 'f', 5);

                                                                lblNote->setText(strDate + "\n1 USD = " + strUahPerUsd + " UAH\n1 EUR = " + strUahPerEur + " UAH\n1 UAH = " + QString::number(1.0/dUahPerRub, 'f', 6) + " RUB");

                                                                QSettings stg(strAppStg, QSettings::IniFormat);
                                                                stg.beginGroup("Settings");
                                                                stg.setValue("DateTime", strDate);
                                                                stg.setValue("USD", strUahPerUsd);
                                                                stg.setValue("EUR", strUahPerEur);
                                                                stg.setValue("RUB", strUahPerRub);
                                                                stg.endGroup();

                                                                lblInfo->setText(tr("Successfully"));
                                                                gbMain->setEnabled(true);
                                                                QTimer::singleShot(1300, lblInfo, SLOT(clear()));
                                                            }
                                                            else
                                                                iSep = 114;
                                                        }
                                                        else
                                                            iSep = 113;
                                                    }
                                                    else
                                                        iSep = 112;
                                                }
                                                else
                                                    iSep = 111;
                                            }
                                            else
                                                iSep = 110;
                                        }
                                        else
                                            iSep = 109;
                                    }
                                    else
                                        iSep = 108;
                                }
                                else
                                    iSep = 107;
                            }
                            else
                                iSep = 106;
                        }
                        else
                            iSep = 105;
                    }
                    else
                        iSep = 104;
                }
                else
                    iSep = 103;
            }
            else
                iSep = 102;
        }
        else
            iSep = 101;
    }
    else
        iSep = 100;

    if (iSep)
        QMessageBox::warning(this, 0, tr("Error:") + " #" + QString::number(iSep));
}
예제 #23
0
static QHash<QByteArray, QByteArray> parseParams(const QByteArray &in, bool *ok = 0)
{
	QHash<QByteArray, QByteArray> out;

	int start = 0;
	while(start < in.size())
	{
		QByteArray var;
		QByteArray val;

		int at = findNext(in, "=;", start);
		if(at != -1)
		{
			var = in.mid(start, at - start).trimmed();
			if(in[at] == '=')
			{
				if(at + 1 >= in.size())
				{
					if(ok)
						*ok = false;
					return QHash<QByteArray, QByteArray>();
				}

				++at;

				if(in[at] == '\"')
				{
					++at;

					bool complete = false;
					for(int n = at; n < in.size(); ++n)
					{
						if(in[n] == '\\')
						{
							if(n + 1 >= in.size())
							{
								if(ok)
									*ok = false;
								return QHash<QByteArray, QByteArray>();
							}

							++n;
							val += in[n];
						}
						else if(in[n] == '\"')
						{
							complete = true;
							at = n + 1;
							break;
						}
						else
							val += in[n];
					}

					if(!complete)
					{
						if(ok)
							*ok = false;
						return QHash<QByteArray, QByteArray>();
					}

					at = in.indexOf(';', at);
					if(at != -1)
						start = at + 1;
					else
						start = in.size();
				}
				else
				{
					int vstart = at;
					at = in.indexOf(';', vstart);
					if(at != -1)
					{
						val = in.mid(vstart, at - vstart).trimmed();
						start = at + 1;
					}
					else
					{
						val = in.mid(vstart).trimmed();
						start = in.size();
					}
				}
			}
			else
				start = at + 1;
		}
		else
		{
			var = in.mid(start).trimmed();
			start = in.size();
		}

		out[var] = val;
	}

	if(ok)
		*ok = true;

	return out;
}
예제 #24
0
void QxtSmtpPrivate::socketRead()
{
    buffer += socket->readAll();
    while (true)
    {
        int pos = buffer.indexOf("\r\n");
        if (pos < 0) return;
        QByteArray line = buffer.left(pos);
        buffer = buffer.mid(pos + 2);
        QByteArray code = line.left(3);
        switch (state)
        {
        case StartState:
            if (code[0] != '2')
            {
                socket->disconnectFromHost();
            }
            else
            {
                ehlo();
            }
            break;
        case HeloSent:
        case EhloSent:
        case EhloGreetReceived:
            parseEhlo(code, (line[3] != ' '), line.mid(4));
            break;
#ifndef QT_NO_OPENSSL
        case StartTLSSent:
            if (code == "220")
            {
                socket->startClientEncryption();
                ehlo();
            }
            else
            {
                authenticate();
            }
            break;
#endif
        case AuthRequestSent:
        case AuthUsernameSent:
            if (authType == AuthPlain) authPlain();
            else if (authType == AuthLogin) authLogin();
            else authCramMD5(line.mid(4));
            break;
        case AuthSent:
            if (code[0] == '2')
            {
                state = Authenticated;
                emit qxt_p().authenticated();
            }
            else
            {
                state = Disconnected;
                emit qxt_p().authenticationFailed();
                emit qxt_p().authenticationFailed( line );
                emit socket->disconnectFromHost();
            }
            break;
        case MailToSent:
        case RcptAckPending:
            if (code[0] != '2') {
                emit qxt_p().mailFailed( pending.first().first, code.toInt() );
                emit qxt_p().mailFailed(pending.first().first, code.toInt(), line);
				// pending.removeFirst();
				// DO NOT remove it, the body sent state needs this message to assigned the next mail failed message that will 
				// the sendNext 
				// a reset will be sent to clear things out
                sendNext();
                state = BodySent;
            }
            else
                sendNextRcpt(code, line);
            break;
        case SendingBody:
            sendBody(code, line);
            break;
        case BodySent:
			if ( pending.count() )
			{
				// if you removeFirst in RcpActpending/MailToSent on an error, and the queue is now empty, 
				// you will get into this state and then crash because no check is done.  CHeck added but shouldnt
				// be necessary since I commented out the removeFirst
				if (code[0] != '2')
				{
					emit qxt_p().mailFailed(pending.first().first, code.toInt() );
					emit qxt_p().mailFailed(pending.first().first, code.toInt(), line);
				}
				else
					emit qxt_p().mailSent(pending.first().first);
	            pending.removeFirst();
			}
            sendNext();
            break;
        case Resetting:
            if (code[0] != '2') {
                emit qxt_p().connectionFailed();
                emit qxt_p().connectionFailed( line );
            }
            else {
                state = Waiting;
                sendNext();
            }
            break;
        }
    }
}
예제 #25
0
static Symbols tokenize(const QByteArray &input, int lineNum = 1, TokenizeMode mode = TokenizeCpp)
{
    Symbols symbols;
    const char *begin = input;
    const char *data = begin;
    while (*data) {
        if (mode == TokenizeCpp) {
            int column = 0;

            const char *lexem = data;
            int state = 0;
            Token token = NOTOKEN;
            for (;;) {
                if (static_cast<signed char>(*data) < 0) {
                    ++data;
                    continue;
                }
                int nextindex = keywords[state].next;
                int next = 0;
                if (*data == keywords[state].defchar)
                    next = keywords[state].defnext;
                else if (!state || nextindex)
                    next = keyword_trans[nextindex][(int)*data];
                if (!next)
                    break;
                state = next;
                token = keywords[state].token;
                ++data;
            }

            // suboptimal, is_ident_char  should use a table
            if (keywords[state].ident && is_ident_char(*data))
                token = keywords[state].ident;

            if (token == NOTOKEN) {
                // an error really
                ++data;
                continue;
            }

            ++column;

            if (token > SPECIAL_TREATMENT_MARK) {
                switch (token) {
                case QUOTE:
                    data = skipQuote(data);
                    token = STRING_LITERAL;
                    // concatenate multi-line strings for easier
                    // STRING_LITERAAL handling in moc
                    if (!Preprocessor::preprocessOnly
                        && !symbols.isEmpty()
                        && symbols.last().token == STRING_LITERAL) {

                        QByteArray newString = symbols.last().unquotedLexem();
                        newString += input.mid(lexem - begin + 1, data - lexem - 2);
                        newString.prepend('\"');
                        newString.append('\"');
                        symbols.last() = Symbol(symbols.last().lineNum,
                                                STRING_LITERAL,
                                                newString);
                        continue;
                    }
                    break;
                case SINGLEQUOTE:
                    while (*data && (*data != '\''
                                     || (*(data-1)=='\\'
                                         && *(data-2)!='\\')))
                        ++data;
                    if (*data)
                        ++data;
                    token = CHARACTER_LITERAL;
                    break;
                case LANGLE_SCOPE:
                    // split <:: into two tokens, < and ::
                    token = LANGLE;
                    data -= 2;
                    break;
                case DIGIT:
                    while (is_digit_char(*data))
                        ++data;
                    if (!*data || *data != '.') {
                        token = INTEGER_LITERAL;
                        if (data - lexem == 1 &&
                            (*data == 'x' || *data == 'X')
                            && *lexem == '0') {
                            ++data;
                            while (is_hex_char(*data))
                                ++data;
                        }
                        break;
                    }
                    token = FLOATING_LITERAL;
                    ++data;
                    // fall through
                case FLOATING_LITERAL:
                    while (is_digit_char(*data))
                        ++data;
                    if (*data == '+' || *data == '-')
                        ++data;
                    if (*data == 'e' || *data == 'E') {
                        ++data;
                        while (is_digit_char(*data))
                            ++data;
                    }
                    if (*data == 'f' || *data == 'F'
                        || *data == 'l' || *data == 'L')
                        ++data;
                    break;
                case HASH:
                    if (column == 1) {
                        mode = PreparePreprocessorStatement;
                        while (*data && (*data == ' ' || *data == '\t'))
                            ++data;
                        if (is_ident_char(*data))
                            mode = TokenizePreprocessorStatement;
                        continue;
                    }
                    break;
                case NEWLINE:
                    ++lineNum;
                    continue;
                case BACKSLASH:
                {
                    const char *rewind = data;
                    while (*data && (*data == ' ' || *data == '\t'))
                        ++data;
                    if (*data && *data == '\n') {
                        ++data;
                        continue;
                    }
                    data = rewind;
                } break;
                case CHARACTER:
                    while (is_ident_char(*data))
                        ++data;
                    token = IDENTIFIER;
                    break;
                case C_COMMENT:
                    if (*data) {
                        if (*data == '\n')
                            ++lineNum;
                        ++data;
                        if (*data) {
                            if (*data == '\n')
                                ++lineNum;
                            ++data;
                        }
                    }
                    while (*data && (*(data-1) != '/' || *(data-2) != '*')) {
                        if (*data == '\n')
                            ++lineNum;
                        ++data;
                    }
                    token = WHITESPACE; // one comment, one whitespace
                    // fall through;
                case WHITESPACE:
                    if (column == 1)
                        column = 0;
                    while (*data && (*data == ' ' || *data == '\t'))
                        ++data;
                    if (Preprocessor::preprocessOnly) // tokenize whitespace
                        break;
                    continue;
                case CPP_COMMENT:
                    while (*data && *data != '\n')
                        ++data;
                    continue; // ignore safely, the newline is a separator
                default:
                    continue; //ignore
                }
            }
#ifdef USE_LEXEM_STORE
            if (!Preprocessor::preprocessOnly
                && token != IDENTIFIER
                && token != STRING_LITERAL
                && token != FLOATING_LITERAL
                && token != INTEGER_LITERAL)
                symbols += Symbol(lineNum, token);
            else
#endif
                symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);

        } else { //   Preprocessor

            const char *lexem = data;
            int state = 0;
            Token token = NOTOKEN;
            if (mode == TokenizePreprocessorStatement) {
                state = pp_keyword_trans[0][(int)'#'];
                mode = TokenizePreprocessor;
            }
            for (;;) {
                if (static_cast<signed char>(*data) < 0) {
                    ++data;
                    continue;
                }

                int nextindex = pp_keywords[state].next;
                int next = 0;
                if (*data == pp_keywords[state].defchar)
                    next = pp_keywords[state].defnext;
                else if (!state || nextindex)
                    next = pp_keyword_trans[nextindex][(int)*data];
                if (!next)
                    break;
                state = next;
                token = pp_keywords[state].token;
                ++data;
            }
            // suboptimal, is_ident_char  should use a table
            if (pp_keywords[state].ident && is_ident_char(*data))
                token = pp_keywords[state].ident;

            switch (token) {
            case NOTOKEN:
                ++data;
                break;
            case PP_IFDEF:
                symbols += Symbol(lineNum, PP_IF);
                symbols += Symbol(lineNum, PP_DEFINED);
                continue;
            case PP_IFNDEF:
                symbols += Symbol(lineNum, PP_IF);
                symbols += Symbol(lineNum, PP_NOT);
                symbols += Symbol(lineNum, PP_DEFINED);
                continue;
            case PP_INCLUDE:
                mode = TokenizeInclude;
                break;
            case PP_QUOTE:
                data = skipQuote(data);
                token = PP_STRING_LITERAL;
                break;
            case PP_SINGLEQUOTE:
                while (*data && (*data != '\''
                                 || (*(data-1)=='\\'
                                     && *(data-2)!='\\')))
                    ++data;
                if (*data)
                    ++data;
                token = PP_CHARACTER_LITERAL;
                break;
            case PP_DIGIT:
                while (is_digit_char(*data))
                    ++data;
                if (!*data || *data != '.') {
                    token = PP_INTEGER_LITERAL;
                    if (data - lexem == 1 &&
                        (*data == 'x' || *data == 'X')
                        && *lexem == '0') {
                        ++data;
                        while (is_hex_char(*data))
                            ++data;
                    }
                    break;
                }
                token = PP_FLOATING_LITERAL;
                ++data;
                // fall through
            case PP_FLOATING_LITERAL:
                while (is_digit_char(*data))
                    ++data;
                if (*data == '+' || *data == '-')
                    ++data;
                if (*data == 'e' || *data == 'E') {
                    ++data;
                    while (is_digit_char(*data))
                        ++data;
                }
                if (*data == 'f' || *data == 'F'
                    || *data == 'l' || *data == 'L')
                    ++data;
                break;
            case PP_CHARACTER:
                if (mode == PreparePreprocessorStatement) {
                    // rewind entire token to begin
                    data = lexem;
                    mode = TokenizePreprocessorStatement;
                    continue;
                }
                while (is_ident_char(*data))
                    ++data;
                token = PP_IDENTIFIER;
                break;
            case PP_C_COMMENT:
                if (*data) {
                    if (*data == '\n')
                        ++lineNum;
                    ++data;
                    if (*data) {
                        if (*data == '\n')
                            ++lineNum;
                        ++data;
                    }
                }
                while (*data && (*(data-1) != '/' || *(data-2) != '*')) {
                    if (*data == '\n')
                        ++lineNum;
                    ++data;
                }
                token = PP_WHITESPACE; // one comment, one whitespace
                // fall through;
            case PP_WHITESPACE:
                while (*data && (*data == ' ' || *data == '\t'))
                    ++data;
                continue; // the preprocessor needs no whitespace
            case PP_CPP_COMMENT:
                while (*data && *data != '\n')
                    ++data;
                continue; // ignore safely, the newline is a separator
            case PP_NEWLINE:
                ++lineNum;
                mode = TokenizeCpp;
                break;
            case PP_BACKSLASH:
            {
                const char *rewind = data;
                while (*data && (*data == ' ' || *data == '\t'))
                    ++data;
                if (*data && *data == '\n') {
                    ++data;
                    continue;
                }
                data = rewind;
            } break;
            case PP_LANGLE:
                if (mode != TokenizeInclude)
                    break;
                token = PP_STRING_LITERAL;
                while (*data && *data != '\n' && *(data-1) != '>')
                    ++data;
                break;
            default:
                break;
            }
            if (mode == PreparePreprocessorStatement)
                continue;
#ifdef USE_LEXEM_STORE
            if (token != PP_IDENTIFIER
                && token != PP_STRING_LITERAL
                && token != PP_FLOATING_LITERAL
                && token != PP_INTEGER_LITERAL)
                symbols += Symbol(lineNum, token);
            else
#endif
                symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);
        }
    }
    symbols += Symbol(); // eof symbol
    return symbols;
}
예제 #26
0
///Extract the hostname, port and attributes
void URIPrivate::parseHostname()
{
   if (!m_Parsed)
      parse();

   const QByteArray extHn = q_ptr->hostname().toLatin1();
   int length(extHn.size()), start(0);
   bool inAttributes = false;

   URI::Section section = URI::Section::HOSTNAME;

   // in case no port, attributes, etc are provided
   m_Hostname2 = q_ptr->hostname();

   for (int i = 0; i < length; i++) {
      const char c = extHn[i];
      switch (c) {
         case ':': //Begin port
            switch(section) {
               case URI::Section::HOSTNAME:
                  m_Hostname2 = extHn.mid(start,i);
                  start = i;
                  section = URI::Section::PORT;
                  break;
               case URI::Section::USER_INFO:
               case URI::Section::CHEVRONS :
               case URI::Section::SCHEME   :
               case URI::Section::TRANSPORT:
               case URI::Section::TAG      :
               case URI::Section::PORT     :
                  break;
            }
            break;
         case ';': //Begin attributes

            if (inAttributes) {
               parseAttribute(extHn, start, i);
            }
            else {
               switch(section) {
                  case URI::Section::HOSTNAME:
                     m_Hostname2 = extHn.mid(start+1,i-start);
                     break;
                  case URI::Section::PORT:
                     m_Port = extHn.mid(start+1,i-start-1).toInt();
                     break;
                  case URI::Section::USER_INFO:
                  case URI::Section::CHEVRONS :
                  case URI::Section::SCHEME   :
                  case URI::Section::TRANSPORT:
                  case URI::Section::TAG      :
                     break;
               }
               inAttributes = true;
            }

            start = i;
            break;
         case '#': //Begin fragments
            //TODO handle fragments to comply to the RFC
            break;
         default:
            break;
      }
   }

   ///Get the remaining attribute
   parseAttribute(extHn, start, length-1);

   m_IsHNParsed = true;
}
예제 #27
0
void PeerWireClient::processIncomingData()
{
    invalidateTimeout = true;
    if (!receivedHandShake) {
        // Check that we received enough data
        if (bytesAvailable() < MinimalHeaderSize)
            return;

        // Sanity check the protocol ID
        QByteArray id = read(ProtocolIdSize + 1);
        if (id.at(0) != ProtocolIdSize || !id.mid(1).startsWith(ProtocolId)) {
            abort();
            return;
        }

        // Discard 8 reserved bytes, then read the info hash and peer ID
        (void) read(8);

        // Read infoHash
        QByteArray peerInfoHash = read(20);
        if (!infoHash.isEmpty() && peerInfoHash != infoHash) {
            abort();
            return;
        }

        emit infoHashReceived(peerInfoHash);
        if (infoHash.isEmpty()) {
            abort();
            return;
        }

        // Send handshake
        if (!sentHandShake)
            sendHandShake();
        receivedHandShake = true;
    }

    // Handle delayed peer id arrival
    if (!gotPeerId) {
        if (bytesAvailable() < 20)
            return;
        gotPeerId = true;
        if (read(20) == peerIdString) {
            // We connected to ourself
            abort();
            return;
        }
    }

    // Initialize keep-alive timer
    if (!keepAliveTimer)
        keepAliveTimer = startTimer(KeepAliveInterval);

    do {
        // Find the packet length
        if (nextPacketLength == -1) {
            if (bytesAvailable() < 4)
                return;

            char tmp[4];
            read(tmp, sizeof(tmp));
            nextPacketLength = fromNetworkData(tmp);

            if (nextPacketLength < 0 || nextPacketLength > 200000) {
                // Prevent DoS
                abort();
                return;
            }
        }

        // KeepAlive
        if (nextPacketLength == 0) {
            nextPacketLength = -1;
            continue;
        }

        // Wait with parsing until the whole packet has been received
        if (bytesAvailable() < nextPacketLength)
            return;

        // Read the packet
        QByteArray packet = read(nextPacketLength);
        if (packet.size() != nextPacketLength) {
            abort();
            return;
        }

        switch (packet.at(0)) {
        case ChokePacket:
            // We have been choked.
            pwState |= ChokedByPeer;
            incoming.clear();
            if (pendingRequestTimer)
                killTimer(pendingRequestTimer);
            emit choked();
            break;
        case UnchokePacket:
            // We have been unchoked.
            pwState &= ~ChokedByPeer;
            emit unchoked();
            break;
        case InterestedPacket:
            // The peer is interested in downloading.
            pwState |= PeerIsInterested;
            emit interested();
            break;
        case NotInterestedPacket:
            // The peer is not interested in downloading.
            pwState &= ~PeerIsInterested;
            emit notInterested();
            break;
        case HavePacket: {
            // The peer has a new piece available.
            quint32 index = fromNetworkData(&packet.data()[1]);
            if (index < quint32(peerPieces.size())) {
                // Only accept indexes within the valid range.
                peerPieces.setBit(int(index));
            }
            emit piecesAvailable(availablePieces());
            break;
        }
        case BitFieldPacket:
            // The peer has the following pieces available.
            for (int i = 1; i < packet.size(); ++i) {
                for (int bit = 0; bit < 8; ++bit) {
                    if (packet.at(i) & (1 << (7 - bit))) {
                        int bitIndex = int(((i - 1) * 8) + bit);
                        if (bitIndex >= 0 && bitIndex < peerPieces.size()) {
                            // Occasionally, broken clients claim to have
                            // pieces whose index is outside the valid range.
                            // The most common mistake is the index == size
                            // case.
                            peerPieces.setBit(bitIndex);
                        }
                    }
                }
            }
            emit piecesAvailable(availablePieces());
            break;
        case RequestPacket: {
            // The peer requests a block.
            quint32 index = fromNetworkData(&packet.data()[1]);
            quint32 begin = fromNetworkData(&packet.data()[5]);
            quint32 length = fromNetworkData(&packet.data()[9]);
            emit blockRequested(int(index), int(begin), int(length));
            break;
        }
        case PiecePacket: {
            int index = int(fromNetworkData(&packet.data()[1]));
            int begin = int(fromNetworkData(&packet.data()[5]));

            incoming.removeAll(TorrentBlock(index, begin, packet.size() - 9));

            // The peer sends a block.
            emit blockReceived(index, begin, packet.mid(9));

            // Kill the pending block timer.
            if (pendingRequestTimer) {
                killTimer(pendingRequestTimer);
                pendingRequestTimer = 0;
            }
            break;
        }
        case CancelPacket: {
            // The peer cancels a block request.
            quint32 index = fromNetworkData(&packet.data()[1]);
            quint32 begin = fromNetworkData(&packet.data()[5]);
            quint32 length = fromNetworkData(&packet.data()[9]);
            for (int i = 0; i < pendingBlocks.size(); ++i) {
                const BlockInfo &blockInfo = pendingBlocks.at(i);
                if (blockInfo.pieceIndex == int(index)
                    && blockInfo.offset == int(begin)
                    && blockInfo.length == int(length)) {
                    pendingBlocks.removeAt(i);
                    break;
                }
            }
            break;
        }
        default:
            // Unsupported packet type; just ignore it.
            break;
        }
        nextPacketLength = -1;
    } while (bytesAvailable() > 0);
}
예제 #28
0
// This function is meant to procces the UDP Packets, a different (but similar) funcion will be created for the TCP packets
// A Mutex is passed to StnInfo so that the data is not deleted before it is proccesed, it is a safety, but not needed.
void EWMessageMgr::proccess_UDPpacket(PACKET packet, QByteArray data)
{

    // If the Packet is Complete
    if (packet.lastOfMsg && packet.fragNum == 0 ) {

        // Declare a new K2infoPacket, put the Package payload bay in there
        MyK2Info = new K2infoPacket;
        memcpy(MyK2Info, &packet.text, data.size()-UDP_HDR);

        // If it's a K2 regular status packet
        if(MyK2Info->k2info.data_type==2) {

            // Initialize Structures
            STATUS_INFO        *MyK2Stat;
            MyK2Head = new K2INFO_HEADER;
            MyK2Stat = new STATUS_INFO;

            // Extract Info and put it back into a data structure
            memcpy(MyK2Head,data.mid(UDP_HDR,sizeof(K2INFO_HEADER)).data(),sizeof(K2INFO_HEADER));
            memcpy(MyK2Stat,data.mid(sizeof(K2INFO_HEADER)+UDP_HDR).data(),sizeof(STATUS_INFO));
            // Finish Extraction

            // Update UI
            if(mutex->tryLock(5000))
                emit exportK2Status(MyK2Head, MyK2Stat, mutex);


            // Destroy Structures
            delete[] MyK2Head;
            delete[] MyK2Stat;
        }

        // If its a K2 extended status packet v2
        if(MyK2Info->k2info.data_type==4) {

            // Initialize Structures
            EXT2_STATUS_INFO   *MyK2Stat2;
            MyK2Head  = new K2INFO_HEADER;
            MyK2Stat2 = new EXT2_STATUS_INFO;

            // Extract Info and put it back into a data structure
            memcpy(MyK2Head  ,data.mid(UDP_HDR,sizeof(K2INFO_HEADER)).data(),sizeof(K2INFO_HEADER));
            memcpy(MyK2Stat2 ,data.mid(sizeof(K2INFO_HEADER)+UDP_HDR).data(),sizeof(EXT2_STATUS_INFO));
            // Finish Extraction

            // Update UI
            if(mutex->tryLock(5000))
                emit exportK2Status2(MyK2Head,MyK2Stat2, mutex);


            // Destroy Structures
            delete[] MyK2Head;
            delete[] MyK2Stat2;
        }

        // Delete K2infoPacket
        delete[] MyK2Info;
    }

    // If not it must be the super long Params Packet ... sigh
    if (packet.fragNum == 0 && !packet.lastOfMsg) {

        // Declare a new K2infoPacket, put the Package payload bay in there
        MyK2Info = new K2infoPacket;
        memcpy(MyK2Info, &packet.text, data.size()-UDP_HDR);

        //Clear our Memory
        MyK2HDR.clear();

        // Declare a new K2HDR Array, put the Package payload in there
        MyK2HDR.resize(data.size()-UDP_HDR);
        memcpy(MyK2HDR.data(),data.mid(UDP_HDR),data.size()-UDP_HDR);

        //We Have begun
        Start = true;

        // Destroy K2infoPacket
        delete[] MyK2Info;

    }

    // The continuation of the last Params Packet
    if (packet.fragNum == 1 && packet.lastOfMsg) {

        if (Start == true) { //yes we did begin this is the continuation, (Remember to code in continuity ie check packet num)
            int nsize = data.size()-UDP_HDR;
            int csize = MyK2HDR.size();

            // Tack on the previous package Info
            MyK2HDR.resize(csize+nsize);
            MyK2HDR.append(data.mid(UDP_HDR).data());

            // Create a the K2INFO Header again and Initialize a new K2_HEADER Instance
            MyK2Head = new K2INFO_HEADER;
            K2_HEADER *MyK2HDS;
            MyK2HDS = new K2_HEADER;

            // Extract the information
            memcpy(MyK2Head,MyK2HDR.data(), sizeof(K2INFO_HEADER));
            memcpy(MyK2HDS,MyK2HDR.mid(sizeof(K2INFO_HEADER)).data(), sizeof(K2_HEADER));
            // Finish Extraction

            // Update UI
            if(mutex->tryLock(5000))
                emit exportK2HeaderS(MyK2Head, MyK2HDS, mutex);

            delete[] MyK2Head;
            delete[] MyK2HDS;
            Start = false;
        }

        else if (Start == false){ // We lost a packet.
            MyK2HDR.clear();
            Start = false;
        }

    }

}
예제 #29
0
static QList<Abi> abiOf(const QByteArray &data)
{
    QList<Abi> result;
    if (data.size() <= 8)
        return result;

    if (data.size() >= 20
            && getUint8(data, 0) == 0x7f && getUint8(data, 1) == 'E' && getUint8(data, 2) == 'L'
            && getUint8(data, 3) == 'F') {
        // ELF format:
        bool isLE = (getUint8(data, 5) == 1);
        quint16 machine = isLE ? getLEUint16(data, 18) : getBEUint16(data, 18);
        quint8 osAbi = getUint8(data, 7);

        Abi::OS os = Abi::UnixOS;
        Abi::OSFlavor flavor = Abi::GenericUnixFlavor;
        // http://www.sco.com/developers/gabi/latest/ch4.eheader.html#elfid
        switch (osAbi) {
        case 2: // NetBSD:
            os = Abi::BsdOS;
            flavor = Abi::NetBsdFlavor;
            break;
        case 3: // Linux:
        case 0: // no extra info available: Default to Linux:
            os = Abi::LinuxOS;
            flavor = Abi::GenericLinuxFlavor;
            break;
        case 6: // Solaris:
            os = Abi::UnixOS;
            flavor = Abi::SolarisUnixFlavor;
            break;
        case 9: // FreeBSD:
            os = Abi::BsdOS;
            flavor = Abi::FreeBsdFlavor;
            break;
        case 12: // OpenBSD:
            os = Abi::BsdOS;
            flavor = Abi::OpenBsdFlavor;
        }

        switch (machine) {
        case 3: // EM_386
            result.append(Abi(Abi::X86Architecture, os, flavor, Abi::ElfFormat, 32));
            break;
        case 8: // EM_MIPS
            result.append(Abi(Abi::MipsArchitecture, os, flavor, Abi::ElfFormat, 32));
            break;
        case 20: // EM_PPC
            result.append(Abi(Abi::PowerPCArchitecture, os, flavor, Abi::ElfFormat, 32));
            break;
        case 21: // EM_PPC64
            result.append(Abi(Abi::PowerPCArchitecture, os, flavor, Abi::ElfFormat, 64));
            break;
        case 40: // EM_ARM
            result.append(Abi(Abi::ArmArchitecture, os, flavor, Abi::ElfFormat, 32));
            break;
        case 62: // EM_X86_64
            result.append(Abi(Abi::X86Architecture, os, flavor, Abi::ElfFormat, 64));
            break;
        case 42: // EM_SH
            result.append(Abi(Abi::ShArchitecture, os, flavor, Abi::ElfFormat, 32));
            break;
        case 50: // EM_IA_64
            result.append(Abi(Abi::ItaniumArchitecture, os, flavor, Abi::ElfFormat, 64));
            break;
        default:
            ;;
        }
    } else if (((getUint8(data, 0) == 0xce || getUint8(data, 0) == 0xcf)
             && getUint8(data, 1) == 0xfa && getUint8(data, 2) == 0xed && getUint8(data, 3) == 0xfe
            )
            ||
            (getUint8(data, 0) == 0xfe && getUint8(data, 1) == 0xed && getUint8(data, 2) == 0xfa
             && (getUint8(data, 3) == 0xce || getUint8(data, 3) == 0xcf)
            )
           ) {
            // Mach-O format (Mac non-fat binary, 32 and 64bit magic):
            quint32 type = (getUint8(data, 1) ==  0xfa) ? getLEUint32(data, 4) : getBEUint32(data, 4);
            result.append(macAbiForCpu(type));
    } else if ((getUint8(data, 0) == 0xbe && getUint8(data, 1) == 0xba
                && getUint8(data, 2) == 0xfe && getUint8(data, 3) == 0xca)
               ||
               (getUint8(data, 0) == 0xca && getUint8(data, 1) == 0xfe
                && getUint8(data, 2) == 0xba && getUint8(data, 3) == 0xbe)
              ) {
        // Mach-0 format Fat binary header:
        bool isLE = (getUint8(data, 0) == 0xbe);
        quint32 count = isLE ? getLEUint32(data, 4) : getBEUint32(data, 4);
        int pos = 8;
        for (quint32 i = 0; i < count; ++i) {
            if (data.size() <= pos + 4)
                break;

            quint32 type = isLE ? getLEUint32(data, pos) : getBEUint32(data, pos);
            result.append(macAbiForCpu(type));
            pos += 20;
        }
    } else if (data.size() >= 20
               && getUint8(data, 16) == 'E' && getUint8(data, 17) == 'P'
               && getUint8(data, 18) == 'O' && getUint8(data, 19) == 'C') {
        result.append(Abi(Abi::ArmArchitecture, Abi::SymbianOS, Abi::SymbianDeviceFlavor, Abi::ElfFormat, 32));
    } else if (data.size() >= 64){
        // Windows PE: values are LE (except for a few exceptions which we will not use here).

        // MZ header first (ZM is also allowed, but rarely used)
        const quint8 firstChar = getUint8(data, 0);
        const quint8 secondChar = getUint8(data, 1);
        if ((firstChar != 'M' || secondChar != 'Z') && (firstChar != 'Z' || secondChar != 'M'))
            return result;

        // Get PE/COFF header position from MZ header:
        qint32 pePos = getLEUint32(data, 60);
        if (pePos <= 0 || data.size() < pePos + 4 + 20) // PE magic bytes plus COFF header
            return result;
        if (getUint8(data, pePos) == 'P' && getUint8(data, pePos + 1) == 'E'
            && getUint8(data, pePos + 2) == 0 && getUint8(data, pePos + 3) == 0)
            result = parseCoffHeader(data.mid(pePos + 4));
    }
    return result;
}
//This function reads in Intel 32-bit .hex file formatted firmware image files and stores the
//parsed data into buffers in the PC system RAM, so that it is in a format more suitable for directly
//programming into the target microcontroller.
HexImporter::ErrorCode HexImporter::ImportHexFile(QString fileName, DeviceData* pData, Device* device)
{
    QFile hexfile(fileName);

    hasEndOfFileRecord = false;
    fileExceedsFlash = false;

    //Open the user specified .hex file.
    if (!hexfile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return CouldNotOpenFile;
    }

    bool ok;
    bool includedInProgrammableRange;
    bool addressWasEndofRange;
    unsigned int segmentAddress = 0;
    unsigned int byteCount;
    unsigned int lineAddress;
    unsigned int deviceAddress;
    unsigned int i;
    unsigned int endDeviceAddressofRegion;
    unsigned int bytesPerAddressAndType;

    unsigned char* pPCRAMBuffer = 0;
    bool importedAtLeastOneByte = false;

    unsigned char type;

    HEX32_RECORD recordType;

    QString hexByte;
    unsigned int wordByte;
    hasConfigBits = false;


    //Parse the entire hex file, line by line.
    while (!hexfile.atEnd())
    {
        //Fetch a line of ASCII text from the .hex file.
        QByteArray line = hexfile.readLine();

        //Do some error checking on the .hex file contents, to make sure the file is
        //formatted like a legitimate Intel 32-bit formatted .hex file.
        if ((line[0] != ':') || (line.size() < 11))
        {
            //Something is wrong if hex line entry, is not minimum length or does not have leading colon (ex: ":BBAAAATTCC")
            //If an error is detected in the hex file formatting, the safest approach is to
            //abort the operation and force the user to supply a properly formatted hex file.
            if(hexfile.isOpen())
                hexfile.close();
            return ErrorInHexFile;
        }

        //Extract the info prefix fields from the hex file line data.
        //Example Intel 32-bit hex file line format is as follows (Note: spaces added to separate fields, actual line does not have spaces in it):
        //: 10 0100 00 214601360121470136007EFE09D21901 40
        //Leading ":" is always present on each line from the .hex file.
        //Next two chars (10) are the byte count of the data payload on this hex file line. (ex: 10 = 0x10 = 16 bytes)
        //Next four chars (0100) are the 16 bit address (needs to be combined with the extended linear address to generate a 32-bit address).
        //Next two chars (00) are the "record type".  "00" means it is a "data" record, which means it contains programmable payload data bytes.
        //Next 2n characters are the data payload bytes (where n is the number of bytes specified in the first two numbers (10 in this example))
        //Last two characters on the line are the two complement of the byte checksum computed on the other bytes in the line.
        //For more details on Intel 32-bit hex file formatting see: http://en.wikipedia.org/wiki/Intel_HEX
        byteCount = line.mid(1, 2).toInt(&ok, 16);                      //Convert the two ASCII chars corresponding to the byte count into a binary encoded byte
        lineAddress = segmentAddress + line.mid(3, 4).toInt(&ok, 16);   //Convert the four ASCII chars that correspond to the line address into a 16-bit binary encoded word
        recordType = (HEX32_RECORD)line.mid(7, 2).toInt(&ok, 16);       //Convert the two ASCII chars corresponding to the record type into a binary encoded byte

        //Error check: Verify checksum byte at the end of the .hex file line is valid.  Note,
        //this is not the same checksum as MPLAB(R) IDE uses/computes for the entire hex file.
        //This is only the mini-checksum at the end of each line in the .hex file.
        unsigned int hexLineChecksum = 0;
        for(i = 0; i < (byteCount+4); i++)  //+4 correction is for byte count, 16-bit address, and record type bytes
        {
            hexByte = line.mid(1 + (2 * i), 2); //Fetch two adjacent ASCII bytes from the .hex file
            wordByte = hexByte.toInt(&ok, 16);  //Re-format the above two ASCII bytes into a single binary encoded byte (0x00-0xFF)
            //Add the newly fetched byte to the running checksum
            hexLineChecksum += (unsigned char)wordByte;
        }
        //Now get the two's complement of the hexLineChecksum.
        hexLineChecksum = 0 - hexLineChecksum;
        hexLineChecksum &= 0xFF;    //Truncate to a single byte.  We now have our computed checksum.  This should match the .hex file.
        //Fetch checksum byte from the .hex file
        hexByte = line.mid(1 + (2 * i), 2);     //Fetch the two ASCII bytes that correspond to the checksum byte
        wordByte = hexByte.toInt(&ok, 16);      //Re-format the above two ASCII bytes into a single binary encoded byte (0x00-0xFF)
        wordByte &= 0xFF;
        //Now check if the checksum we computed matches the one at the end of the line in the hex file.
        if(hexLineChecksum != wordByte)
        {
            //Checksum in the hex file doesn't match the line contents.  This implies a corrupted hex file.
            //If an error is detected in the hex file formatting, the safest approach is to
            //abort the operation and force the user to supply a properly formatted hex file.
            if(hexfile.isOpen())
                hexfile.close();
            return ErrorInHexFile;
        }



        //Check the record type of the hex line, to determine how to continue parsing the data.
        if (recordType == END_OF_FILE)                        // end of file record
        {
            hasEndOfFileRecord = true;
            break;
        }
        else if ((recordType == EXTENDED_SEGMENT_ADDR) || (recordType == EXTENDED_LINEAR_ADDR)) // Segment address
        {
            //Error check: Make sure the line contains the correct number of bytes for the specified record type
            if((unsigned int)line.size() >= (11 + (2 * byteCount)))
            {
                //Fetch the payload, which is the upper 4 or 16-bits of the 20-bit or 32-bit hex file address
                segmentAddress = line.mid(9, 4).toInt(&ok, 16);

                //Load the upper bits of the address
                if (recordType == EXTENDED_SEGMENT_ADDR)
                {
                    segmentAddress <<= 4;
                }
                else
                {
                    segmentAddress <<= 16;
                }

                //Update the line address, now that we know the upper bits are something new.
                lineAddress = segmentAddress + line.mid(3, 4).toInt(&ok, 16);
            }
            else
            {
                //Length appears to be wrong in hex line entry.
                //If an error is detected in the hex file formatting, the safest approach is to
                //abort the operation and force the user to supply a properly formatted hex file.
                if(hexfile.isOpen())
                    hexfile.close();
                return ErrorInHexFile;
            }

        } // end if ((recordType == EXTENDED_SEGMENT_ADDR) || (recordType == EXTENDED_LINEAR_ADDR)) // Segment address
        else if (recordType == DATA)                        // Data Record
        {
            //Error check to make sure line is long enough to be consistent with the specified record type
            if ((unsigned int)line.size() < (11 + (2 * byteCount)))
            {
                //If an error is detected in the hex file formatting, the safest approach is to
                //abort the operation and force the user to supply a proper hex file.
                if(hexfile.isOpen())
                    hexfile.close();
                return ErrorInHexFile;
            }


            //For each data payload byte we find in the hex file line, check if it is contained within
            //a progammable region inside the microcontroller.  If so save it.  If not, discard it.
            for(i = 0; i < byteCount; i++)
            {
                //Use the hex file linear byte address, to compute other imformation about the
                //byte/location.  The GetDeviceAddressFromHexAddress() function gives us a pointer to
                //the PC RAM buffer byte that will get programmed into the microcontroller, which corresponds
                //to the specified .hex file extended address.
                //The function also returns a boolean letting us know if the address is part of a programmable memory region on the device.
                deviceAddress = device->GetDeviceAddressFromHexAddress(lineAddress + i, pData, type, includedInProgrammableRange, addressWasEndofRange, bytesPerAddressAndType, endDeviceAddressofRegion, pPCRAMBuffer);
                //Check if the just parsed hex byte was included in one of the microcontroller reported programmable memory regions.
                //If so, save the byte into the proper location in the PC RAM buffer, so it can be programmed later.
                if((includedInProgrammableRange == true) && (pPCRAMBuffer != 0)) //Make sure pPCRAMBuffer pointer is valid before using it.
                {
                    //Print debug output text to debug window
                    if(i == 0)
                    {
                        qDebug(QString("Importing .hex file line with device address: 0x" + QString::number(deviceAddress, 16)).toLatin1());
                    }

                    //Fetch ASCII encoded payload byte from .hex file and save the byte to our temporary RAM buffer.
                    hexByte = line.mid(9 + (2 * i), 2);  //Fetch two ASCII data payload bytes from the .hex file
                    wordByte = hexByte.toInt(&ok, 16);   //Re-format the above two ASCII bytes into a single binary encoded byte (0x00-0xFF)

                    *pPCRAMBuffer = (unsigned char)wordByte;    //Save the .hex file data byte into the PC RAM buffer that holds the data to be programmed
                    importedAtLeastOneByte = true;       //Set flag so we know we imported something successfully.

                    //Check if we just parsed a config bit byte.  If so, set flag so the user is no longer locked out
                    //of programming the config bits section.
                    if(type == CONFIG_MEMORY)
                    {
                        hasConfigBits = true;
                    }
                }
                else if((includedInProgrammableRange == true) && (pPCRAMBuffer == 0))
                {
                    //Previous memory allocation must have failed, or otherwise pPCRAMBuffer would not be = 0.
                    //Since the memory allocation failed, we should bug out and let the user know.
                    if(hexfile.isOpen())
                        hexfile.close();
                    return InsufficientMemory;
                }
            }//for(i = 0; i < byteCount; i++)
        } // end else if (recordType == DATA)
    }//while (!hexfile.atEnd())

    //If we get to here, that means we reached the end of the hex file, or we found a END_OF_FILE record in the .hex file.
    if(hexfile.isOpen())
    {
        hexfile.close();
    }

    //Check if we imported any data from the .hex file.
    if(importedAtLeastOneByte == true)
    {
        qDebug(QString("Hex File imported successfully.").toLatin1());
        return Success;
    }
    else
    {
        //If we get to here, we didn't import anything.  The hex file must have been empty or otherwise didn't
        //contain any data that overlaps a device programmable region.  We should let the user know they should
        //supply a better hex file designed for their device.
        return NoneInRange;
    }
}