Exemple #1
0
void tH3000LinkRx::RxSerialData(const QByteArray& rxData)
{
    bool messageReceived = false;

    // Receive buffer is a QByteArray
    // This could be optimised to be char array to reduce allocs and copies
    m_RxBuffer += rxData;

    int endIndex = m_RxBuffer.indexOf("\r\n");

    while(endIndex != -1)
    {
        QByteArray RxMessage = m_RxBuffer.left(endIndex);

        if(RxMessage.size() > 0)
        {
            bool messageOk = false;

#ifdef LOG_H3000_RX
            DbgPrintf("**** H3000 Rx %s", RxMessage.constData());
#endif
            // Check the checksum
            int checksumIndex = RxMessage.lastIndexOf('*');

            if(checksumIndex != -1)
            {
                unsigned char calcChecksum = static_cast<unsigned char>( tH3000Command::CalculateChecksum( RxMessage.left( checksumIndex) ) );
                unsigned char checksum = static_cast<unsigned char>( RxMessage.mid(checksumIndex + 1, 2).toInt(0, 16) );

                if(checksum == calcChecksum)
                {
                    messageOk = true;
                }
            }

            if(messageOk == true)
            {
                QByteArray strippedMessage = RxMessage.left(checksumIndex);

                if(RxMessage.at(0) == '#')
                {
                    emit H3000ReceivedEchoResponse(RxMessage);
                }
                else if(RxMessage.at(0) == 'V')
                {
                    ProcessReceivedValue(strippedMessage);
                }
                else if(RxMessage.at(0) == 'U') 
                {
                    ProcessReceivedTableData(strippedMessage);
                }
                else if(RxMessage.at(0) == 'L')
                {
                    ProcessReceivedPosition(strippedMessage);
                }
                else if(RxMessage.at(0) == 'T')
                {
                    ProcessReceivedUTC(strippedMessage);
                }
                else if(RxMessage.at(0) == 'M')
                {
                    ProcessReceivedTrueMagSetting(strippedMessage);
                }

                messageReceived = true;
            }
        }

        m_RxBuffer = m_RxBuffer.mid(endIndex + 2);

        endIndex = m_RxBuffer.indexOf("\r\n");
    }

    if((messageReceived) && (!m_DataReceived))
    {
        m_DataReceived = true;

        emit H3000LinkDataReceived();
    }
}
char IoInterface::getOperandFromMessage(QByteArray message)
{
    char operand = message.at(2) & 0xff;
    return operand;
}
bool KeePass2Reader::readHeaderField()
{
    QByteArray fieldIDArray = m_headerStream->read(1);
    if (fieldIDArray.size() != 1) {
        raiseError("Invalid header id size");
        return false;
    }
    quint8 fieldID = fieldIDArray.at(0);

    bool ok;
    quint16 fieldLen = Endian::readUInt16(m_headerStream, KeePass2::BYTEORDER, &ok);
    if (!ok) {
        raiseError("Invalid header field length");
        return false;
    }

    QByteArray fieldData;
    if (fieldLen != 0) {
        fieldData = m_headerStream->read(fieldLen);
        if (fieldData.size() != fieldLen) {
            raiseError("Invalid header data length");
            return false;
        }
    }

    switch (fieldID) {
    case KeePass2::EndOfHeader:
        m_headerEnd = true;
        break;

    case KeePass2::CipherID:
        setCipher(fieldData);
        break;

    case KeePass2::CompressionFlags:
        setCompressionFlags(fieldData);
        break;

    case KeePass2::MasterSeed:
        setMasterSeed(fieldData);
        break;

    case KeePass2::TransformSeed:
        setTransformSeed(fieldData);
        break;

    case KeePass2::TransformRounds:
        setTansformRounds(fieldData);
        break;

    case KeePass2::EncryptionIV:
        setEncryptionIV(fieldData);
        break;

    case KeePass2::ProtectedStreamKey:
        setProtectedStreamKey(fieldData);
        break;

    case KeePass2::StreamStartBytes:
        setStreamStartBytes(fieldData);
        break;

    case KeePass2::InnerRandomStreamID:
        setInnerRandomStreamID(fieldData);
        break;

    default:
        qWarning("Unknown header field read: id=%d", fieldID);
        break;
    }

    return !m_headerEnd;
}
Exemple #4
0
// Parse property (2 byte property + 2 byte length + value)
QString ChemData::ParseProperty( QByteArray a )
{
    QString propvalue;
    QString sx, sy;

    propvalue = "";

    if ( ( a[0] == '0' ) && ( a[1] == '2' ) ) { // position, p
        int y1 = ( unsigned char ) a[4] + ( unsigned char ) a[5] * 256 + ( unsigned char ) a[6] * 65536 + ( unsigned char ) a[7] * 16777216;
        int x1 = ( unsigned char ) a[8] + ( unsigned char ) a[9] * 256 + ( unsigned char ) a[10] * 65536 + ( unsigned char ) a[11] * 16777216;

        sx.setNum( ( double ) x1 / 65536.0 );
        sy.setNum( ( double ) y1 / 65536.0 );
        propvalue.append( "p=\"" );
        propvalue.append( sx );
        propvalue.append( " " );
        propvalue.append( sy );
        propvalue.append( "\"" );
        return propvalue;
    }
    if ( ( a[0] == '4' ) && ( a[1] == '2' ) ) { // bounding box
        int y1 = ( unsigned char ) a[4] + ( unsigned char ) a[5] * 256 + ( unsigned char ) a[6] * 65536 + ( unsigned char ) a[7] * 16777216;
        int x1 = ( unsigned char ) a[8] + ( unsigned char ) a[9] * 256 + ( unsigned char ) a[10] * 65536 + ( unsigned char ) a[11] * 16777216;
        int y2 = ( unsigned char ) a[12] + ( unsigned char ) a[13] * 256 + ( unsigned char ) a[14] * 65536 + ( unsigned char ) a[15] * 16777216;
        int x2 = ( unsigned char ) a[16] + ( unsigned char ) a[17] * 256 + ( unsigned char ) a[18] * 65536 + ( unsigned char ) a[19] * 16777216;

        sx.setNum( ( double ) x1 / 65536.0 );
        sy.setNum( ( double ) y1 / 65536.0 );
        QString sx2, sy2;

        sx2.setNum( ( double ) x2 / 65536.0 );
        sy2.setNum( ( double ) y2 / 65536.0 );
        propvalue.append( "BoundingBox=\"" );
        propvalue.append( sx );
        propvalue.append( " " );
        propvalue.append( sy );
        propvalue.append( " " );
        propvalue.append( sx2 );
        propvalue.append( " " );
        propvalue.append( sy2 );
        propvalue.append( "\"" );
        return propvalue;
    }
    if ( ( a[0] == '4' ) && ( a[1] == '6' ) ) { // bond begin B
        propvalue.append( "B=\"" );
        int x1 = ( unsigned char ) a[4] + ( unsigned char ) a[5] * 256 + ( unsigned char ) a[6] * 65536 + ( unsigned char ) a[7] * 16777216;

        sx.setNum( x1 );
        propvalue.append( sx );
        propvalue.append( "\"" );
        return propvalue;
    }
    if ( ( a[0] == '5' ) && ( a[1] == '6' ) ) { // bond end E
        propvalue.append( "E=\"" );
        int x1 = ( unsigned char ) a[4] + ( unsigned char ) a[5] * 256 + ( unsigned char ) a[6] * 65536 + ( unsigned char ) a[7] * 16777216;

        sx.setNum( x1 );
        propvalue.append( sx );
        propvalue.append( "\"" );
        return propvalue;
    }
    if ( ( a[0] == '0' ) && ( a[1] == '6' ) ) { // bond order
        propvalue.append( "Order=\"" );
        int x1 = ( unsigned char ) a[4];

        sx.setNum( x1 );
        propvalue.append( sx );
        propvalue.append( "\"" );
        return propvalue;
    }
    if ( ( a[0] == '1' ) && ( a[1] == '6' ) ) { // bond display property
        int x1 = ( unsigned char ) a[4];

        if ( x1 == 3 )
            propvalue = "Display=\"WedgedHashBegin\"";
        if ( x1 == 6 )
            propvalue = "Display=\"WedgeBegin\"";
        return propvalue;
    }
    if ( ( a[0] == '0' ) && ( a[1] == 'a' ) ) { // graphic type
        if ( a[4] == '1' )
            propvalue = "GraphicType=\"Line\"";
        if ( a[4] == '2' )
            propvalue = "GraphicType=\"Arc\"";
        if ( a[4] == '6' )
            propvalue = "GraphicType=\"Bracket\"";
        if ( a[4] == '7' )
            propvalue = "GraphicType=\"Symbol\"";
        return propvalue;
    }
    if ( ( a[0] == '6' ) && ( a[1] == 'a' ) ) { // bracket type
        if ( a[4] == '0' )
            propvalue = "BracketType=\"RoundPair\"";
        if ( a[4] == '1' )
            propvalue = "BracketType=\"SquarePair\"";
        if ( a[4] == '2' )
            propvalue = "BracketType=\"CurlyPair\"";
        return propvalue;
    }
    if ( ( a[0] == '2' ) && ( a[1] == 'a' ) ) { // arrow type
        propvalue = "ArrowType=\"FullHead\"";
        return propvalue;
    }
    if ( ( a[0] == '0' ) && ( a[1] == '7' ) ) { // <s>
        propvalue.append( "<s size=\"12\">" );
        int x1 = ( a[4] * 10 ) + 6;

        for ( int d = x1; d < a.size(); d++ )
            propvalue += a.at( d );
        propvalue.append( "</s>" );
        return propvalue;
    }
    qDebug() << "Unrecognized property: " << hex << ( int ) a[1] << " " << ( int ) a[0] << " [" << dec << a.size() - 4 << " bytes]";
    return QString( "" );
}
//读取数据
void MainWindow::readMyCom()
{
    QByteArray temp ;
    QByteArray shiftElement ;
    QByteArray shiftResult ;
    QString buf;

    //if(!temp.isEmpty()){
    if(myCom->bytesAvailable() >=41 )
      {
            shiftElement=myCom->readAll();
            temp=shiftElement;
            for (int i = 0; i <= shiftElement.length (); i++)//读取的19位数据循环移位,再相应输出到LCDNumberWidget显示
            {
                if(shiftElement[i]=='<')

                {
                    for(int j=0;j<40;j++)
                    {
                        if(i+j>40)
                        shiftResult[j]=shiftElement[i+j-41];

                        else
                        shiftResult[j]=shiftElement[i+j];
                    }
                break;
                }
            }
            ui->textBrowser->setTextColor(Qt::black);
            if(ui->ccradioButton->isChecked())
            {
                buf = shiftResult;
            }
            else if(ui->chradioButton->isChecked())
            {
                QString str;
                for(int i = 0; i < temp.count(); i++)
                {
                    QString s;
                    s.sprintf("0x%02x, ", (unsigned char)temp.at(i));
                    buf += s;
                }
            }

        if(!write2fileName.isEmpty())
        {
            QFile file(write2fileName);
            //如果打开失败则给出提示并退出函数
            if(!file.open(QFile::WriteOnly | QIODevice::Text))
            {
                QMessageBox::warning(this, tr("写入文件"), tr("打开文件 %1 失败, 无法写入\n%2").arg(write2fileName).arg(file.errorString()), QMessageBox::Ok);
                return;
            }
            QTextStream out(&file);
            out<<buf;
            file.close();
        }



        Temp=buf.mid(7,2);
        ui->Temp_lcdNumber->display(Temp);

        Humidity=buf.mid(9,2);
        ui->Humidity_lcdNumber->display(Humidity);

        Lux=buf.mid(2,5);
        ui->Lux_lcdNumber->display(Lux);


        Red=buf.mid(12,3);
        ui->Red_lcdNumber->display(Red);

        Green=buf.mid(16,3);
        ui->Green_lcdNumber->display(Green);

        Blue=buf.mid(20,3);
        ui->Blue_lcdNumber->display(Blue);


        Red_SpinBox=Red;
        Green_SpinBox=Green;
        Blue_SpinBox=Blue;
        ALL_SpinBox=Red.append(Green).append(Blue);



        ui->textBrowser->setText(ui->textBrowser->document()->toPlainText() + buf);
        QTextCursor cursor = ui->textBrowser->textCursor();
        cursor.movePosition(QTextCursor::End);
        ui->textBrowser->setTextCursor(cursor);
        ui->recvbyteslcdNumber->display(ui->recvbyteslcdNumber->value() + temp.size());
        ui->statusBar->showMessage(tr("成功读取%1字节数据").arg(temp.size()));
    }
}
Exemple #6
0
/// reads all bytes from the io device, while removing comments and keeping the number of lines
/// quick and dirty 'lexer' that replaces every comment by spaces (so the number of charactes keeps the same)
QByteArray JsonParser::stripCommentsFromJson( const QByteArray& bytesIn )
{
    QByteArray result;
    enum {
        StateNormal,
        StateString,
        StateLineComment,
        StateBlockComment
    } state = StateNormal;
    for( int i=0,cnt=bytesIn.size(); i<cnt; ++i ) {
        char c = bytesIn.at(i);
        switch( state ) {
            case StateNormal:
                // a '/'
                if( c == '/' ) {
                    char c2 = ((i+1)<cnt) ? bytesIn.at(i+1) : 0;
                    if( c2 == '/') {
                        i++;
                        state = StateLineComment;
                        result.append(' ');
                        result.append(' ');
                        break;
                    } else if ( c2 == '*') {
                        i++;
                        state = StateBlockComment;
                        result.append(' ');
                        result.append(' ');
                        break;
                    }
                // start of a string
                } else if( c == '\"') {
                    state = StateString;
                }
                result.append(c);
                break;

            case StateString:
                if( c == '\\' ) {
                    char c2 = ((i+1)<cnt) ? bytesIn.at(i+1) : 0;
                    if( c2 == '\"') {
                        i++;
                        result.append('\\');
                        result.append('\"');
                        break;
                    }
                } else if( c == '\"') {
                    state = StateNormal;
                }
                result.append(c);
                break;

            case StateLineComment:
                if( c == '\r') {
                    result.append('\r');
                }
                else if( c == '\n' ) {
                    result.append(c);
                    state = StateNormal;
                } else {
                    result.append(' ');
                }
                break;

            case StateBlockComment:
                if( c == '*') {
                    char c2 = ((i+1)<cnt) ? bytesIn.at(i+1) : 0;
                    if( c2 == '/') {
                        i++;
                        state = StateNormal;
                        result.append(' ');
                    }
                    result.append(' ');
                } else if( c == '\r' || c == '\n' ) {
                    result.append(c);
                } else {
                    result.append(' ');
                }
                break;
        }
    }
    return result;
}
Exemple #7
0
LangLoaderPlain::LangLoaderPlain(const QString &file, const LangLoaderRequest &request) : file(file), request(request), readingAll(request.contains(lngkeys_cnt)) {
	QFile f(file);
	if (!f.open(QIODevice::ReadOnly)) {
		error(qsl("Could not open input file!"));
		return;
	}
	if (f.size() > 1024 * 1024) {
		error(qsl("Too big file: %1").arg(f.size()));
		return;
	}
	QByteArray checkCodec = f.read(3);
	if (checkCodec.size() < 3) {
		error(qsl("Bad lang input file: %1").arg(file));
		return;
	}
	f.seek(0);

	QByteArray data;
	int skip = 0;
	if ((checkCodec.at(0) == '\xFF' && checkCodec.at(1) == '\xFE') || (checkCodec.at(0) == '\xFE' && checkCodec.at(1) == '\xFF') || (checkCodec.at(1) == 0)) {
		QTextStream stream(&f);
		stream.setCodec("UTF-16");

		QString string = stream.readAll();
		if (stream.status() != QTextStream::Ok) {
			error(qsl("Could not read valid UTF-16 file: % 1").arg(file));
			return;
		}
		f.close();

		data = string.toUtf8();
	} else if (checkCodec.at(0) == 0) {
		QByteArray tmp = "\xFE\xFF" + f.readAll(); // add fake UTF-16 BOM
		f.close();

		QTextStream stream(&tmp);
		stream.setCodec("UTF-16");
		QString string = stream.readAll();
		if (stream.status() != QTextStream::Ok) {
			error(qsl("Could not read valid UTF-16 file: % 1").arg(file));
			return;
		}

		data = string.toUtf8();
	} else {
		data = f.readAll();
		if (checkCodec.at(0) == '\xEF' && checkCodec.at(1) == '\xBB' && checkCodec.at(2) == '\xBF') {
			skip = 3; // skip UTF-8 BOM
		}
	}

	const char *text = data.constData() + skip, *end = text + data.size() - skip;
	try {
		while (true) {
			if (!readKeyValue(text, end)) {
				break;
			}
		}
	} catch (std::exception &e) {
		error(QString::fromUtf8(e.what()));
		return;
	}
}
bool CWizRtfReader::load(const QString& strFile, QString& strText)
{
    QByteArray ba = file_load (strFile);

    QString text;
    text.reserve (ba.size());

    int i = 0;
    int l = ba.size();

    QString ansicgp;
    int n = ba.indexOf ("ansicpg");
    if (n != -1)
    {
        int m = ba.indexOf ('\\', n);
        n += 7;
        ansicgp = ba.mid (n, m - n);
    }

    if (ansicgp.isEmpty()) //assuming unicode
    {
        while (i < l)
            if ((ba.at(i) == '\\') && (ba.at(i + 1) == 'u'))
            {
                QByteArray ta = ba.mid (i, 7);
                ta = ta.mid (2, 4);
                QChar c (ta.toInt());
                text.append (c);
                i += 7 + 3;
            }
            else
            {
                text.append (ba.at(i));
                i++;
            }
    }
    else
    {
        ansicgp.prepend ("CP");

        QTextCodec *codec = QTextCodec::codecForName (ansicgp.toUtf8().data());
        qDebug() << "not unicode!";

        while (i < l)
            if ((ba.at(i) == '\\') && (ba.at(i + 1) == '\''))
            {
                QByteArray ta = ba.mid (i, 4);
                ta = ta.mid (2, 2);
                QByteArray bh = ta.fromHex (ta);
                text.append (codec->toUnicode (bh));
                i += 4;
            }
            else
            {
                text.append (ba.at(i));
                i++;
            }
    }

    strText = rtf_strip (text);

    return true;
}
// This code is shared with moc.cpp
static QByteArray normalizeTypeInternalQt47(const char *t, const char *e, bool fixScope = false, bool adjustConst = true)
{
    int len = e - t;
    /*
      Convert 'char const *' into 'const char *'. Start at index 1,
      not 0, because 'const char *' is already OK.
    */
    QByteArray constbuf;
    for (int i = 1; i < len; i++) {
        if ( t[i] == 'c'
             && strncmp(t + i + 1, "onst", 4) == 0
             && (i + 5 >= len || !is_ident_char(t[i + 5]))
             && !is_ident_char(t[i-1])
             ) {
            constbuf = QByteArray(t, len);
            if (is_space(t[i-1]))
                constbuf.remove(i-1, 6);
            else
                constbuf.remove(i, 5);
            constbuf.prepend("const ");
            t = constbuf.data();
            e = constbuf.data() + constbuf.length();
            break;
        }
        /*
          We musn't convert 'char * const *' into 'const char **'
          and we must beware of 'Bar<const Bla>'.
        */
        if (t[i] == '&' || t[i] == '*' ||t[i] == '<')
            break;
    }
    if (adjustConst && e > t + 6 && strncmp("const ", t, 6) == 0) {
        if (*(e-1) == '&') { // treat const reference as value
            t += 6;
            --e;
        } else if (is_ident_char(*(e-1)) || *(e-1) == '>') { // treat const value as value
            t += 6;
        }
    }
    QByteArray result;
    result.reserve(len);

#if 1
    // consume initial 'const '
    if (strncmp("const ", t, 6) == 0) {
        t+= 6;
        result += "const ";
    }
#endif

    // some type substitutions for 'unsigned x'
    if (strncmp("unsigned", t, 8) == 0) {
        // make sure "unsigned" is an isolated word before making substitutions
        if (!t[8] || !is_ident_char(t[8])) {
            if (strncmp(" int", t+8, 4) == 0) {
                t += 8+4;
                result += "uint";
            } else if (strncmp(" long", t+8, 5) == 0) {
                if ((strlen(t + 8 + 5) < 4 || strncmp(t + 8 + 5, " int", 4) != 0) // preserve '[unsigned] long int'
                    && (strlen(t + 8 + 5) < 5 || strncmp(t + 8 + 5, " long", 5) != 0) // preserve '[unsigned] long long'
                   ) {
                    t += 8+5;
                    result += "ulong";
                }
            } else if (strncmp(" short", t+8, 6) != 0  // preserve unsigned short
                && strncmp(" char", t+8, 5) != 0) {    // preserve unsigned char
                //  treat rest (unsigned) as uint
                t += 8;
                result += "uint";
            }
        }
    } else {
        // discard 'struct', 'class', and 'enum'; they are optional
        // and we don't want them in the normalized signature
        struct {
            const char *keyword;
            int len;
        } optional[] = {
            { "struct ", 7 },
            { "class ", 6 },
            { "enum ", 5 },
            { 0, 0 }
        };
        int i = 0;
        do {
            if (strncmp(optional[i].keyword, t, optional[i].len) == 0) {
                t += optional[i].len;
                break;
            }
        } while (optional[++i].keyword != 0);
    }

    bool star = false;
    while (t != e) {
        char c = *t++;
        if (fixScope && c == ':' && *t == ':' ) {
            ++t;
            c = *t++;
            int i = result.size() - 1;
            while (i >= 0 && is_ident_char(result.at(i)))
                --i;
            result.resize(i + 1);
        }
        star = star || c == '*';
        result += c;
        if (c == '<') {
            //template recursion
            const char* tt = t;
            int templdepth = 1;
            while (t != e) {
                c = *t++;
                if (c == '<')
                    ++templdepth;
                if (c == '>')
                    --templdepth;
                if (templdepth == 0 || (templdepth == 1 && c == ',')) {
                    result += normalizeTypeInternalQt47(tt, t-1, fixScope, false);
                    result += c;
                    if (templdepth == 0) {
                        if (*t == '>')
                            result += ' '; // avoid >>
                        break;
                    }
                    tt = t;
                }
            }
        }

        // cv qualifers can appear after the type as well
        if (!is_ident_char(c) && t != e && (e - t >= 5 && strncmp("const", t, 5) == 0)
            && (e - t == 5 || !is_ident_char(t[5]))) {
            t += 5;
            while (t != e && is_space(*t))
                ++t;
            if (adjustConst && t != e && *t == '&') {
                // treat const ref as value
                ++t;
            } else if (adjustConst && !star) {
                // treat const as value
            } else if (!star) {
                // move const to the front (but not if const comes after a *)
                result.prepend("const ");
            } else {
                // keep const after a *
                result += "const";
            }
        }
    }

    return result;
}
Exemple #10
0
static quint32 getBEUint16(const QByteArray &ba, int pos)
{
    Q_ASSERT(ba.size() >= pos + 1);
    return (static_cast<quint16>(static_cast<quint8>(ba.at(pos))) << 8) + static_cast<quint8>(ba.at(pos + 1));
}
Exemple #11
0
QByteArray NfcTagType1::processCommand(const QByteArray &command)
{
    lastAccess = QDateTime::currentMSecsSinceEpoch();

    QByteArray response;

    bool tagType1 = (hr0 & 0xf0) == 0x10;
    bool dynamic = (hr0 & 0x0f) != 0x01;

    if (command.length() == 9) {
        // static memory model command
        quint8 opcode = command.at(0);
        quint8 address = command.at(1);
        quint8 data = command.at(2);
        QByteArray uid = command.mid(3, 4);

        // check checksum
        if (qNfcChecksum(command.constData(), command.length()) != 0)
            return QByteArray();

        // check UID
        if (uid != memory.left(4))
            return QByteArray();

        switch (opcode) {
        case 0x00:  // RALL
            response.append(hr0);
            response.append(hr1);
            response.append(memory.left(120));
            break;
        case 0x01:  // READ
            response.append(address);
            if (address & 0x80)
                response.append(char(0x00));
            else
                response.append(memory.at(address));
            break;
        case 0x53: { // WRITE-E
            quint8 block = address >> 3;
            if (block == 0x00 || block == 0x0d || block == 0x0e)    // locked blocks
                break;

            quint16 lock = (readData(0x0e, 0x01) << 8) | readData(0x0e, 0x00);
            if ((0x01 << block) & lock)    // locked blocks
                break;

            // FIXME: Test dynamic lock bytes

            memory[address] = data;

            response.append(address);
            response.append(data);
            break;
        }
        case 0x1a: { // WRITE-NE
            quint8 block = address >> 3;
            if (block == 0x00 || block == 0x0d)  // locked blocks
                break;

            quint16 lock = (readData(0x0e, 0x01) << 8) | readData(0x0e, 0x00);
            if ((0x01 << block) & lock)    // locked blocks
                break;


            // FIXME: Test dynamic lock bytes

            memory[address] = memory.at(address) | data;

            response.append(address);
            response.append(memory.at(address));
            break;
        }
        case 0x78:  // RID
            response.append(hr0);
            response.append(hr1);
            response.append(memory.left(4));
            break;
        }
    } else if (tagType1 && dynamic && command.length() == 16) {
Exemple #12
0
static QList<Abi> parseCoffHeader(const QByteArray &data)
{
    QList<Abi> result;
    if (data.size() < 20)
        return result;

    Abi::Architecture arch = Abi::UnknownArchitecture;
    Abi::OSFlavor flavor = Abi::UnknownFlavor;
    int width = 0;

    // Get machine field from COFF file header
    quint16 machine = getLEUint16(data, 0);
    switch (machine) {
    case 0x01c0: // ARM LE
    case 0x01c2: // ARM or thumb
    case 0x01c4: // ARMv7 thumb
        arch = Abi::ArmArchitecture;
        width = 32;
        break;
    case 0x8664: // x86_64
        arch = Abi::X86Architecture;
        width = 64;
        break;
    case 0x014c: // i386
        arch = Abi::X86Architecture;
        width = 32;
        break;
    case 0x0166: // MIPS, little endian
        arch = Abi::MipsArchitecture;
        width = 32;
        break;
    case 0x0200: // ia64
        arch = Abi::ItaniumArchitecture;
        width = 64;
        break;
    }

    if (data.size() >= 24) {
        // Get Major and Minor Image Version from optional header fields
        quint8 minorLinker = data.at(23);
        switch (data.at(22)) {
        case 2:
        case 3: // not yet reached:-)
            flavor = Abi::WindowsMSysFlavor;
            break;
        case 8:
            flavor = Abi::WindowsMsvc2005Flavor;
            break;
        case 9:
            flavor = Abi::WindowsMsvc2008Flavor;
            break;
        case 10:
            flavor = Abi::WindowsMsvc2010Flavor;
            break;
        case 11:
            flavor = Abi::WindowsMsvc2012Flavor;
            break;
        case 12:
            flavor = Abi::WindowsMsvc2013Flavor;
            break;
        default: // Keep unknown flavor
            if (minorLinker != 0)
                flavor = Abi::WindowsMSysFlavor; // MSVC seems to avoid using minor numbers
            else
                qWarning("%s: Unknown MSVC flavour encountered.", Q_FUNC_INFO);
            break;
        }
    }

    if (arch != Abi::UnknownArchitecture && width != 0)
        result.append(Abi(arch, Abi::WindowsOS, flavor, Abi::PEFormat, width));

    return result;
}
bool MStyleSheetAttribute::writeAttribute(MUniqueStringCache::Index filename,
        MStyle *style,
        const QMetaProperty &property,
        M::Orientation orientation) const
{
    // first check if the attribute is cached orientation independent, if not found
    // check for the given orientation
    QVariant cachedVariant = variantCache[M::Landscape + 1][value][property.userType()];
    if (cachedVariant.isValid()) {
        return property.write(style, cachedVariant);
    } else {
        cachedVariant = variantCache[orientation][value][property.userType()];
        if (cachedVariant.isValid()) {
            style->setOrientationDependent(true);
            return property.write(style, cachedVariant);
        }
    }

    bool conversionOK = false;
    // most types are the same in landscape and portrait
    CacheOrientationFlags cacheOrientation = CacheOrientationFlags(PortraitFlag | LandscapeFlag);

    QLatin1String vs = MStyleSheetParser::stringCacheWithoutReverseLookup()->indexToString(value);
    QByteArray valueString = QByteArray::fromRawData(vs.latin1(), strlen(vs.latin1()));

    const int attributeType = property.userType();
    if (attributeType == QMetaType::Bool) {
        bool result = booleanFromString(valueString, &conversionOK);
        if (conversionOK) {
            return fillProperty(property, style, cacheOrientation, result);
        }
    } else if (attributeType == QMetaType::Int) {
        int integer = attributeToInt(valueString, &conversionOK);
        if (conversionOK) {
            return fillProperty(property, style, cacheOrientation, integer);
        }
    } else if (attributeType == QMetaType::QColor) {
        if(valueString == "none")
            return fillProperty(property, style, cacheOrientation, QColor());

        QColor color = colorFromString(valueString, &conversionOK);
        if (conversionOK) {
            return fillProperty(property, style, cacheOrientation, color);
        }
    } else if (attributeType == QMetaType::QReal) {
        qreal real = attributeToFloat(valueString, &conversionOK);
        if (conversionOK) {
            return fillProperty(property, style, cacheOrientation, real);
        }
    } else if (attributeType == qMetaTypeId<const QPixmap*>()) {
        if(valueString == "none")
            return fillProperty(property, style, cacheOrientation, qVariantFromValue((const QPixmap *) NULL));

        //"image: image_id;"
        //"image: image_id 64px 64px;"
        //"image: "image id";"
        //"image: "image id" 64px 64px;"

        QList<QByteArray> list;
        if (valueString.startsWith('\"')) {
            //parse name inside quotes
            int idx = valueString.indexOf('\"', 1);
            if (idx != -1) {
                //get quoted image_id
                QByteArray imageid = valueString.mid(1, idx - 1);

                //split rest of the parameters
                QByteArray values = valueString.mid(idx + 1).trimmed();
                list = values.split(' ');
                list.removeAll("");

                //insert image_id as first parameter
                list.insert(0, imageid);
            }
        } else {
            //no quotes, just split the parameters
            list = valueString.split(' ');
            list.removeAll("");
        }

        //only image_id
        if (list.size() == 1) {
            const QPixmap *pixmap = MTheme::pixmap(list.at(0));
            return fillProperty(property, style, cacheOrientation, qVariantFromValue(pixmap), false);
        }
        //image_id + width + height
        else if (list.size() == 3) {
            int width = attributeToInt(list.at(1), &conversionOK, WidthAttribute, orientation, &cacheOrientation);
            int height = attributeToInt(list.at(2), &conversionOK, HeightAttribute, orientation, &cacheOrientation);
            const QPixmap *pixmap = MTheme::pixmap(list.at(0), QSize(width, height));
            return fillProperty(property, style, cacheOrientation, qVariantFromValue(pixmap), false);
        }
        //no parameters
        else if (list.size() == 0) {
            //init null pixmap which is ok if someone does not want to use it
            return fillProperty(property, style, cacheOrientation, qVariantFromValue((const QPixmap *) NULL));
        }
    } else if (attributeType == qMetaTypeId<const MScalableImage*>() || attributeType == qMetaTypeId<MBackgroundTiles>()) {
        //"background: image_id left right top bottom;"
        //"background: image_id;"
        //"background: "image id" left right top bottom;"
        //"background: "image id";"

        QList<QByteArray> list;
        if (valueString.startsWith('\"')) {
            //parse name inside quotes
            int idx = valueString.indexOf('\"', 1);
            if (idx != -1) {
                //get quoted image_id
                QByteArray imageid = valueString.mid(1, idx - 1);

                //split rest of the parameters
                QByteArray values = valueString.mid(idx + 1).trimmed();
                list = values.split(' ');
                list.removeAll("");
                //insert image_id as first parameter
                list.insert(0, imageid);
            }
        } else {
            //no quotes, just split the parameters
            list = valueString.split(' ');
            list.removeAll("");
        }

        //no parameters
        if (valueString.isEmpty() || valueString == "none") {
            //init null image which is ok if someone does not want to use it
            if(attributeType == qMetaTypeId<const MScalableImage*>())
                return fillProperty(property, style, cacheOrientation, qVariantFromValue((const MScalableImage *) NULL));
            else
                return fillProperty(property, style, cacheOrientation, QVariant::fromValue(MBackgroundTiles()), false);
        }
        //only image_id
        else if (list.size() == 1) {
            if(attributeType == qMetaTypeId<const MScalableImage*>()) {
                const MScalableImage *image = MTheme::scalableImage(list.at(0), 0, 0, 0, 0);
                return fillProperty(property, style, cacheOrientation, qVariantFromValue(image), false);
            } else {
                return fillProperty(property, style, cacheOrientation, QVariant::fromValue(MBackgroundTiles(list.at(0), 0,0,0,0)), false);
            }
        }
        //image_id + border width paramaters
        else if (list.size() == 5) {
            //image_id and the border parameters
            if(attributeType == qMetaTypeId<const MScalableImage*>()) {
                const MScalableImage *image = MTheme::scalableImage(list.at(0),
                                                attributeToInt(list.at(1), &conversionOK),
                                                attributeToInt(list.at(2), &conversionOK),
                                                attributeToInt(list.at(3), &conversionOK),
                                                attributeToInt(list.at(4), &conversionOK));
                return fillProperty(property, style, cacheOrientation, qVariantFromValue(image), false);
            } else {
                return fillProperty(property, style, cacheOrientation, QVariant::fromValue(MBackgroundTiles(list.at(0),
                                                                attributeToInt(list.at(1), &conversionOK),
                                                                attributeToInt(list.at(2), &conversionOK),
                                                                attributeToInt(list.at(3), &conversionOK),
                                                                attributeToInt(list.at(4), &conversionOK))), false);
            }
        }
    } else if (attributeType == QMetaType::QSize || attributeType == QMetaType::QSizeF) {
        //size: 25px 25px;

        //just split into pieces and create QSize or QSizeF depending on the attributeType
        QList<QByteArray> list = valueString.split(' ');
        list.removeAll("");
        if (list.size() == 2) {
            if (attributeType == QMetaType::QSize) {
                int width = attributeToInt(list.at(0), &conversionOK, WidthAttribute, orientation, &cacheOrientation);
                int height = attributeToInt(list.at(1), &conversionOK, HeightAttribute, orientation, &cacheOrientation);
                return fillProperty(property, style, cacheOrientation, QSize(width, height));
            } else {
                qreal width = attributeToFloat(list.at(0), &conversionOK, WidthAttribute, orientation, &cacheOrientation);
                qreal height = attributeToFloat(list.at(1), &conversionOK, HeightAttribute, orientation, &cacheOrientation);
                return fillProperty(property, style, cacheOrientation, QSizeF(width, height));
            }
        }
    } else if (attributeType == QMetaType::QPoint || attributeType == QMetaType::QPointF) {
        //"point: 256px 123px;

        //just split into pieces and create QPoint or QPointF depending on the attributeType
        QList<QByteArray> list = valueString.split(' ');
        list.removeAll("");
        if (list.size() == 2) {
            if (attributeType == QMetaType::QPoint) {
                int x = attributeToInt(list.at(0), &conversionOK, WidthAttribute, orientation, &cacheOrientation);
                int y = attributeToInt(list.at(1), &conversionOK, HeightAttribute, orientation, &cacheOrientation);
                return fillProperty(property, style, cacheOrientation, QPoint(x, y));
            } else {
                qreal x = attributeToFloat(list.at(0), &conversionOK, WidthAttribute, orientation, &cacheOrientation);
                qreal y = attributeToFloat(list.at(1), &conversionOK, HeightAttribute, orientation, &cacheOrientation);
                return fillProperty(property, style, cacheOrientation, QPointF(x, y));
            }
        }
    } else if (attributeType == QMetaType::QFont) {
        QFont font = fontFromString(valueString, &conversionOK);
        if (conversionOK) {
            return fillProperty(property, style, cacheOrientation, font);
        }
    } else if (attributeType == QMetaType::QString) {
        if (valueString.length() >= 2) {
            if ((valueString.at(0) == 0x22) && (valueString.at(valueString.length()-1) == 0x22)) {
                return fillProperty(property, style, cacheOrientation, QString(valueString.mid(1, valueString.length() - 2)));
            }
        } else if (valueString.length() == 0) {
            return fillProperty(property, style, cacheOrientation, QString());
        }
    } else if (attributeType == QMetaType::QChar) {
        if (valueString.length() == 3) {
            if ((valueString.at(0) == '\'') && (valueString.at(2) == '\'')) {
                return fillProperty(property, style, cacheOrientation, static_cast<QChar>(valueString.at(1)));
            }
        }
    } else if (attributeType == qMetaTypeId<Qt::Alignment>()) {
        if (DataTypeConverter.ALIGNMENTS.contains(valueString)) {
            return fillProperty(property, style, cacheOrientation, qVariantFromValue(DataTypeConverter.ALIGNMENTS[valueString]));
        }
    } else if (attributeType == qMetaTypeId<Qt::Orientation>()) {
        if (DataTypeConverter.ORIENTATIONS.contains(valueString)) {
            return fillProperty(property, style, cacheOrientation, qVariantFromValue(DataTypeConverter.ORIENTATIONS[valueString]));
        }
    } else if (attributeType == qMetaTypeId<QTextCharFormat::UnderlineStyle>()) {
        if (DataTypeConverter.UNDERLINESTYLES.contains(valueString)) {
            return fillProperty(property, style, cacheOrientation, qVariantFromValue(DataTypeConverter.UNDERLINESTYLES[valueString]));
        }
    } else if (attributeType == qMetaTypeId<Qt::PenStyle>()) {
        if (DataTypeConverter.PENSTYLES.contains(valueString)) {
            return fillProperty(property, style, cacheOrientation, qVariantFromValue(DataTypeConverter.PENSTYLES[valueString]));
        }
    } else if (attributeType == qMetaTypeId<Qt::Axis>()) {
        if (DataTypeConverter.AXES.contains(valueString)) {
            return fillProperty(property, style, cacheOrientation, qVariantFromValue(DataTypeConverter.AXES[valueString]));
        }
    } else if (attributeType == qMetaTypeId<MFeedback>()) {
        MFeedback feedback(valueString);
        return fillProperty(property, style, cacheOrientation, qVariantFromValue(feedback));
    } else if (attributeType == QMetaType::QEasingCurve) {
        QEasingCurve curve;
        // curve type
        QList<QByteArray> list = valueString.split(',');
        if (list.size() > 0) {
            if (DataTypeConverter.EASINGCURVETYPES.contains(list.at(0))) {
                int type = DataTypeConverter.EASINGCURVETYPES[list.at(0)];
                if (type < FirstCustomType)
                    curve.setType(static_cast<QEasingCurve::Type>(type));
                else if (type == OvershotBezier)
                    curve = MOvershotBezierEasingCurve();
                // curve amplitude
                if (list.size() > 1) {
                    curve.setAmplitude((qreal) list.at(1).toDouble());
                    // curve overshoot
                    if (list.size() > 2) {
                        curve.setOvershoot((qreal) list.at(2).toDouble());
                        // curve period
                        if (list.size() > 3) {
                            curve.setPeriod((qreal) list.at(3).toDouble());
                        }
                    }
                }
                return fillProperty(property, style, cacheOrientation, qVariantFromValue(curve));
            }
        }
    } else if (attributeType == qMetaTypeId<QTextOption::WrapMode>()) {
        if (DataTypeConverter.WRAPMODES.contains(valueString)) {
            return fillProperty(property, style, cacheOrientation, qVariantFromValue(DataTypeConverter.WRAPMODES[valueString]));
        }
    }

    MStyleSheetParser::outputParseError(MStyleSheetParser::stringCacheWithReverseLookup()->indexToString(filename), "Not a valid attribute(" + QLatin1String(property.typeName()) + "): " + MStyleSheetParser::stringCacheWithoutReverseLookup()->indexToString(name) + " : " + valueString, MStyleSheetParser::getLineNum(MStyleSheetParser::stringCacheWithReverseLookup()->indexToString(filename), position));
    return false;
}
Exemple #14
0
void Generator::generateCode()
{
    bool isQt = (cdef->classname == "Qt");
    bool isQObject = (cdef->classname == "QObject");
    bool isConstructible = !cdef->constructorList.isEmpty();

//
// build the data array
//
    int i = 0;


    // filter out undeclared enumerators and sets
    {
        QList<EnumDef> enumList;
        for (i = 0; i < cdef->enumList.count(); ++i) {
            EnumDef def = cdef->enumList.at(i);
            if (cdef->enumDeclarations.contains(def.name)) {
                enumList += def;
            }
            QByteArray alias = cdef->flagAliases.value(def.name);
            if (cdef->enumDeclarations.contains(alias)) {
                def.name = alias;
                enumList += def;
            }
        }
        cdef->enumList = enumList;
    }


    QByteArray qualifiedClassNameIdentifier = cdef->qualified;
    qualifiedClassNameIdentifier.replace(':', '_');

    int index = 12;
    fprintf(out, "static const uint qt_meta_data_%s[] = {\n", qualifiedClassNameIdentifier.constData());
    fprintf(out, "\n // content:\n");
    fprintf(out, "    %4d,       // revision\n", 2);
    fprintf(out, "    %4d,       // classname\n", strreg(cdef->qualified));
    fprintf(out, "    %4d, %4d, // classinfo\n", cdef->classInfoList.count(), cdef->classInfoList.count() ? index : 0);
    index += cdef->classInfoList.count() * 2;

    int methodCount = cdef->signalList.count() + cdef->slotList.count() + cdef->methodList.count();
    fprintf(out, "    %4d, %4d, // methods\n", methodCount, methodCount ? index : 0);
    index += methodCount * 5;
    fprintf(out, "    %4d, %4d, // properties\n", cdef->propertyList.count(), cdef->propertyList.count() ? index : 0);
    index += cdef->propertyList.count() * 3;
    if(cdef->notifyableProperties)
        index += cdef->propertyList.count();
    fprintf(out, "    %4d, %4d, // enums/sets\n", cdef->enumList.count(), cdef->enumList.count() ? index : 0);

    int enumsIndex = index;
    for (i = 0; i < cdef->enumList.count(); ++i)
        index += 4 + (cdef->enumList.at(i).values.count() * 2);
    fprintf(out, "    %4d, %4d, // constructors\n", isConstructible ? cdef->constructorList.count() : 0,
            isConstructible ? index : 0);

//
// Build classinfo array
//
    generateClassInfos();

//
// Build signals array first, otherwise the signal indices would be wrong
//
    generateFunctions(cdef->signalList, "signal", MethodSignal);

//
// Build slots array
//
    generateFunctions(cdef->slotList, "slot", MethodSlot);

//
// Build method array
//
    generateFunctions(cdef->methodList, "method", MethodMethod);


//
// Build property array
//
    generateProperties();

//
// Build enums array
//
    generateEnums(enumsIndex);

//
// Build constructors array
//
    if (isConstructible)
        generateFunctions(cdef->constructorList, "constructor", MethodConstructor);

//
// Terminate data array
//
    fprintf(out, "\n       0        // eod\n};\n\n");

//
// Build stringdata array
//
    fprintf(out, "static const char qt_meta_stringdata_%s[] = {\n", qualifiedClassNameIdentifier.constData());
    fprintf(out, "    \"");
    int col = 0;
    int len = 0;
    for (i = 0; i < strings.size(); ++i) {
        QByteArray s = strings.at(i);
        len = s.length();
        if (col && col + len >= 72) {
            fprintf(out, "\"\n    \"");
            col = 0;
        } else if (len && s.at(0) >= '0' && s.at(0) <= '9') {
            fprintf(out, "\"\"");
            len += 2;
        }
        int idx = 0;
        while (idx < s.length()) {
            if (idx > 0) {
                col = 0;
                fprintf(out, "\"\n    \"");
            }
            int spanLen = qMin(70, s.length() - idx);
            // don't cut escape sequences at the end of a line
            int backSlashPos = s.lastIndexOf('\\', idx + spanLen - 1);
            if (backSlashPos >= idx) {
                int escapeLen = lengthOfEscapeSequence(s, backSlashPos);
                spanLen = qBound(spanLen, backSlashPos + escapeLen - idx, s.length() - idx);
            }
            fwrite(s.constData() + idx, 1, spanLen, out);
            idx += spanLen;
            col += spanLen;
        }

        fputs("\\0", out);
        col += len + 2;
    }
    fprintf(out, "\"\n};\n\n");


//
// Generate internal qt_static_metacall() function
//
    if (isConstructible)
        generateStaticMetacall(qualifiedClassNameIdentifier);

//
// Build extra array
//
    QList<QByteArray> extraList;
    for (int i = 0; i < cdef->propertyList.count(); ++i) {
        const PropertyDef &p = cdef->propertyList.at(i);
        if (!isVariantType(p.type) && !metaTypes.contains(p.type)) {
            int s = p.type.lastIndexOf("::");
            if (s > 0) {
                QByteArray scope = p.type.left(s);
                if (scope != "Qt" && scope != cdef->classname && !extraList.contains(scope))
                    extraList += scope;
            }
        }
    }
    if (!extraList.isEmpty()) {
        fprintf(out, "static const QMetaObject *qt_meta_extradata_%s[] = {\n    ", qualifiedClassNameIdentifier.constData());
        for (int i = 0; i < extraList.count(); ++i) {
            if (i)
                fprintf(out, ",\n    ");
            fprintf(out, "    &%s::staticMetaObject", extraList.at(i).constData());
        }
        fprintf(out, ",0\n};\n\n");
    }

    if (isConstructible || !extraList.isEmpty()) {
        fprintf(out, "static const QMetaObjectExtraData qt_meta_extradata2_%s = {\n    ",
                qualifiedClassNameIdentifier.constData());
        if (extraList.isEmpty())
            fprintf(out, "0, ");
        else
            fprintf(out, "qt_meta_extradata_%s, ", qualifiedClassNameIdentifier.constData());
        if (!isConstructible)
            fprintf(out, "0");
        else
            fprintf(out, "%s_qt_static_metacall", qualifiedClassNameIdentifier.constData());
        fprintf(out, " \n};\n\n");
    }

//
// Finally create and initialize the static meta object
//

    if (isQt)
        fprintf(out, "const QMetaObject QObject::staticQtMetaObject = {\n");
    else
        fprintf(out, "const QMetaObject %s::staticMetaObject = {\n", cdef->qualified.constData());

    if (isQObject)
        fprintf(out, "    { 0, ");
    else if (cdef->superclassList.size())
        fprintf(out, "    { &%s::staticMetaObject, ", purestSuperClass.constData());
    else
        fprintf(out, "    { 0, ");
    fprintf(out, "qt_meta_stringdata_%s,\n      qt_meta_data_%s, ",
             qualifiedClassNameIdentifier.constData(), qualifiedClassNameIdentifier.constData());
    if (!isConstructible && extraList.isEmpty())
        fprintf(out, "0 }\n");
    else
        fprintf(out, "&qt_meta_extradata2_%s }\n", qualifiedClassNameIdentifier.constData());
    fprintf(out, "};\n");

    if (isQt || !cdef->hasQObject)
        return;

    fprintf(out, "\nconst QMetaObject *%s::metaObject() const\n{\n    return &staticMetaObject;\n}\n",
            cdef->qualified.constData());
//
// Generate smart cast function
//
    fprintf(out, "\nvoid *%s::qt_metacast(const char *_clname)\n{\n", cdef->qualified.constData());
    fprintf(out, "    if (!_clname) return 0;\n");
    fprintf(out, "    if (!strcmp(_clname, qt_meta_stringdata_%s))\n"
                  "        return static_cast<void*>(const_cast< %s*>(this));\n",
            qualifiedClassNameIdentifier.constData(), cdef->classname.constData());
    for (int i = 1; i < cdef->superclassList.size(); ++i) { // for all superclasses but the first one
        if (cdef->superclassList.at(i).second == FunctionDef::Private)
            continue;
        const char *cname = cdef->superclassList.at(i).first;
        fprintf(out, "    if (!strcmp(_clname, \"%s\"))\n        return static_cast< %s*>(const_cast< %s*>(this));\n",
                cname, cname, cdef->classname.constData());
    }
    for (int i = 0; i < cdef->interfaceList.size(); ++i) {
        const QList<ClassDef::Interface> &iface = cdef->interfaceList.at(i);
        for (int j = 0; j < iface.size(); ++j) {
            fprintf(out, "    if (!strcmp(_clname, %s))\n        return ", iface.at(j).interfaceId.constData());
            for (int k = j; k >= 0; --k)
                fprintf(out, "static_cast< %s*>(", iface.at(k).className.constData());
            fprintf(out, "const_cast< %s*>(this)%s;\n",
                    cdef->classname.constData(), QByteArray(j+1, ')').constData());
        }
    }
    if (!purestSuperClass.isEmpty() && !isQObject) {
        QByteArray superClass = purestSuperClass;
        // workaround for VC6
        if (superClass.contains("::")) {
            fprintf(out, "    typedef %s QMocSuperClass;\n", superClass.constData());
            superClass = "QMocSuperClass";
        }
        fprintf(out, "    return %s::qt_metacast(_clname);\n", superClass.constData());
    } else {
        fprintf(out, "    return 0;\n");
    }
    fprintf(out, "}\n");

//
// Generate internal qt_metacall()  function
//
    generateMetacall();

//
// Generate internal signal functions
//
    for (int signalindex = 0; signalindex < cdef->signalList.size(); ++signalindex)
        generateSignal(&cdef->signalList[signalindex], signalindex);
}
Exemple #15
0
void SensorAgent::processAnswer( const char *buf, int buflen )
{
  //It is possible for an answer/error message  to be split across multiple processAnswer calls.  This makes our life more difficult
  //We have to keep track of the state we are in.  Any characters that we have not parsed yet we put in
  //mLeftOverBuffer
  QByteArray buffer = QByteArray::fromRawData(buf, buflen);
  if(!mLeftOverBuffer.isEmpty()) {
	buffer = mLeftOverBuffer + buffer; //If we have data left over from a previous processAnswer, then we have to prepend this on
	mLeftOverBuffer.clear();
  }
  
#if SA_TRACE
  qDebug() << "<- " << QString::fromUtf8(buffer, buffer.size());
#endif
  int startOfAnswer = 0;  //This can become >= buffer.size(), so check before using!
  for ( int i = 0; i < buffer.size(); ++i ) {
    if ( buffer.at(i) == '\033' ) {  // 033 in octal is the escape character.  The signifies the start of an error
      int startOfError = i;
      bool found = false;
      while(++i < buffer.size()) {
        if(buffer.at(i) == '\033') {
	  QString error = QString::fromUtf8(buffer.constData() + startOfError+1, i-startOfError-1);
	  if ( error.startsWith(QLatin1String("RECONFIGURE")) ) {
            emit reconfigure( this );
 	  }
          else {
            /* We just received the end of an error message, so we
             * can display it. */
            SensorMgr->notify( i18nc( "%1 is a host name", "Message from %1:\n%2",
                               mHostName ,
                               error ) );
          }
          found = true;
	  break;
	}
      }
      if(found) {
        buffer.remove(startOfError, i-startOfError+1);
	i = startOfAnswer - 1;
	continue;
      } else {
        //We have not found the end of the escape string.  Try checking in the next packet
        mLeftOverBuffer = QByteArray(buffer.constData()+startOfAnswer, buffer.size()-startOfAnswer);
        return;
      }
    }

    //The spec was supposed to be that it returned "\nksysguardd> " but some seem to forget the space, so we have to compensate.  Sigh 
    if( (i==startOfAnswer && buffer.size() -i >= (signed)(sizeof("ksysguardd>"  ))-1 && qstrncmp(buffer.constData()+i, "ksysguardd>",   sizeof("ksysguardd>"  )-1) == 0) ||
	(buffer.size() -i >= (signed)(sizeof("\nksysguardd>"))-1 && qstrncmp(buffer.constData()+i, "\nksysguardd>", sizeof("\nksysguardd>")-1) == 0)) {

	QByteArray answer(buffer.constData()+startOfAnswer, i-startOfAnswer);
	if(!answer.isEmpty())
		mAnswerBuffer << answer;
#if SA_TRACE
	qDebug() << "<= " << mAnswerBuffer
		<< "(" << mInputFIFO.count() << "/"
		<< mProcessingFIFO.count() << ")" << endl;
#endif
	if(buffer.at(i) == '\n')
		i++;
	i += sizeof("ksysguardd>") -2;  //Move i on to the next answer (if any). -2 because sizeof adds one for \0  and the for loop will increment by 1 also
	if(i+1 < buffer.size() && buffer.at(i+1) == ' ') i++;
	startOfAnswer = i+1;

	//We have found the end of one reply
	if ( !mDaemonOnLine ) {
		/* First '\nksysguardd> ' signals that the daemon is
	  	 * ready to serve requests now. */
		mDaemonOnLine = true;
#if SA_TRACE
		qDebug() << "Daemon now online!";
#endif
		mAnswerBuffer.clear();
		continue;
	}

	//Deal with the answer we have now read in

	// remove pending request from FIFO
	if ( mProcessingFIFO.isEmpty() ) {
		qDebug()	<< "ERROR: Received answer but have no pending "
				<< "request!" << endl;
		mAnswerBuffer.clear();
		continue;
	}
		
	SensorRequest *req = mProcessingFIFO.dequeue();
	// we are now responsible for the memory of req - we must delete it!
	if ( !req->client() ) {
		/* The client has disappeared before receiving the answer
		 * to his request. */
		delete req;
		mAnswerBuffer.clear();
		continue;
	}
		
	if(!mAnswerBuffer.isEmpty() && mAnswerBuffer[0] == "UNKNOWN COMMAND") {
		/* Notify client that the sensor seems to be no longer available. */
        qDebug() << "Received UNKNOWN COMMAND for: " << req->request();
		req->client()->sensorLost( req->id() );
	} else {
		// Notify client of newly arrived answer.
		req->client()->answerReceived( req->id(), mAnswerBuffer );
	}
	delete req;
	mAnswerBuffer.clear();
    } else if(buffer.at(i) == '\n'){
	mAnswerBuffer << QByteArray(buffer.constData()+startOfAnswer, i-startOfAnswer);
	startOfAnswer = i+1;
    }
  }

  mLeftOverBuffer += QByteArray(buffer.constData()+startOfAnswer, buffer.size()-startOfAnswer);
  executeCommand();
}
Exemple #16
0
Type Moc::parseType()
{
    Type type;
    bool hasSignedOrUnsigned = false;
    bool isVoid = false;
    type.firstToken = lookup();
    for (;;) {
        switch (next()) {
            case SIGNED:
            case UNSIGNED:
                hasSignedOrUnsigned = true;
                // fall through
            case CONST:
            case VOLATILE:
                type.name += lexem();
                type.name += ' ';
                if (lookup(0) == VOLATILE)
                    type.isVolatile = true;
                continue;
            case Q_MOC_COMPAT_TOKEN:
            case Q_QT3_SUPPORT_TOKEN:
            case Q_INVOKABLE_TOKEN:
            case Q_SCRIPTABLE_TOKEN:
            case Q_SIGNALS_TOKEN:
            case Q_SLOTS_TOKEN:
            case Q_SIGNAL_TOKEN:
            case Q_SLOT_TOKEN:
                type.name += lexem();
                return type;
            default:
                prev();
                break;
        }
        break;
    }
    test(ENUM) || test(CLASS) || test(STRUCT);
    for(;;) {
        switch (next()) {
        case IDENTIFIER:
            // void mySlot(unsigned myArg)
            if (hasSignedOrUnsigned) {
                prev();
                break;
            }
        case CHAR:
        case SHORT:
        case INT:
        case LONG:
            type.name += lexem();
            // preserve '[unsigned] long long', 'short int', 'long int', 'long double'
            if (test(LONG) || test(INT) || test(DOUBLE)) {
                type.name += ' ';
                prev();
                continue;
            }
            break;
        case FLOAT:
        case DOUBLE:
        case VOID:
        case BOOL:
            type.name += lexem();
            isVoid |= (lookup(0) == VOID);
            break;
        default:
            prev();
            ;
        }
        if (test(LANGLE)) {
            QByteArray templ = lexemUntil(RANGLE);
            for (int i = 0; i < templ.size(); ++i) {
                type.name += templ.at(i);
                if ((templ.at(i) == '<' && i < templ.size()-1 && templ.at(i+1) == ':')
                    || (templ.at(i) == '>' && i < templ.size()-1 && templ.at(i+1) == '>')) {
                    type.name += ' ';
                }
            }
        }
        if (test(SCOPE)) {
            type.name += lexem();
            type.isScoped = true;
        } else {
            break;
        }
    }
    while (test(CONST) || test(VOLATILE) || test(SIGNED) || test(UNSIGNED)
           || test(STAR) || test(AND) || test(ANDAND)) {
        type.name += ' ';
        type.name += lexem();
        if (lookup(0) == AND)
            type.referenceType = Type::Reference;
        else if (lookup(0) == ANDAND)
            type.referenceType = Type::RValueReference;
        else if (lookup(0) == STAR)
            type.referenceType = Type::Pointer;
    }
    // transform stupid things like 'const void' or 'void const' into 'void'
    if (isVoid && type.referenceType == Type::NoReference) {
        type.name = "void";
    }
    return type;
}
Exemple #17
0
QList<QNetworkCookie> QNetworkCookiePrivate::parseSetCookieHeaderLine(const QByteArray &cookieString)
{
    // According to http://wp.netscape.com/newsref/std/cookie_spec.html,<
    // the Set-Cookie response header is of the format:
    //
    //   Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
    //
    // where only the NAME=VALUE part is mandatory
    //
    // We do not support RFC 2965 Set-Cookie2-style cookies

    QList<QNetworkCookie> result;
    QDateTime now = QDateTime::currentDateTime().toUTC();

    int position = 0;
    const int length = cookieString.length();
    while (position < length) {
        QNetworkCookie cookie;

        // The first part is always the "NAME=VALUE" part
        QPair<QByteArray,QByteArray> field = nextField(cookieString, position, true);
        if (field.first.isEmpty() || field.second.isNull())
            // parsing error
            break;
        cookie.setName(field.first);
        cookie.setValue(field.second);

        position = nextNonWhitespace(cookieString, position);
        while (position < length) {
            switch (cookieString.at(position++)) {
            case ';':
                // new field in the cookie
                field = nextField(cookieString, position, false);
                field.first = field.first.toLower(); // everything but the NAME=VALUE is case-insensitive

                if (field.first == "expires") {
                    position -= field.second.length();
                    int end;
                    for (end = position; end < length; ++end)
                        if (isValueSeparator(cookieString.at(end)))
                            break;

                    QByteArray dateString = cookieString.mid(position, end - position).trimmed();
                    position = end;
                    QDateTime dt = parseDateString(dateString.toLower());
                    if (!dt.isValid()) {
                        return result;
                    }
                    cookie.setExpirationDate(dt);
                } else if (field.first == "domain") {
                    QByteArray rawDomain = field.second;
                    QString maybeLeadingDot;
                    if (rawDomain.startsWith('.')) {
                        maybeLeadingDot = QLatin1Char('.');
                        rawDomain = rawDomain.mid(1);
                    }

                    QString normalizedDomain = QUrl::fromAce(QUrl::toAce(QString::fromUtf8(rawDomain)));
                    if (normalizedDomain.isEmpty() && !rawDomain.isEmpty())
                        return result;
                    cookie.setDomain(maybeLeadingDot + normalizedDomain);
                } else if (field.first == "max-age") {
                    bool ok = false;
                    int secs = field.second.toInt(&ok);
                    if (!ok)
                        return result;
                    cookie.setExpirationDate(now.addSecs(secs));
                } else if (field.first == "path") {
                    QString path = QUrl::fromPercentEncoding(field.second);
                    cookie.setPath(path);
                } else if (field.first == "secure") {
                    cookie.setSecure(true);
                } else if (field.first == "httponly") {
                    cookie.setHttpOnly(true);
                } else if (field.first == "comment") {
                    //cookie.setComment(QString::fromUtf8(field.second));
                } else if (field.first == "version") {
                    if (field.second != "1") {
                        // oops, we don't know how to handle this cookie
                        return result;
                    }
                } else {
                    // got an unknown field in the cookie
                    // what do we do?
                }

                position = nextNonWhitespace(cookieString, position);
            }
        }

        if (!cookie.name().isEmpty())
            result += cookie;
    }

    return result;
}
Exemple #18
0
void PacketsSplitter::addReadedBytes(const QByteArray &bytes)
{
#ifdef DEBUG0
    qDebug() << "!!\n!!" << bytes.toHex() << "!!\n!!";
#endif
    switch (m_byteIndex) {
    case 0:
    case 1:
        if(bytes.at(0) == 0xFF - 0x100) {
            ++m_byteIndex;
            m_packet.append(bytes);
        } else {
            m_byteIndex = 0;
            m_packet.clear();
        }
        break;
    case 2:
        if(bytes.at(0) == 0x16) {
            ++m_byteIndex;
            m_packet.append(bytes);
        } else {
            m_byteIndex = 0;
            m_packet.clear();
        }
        break;
    case 3:
        ++m_byteIndex;
        m_packetLength = bytes.at(0);
        m_packet.append(bytes);
        break;
    case 4:
        if(bytes.at(0) == 0x04) {
            ++m_byteIndex;
            m_packet.append(bytes);
        } else {
            m_byteIndex = 0;
            m_packet.clear();
        }
        break;
    default:
        if(m_byteIndex == m_packetLength - 1) {
#ifdef DEBUG0
            qDebug() << QString("pas #%1").arg(QString::number(m_byteIndex));
#endif
            m_byteIndex = 0;
            m_packet.append(bytes);
            char checkSum = 0;
            for(int i = 0; i < m_packetLength - 1; ++i) {
                checkSum += m_packet.at(i);
            }
#ifdef DEBUG
            qDebug() << "Calculated checksum:" << (int)checkSum;
            qDebug() << "Received checksum:" << (int)m_packet.at(m_packetLength - 1);
#endif
            if(checkSum == m_packet.at(m_packetLength - 1)) {
#ifdef DEBUG
                qDebug() << "Readed packet" << m_packet.toHex().toUpper();
#endif                
                emit packetIsReaded(true);
                emit readedPacket(m_packet);
            } else {
                emit packetIsReaded(false);
            }
            m_packet.clear();
            m_packetLength = 0;
        } else {
#ifdef DEBUG0
            qDebug() << QString("pas #%1").arg(QString::number(m_byteIndex));
#endif
            ++m_byteIndex;
            m_packet.append(bytes);
        }
        break;
    }
}
void QWSDirectPainterSurface::setPermanentState(const QByteArray &ba)
{
    if (ba.size() > 0 && ba.at(0) == 'r')
        setReserved();
    setSurfaceFlags(surfaceFlags() | Opaque);
}
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);
}
bool DataBus::GetClientMethodInfoResponsePacket::parse(const Packet &packet,
                                                       MethodInfo *methodInfo,
                                                       quint8 *noOfParameters,
                                                       quint8 *noOfReturnValues)
{
    // Check parameters
    if ((packet.getSource() == 0) ||
        (packet.getPacketType() != PacketType_GetClientMethodInfoResponse) ||
        (methodInfo == 0) ||
        (noOfParameters == 0) ||
        (noOfReturnValues == 0))
    {
        // Error, invalid parameters
        return false;
    }

    // Get data
    QByteArray data = packet.getData();

    if (data.size() < 4)
    {
        // Error, invalid size
        return false;
    }

    // Get Method ID
    quint8 id = static_cast<quint8>(data.at(0));

    // Get Property Name
    QString name;

    if (Value::fromBinary(data, &name, 1) == false)
    {
        // Error, failed to get Name
        return false;
    }

    int nameSize = name.toUtf8().size();

    if (nameSize > STRING_MAX_LENGTH)
    {
        // Error, name is too long
        return false;
    }

    if (data.size() != (nameSize + 4))
    {
        // Error, invalid size
        return false;
    }

    // Get No of parameters
    quint8 parameterCount = static_cast<quint8>(data.at(nameSize + 2));

    // Get No of return values
    quint8 returnValueCount = static_cast<quint8>(data.at(nameSize + 3));

    // Save values
    methodInfo->setId(id);
    methodInfo->setName(name);
    *noOfParameters = parameterCount;
    *noOfReturnValues = returnValueCount;

    // Success
    return true;
}
Exemple #22
0
void WebSocketWorker::ProcessFrames(QTcpSocket *socket)
{
    while (m_isRunning && socket && socket->bytesAvailable() >= 2) // No header? Return and wait for more
    {
        uint8_t headerSize = 2; // Smallest possible header size is 2 bytes, greatest is 14 bytes

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

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

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

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

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

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

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

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

                m_errorCount++;

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

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

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

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

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

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

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

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

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

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

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

                m_readFrame.payload.append(frame.payload);

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

        frame.reset();
    }
}
Exemple #23
0
bool decompress0x11(const QByteArray& input, QByteArray& output, 
    quint16 width, quint16 height, Page* page, QTextStream& err)
{
    quint32 lastOccur, bandSize, idx=4, w=0;
    short occurTable[0x40];
    QByteArray data;

    // Check the size
    if (input.size() < 0x40*2 + 4) {
        err << _("Algo0x11: bad band size") << endl;
        return false;
    }

    // Prepare the band buffer
    bandSize = (width * height + 7) >> 3;
    data.fill(0xff, bandSize);

    // Extract the header data and the occurrence table
    lastOccur = page->read32(input, 0);
    for (unsigned int i=0; i < 0x40; i++)
        occurTable[i] = ~page->read16(input, idx + i*2);
    idx += 0x40 * 2;

    // Extract the first uncompressed data
    if (input.size() <= idx + lastOccur) {
        err << _("Algo0x11: invalid band size") << endl;
        return false;
    }
    for (w=0; w < lastOccur; w++)
        data[w] = page->read8(input, idx + w);
    idx += lastOccur;

    // Decompress the other data
    while (input.size() > idx) {
        quint8 counter = page->read8(input, idx++);

        // Compressed
        if (counter & 0x80) {
            quint8 number = page->read8(input, idx++);
            quint32 toRead, ref;

            toRead = ((number & 0xC0) << 1) + (counter & 0x7F) + 3;
            number = number & ~0xC0;
            ref = w + 1;
            for (unsigned int i=0; i < toRead; i++, w++)
                data[w] = data.at(ref + occurTable[number] + i);

        // Uncompressed
        } else {
            for (unsigned int i = 0; i <= counter; i++, w++)
                data[w] = page->read8(input, idx++);
        }
    }

    // Rotate the data
    output.fill(0, bandSize);
    for (unsigned int i = 0; i < bandSize; i++) {
        uint32_t x, y;

        x = i / height;
        y = i % height;
        output[x + y * (width / 8)] = ~data[i];
    }

    return true;
}
void DeviceRS232Rubin201::onDataAvailable()
{
        reqtimer->stop();
        QByteArray qb = port->readAll();


        //displaying everything came to console
        QString txt = "<";


               for (int i=0; i<qb.size(); i++)
               {
                   txt.append(QString(" 0x").append( QString::number(qb.at(i),16 )).append("\n") );

               }

            //

        for (int i=0; i<qb.size(); i++)
        {
            buffer.append (qb.at(i));

            if (qb.at(i)==0xffffffffffffff82) //пришла команда на измерение
            {
                buffer.clear();
                buffer.append(0xffffffffffffff82);
            }



        }

        if ( (buffer.size()>2)&& (buffer.at(0)==0xffffffffffffff82)  ) //можно пробовать нечто интерпретировать
       {
            if (waitingForConnect)
            {
             setConnectedState(1);
             //waitingForConnect=0; //при этом закомментированном начинает работать нормально!
             return;
            }




            //int t = buffer.at(1)<<8 + buffer.at(2);
            unsigned char high =  (unsigned char ) buffer.at(1);
            unsigned char low=  (unsigned char ) buffer.at(2);
            int  t = high;
            t= t <<8;
            t+=low;

            double result = t;
            result/=100;
            result*=buffer.at(3)?-1:1;

       /*     ms ("result");
            ms (QString::number(result).append(buffer.at(4)?" дБ":" дБм") );
            ms ("\n\n");
*/

            //devman->acceptMeausure(result, id, buffer.at(4));




            fireMeasurementData(id,result, QString::number(buffer.at(4)));


            //1 - dB    0 - dBm - that's about last parameter


            buffer.clear();




        }




}
void IoInterface::printMessageInfo(QByteArray message)
{
    qDebug() << "printMessageInfo";
    QString temp;

    // 0x00 <TV> 0x01 <Refrigerator> 0x02 <Light> 0x03 <Heater> 0x04 <Cooler>
    char deviceType = (message.at(0) & 0xff);
    switch(deviceType)
    {
        case 0x00:
            qDebug() << "Device <TV>";
        break;
        case 0x01:
            qDebug() << "Device <Refrigerator>";
        break;
        case 0x02:
            qDebug() << "Device <Light>";
        break;
        case 0x03:
            qDebug() << "Device <Heater>";
        break;
        case 0x04:
            qDebug() << "Device <Cooler>";
        break;
        default:
        break;
    }

    // 0x00 <broadcast> 0x40 <set> 0x80 <get> 0xC0 <res for get>
    char operationType = (message.at(1) & 0xf0);
    switch(operationType)
    {
        case 0x00:
            qDebug() << "operation <broadcast>";
        break;
        case 0x40:
            qDebug() << "operation <set>";
        break;
        case 0x80:
            qDebug() << "operation <get>";
        break;
        case 0xc0:
            qDebug() << "operation <res for get>";
        break;
        default:
        break;
    }

    char operation = message.at(1) & 0x0F;

    // 0x00, 0x01, 0x02, 0x03
    switch(operation)
    {
        case 0x00:
            qDebug() << "ATTR_0";
        break;
        case 0x01:
            qDebug() << "ATTR_1";
        break;
        case 0x02:
            qDebug() << "ATTR_2";
        break;
        case 0x03:
            qDebug() << "ATTR_3";
        break;
        default:
        break;
    }

    char operand = message.at(2) & 0xff;
    qDebug() << operand;

}
Exemple #26
0
/**
 * Converts a byte array to a char array
 * @param src Byte array
 * @param dest Char array
 */
void AES::qByteArrayToUCharArray(QByteArray src, unsigned char *dest) {
    for (int i = 0; i < src.size(); i++) {
        dest[i] = src.at(i);
    }
}
/*!
*  Traitement des messages valides en provenance du XBEE
*  Refirige les données vers le decodeur du messenger
*/
void CXbeeNetworkMessenger::Xbee_readyBytes(QByteArray data, unsigned short src_addr)
{
    for (int i=0; i<data.size(); i++) {
        m_xbee_messenger.decode(data.at(i), src_addr);
    }
}
Exemple #28
0
bool Dorade::copyField(const QString& oldFieldName, const QString& newFieldName,
					   const QString& newFieldDesc, const QString& newFieldUnits)
{

	// Copy a field over and rename it
	int oldIndex = -1;
	int newIndex = rptr->num_param_desc;

	for (int j=0; j<(rptr->num_param_desc); j++) {
		QString fieldName = pptr[j].parm_name;
		if (fieldName.size() > 8) fieldName.resize(8);
		fieldName.remove(QRegExp("[\\s+]"));
		if (oldFieldName == fieldName) {
			// Match
			oldIndex = j;
			break;
		}
	}
	if ((oldIndex < 0) or (oldIndex > newIndex)) {
		// No match
		return false;
	}

	// Increment rptr & sswb
	rptr->num_param_desc++;
	ssptr->num_params++;

	// Copy parm info, rename it
	pptr[newIndex] = pptr[oldIndex];
	memset(pptr[newIndex].parm_name,' ',8);
	for (int c=0; c < 8; c++) {
		if (c < newFieldName.size()) {
			QByteArray ba = newFieldName.toLocal8Bit();
			pptr[newIndex].parm_name[c] = ba.at(c);
		}
	}
	memset(pptr[newIndex].parm_desc,' ',40);
	for (int c=0; c < 40; c++) {
		if (c < newFieldDesc.size()) {
			QByteArray ba = newFieldDesc.toLocal8Bit();
			pptr[newIndex].parm_desc[c] = ba.at(c);
		}
	}
	memset(pptr[newIndex].parm_unit,' ',8);
	for (int c=0; c < 8; c++) {
		if (c < newFieldUnits.size()) {
			QByteArray ba = newFieldUnits.toLocal8Bit();
			pptr[newIndex].parm_unit[c] = ba.at(c);
		}
	}
	// Copy the RDAT blocks
	for (int i=0; i<(sptr->num_rays); i++) {
		dptr[newIndex][i] = dptr[oldIndex][i];
		memset(dptr[newIndex][i].parm_name,' ',8);
		for (int c=0; c < 8; c++) {
			if (c < newFieldName.size()) {
				QByteArray ba = newFieldName.toLocal8Bit();
				dptr[newIndex][i].parm_name[c] = ba.at(c);
			}
		}
	}

	return true;
}
// ### move this to qnetworkcookie_p.h and share with qnetworkaccesshttpbackend
static QPair<QByteArray, QByteArray> nextField(const QByteArray &text, int &position, bool isNameValue)
{
    // format is one of:
    //    (1)  token
    //    (2)  token = token
    //    (3)  token = quoted-string
    int i;
    const int length = text.length();
    position = nextNonWhitespace(text, position);

    // parse the first part, before the equal sign
    for (i = position; i < length; ++i) {
        register char c = text.at(i);
        if (c == ';' || c == ',' || c == '=')
            break;
    }

    QByteArray first = text.mid(position, i - position).trimmed();
    position = i;

    if (first.isEmpty())
        return qMakePair(QByteArray(), QByteArray());
    if (i == length || text.at(i) != '=')
        // no equal sign, we found format (1)
        return qMakePair(first, QByteArray());

    QByteArray second;
    second.reserve(32);         // arbitrary but works for most cases

    i = nextNonWhitespace(text, position + 1);
    if (i < length && text.at(i) == '"') {
        // a quote, we found format (3), where:
        // quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
        // qdtext         = <any TEXT except <">>
        // quoted-pair    = "\" CHAR

        // If its NAME=VALUE, retain the value as is
        // refer to ttp://bugreports.qt.nokia.com/browse/QTBUG-17746
        if (isNameValue)
            second += '"';
        ++i;
        while (i < length) {
            register char c = text.at(i);
            if (c == '"') {
                // end of quoted text
                if (isNameValue)
                    second += '"';
                break;
            } else if (c == '\\') {
                if (isNameValue)
                    second += '\\';
                ++i;
                if (i >= length)
                    // broken line
                    return qMakePair(QByteArray(), QByteArray());
                c = text.at(i);
            }

            second += c;
            ++i;
        }

        for ( ; i < length; ++i) {
            register char c = text.at(i);
            if (c == ',' || c == ';')
                break;
        }
        position = i;
    } else {
        // no quote, we found format (2)
        position = i;
        for ( ; i < length; ++i) {
            register char c = text.at(i);
            if (c == ',' || c == ';' || isLWS(c))
                break;
        }

        second = text.mid(position, i - position).trimmed();
        position = i;
    }

    if (second.isNull())
        second.resize(0); // turns into empty-but-not-null
    return qMakePair(first, second);
}
void wrapInFunction()
{

//! [0]
QByteArray ba("Hello");
//! [0]


//! [1]
QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
//! [1]


//! [2]
for (int i = 0; i < ba.size(); ++i) {
    if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
        cout << "Found character in range [a-f]" << endl;
}
//! [2]


//! [3]
QByteArray x("and");
x.prepend("rock ");         // x == "rock and"
x.append(" roll");          // x == "rock and roll"
x.replace(5, 3, "&");       // x == "rock & roll"
//! [3]


//! [4]
QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
    cout << "Found <b> tag at index position " << j << endl;
    ++j;
}
//! [4]


//! [5]
QByteArray().isNull();          // returns true
QByteArray().isEmpty();         // returns true

QByteArray("").isNull();        // returns false
QByteArray("").isEmpty();       // returns true

QByteArray("abc").isNull();     // returns false
QByteArray("abc").isEmpty();    // returns false
//! [5]


//! [6]
QByteArray ba("Hello");
int n = ba.size();          // n == 5
ba.data()[0];               // returns 'H'
ba.data()[4];               // returns 'o'
ba.data()[5];               // returns '\0'
//! [6]


//! [7]
QByteArray().isEmpty();         // returns true
QByteArray("").isEmpty();       // returns true
QByteArray("abc").isEmpty();    // returns false
//! [7]


//! [8]
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
    cout << "[" << *data << "]" << endl;
    ++data;
}
//! [8]


//! [9]
QByteArray ba;
for (int i = 0; i < 10; ++i)
    ba[i] = 'A' + i;
// ba == "ABCDEFGHIJ"
//! [9]


//! [10]
QByteArray ba("Stockholm");
ba.truncate(5);             // ba == "Stock"
//! [10]


//! [11]
QByteArray ba("STARTTLS\r\n");
ba.chop(2);                 // ba == "STARTTLS"
//! [11]


//! [12]
QByteArray x("free");
QByteArray y("dom");
x += y;
// x == "freedom"
//! [12]


//! [13]
QByteArray().isNull();          // returns true
QByteArray("").isNull();        // returns false
QByteArray("abc").isNull();     // returns false
//! [13]


//! [14]
QByteArray ba("Istambul");
ba.fill('o');
// ba == "oooooooo"

ba.fill('X', 2);
// ba == "XX"
//! [14]


//! [15]
QByteArray x("ship");
QByteArray y("air");
x.prepend(y);
// x == "airship"
//! [15]


//! [16]
QByteArray x("free");
QByteArray y("dom");
x.append(y);
// x == "freedom"
//! [16]


//! [17]
QByteArray ba("Meal");
ba.insert(1, QByteArray("ontr"));
// ba == "Montreal"
//! [17]


//! [18]
QByteArray ba("Montreal");
ba.remove(1, 4);
// ba == "Meal"
//! [18]


//! [19]
QByteArray x("Say yes!");
QByteArray y("no");
x.replace(4, 3, y);
// x == "Say no!"
//! [19]


//! [20]
QByteArray ba("colour behaviour flavour neighbour");
ba.replace(QByteArray("ou"), QByteArray("o"));
// ba == "color behavior flavor neighbor"
//! [20]


//! [21]
QByteArray x("sticky question");
QByteArray y("sti");
x.indexOf(y);               // returns 0
x.indexOf(y, 1);            // returns 10
x.indexOf(y, 10);           // returns 10
x.indexOf(y, 11);           // returns -1
//! [21]


//! [22]
QByteArray ba("ABCBA");
ba.indexOf("B");            // returns 1
ba.indexOf("B", 1);         // returns 1
ba.indexOf("B", 2);         // returns 3
ba.indexOf("X");            // returns -1
//! [22]


//! [23]
QByteArray x("crazy azimuths");
QByteArray y("az");
x.lastIndexOf(y);           // returns 6
x.lastIndexOf(y, 6);        // returns 6
x.lastIndexOf(y, 5);        // returns 2
x.lastIndexOf(y, 1);        // returns -1
//! [23]


//! [24]
QByteArray ba("ABCBA");
ba.lastIndexOf("B");        // returns 3
ba.lastIndexOf("B", 3);     // returns 3
ba.lastIndexOf("B", 2);     // returns 1
ba.lastIndexOf("X");        // returns -1
//! [24]


//! [25]
QByteArray url("ftp://ftp.qt-project.org/");
if (url.startsWith("ftp:"))
    ...
//! [25]


//! [26]
QByteArray url("http://qt-project.org/doc/qt-5.0/qtdoc/index.html");
if (url.endsWith(".html"))
    ...
//! [26]


//! [27]
QByteArray x("Pineapple");
QByteArray y = x.left(4);
// y == "Pine"
//! [27]


//! [28]
QByteArray x("Pineapple");
QByteArray y = x.right(5);
// y == "apple"
//! [28]


//! [29]
QByteArray x("Five pineapples");
QByteArray y = x.mid(5, 4);     // y == "pine"
QByteArray z = x.mid(5);        // z == "pineapples"
//! [29]


//! [30]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toLower();
// y == "qt by digia"
//! [30]


//! [31]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toUpper();
// y == "QT BY DIGIA"
//! [31]


//! [32]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.simplified();
// ba == "lots of whitespace";
//! [32]


//! [33]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.trimmed();
// ba == "lots\t of\nwhitespace";
//! [33]


//! [34]
QByteArray x("apple");
QByteArray y = x.leftJustified(8, '.');   // y == "apple..."
//! [34]


//! [35]
QByteArray x("apple");
QByteArray y = x.rightJustified(8, '.');    // y == "...apple"
//! [35]


//! [36]
QByteArray str("FF");
bool ok;
int hex = str.toInt(&ok, 16);     // hex == 255, ok == true
int dec = str.toInt(&ok, 10);     // dec == 0, ok == false
//! [36]


//! [37]
QByteArray str("FF");
bool ok;
long hex = str.toLong(&ok, 16);   // hex == 255, ok == true
long dec = str.toLong(&ok, 10);   // dec == 0, ok == false
//! [37]


//! [38]
QByteArray string("1234.56");
double a = string.toDouble();   // a == 1234.56
//! [38]


//! [39]
QByteArray text("Qt is great!");
text.toBase64();        // returns "UXQgaXMgZ3JlYXQh"
//! [39]

//! [39bis]
QByteArray text("<p>Hello?</p>");
text.toBase64(QByteArray::Base64 | QByteArray::OmitTrailingEquals);      // returns "PHA+SGVsbG8/PC9wPg"
text.toBase64(QByteArray::Base64);                                       // returns "PHA+SGVsbG8/PC9wPg=="
text.toBase64(QByteArray::Base64Url);                                    // returns "PHA-SGVsbG8_PC9wPg=="
text.toBase64(QByteArray::Base64Url | QByteArray::OmitTrailingEquals);   // returns "PHA-SGVsbG8_PC9wPg"
//! [39bis]


//! [40]
QByteArray ba;
int n = 63;
ba.setNum(n);           // ba == "63"
ba.setNum(n, 16);       // ba == "3f"
//! [40]


//! [41]
int n = 63;
QByteArray::number(n);              // returns "63"
QByteArray::number(n, 16);          // returns "3f"
QByteArray::number(n, 16).toUpper();  // returns "3F"
//! [41]


//! [42]
QByteArray ba = QByteArray::number(12.3456, 'E', 3);
// ba == 1.235E+01
//! [42]


//! [43]
 static const char mydata[] = {
    0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
    0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
    ...
    0x6d, 0x5b
};

QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
QDataStream in(&data, QIODevice::ReadOnly);
...
//! [43]


//! [44]
QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
text.data();            // returns "Qt is great!"
//! [44]

//! [44bis]
QByteArray::fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray::Base64Encoding); // returns "<p>Hello?</p>"
QByteArray::fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray::Base64UrlEncoding); // returns "<p>Hello?</p>"
//! [44bis]


//! [45]
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data();            // returns "Qt is great!"
//! [45]

//! [46]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size()];
strcpy(data, text.data());
delete [] data;
//! [46]

//! [47]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size() + 1];
strcpy(data, text.data());
delete [] data;
//! [47]

//! [48]
QByteArray ba1("ca\0r\0t");
ba1.size();                     // Returns 2.
ba1.constData();                // Returns "ca" with terminating \0.

QByteArray ba2("ca\0r\0t", 3);
ba2.size();                     // Returns 3.
ba2.constData();                // Returns "ca\0" with terminating \0.

QByteArray ba3("ca\0r\0t", 4);
ba3.size();                     // Returns 4.
ba3.constData();                // Returns "ca\0r" with terminating \0.

const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
QByteArray ba4(QByteArray::fromRawData(cart, 6));
ba4.size();                     // Returns 6.
ba4.constData();                // Returns "ca\0r\0t" without terminating \0.
//! [48]

}