Esempio n. 1
0
void ServerController::socketReadyRead()
{
    switch (m_connectionType) {
    case StreamConnection:
        while (m_socket->canReadLine()) {
            const QByteArray line = m_socket->readLine().trimmed();

            qDebug() << "Server read line:" << line;

            QByteArray command;
            QByteArray parameter;

            int index = line.indexOf(' ');
            if (index >= 0) {
                command = line.left(index);
                parameter = line.mid(index + 1);
            } else {
                command = line;
            }

            if (command == "ECHO") {
                m_socket->write(parameter + '\n');
            } else if (command == "DISCONNECT") {
                m_socket->disconnectFromService();
                break;
            } else if (command == "CLOSE") {
                m_socket->close();
                break;
            } else if (command == "URI") {
                m_socket->write(m_service.toLatin1());
                m_socket->write("\n");
            }
        }
        break;
    case DatagramConnection:
        while (m_socket->hasPendingDatagrams()) {
            qint64 size = m_socket->pendingDatagramSize();
            QByteArray data;
            data.resize(size);
            m_socket->readDatagram(data.data(), data.size());

            QByteArray command;
            QByteArray parameter;

            int index = data.indexOf(' ');
            if (index >= 0) {
                command = data.left(index);
                parameter = data.mid(index + 1);
            } else {
                command = data;
            }

            if (command == "ECHO") {
                m_socket->writeDatagram(parameter);
            } else if (command == "DISCONNECT") {
                m_socket->disconnectFromService();
                break;
            } else if (command == "CLOSE") {
                m_socket->close();
                break;
            } else if (command == "URI") {
                m_socket->writeDatagram(m_service.toLatin1());
            }
        }
        break;
    }
}
Esempio n. 2
0
void Widget::tcpProcessData(QByteArray data, QTcpSocket* socket)
{
    QByteArray* recvBuffer=nullptr;
    for (auto pair : tcpClientsList)
    {
        if (pair.first == socket)
        {
            recvBuffer = pair.second;
            break;
        }
    }
    if (recvBuffer == nullptr)
    {
        logError(tr("TCP: Error fetching the socket's associated recv buffer"));
        return;
    }

#if DEBUG_LOG
    logMessage("tcpProcessData received : "+data);
#endif

    // Login request (forwarded)
    if (useRemoteLogin && recvBuffer->contains("commfunction=login&") && recvBuffer->contains("&version="))
    {
        logError(tr("TCP: Remote login not implemented yet."));
        // We need to add the client with his IP/port/passhash to tcpPlayers if he isn't already there
        Player newPlayer;
        newPlayer.IP = socket->peerAddress().toIPv4Address();
        newPlayer.port = socket->peerPort();
        QString passhash = QString(*recvBuffer);
        passhash = passhash.mid(passhash.indexOf("passhash=")+9);
        passhash.truncate(passhash.indexOf('&'));
        newPlayer.passhash = passhash;
        logMessage(tr("IP:","IP address")+newPlayer.IP
                   +tr(", passhash:","A cryptographic hash of a password")+newPlayer.passhash);

        // Then connect to the remote and forward the client's requests
        if (!remoteLoginSock.isOpen())
        {
            remoteLoginSock.connectToHost(remoteLoginIP, remoteLoginPort);
            remoteLoginSock.waitForConnected(remoteLoginTimeout);
            if (!remoteLoginSock.isOpen())
            {
                logError(tr("TCP: Can't connect to remote login server : timed out"));
                return;
            }
        }
        // We just blindly send everything that we're going to remove from recvBuffer at the end of tcpProcessData
        QByteArray toSend = *recvBuffer;
        toSend.left(toSend.indexOf(data) + data.size());
        remoteLoginSock.write(toSend);
    }
    else if (useRemoteLogin && recvBuffer->contains("Server:")) // Login reply (forwarded)
    {
        logError(tr("TCP: Remote login not implemented yet."));
        // First we need to find a player matching the received passhash in tcpPlayers
        // Use the player's IP/port to find a matching socket in tcpClientsList
        // The login headers are all the same, so we can just use loginHeader.bin and send back data
    }
    else if (recvBuffer->contains("commfunction=login&") && recvBuffer->contains("&version=")) // Login request
    {
        QString postData = QString(*recvBuffer);
        *recvBuffer = recvBuffer->right(postData.size()-postData.indexOf("version=")-8-4); // 4 : size of version number (ie:version=1344)
        logMessage(tr("TCP: Login request received :"));
        QFile file(QString(NETDATAPATH)+"/loginHeader.bin");
        QFile fileServersList(SERVERSLISTFILEPATH);
        QFile fileBadPassword(QString(NETDATAPATH)+"/loginWrongPassword.bin");
        QFile fileMaxRegistration(QString(NETDATAPATH)+"/loginMaxRegistered.bin");
        if (!file.open(QIODevice::ReadOnly) || !fileBadPassword.open(QIODevice::ReadOnly)
        || !fileMaxRegistration.open(QIODevice::ReadOnly) || !fileServersList.open(QIODevice::ReadOnly))
        {
            logError(tr("TCP: Error reading data files"));
            stopServer();
        }
        else
        {
            logMessage(tr("Version : ","Version of the client software")
                           +postData.mid(postData.indexOf("version=")+8));
            bool ok=true;
            postData = postData.right(postData.size()-postData.indexOf("username="******"passhash=")-9);
            QString passhash = postData;
            passhash.truncate(postData.indexOf('&'));
            logMessage(tr("IP : ","An IP address")+socket->peerAddress().toString());
            logMessage(tr("Username : "******"Passhash : ","A cryptographic hash of a password")+passhash);

            // Add player to the players list
            Player* player = Player::findPlayer(Player::tcpPlayers, username);
            if (player->name != username) // Not found, create a new player
            {
                // Check max registered number
                if (Player::tcpPlayers.size() >= maxRegistered)
                {
                    logError(tr("TCP: Registration failed, too many players registered"));
                    socket->write(fileMaxRegistration.readAll());
                    ok = false;
                }
                else
                {
                    logMessage(tr("TCP: Creating user %1 in database").arg(username));
                    Player* newPlayer = new Player;
                    newPlayer->name = username;
                    newPlayer->passhash = passhash;
                    newPlayer->IP = socket->peerAddress().toString();
                    newPlayer->connected = false; // The connection checks are done by the game servers

                    Player::tcpPlayers << newPlayer;
                    if (!Player::savePlayers(Player::tcpPlayers))
                        ok = false;
                }
            }
            else // Found, compare passhashes, check if already connected
            {
                if (player->passhash != passhash) // Bad password
                {
                    logMessage(tr("TCP: Login failed, wrong password"));
                    socket->write(fileBadPassword.readAll());
                    socket->close();
                    ok=false;
                }
                else // Good password
                {
                    player->IP = socket->peerAddress().toString();
                    player->lastPingTime = timestampNow();
                    player->connected = true;
                }
            }

            if (ok) // Send servers list
            {
                // HTTP reply template
                static const QByteArray data1 = QByteArray::fromHex("0D0A61757468726573706F6E73653A0A747275650A");
                static const QByteArray data2 = QByteArray::fromHex("0A310A");
                static const QByteArray data3 = QByteArray::fromHex("0D0A300D0A0D0A");

                QByteArray customData = file.readAll();
                QByteArray sesskey = QCryptographicHash::hash(QString(passhash + saltPassword).toLatin1(), QCryptographicHash::Md5).toHex();
#if DEBUG_LOG
                logMessage("TCP: Hash of '"+QString(passhash + saltPassword).toLatin1()+"' is '"+sesskey+"'");
                logMessage("TCP: Sesskey is '"+sesskey+"', passhash is '"+passhash+"', salt is '"+saltPassword+"'");
#endif
                sesskey += passhash;
                QByteArray serversList;
                QByteArray line;
                do {
                    line = fileServersList.readLine().trimmed();
                    serversList+=line;
                    serversList+=0x0A;
                } while (!line.isEmpty());
                serversList = serversList.trimmed();
                int dataSize = data1.size() + sesskey.size() + data2.size() + serversList.size() - 2;
                QString dataSizeStr = QString().setNum(dataSize, 16);

                customData += dataSizeStr;
                customData += data1;
                customData += sesskey;
                customData += data2;
                customData += serversList;
                customData += data3;

                logMessage(tr("TCP: Login successful, sending servers list"));
                socket->write(customData);
                socket->close();
            }
        }
    }
    else if (data.contains("commfunction=removesession"))
    {
#if DEBUG_LOG
        logMessage(tr("TCP: Session closed by client"));
#endif
    }
    else // Unknown request, erase tcp buffer
    {
        // Display data
        logError(tr("TCP: Unknown request received : "));
        logMessage(QString(data.data()));
    }
}
Esempio n. 3
0
void Message_Handler::parser(QByteArray data){
    QByteArray tmp;
    int digit = 1;
    int i=0;
    int sign=0;

    if(data.startsWith('{')){
        while(data.count() > 0){
            data.remove(0,data.indexOf('"')+1);
            tmp = data.left(data.indexOf('"'));
            data.remove(0,data.indexOf('"')+1);
            if(QString(tmp)=="MessageType"){
                data.remove(0,data.indexOf(':')+2);
                tmp = data.left(data.indexOf('"'));
                data.remove(0,data.indexOf(',')+1);
                if(QString(tmp)=="GetState")
                    msg.MessageType = 1;
                else if(QString(tmp)=="GetPID")
                    msg.MessageType = 2;
                else if(QString(tmp)=="SetPID")
                    msg.MessageType = 3;
                else if(QString(tmp)=="SetMainPower")
                    msg.MessageType = 4;
                else
                    msg.MessageType = 0;
            }
            else if(QString(tmp)=="KalmanXangle"){
                data.remove(0,data.indexOf(':')+1);
                msg.KalmanX = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.KalmanX*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.KalmanX += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
                msg.KalmanX /= 1000;
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="KalmanYangle"){
                data.remove(0,data.indexOf(':')+1);
                msg.KalmanY = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.KalmanY*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.KalmanY += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
                msg.KalmanY /= 1000;
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="Altitude"){
                data.remove(0,data.indexOf(':')+1);
                msg.Altitude = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.Altitude*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.Altitude += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
                msg.Altitude /= 1000;
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="Ki"){
                data.remove(0,data.indexOf(':')+1);
                msg.Ki = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.Ki*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.Ki += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="Kd"){
                data.remove(0,data.indexOf(':')+1);
                msg.Kd = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.Kd*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.Kd += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="Kp"){
                data.remove(0,data.indexOf(':')+1);
                msg.Kp = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.Kp*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.Kp += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="MotorState0"){
                data.remove(0,data.indexOf(':')+1);
                msg.MotorState0 = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.MotorState0*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.MotorState0 += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="MotorState1"){
                data.remove(0,data.indexOf(':')+1);
                msg.MotorState1 = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.MotorState1*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.MotorState1 += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="MotorState2"){
                data.remove(0,data.indexOf(':')+1);
                msg.MotorState2 = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.MotorState2*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.MotorState2 += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="MotorState3"){
                data.remove(0,data.indexOf(':')+1);
                msg.MotorState3 = 0;
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                digit = 1;
                for(i= sign;i>=0;i--)
                {
                    if(data[i]=='-') msg.MotorState3*=-1;
                    if(data[i] <='9' && data[i] >= '0')
                    {
                        msg.MotorState3 += digit * (data[i]-0x30);
                        digit *= 10;
                    }

                }
              data.remove(0,sign+1);
            }
            else if(QString(tmp)=="MainPowerStatus"){
                data.remove(0,data.indexOf(':')+2);
                tmp = data.left(data.indexOf('"'));
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                data.remove(0,sign+1);
                if(QString(tmp)=="true")
                    msg.MainPowerStatus = true;
                else if(QString(tmp)=="false")
                    msg.MainPowerStatus = false;
            }
            else if(QString(tmp)=="SetPIDSuccess"){
                data.remove(0,data.indexOf(':')+2);
                tmp = data.left(data.indexOf('"'));
                sign = data.indexOf(',');
                if(sign == -1) sign = data.indexOf('}');
                data.remove(0,sign+1);
                if(QString(tmp)=="true")
                    msg.SetPIDSuccess = true;
                else if(QString(tmp)=="false")
                    msg.SetPIDSuccess = false;
            }

        }







    }


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

    for (;;) {
        pos = skipWhitespace(header, pos);
        if (pos >= header.length())
            return result;

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

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

        key = header.mid(pos,  equal - pos).trimmed();
        pos = equal + 1;

        pos = skipWhitespace(header, pos);
        if (pos >= header.length())
            return result;

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

                value += c;
                ++pos;
            }
        } else {
            while (pos < header.length()) {
                char c = header.at(pos);
                if (c == ' ' || c == '\t' || c == '\r'
                    || c == '\n' || c == ';') {
                    break;
                }
                value += c;
                ++pos;
            }
        }

        result.insert(key, value);
    }
    return result;
}
Esempio n. 5
0
static QString generateInterfaceXml(const QMetaObject *mo, int flags, int methodOffset, int propOffset)
{
    QString retval;

    // start with properties:
    if (flags & (QDBusConnection::ExportScriptableProperties |
                 QDBusConnection::ExportNonScriptableProperties)) {
        for (int i = propOffset; i < mo->propertyCount(); ++i) {
            static const char *accessvalues[] = {0, "read", "write", "readwrite"};

            QMetaProperty mp = mo->property(i);

            if (!((mp.isScriptable() && (flags & QDBusConnection::ExportScriptableProperties)) ||
                  (!mp.isScriptable() && (flags & QDBusConnection::ExportNonScriptableProperties))))
                continue;

            int access = 0;
            if (mp.isReadable())
                access |= 1;
            if (mp.isWritable())
                access |= 2;

            int typeId = qDBusNameToTypeId(mp.typeName());
            if (!typeId)
                continue;
            const char *signature = QDBusMetaType::typeToSignature(typeId);
            if (!signature)
                continue;

            retval += QString::fromLatin1("    <property name=\"%1\" type=\"%2\" access=\"%3\"")
                      .arg(QLatin1String(mp.name()))
                      .arg(QLatin1String(signature))
                      .arg(QLatin1String(accessvalues[access]));

            if (QDBusMetaType::signatureToType(signature) == QVariant::Invalid) {
                const char *typeName = QVariant::typeToName(QVariant::Type(typeId));
                retval += QString::fromLatin1(">\n      <annotation name=\"com.trolltech.QtDBus.QtTypeName\" value=\"%3\"/>\n    </property>\n")
                          .arg(typeNameToXml(typeName));
            } else {
                retval += QLatin1String("/>\n");
            }
        }
    }

    // now add methods:
    for (int i = methodOffset; i < mo->methodCount(); ++i) {
        QMetaMethod mm = mo->method(i);
        QByteArray signature = mm.signature();
        int paren = signature.indexOf('(');

        bool isSignal;
        if (mm.methodType() == QMetaMethod::Signal)
            // adding a signal
            isSignal = true;
        else if (mm.methodType() == QMetaMethod::Slot && mm.access() == QMetaMethod::Public)
            isSignal = false;
        else
            continue;           // neither signal nor public slot

        if (isSignal && !(flags & (QDBusConnection::ExportScriptableSignals |
                                   QDBusConnection::ExportNonScriptableSignals)))
            continue;           // we're not exporting any signals
        if (!isSignal && !(flags & (QDBusConnection::ExportScriptableSlots |
                                    QDBusConnection::ExportNonScriptableSlots)))
            continue;           // we're not exporting any slots

        QString xml = QString::fromLatin1("    <%1 name=\"%2\">\n")
                      .arg(isSignal ? QLatin1String("signal") : QLatin1String("method"))
                      .arg(QLatin1String(signature.left(paren)));

        // check the return type first
        int typeId = qDBusNameToTypeId(mm.typeName());
        if (typeId) {
            const char *typeName = QDBusMetaType::typeToSignature(typeId);
            if (typeName) {
                xml += QString::fromLatin1("      <arg type=\"%1\" direction=\"out\"/>\n")
                       .arg(typeNameToXml(typeName));

                // do we need to describe this argument?
                if (QDBusMetaType::signatureToType(typeName) == QVariant::Invalid)
                    xml += QString::fromLatin1("      <annotation name=\"com.trolltech.QtDBus.QtTypeName.Out0\" value=\"%1\"/>\n")
                           .arg(typeNameToXml(mm.typeName()));
            } else
                continue;
        }
        else if (*mm.typeName())
            continue;           // wasn't a valid type

        QList<QByteArray> names = mm.parameterNames();
        QList<int> types;
        int inputCount = qDBusParametersForMethod(mm, types);
        if (inputCount == -1)
            continue;           // invalid form
        if (isSignal && inputCount + 1 != types.count())
            continue;           // signal with output arguments?
        if (isSignal && types.at(inputCount) == QDBusMetaTypeId::message)
            continue;           // signal with QDBusMessage argument?
        if (isSignal && mm.attributes() & QMetaMethod::Cloned)
            continue;           // cloned signal?

        int j;
        bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
        for (j = 1; j < types.count(); ++j) {
            // input parameter for a slot or output for a signal
            if (types.at(j) == QDBusMetaTypeId::message) {
                isScriptable = true;
                continue;
            }

            QString name;
            if (!names.at(j - 1).isEmpty())
                name = QString::fromLatin1("name=\"%1\" ").arg(QLatin1String(names.at(j - 1)));

            bool isOutput = isSignal || j > inputCount;

            const char *signature = QDBusMetaType::typeToSignature(types.at(j));
            xml += QString::fromLatin1("      <arg %1type=\"%2\" direction=\"%3\"/>\n")
                   .arg(name)
                   .arg(QLatin1String(signature))
                   .arg(isOutput ? QLatin1String("out") : QLatin1String("in"));

            // do we need to describe this argument?
            if (QDBusMetaType::signatureToType(signature) == QVariant::Invalid) {
                const char *typeName = QVariant::typeToName( QVariant::Type(types.at(j)) );
                xml += QString::fromLatin1("      <annotation name=\"com.trolltech.QtDBus.QtTypeName.%1%2\" value=\"%3\"/>\n")
                       .arg(isOutput ? QLatin1String("Out") : QLatin1String("In"))
                       .arg(isOutput && !isSignal ? j - inputCount : j - 1)
                       .arg(typeNameToXml(typeName));
            }
        }

        int wantedMask;
        if (isScriptable)
            wantedMask = isSignal ? QDBusConnection::ExportScriptableSignals
                                  : QDBusConnection::ExportScriptableSlots;
        else
            wantedMask = isSignal ? QDBusConnection::ExportNonScriptableSignals
                                  : QDBusConnection::ExportNonScriptableSlots;
        if ((flags & wantedMask) != wantedMask)
            continue;

        if (qDBusCheckAsyncTag(mm.tag()))
            // add the no-reply annotation
            xml += QLatin1String("      <annotation name=\"" ANNOTATION_NO_WAIT "\""
                                 " value=\"true\"/>\n");

        retval += xml;
        retval += QString::fromLatin1("    </%1>\n")
                  .arg(isSignal ? QLatin1String("signal") : QLatin1String("method"));
    }

    return retval;
}
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]

}
Esempio n. 7
0
VCard::List VCardParser::parseVCards( const QByteArray &text )
{
  VCard currentVCard;
  VCard::List vCardList;
  QByteArray currentLine;

  QList<QByteArray> lines = text.split( '\n' );

  bool inVCard = false;
  QList<QByteArray>::Iterator it( lines.begin() );
  QList<QByteArray>::Iterator linesEnd( lines.end() );
  for ( ; it != linesEnd; ++it ) {
    // remove the trailing \r, left from \r\n
    if ( ( *it ).endsWith( '\r' ) ) {
        ( *it ).chop( 1 );
    }

    if ( ( *it ).startsWith( ' ' ) ||
         ( *it ).startsWith( '\t' ) ) { //folded line => append to previous
      currentLine.append( ( *it ).mid( 1 ) );
      continue;
    } else {
      if ( ( *it ).trimmed().isEmpty() ) { // empty line
        continue;
      }
      if ( inVCard && !currentLine.isEmpty() ) { // now parse the line
        int colon = currentLine.indexOf( ':' );
        if ( colon == -1 ) { // invalid line
          currentLine = ( *it );
          continue;
        }

        VCardLine vCardLine;
        const QByteArray key = currentLine.left( colon ).trimmed();
        QByteArray value = currentLine.mid( colon + 1 );

        QList<QByteArray> params = key.split( ';' );

        // check for group
        int groupPos = params[ 0 ].indexOf( '.' );
        if ( groupPos != -1 ) {
          vCardLine.setGroup( QString::fromLatin1( params[ 0 ].left( groupPos ) ) );
          vCardLine.setIdentifier( QString::fromLatin1( params[ 0 ].mid( groupPos + 1 ) ) );
        } else {
          vCardLine.setIdentifier( QString::fromLatin1( params[ 0 ] ) );
        }

        if ( params.count() > 1 ) { // find all parameters
          QList<QByteArray>::ConstIterator paramIt( params.constBegin() );
          for ( ++paramIt; paramIt != params.constEnd(); ++paramIt ) {
            QList<QByteArray> pair = ( *paramIt ).split( '=' );
            if ( pair.count() == 1 ) {
              // correct the f*****g 2.1 'standard'
              if ( pair[ 0 ].toLower() == "quoted-printable" ) {
                pair[ 0 ] = "encoding";
                pair.append( "quoted-printable" );
              } else if ( pair[ 0 ].toLower() == "base64" ) {
                pair[ 0 ] = "encoding";
                pair.append( "base64" );
              } else {
                pair.prepend( "type" );
              }
            }
            if ( pair[ 1 ].indexOf( ',' ) != -1 ) { // parameter in type=x,y,z format
              const QList<QByteArray> args = pair[ 1 ].split( ',' );
              QList<QByteArray>::ConstIterator argIt;
              QList<QByteArray>::ConstIterator argEnd( args.constEnd() );
              for ( argIt = args.constBegin(); argIt != argEnd; ++argIt ) {
                vCardLine.addParameter( QString::fromLatin1( pair[ 0 ].toLower() ),
                                        QString::fromLatin1( *argIt ) );
              }
            } else {
              vCardLine.addParameter( QString::fromLatin1( pair[ 0 ].toLower() ),
                                      QString::fromLatin1( pair[ 1 ] ) );
            }
          }
        }

        removeEscapes( value );

        QByteArray output;
        bool wasBase64Encoded = false;

        if ( vCardLine.parameterList().contains( QLatin1String( "encoding" ) ) ) {
          const QString encoding = vCardLine.parameter( QLatin1String( "encoding" ) ).toLower();

          // have to decode the data
          if ( encoding == QLatin1String( "b" ) || encoding == QLatin1String( "base64" ) ) {
            output = QByteArray::fromBase64( value );
            wasBase64Encoded = true;
          }
          else if ( encoding == QLatin1String( "quoted-printable" ) ) {
            // join any qp-folded lines
            while ( value.endsWith( '=' ) && it != linesEnd ) {
              value.chop( 1 ); // remove the '='
              value.append( *it );
              ++it;
            }
            KCodecs::quotedPrintableDecode( value, output );
          } else if ( encoding == QLatin1String( "8bit" ) ) {
            output = value;
          } else {
            qDebug( "Unknown vcard encoding type!" );
          }
        } else {
          output = value;
        }

        if ( vCardLine.parameterList().contains( QLatin1String( "charset" ) ) ) {
          // have to convert the data
          QTextCodec *codec = QTextCodec::codecForName(
            vCardLine.parameter( QLatin1String( "charset" ) ).toLatin1() );
          if ( codec ) {
            vCardLine.setValue( codec->toUnicode( output ) );
          } else {
            vCardLine.setValue( QString::fromUtf8( output ) );
          }
        } else if ( wasBase64Encoded ) {
            vCardLine.setValue( output );
        } else {
            vCardLine.setValue( QString::fromUtf8( output ) );
        }

        currentVCard.addLine( vCardLine );
      }

      // we do not save the start and end tag as vcardline
      if ( ( *it ).toLower().startsWith( "begin:vcard" ) ) { //krazy:exclude=strings
        inVCard = true;
        currentLine.clear();
        currentVCard.clear(); // flush vcard
        continue;
      }

      if ( ( *it ).toLower().startsWith( "end:vcard" ) ) { //krazy:exclude=strings
        inVCard = false;
        vCardList.append( currentVCard );
        currentLine.clear();
        currentVCard.clear(); // flush vcard
        continue;
      }

      currentLine = ( *it );
    }
  }

  return vCardList;
}
Esempio n. 8
0
/*!
 * \reimp
 */
bool QxtHttpServerConnector::canParseRequest(const QByteArray& buffer)
{
    if (buffer.indexOf("\r\n\r\n") >= 0) return true; // 1.0+
    if (buffer.indexOf("\r\n") >= 0 && buffer.indexOf("HTTP/") == -1) return true; // 0.9
    return false;
}
// ### merge with nextField in cookiejar.cpp
static QHash<QByteArray, QByteArray> parseHttpOptionHeader(const QByteArray &header)
{
    // The HTTP header is of the form:
    // header          = #1(directives)
    // directives      = token | value-directive
    // value-directive = token "=" (token | quoted-string)
    QHash<QByteArray, QByteArray> result;

    int pos = 0;
    while (true) {
        // skip spaces
        pos = nextNonWhitespace(header, pos);
        if (pos == header.length())
            return result;      // end of parsing

        // pos points to a non-whitespace
        int comma = header.indexOf(',', pos);
        int equal = header.indexOf('=', pos);
        if (comma == pos || equal == pos)
            // huh? Broken header.
            return result;

        // The key name is delimited by either a comma, an equal sign or the end
        // of the header, whichever comes first
        int end = comma;
        if (end == -1)
            end = header.length();
        if (equal != -1 && end > equal)
            end = equal;        // equal sign comes before comma/end
        QByteArray key = QByteArray(header.constData() + pos, end - pos).trimmed().toLower();
        pos = end + 1;

        if (equal != -1) {
            // case: token "=" (token | quoted-string)
            // skip spaces
            pos = nextNonWhitespace(header, pos);
            if (pos == header.length())
                // huh? Broken header
                return result;

            QByteArray value;
            value.reserve(header.length() - pos);
            if (header.at(pos) == '"') {
                // case: quoted-string
                // quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
                // qdtext         = <any TEXT except <">>
                // quoted-pair    = "\" CHAR
                ++pos;
                while (pos < header.length()) {
                    register char c = header.at(pos);
                    if (c == '"') {
                        // end of quoted text
                        break;
                    } else if (c == '\\') {
                        ++pos;
                        if (pos >= header.length())
                            // broken header
                            return result;
                        c = header.at(pos);
                    }

                    value += c;
                    ++pos;
                }
            } else {
                // case: token
                while (pos < header.length()) {
                    register char c = header.at(pos);
                    if (isSeparator(c))
                        break;
                    value += c;
                    ++pos;
                }
            }

            result.insert(key, value);

            // find the comma now:
            comma = header.indexOf(',', pos);
            if (comma == -1)
                return result;  // end of parsing
            pos = comma + 1;
        } else {
            // case: token
            // key is already set
            result.insert(key, QByteArray());
        }
    }
}
Esempio n. 10
0
QString QHostInfo::localDomainName()
{
#if !defined(Q_OS_VXWORKS)
    resolveLibrary();
    if (local_res_ninit) {
        // using thread-safe version
        res_state_ptr state = res_state_ptr(qMalloc(sizeof(*state)));
        Q_CHECK_PTR(state);
        memset(state, 0, sizeof(*state));
        local_res_ninit(state);
        QString domainName = QUrl::fromAce(state->defdname);
        if (domainName.isEmpty())
            domainName = QUrl::fromAce(state->dnsrch[0]);
        local_res_nclose(state);
        qFree(state);

        return domainName;
    }

    if (local_res_init && local_res) {
        // using thread-unsafe version

#if defined(QT_NO_GETADDRINFO)
        // We have to call res_init to be sure that _res was initialized
        // So, for systems without getaddrinfo (which is thread-safe), we lock the mutex too
        QMutexLocker locker(::getHostByNameMutex());
#endif
        local_res_init();
        QString domainName = QUrl::fromAce(local_res->defdname);
        if (domainName.isEmpty())
            domainName = QUrl::fromAce(local_res->dnsrch[0]);
        return domainName;
    }
#endif
    // nothing worked, try doing it by ourselves:
    QFile resolvconf;
#if defined(_PATH_RESCONF)
    resolvconf.setFileName(QFile::decodeName(_PATH_RESCONF));
#else
    resolvconf.setFileName(QLatin1String("/etc/resolv.conf"));
#endif
    if (!resolvconf.open(QIODevice::ReadOnly))
        return QString();       // failure

    QString domainName;
    while (!resolvconf.atEnd()) {
        QByteArray line = resolvconf.readLine().trimmed();
        if (line.startsWith("domain "))
            return QUrl::fromAce(line.mid(sizeof "domain " - 1).trimmed());

        // in case there's no "domain" line, fall back to the first "search" entry
        if (domainName.isEmpty() && line.startsWith("search ")) {
            QByteArray searchDomain = line.mid(sizeof "search " - 1).trimmed();
            int pos = searchDomain.indexOf(' ');
            if (pos != -1)
                searchDomain.truncate(pos);
            domainName = QUrl::fromAce(searchDomain);
        }
    }

    // return the fallen-back-to searched domain
    return domainName;
}
Esempio n. 11
0
File: main.cpp Progetto: RSATom/Qt
QT_USE_NAMESPACE

int main(int argc, char **argv)
{
    if (FAILED(CoInitialize(0))) {
        qErrnoWarning("CoInitialize() failed.");
        return -1;
    }

    enum State {
        Default = 0,
            OutOption
    } state;
    state = Default;

    QByteArray outname;
    QByteArray object;

    for (int a = 1; a < argc; ++a) {
        QByteArray arg(argv[a]);
        const char first = arg[0];
        switch(state) {
        case Default:
            if (first == '-' || first == '/') {
                arg = arg.mid(1).toLower();
                if (arg == "o")
                    state = OutOption;
                else if (arg == "v") {
                    qWarning("dumpdoc: Version 1.0");
                    return 0;
                } else if (arg == "h") {
                    qWarning("dumpdoc Usage:\n\tdumpdoc object [-o <file>]"
                        "              \n\tobject   : object[/subobject]*"
                        "              \n\tsubobject: property\n"
                        "      \nexample:\n\tdumpdoc Outlook.Application/Session/CurrentUser -o outlook.html");
                    return 0;
                }
            } else {
                object = arg;
            }
            break;
        case OutOption:
            outname = arg;
            state = Default;
            break;

        default:
            break;
        }
    }

    if (object.isEmpty()) {
        qWarning("dumpdoc: No object name provided.\n"
            "         Use -h for help.");
        return -1;
    }
    QFile outfile;
    if (!outname.isEmpty()) {
        outfile.setFileName(QString::fromLatin1(outname.constData()));
        if (!outfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qWarning("dumpdoc: Could not open output file '%s'", outname.data());
        }
    } else {
        outfile.open(stdout, QIODevice::WriteOnly);
    }
    QTextStream out(&outfile);

    QByteArray subobject = object;
    int index = subobject.indexOf('/');
    if (index != -1)
        subobject.truncate(index);

    QAxObject topobject(QString::fromLatin1(subobject.constData()));

    if (topobject.isNull()) {
        qWarning("dumpdoc: Could not instantiate COM object '%s'", subobject.data());
        return -2;
    }

    QAxObject *axobject = &topobject;
    while (index != -1 && axobject) {
        index++;
        subobject = object.mid(index);
        if (object.indexOf('/', index) != -1) {
            int oldindex = index;
            index = object.indexOf('/', index);
            subobject = object.mid(oldindex, index-oldindex);
        } else {
            index = -1;
        }

        axobject = axobject->querySubObject(subobject);
    }
    if (!axobject || axobject->isNull()) {
        qWarning("dumpdoc: Subobject '%s' does not exist in '%s'", subobject.data(), object.data());
        return -3;
    }

    QString docu = axobject->generateDocumentation();
    out << docu;
    return 0;
}
Esempio n. 12
0
void HttpProxy::onSocketReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    QTcpSocket *proxySocket = nullptr;

    QByteArray reqData = socket->readAll();
    int pos = reqData.indexOf("\r\n");
    QByteArray reqLine = reqData.left(pos);
    reqData.remove(0, pos + 2);

    QList<QByteArray> entries = reqLine.split(' ');
    QByteArray method = entries.value(0);
    QByteArray address = entries.value(1);
    QByteArray version = entries.value(2);

    QString host;
    quint16 port;
    QString key;

    if (method != "CONNECT") {
        QUrl url = QUrl::fromEncoded(address);
        if (!url.isValid()) {
            emit error("Invalid URL: " + url.toString());
            socket->disconnectFromHost();
            return;
        }
        host = url.host();
        port = url.port(80);
        QString req = url.path();
        if (url.hasQuery()) {
            req.append('?').append(url.query());
        }
        reqLine = method + " " + req.toUtf8() + " " + version + "\r\n";
        reqData.prepend(reqLine);
        key = host + ':' + QString::number(port);
        proxySocket = socket->findChild<QTcpSocket *>(key);
        if (proxySocket) {
            proxySocket->write(reqData);
            return;//if we find an existing socket, then use it and return
        }
    } else {//CONNECT method
        /*
         * according to http://tools.ietf.org/html/draft-luotonen-ssl-tunneling-03
         * the first line would CONNECT HOST:PORT VERSION
         */
        QList<QByteArray> host_port_list = address.split(':');
        host = QString(host_port_list.first());
        port = host_port_list.last().toUShort();
    }

    proxySocket = new QTcpSocket(socket);
    proxySocket->setProxy(upstreamProxy);
    if (method != "CONNECT") {
        proxySocket->setObjectName(key);
        proxySocket->setProperty("reqData", reqData);
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnected);
        connect (proxySocket, &QTcpSocket::readyRead, this, &HttpProxy::onProxySocketReadyRead);
    } else {
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnectedHttps);
    }
    connect (proxySocket, &QTcpSocket::disconnected, proxySocket, &QTcpSocket::deleteLater);
    connect (proxySocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &HttpProxy::onSocketError);
    proxySocket->connectToHost(host, port);
}
static QFontEngine::FaceId fontFile(const QByteArray &_xname, QFreetypeFace **freetype, int *synth)
{
    *freetype = 0;
    *synth = 0;

    QByteArray xname = _xname.toLower();

    int pos = 0;
    int minus = 0;
    while (minus < 5 && (pos = xname.indexOf('-', pos + 1)))
        ++minus;
    QByteArray searchname = xname.left(pos);
    while (minus < 12 && (pos = xname.indexOf('-', pos + 1)))
        ++minus;
    QByteArray encoding = xname.mid(pos + 1);
    //qDebug("xname='%s', searchname='%s', encoding='%s'", xname.data(), searchname.data(), encoding.data());
    QStringList fontpath = fontPath();
    QFontEngine::FaceId face_id;
    face_id.index = 0;

    QByteArray best_mapping;

    for (QStringList::ConstIterator it = fontpath.constBegin(); it != fontpath.constEnd(); ++it) {
        if (!(*it).startsWith(QLatin1Char('/')))
            continue; // not a path name, a font server
        QString fontmapname;
        int num = 0;
        // search font.dir and font.scale for the right file
        while (num < 2) {
            if (num == 0)
                fontmapname = (*it) + QLatin1String("/fonts.scale");
            else
                fontmapname = (*it) + QLatin1String("/fonts.dir");
            ++num;
            //qWarning(fontmapname);
            QFile fontmap(fontmapname);
            if (!fontmap.open(QIODevice::ReadOnly))
                continue;
            while (!fontmap.atEnd()) {
                QByteArray mapping = fontmap.readLine();
                QByteArray lmapping = mapping.toLower();

                //qWarning(xfontname);
                //qWarning(mapping);
                if (!lmapping.contains(searchname))
                    continue;
                int index = mapping.indexOf(' ');
                QByteArray ffn = mapping.mid(0,index);
                // remove bitmap formats freetype can't handle
                if (ffn.contains(".spd") || ffn.contains(".phont"))
                    continue;
                bool best_match = false;
                if (!best_mapping.isEmpty()) {
                    if (lmapping.contains("-0-0-0-0-")) { // scalable font
                        best_match = true;
                        goto found;
                    }
                    if (lmapping.contains(encoding) && !best_mapping.toLower().contains(encoding))
                        goto found;
                    continue;
                }

            found:
                int colon = ffn.lastIndexOf(':');
                if (colon != -1) {
                    QByteArray s = ffn.left(colon);
                    ffn = ffn.mid(colon + 1);
                    if (s.contains("ds="))
                        *synth |= QFontEngine::SynthesizedBold;
                    if (s.contains("ai="))
                        *synth |= QFontEngine::SynthesizedItalic;
                }
                face_id.filename = (*it).toLocal8Bit() + '/' + ffn;
                best_mapping = mapping;
                if (best_match)
                    goto end;
            }
        }
    }
end:
//     qDebug("fontfile for %s is from '%s'\n    got %s synth=%d", xname.data(),
//            best_mapping.data(), face_id.filename.data(), *synth);
    *freetype = QFreetypeFace::getFace(face_id);
    if (!*freetype) {
        face_id.index = 0;
        face_id.filename = QByteArray();
    }
    return face_id;
}
Esempio n. 14
0
static int getWordSizeOfOS()
{
#if defined(Q_OS_WIN64)
    return 64; // 64-bit process running on 64-bit windows
#elif defined(Q_OS_WIN32)

    // determine if 32-bit process running on 64-bit windows in WOW64 emulation
    // or 32-bit process running on 32-bit windows
    // default bIsWow64 to false for 32-bit process on 32-bit windows

    BOOL bIsWow64 = false; // must default to false
    typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);

    LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
        GetModuleHandle("kernel32"), "IsWow64Process");

    if (NULL != fnIsWow64Process) {
        if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
            assert(false); // something went majorly wrong
        }
    }
    return bIsWow64 ? 64 : 32;

#elif defined (Q_OS_LINUX)
    // http://stackoverflow.com/questions/246007/how-to-determine-whether-a-given-linux-is-32-bit-or-64-bit
    QString exe(QLatin1String("getconf"));
    QStringList args;
    args << QLatin1String("LONG_BIT");
    QProcess proc;
    proc.setEnvironment(QProcess::systemEnvironment());
    proc.start(exe, args);
    if (proc.waitForStarted() && proc.waitForFinished()) {
        QByteArray info = proc.readAll();
        info.replace('\n',"");
        return info.toInt();
    }

    return 0; // failed

#elif defined (Q_OS_UNIX) || defined (Q_OS_MAC)
    QString exe(QLatin1String("uname"));
    QStringList args;
    args << QLatin1String("-m");
    QProcess proc;
    proc.setEnvironment(QProcess::systemEnvironment());
    proc.start(exe, args);
    if (proc.waitForStarted() && proc.waitForFinished()) {
        QByteArray info = proc.readAll();
        info.replace('\n',"");
        if (info.indexOf("x86_64") >= 0)
            return 64;
        else if (info.indexOf("amd64") >= 0)
            return 64;
        else if (info.indexOf("ia64") >= 0)
            return 64;
        else if (info.indexOf("ppc64") >= 0)
            return 64;
        else if (info.indexOf("i386") >= 0)
            return 32;
        else if (info.indexOf("i686") >= 0)
            return 32;
        else if (info.indexOf("x86") >= 0)
            return 32;
    }

    return 0; // failed
#else
    return 0; // unknown
#endif
}
Esempio n. 15
0
unsigned RunControlContext::threadIdFromTcdfId(const QByteArray &id)
{
    const int tPos = id.indexOf(".t");
    return tPos != -1 ? id.mid(tPos + 2).toUInt() : uint(0);
}
Esempio n. 16
0
void UmlPackage::fileControl(bool ci)
{
    UmlPackage * prj = getProject();
    QByteArray prjfile = prj->supportFile();
    BooL rec;
    BooL reload;
    QByteArray cmd;

    if (! prj->propertyValue((ci) ? "check-in-cmd" : "check-out-cmd", cmd))
        cmd = "specify the command containing %file and %dir or %dironly";

    Dialog dialog(ci, cmd, rec, reload);	// the dialog execution set 'cmd' and 'rec'

    if (dialog.exec() == QDialog::Accepted) {
        // save the command for a future usage
        prj->set_PropertyValue((ci) ? "check-in-cmd" : "check-out-cmd", cmd);

        if (reload)
            saveProject();

        // get files list
        QHash<QString,void*> files;

        getFiles(files, (rec) ? ~0u : 1);

        if (this == prj)
            getAuxFiles(files);

        // apply the command on each file
        QHashIterator<QString,void*> it(files);
        QFileInfo prjpath(prjfile);
        QString dir = prjpath.path();
        QString dironly = dir;
        int index;

        if ((dironly.length() > 3) &&
            (dironly[1] == ':') &&
            (dironly[2] == '/'))
            dironly = dironly.mid(2);

        while ((index = cmd.indexOf("%dironly")) != -1)
            cmd.replace(index, 8, dironly.toLatin1());

        while ((index = cmd.indexOf("%dir")) != -1)
            cmd.replace(index, 4, dir.toLatin1());

        while (it.hasNext()) {
            it.next();
            QString s = cmd;

            while ((index = s.indexOf("%file")) != -1)
                s.replace(index, 5, it.key().toLatin1());

            system((const char *) s.toLatin1().constData());
            //++it;
        }

        UmlCom::trace("Done.");

        if (reload)
            loadProject(prjfile);
    }
}
Esempio n. 17
0
int main(int argc, char *argv[])
{
    QProcess* algepapcheck = new QProcess(NULL);
    QByteArray* algepapcheckreturn = new QByteArray(NULL);
    int *j = new int(0);
    int *countofalgepapruned = new int(0);
    algepapcheck->start("/bin/ps -e");
    while(algepapcheck->waitForReadyRead()) {
        algepapcheckreturn->append(algepapcheck->readAll());
    }
    while ((*j = algepapcheckreturn->indexOf("algepap", *j)) != -1) {
        (*countofalgepapruned)++;
        ++(*j);
    }
    delete algepapcheck;
    delete algepapcheckreturn;
    delete j;

    //Q_INIT_RESOURCE(algepap);

    QApplication a(argc, argv);

    if(*countofalgepapruned > 1) {
        QMessageBox::information(0, QObject::tr("AlgePap"),
                              QObject::tr("Algepap is already runing .....         "));
        return 0;
    }
    delete countofalgepapruned;

    //checking user data status
    QDir* DATADIR = new QDir(QDir::home().path()+"/.algepap");
    if(!DATADIR->exists())
    {
        DATADIR->mkdir(DATADIR->path());
        if(!DATADIR->exists("/usr/share/algepap/DATA"))
            return 0;
        system(QString("cp -r /usr/share/algepap/DATA "+DATADIR->path()).toAscii().data());
        DATADIR->mkdir(DATADIR->path()+"/TMP");
    }

    QString* browse = new QString(DATADIR->path()+"/DATA/bin/browse");
    QString* downloadnews = new QString(DATADIR->path()+"/DATA/bin/downloadnewspapers");
    QString* desktop = new QString(DATADIR->path()+"/DATA/bin/desktop");
    chmod(browse->toLatin1().constData(),0755);
    chmod(downloadnews->toLatin1().constData(),0755);
    chmod(desktop->toLatin1().constData(),0755);
    delete browse;
    delete downloadnews;
    delete desktop;
    delete DATADIR;
    a.setApplicationVersion("1.0");
    a.setApplicationName("algepap");
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        QMessageBox::critical(0, QObject::tr("AlgePap"),
                              QObject::tr("AlgePap couldn't detect any system tray "
                                          "on this system."));
        return 1;
    }
    QApplication::setQuitOnLastWindowClosed(false);
    AlgePapMain *w = new AlgePapMain(NULL,QDir::home().path()+"/.algepap");
    w->show();
    return a.exec();
}
Esempio n. 18
0
QByteArray JsonValue::parseCString(const char *&from, const char *to)
{
    QByteArray result;
    JDEBUG("parseCString: " << QByteArray(from, to - from));
    if (*from != '"') {
        qDebug() << "JSON Parse Error, double quote expected";
        ++from; // So we don't hang
        return QByteArray();
    }
    const char *ptr = from;
    ++ptr;
    while (ptr < to) {
        if (*ptr == '"') {
            ++ptr;
            result = QByteArray(from + 1, ptr - from - 2);
            break;
        }
        if (*ptr == '\\') {
            ++ptr;
            if (ptr == to) {
                qDebug() << "JSON Parse Error, unterminated backslash escape";
                from = ptr; // So we don't hang
                return QByteArray();
            }
        }
        ++ptr;
    }
    from = ptr;

    int idx = result.indexOf('\\');
    if (idx >= 0) {
        char *dst = result.data() + idx;
        const char *src = dst + 1, *end = result.data() + result.length();
        do {
            char c = *src++;
            switch (c) {
                case 'a': *dst++ = '\a'; break;
                case 'b': *dst++ = '\b'; break;
                case 'f': *dst++ = '\f'; break;
                case 'n': *dst++ = '\n'; break;
                case 'r': *dst++ = '\r'; break;
                case 't': *dst++ = '\t'; break;
                case 'v': *dst++ = '\v'; break;
                case '"': *dst++ = '"'; break;
                case '\\': *dst++ = '\\'; break;
                default:
                    {
                        int chars = 0;
                        uchar prod = 0;
                        forever {
                            if (c < '0' || c > '7') {
                                --src;
                                break;
                            }
                            prod = prod * 8 + c - '0';
                            if (++chars == 3 || src == end)
                                break;
                            c = *src++;
                        }
                        if (!chars) {
                            qDebug() << "JSON Parse Error, unrecognized backslash escape";
                            return QByteArray();
                        }
                        *dst++ = prod;
                    }
            }
            while (src != end) {
                char c = *src++;
                if (c == '\\')
                    break;
                *dst++ = c;
            }
        } while (src != end);
        *dst = 0;
        result.truncate(dst - result.data());
    }
Esempio n. 19
0
int LoadImage::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (pdata.isEmpty())
  {
    errMsg = TR("<font color=orange>The image %1 is empty.</font>")
                         .arg(_name);
    return -2;
  }

  QByteArray encodeddata;
  if (DEBUG)
    qDebug("LoadImage::writeToDB(): image starts with %s",
           pdata.left(10).data());
  if (QString(pdata.left(pdata.indexOf("\n"))).contains(QRegExp("^\\s*begin \\d+ \\S+")))
  {
    if (DEBUG) qDebug("LoadImage::writeToDB() image is already uuencoded");
    encodeddata = pdata;
  }
  else
  {
    // there's just GOT to be a better way to do this
    QImageWriter imageIo;
    QBuffer      imageBuffer;

    imageBuffer.open(QIODevice::ReadWrite);
    imageIo.setDevice(&imageBuffer);
    imageIo.setFormat(_filename.right(_filename.size() -
                                      _filename.lastIndexOf(".") - 1).toAscii());
    if (DEBUG)
      qDebug("LoadImage::writeToDB() image has format %s",
             imageIo.format().data());
    QImage image;
    image.loadFromData(pdata);
    if (!imageIo.write(image))
    {
      errMsg = TR("<font color=orange>Error processing image %1: "
                           "<br>%2</font>")
                .arg(_name).arg(imageIo.errorString());
      return -3;
    }

    imageBuffer.close();
    encodeddata = QUUEncode(imageBuffer).toAscii();
    if (DEBUG) qDebug("LoadImage::writeToDB() image was uuencoded: %s",
                      encodeddata.left(160).data());
  }

  _selectMql = new MetaSQLQuery("SELECT image_id, -1, -1"
                      "  FROM <? literal(\"tablename\") ?> "
                      " WHERE (image_name=<? value(\"name\") ?>);");

  _updateMql = new MetaSQLQuery("UPDATE <? literal(\"tablename\") ?> "
                      "   SET image_data=<? value(\"source\") ?>,"
                      "       image_descrip=<? value(\"notes\") ?> "
                      " WHERE (image_id=<? value(\"id\") ?>) "
                      "RETURNING image_id AS id;");

  _insertMql = new MetaSQLQuery("INSERT INTO <? literal(\"tablename\") ?> ("
                      "   image_id, image_name, image_data, image_descrip"
                      ") VALUES ("
                      "  DEFAULT, <? value(\"name\") ?>,"
                      "  <? value(\"source\") ?>, <? value(\"notes\") ?>) "
                      "RETURNING image_id AS id;");

  ParameterList params;
  params.append("tablename", "image");

  return Loadable::writeToDB(encodeddata, pkgname, errMsg, params);
}
void MockHttpNetworkReplyPrivate::parse()
{
    Q_Q(MockHttpNetworkReply);
    
    QString version;
    quint16 statusCode;
    QString reasonPhrase;
    

    int idx = buffer.indexOf("\r\n");
                
    // The response is invalid, due to the absence of a delimiter signalling the
    // end of the status line.
    if (-1 == idx) {
        emit q->error(QNetworkReply::ProtocolFailure);
        emit q->finished();
        return;
    }
            
            
    QByteArray statusLine = buffer.left(idx);
    buffer.remove(0, idx + 2);

    // Parse out the HTTP version. If the space character, which separates it
    // from the status code, is not found, then the response is invalid.
    idx = statusLine.indexOf(' ');
    if (-1 == idx) {
        emit q->error(QNetworkReply::ProtocolFailure);
        emit q->finished();
        return;
    }
    if (!statusLine.startsWith("HTTP/")) {
        emit q->error(QNetworkReply::ProtocolFailure);
        emit q->finished();
        return;
    }
            
    version = QString::fromUtf8(statusLine.mid(5, idx - 5));
    statusLine.remove(0, idx + 1);

    // Parse out the status code. If the space character, which separates it
    // from the reason phrase, is not found, then the request is invalid.
    idx = statusLine.indexOf(' ');
    if (-1 == idx) {
        emit q->error(QNetworkReply::ProtocolFailure);
        emit q->finished();
        return;
    }
            
    statusCode = QString::fromUtf8(statusLine.left(idx)).toInt();
    statusLine.remove(0, idx + 1);
    q->setAttribute(QNetworkRequest::HttpStatusCodeAttribute, statusCode);

    // The remainder of the status line consists of the reason phrase.
    reasonPhrase = statusLine;
    q->setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, reasonPhrase);


    idx = buffer.indexOf("\r\n\r\n");
            
    // The response is invalid, due to the absence of a delimiter signalling the
    // end of the headers.
    if (-1 == idx) {
        emit q->error(QNetworkReply::ProtocolFailure);
        emit q->finished();
        return;
    }
    
    while (buffer.size() > 0) {
        idx = buffer.indexOf("\r\n");

        // The parser has encountered the end of headers.  The remainder of the
        // buffer is the body of the message.
        if (0 == idx) {
            buffer.remove(0, idx + 2);
            break;
        }

        QByteArray header = buffer.left(idx);
        QByteArray field;
        QByteArray value;

        int idy = header.indexOf(':');
        if (-1 == idy) {
            emit q->error(QNetworkReply::ProtocolFailure);
            emit q->finished();
            return;
        }
        
        field = header.left(idy);
        value = header.mid(idy + 2);
        q->setRawHeader(field, value);
        
        if ((QString::fromUtf8(field) == "Location") && (statusCode == 301 || statusCode == 302 || statusCode == 307)) {
            q->setAttribute(QNetworkRequest::RedirectionTargetAttribute, QUrl(QString::fromUtf8(value)));
        }

        buffer.remove(0, idx + 2);
    }

    emit q->metaDataChanged();
    emit q->readyRead();
    
    if (statusCode / 100 == 4) {
        switch (statusCode) {
        case 401: // Unauthorized
            emit q->error(QNetworkReply::AuthenticationRequiredError);
            break;
        case 403: // Forbidden
        case 405: // Method Not Allowed
            emit q->error(QNetworkReply::ContentOperationNotPermittedError);
            break;
        case 404: // Not Found
            emit q->error(QNetworkReply::ContentNotFoundError);
            break;
        case 407: // Proxy Authentication Required
            emit q->error(QNetworkReply::ProxyAuthenticationRequiredError);
            break;
        default:
            emit q->error(QNetworkReply::UnknownContentError);
            break;
        }
    } else if (statusCode / 100 == 5) {
        switch (statusCode) {
        case 500: // Internal Server Error
            emit q->error(QNetworkReply::UnknownContentError);
            break;
        default:
            emit q->error(QNetworkReply::ProtocolUnknownError);
            break;
        }
    }
    
    emit q->finished();
}
Esempio n. 21
0
void DebugSession::dataAvailable()
{
    QByteArray data = m_debuggerProcess->readAllStandardOutput();
    kDebug() << data.length() << "bytes of data available";
    
    // remove pointless state changes
    data.replace(debuggerOutputBegin+debuggerOutputEnd, "");
    data.replace(debuggerOutputEnd+debuggerOutputBegin, "");
    
    bool endsWithPrompt = false;
    if ( data.endsWith(debuggerPrompt) ) {
        endsWithPrompt = true;
        // remove the prompt
        data = data.mid(0, data.length() - debuggerPrompt.length());
    }
    
    // scan the data, and seperate program output from debugger output
    int len = data.length();
    int delimiterSkip = debuggerOutputEnd.length();
    int i = 0;
    QByteArray realData;
    while ( i < len ) {
        int nextChangeAt = data.indexOf(m_inDebuggerData ? debuggerOutputEnd : debuggerOutputBegin, i);
        bool atLastChange = nextChangeAt == -1;
        nextChangeAt = atLastChange ? len : qMin(nextChangeAt, len);
        
        if ( m_inDebuggerData == 1 ) {
            if ( i == 0 ) {
                i = delimiterSkip;
            }
            m_buffer.append(data.mid(i, nextChangeAt - i));
            kDebug() << i << nextChangeAt - i;
            kDebug() << m_buffer;
        }
        else if ( m_inDebuggerData == 0 ) {
            QByteArray d = data.mid(i, nextChangeAt - i);
            if ( d.length() > 0 ) {
                realData.append(d);
            }
        }
        
        i = nextChangeAt + delimiterSkip;
        if ( m_inDebuggerData != 1 ) m_inDebuggerData = 1;
        else m_inDebuggerData = 0;
        
        if ( atLastChange ) {
            break;
        }
    }
    
    while (int index = realData.indexOf(debuggerPrompt) != -1 ) {
        realData.remove(index-1, debuggerPrompt.length());
    }
    if ( ! realData.isEmpty() ) {
        // FIXME this is not very elegant.
        QStringList items = byteArrayToStringList(realData);
        emit realDataReceived(items);
    }
    
    // Although unbuffered, it seems guaranteed that the debugger prompt is written at once.
    // I don't think a python statement like print "FooBar" will ever break the output into two parts.
    // TODO find explicit documentation for this somewhere.
    if ( endsWithPrompt ) {
        if ( state() == StartingState ) {
            setState(PausedState);
            raiseEvent(connected_to_program);
        }
        else {
            notifyNext();
            if ( m_commandQueue.isEmpty() ) {
                kDebug() << "Changing state to PausedState";
                setState(PausedState);
            }
        }
        m_processBusy = false;
        emit debuggerReady();
    }
    
    data = m_debuggerProcess->readAllStandardError();
    if ( ! data.isEmpty() ) {
        emit stderrReceived(byteArrayToStringList(data));
    }
}
Esempio n. 22
0
	QByteArray update(const QByteArray &buf)
	{
		if(mode == Read)
		{
			QByteArray out;

			if(state == Normal)
			{
				out = buf;
			}
			else
			{
				out.resize(buf.size() + 1);
				out[0] = '\r';
				memcpy(out.data() + 1, buf.data(), buf.size());
			}

			int n = 0;
			while(1)
			{
				n = out.indexOf('\r', n);
				// not found
				if(n == -1)
				{
					break;
				}
				// found, not last character
				if(n < (buf.size() - 1))
				{
					if(out[n + 1] == '\n')
					{
						// clip out the '\r'
						memmove(out.data() + n, out.data() + n + 1, out.size() - n - 1);
						out.resize(out.size() - 1);
					}
				}
				// found, last character
				else
				{
					state = Partial;
					break;
				}
				++n;
			}

			return out;
		}
		else
		{
			if(write_conv)
			{
				QByteArray out;
				int prev = 0;
				int at = 0;

				while(1)
				{
					int n = buf.indexOf('\n', at);
					if(n == -1)
						break;

					int chunksize = n - at;
					int oldsize = out.size();
					out.resize(oldsize + chunksize + 2);
					memcpy(out.data() + oldsize, buf.data() + at, chunksize);
					memcpy(out.data() + oldsize + chunksize, "\r\n", 2);

					list.append(prebytes + n + 1 - prev);
					prebytes = 0;
					prev = n;

					at = n + 1;
				}
				if(at < buf.size())
				{
					int chunksize = buf.size() - at;
					int oldsize = out.size();
					out.resize(oldsize + chunksize);
					memcpy(out.data() + oldsize, buf.data() + at, chunksize);
				}

				prebytes += buf.size() - prev;
				return out;
			}
			else
				return buf;
		}
	}
Esempio n. 23
0
void Widget::tcpProcessPendingDatagrams()
{
    // Find who's sending
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0)
        return;

    unsigned nTries = 0;

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

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

                // Detect and send data files if we need to
                QByteArray data = *tcpReceivedDatas;
                //logMessage("DataReceived:"+data);

                // Get the payload only (remove headers)
                data = removeHTTPHeader(data, "POST ");
                data = removeHTTPHeader(data, "GET ");
                data = removeHTTPHeader(data, "User-Agent:");
                data = removeHTTPHeader(data, "Host:");
                data = removeHTTPHeader(data, "host:");
                data = removeHTTPHeader(data, "Accept:");
                data = removeHTTPHeader(data, "Content-Length:");
                data = removeHTTPHeader(data, "Content-Type:");
                data = removeHTTPHeader(data, "Server:");
                data = removeHTTPHeader(data, "Date:");
                data = removeHTTPHeader(data, "Transfert-Encoding:");
                data = removeHTTPHeader(data, "Connection:");
                data = removeHTTPHeader(data, "Vary:");
                data = removeHTTPHeader(data, "X-Powered-By:");
                data = removeHTTPHeader(data, "accept-encoding:");
                data = removeHTTPHeader(data, "if-modified-since:");

                if (data.size() >= length) // Wait until we have all the data
                {
                    data.truncate(length);

                    // Process data, if the buffer is not empty, keep reading
                    tcpProcessData(data, socket);
                    // Delete the processed message from the buffer
                    *tcpReceivedDatas = tcpReceivedDatas->right(tcpReceivedDatas->size() - tcpReceivedDatas->indexOf(data) - data.size());
                    if (tcpReceivedDatas->isEmpty())
                        return;
                    nTries=0;
                }
            }
        }
        else if (tcpReceivedDatas->contains("\r\n\r\n")) // POST or GET request, without a Content-Length header
        {
            QByteArray data = *tcpReceivedDatas;
            data = data.left(data.indexOf("\r\n\r\n")+4);

            int i1=0;
            do
            {
                i1 = data.indexOf("GET");
                if (i1 != -1)
                {
                    int i2 = data.indexOf("HTTP")-1;
                    QString path = data.mid(i1 + 4, i2-i1-4);
                    data = removeHTTPHeader(data, "POST ");
                    data = removeHTTPHeader(data, "GET ");
                    logMessage("Received GET:"+path);
                    QFile head(QString(NETDATAPATH)+"/dataHeader.bin");
                    QFile res("data/"+path);
                    head.open(QIODevice::ReadOnly);
                    if (!head.isOpen())
                    {
                        logMessage("Can't open header : "+head.errorString());
                        continue;
                    }
                    res.open(QIODevice::ReadOnly);
                    if (!res.isOpen())
                    {
                        logMessage("File not found");
                        head.close();
                        continue;
                    }
                    socket->write(head.readAll());
                    socket->write(QString("Content-Length: "+QString().setNum(res.size())+"\r\n\r\n").toLocal8Bit());
                    socket->write(res.readAll());
                    head.close();
                    res.close();
                    logMessage("Sent "+QString().setNum(res.size()+head.size())+" bytes");
                }
            } while (i1 != -1);

            *tcpReceivedDatas = tcpReceivedDatas->mid(data.size());
        }
    }
}
Esempio n. 24
0
void ECMAscriptTest::runAllTests()
{
    static const QByteArray include = "$INCLUDE(\"";

    QFETCH(QString, filename);
    QByteArray expectedError;

    QFile input( filename );

    foreach ( const QByteArray &skip, skips.keys() ) {
        if ( skip == QTest::currentDataTag() )
            QSKIP( skips[ skip ], SkipSingle );
    }

    QVERIFY( input.open( QIODevice::ReadOnly ) );

    const QByteArray testdata = input.readAll();

    QVERIFY( ! testdata.isEmpty() );

    RefPtr<KJS::Interpreter> interp = new KJS::Interpreter(global);

    KJS::Interpreter::setShouldPrintExceptions(true);

    QByteArray testscript;

    // test is expected to fail
    if ( testdata.indexOf( "@negative" ) >= 0 ) {
        expectedError = getTextProperty( "@negative", testdata );
        if ( expectedError.isEmpty() )
            expectedError = ".";
    }

    int from = 0;
    while ( ( from = testdata.indexOf( include, from ) ) >= 0 ) {
        int endq = testdata.indexOf( "\"", from + include.length() );
        QVERIFY( endq >= 0 );

        const QByteArray includeFile = testdata.mid( from + include.length(), endq - from - include.length() );

        if ( ! includes.contains( includeFile ) )
            QVERIFY( loadInclude( includeFile ) );

        testscript += includes[ includeFile ];
        from = endq;
    }

    testscript += testrunner;

    testscript += testdata;

    const QFileInfo info( input );

    const QString scriptutf = QString::fromUtf8( testscript.constData() );

    KJS::Completion completion = interp->evaluate(info.fileName().toAscii().constData(), 0, scriptutf);

    const bool knownBroken = expectedBroken.contains( QString::fromAscii( QTest::currentDataTag() ) );

    if ( expectedError.isEmpty() ) {
        ECMATEST_VERIFY( completion.complType() != KJS::Throw );
    } else {
        if ( knownBroken && completion.complType() != KJS::Throw ) {
            QEXPECT_FAIL(QTest::currentDataTag(), "It is known that KJS doesn't pass this test", Abort);
            m_failed++;
        }

        QCOMPARE( completion.complType(), KJS::Throw );
        QVERIFY( completion.value() != NULL );

        const QString eMsg = exceptionToString( interp->execState(), completion.value() );

        if ( expectedError == "^((?!NotEarlyError).)*$" ) {
            ECMATEST_VERIFY( eMsg.indexOf( "NotEarlyError" ) == -1 );
        } else if ( expectedError == "." ) {
            // means "every exception passes
        } else {
            ECMATEST_VERIFY( eMsg.indexOf( expectedError ) >= 0 );
        }
    }
}
void ProtocolController::onServerDataEvent(QByteArray &data)
{
    const QByteArray seperator("\r\n");

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

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

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

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

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

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

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

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

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

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

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

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

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

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

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

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

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

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

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

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

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

            Symbols saveSymbols = symbols;
            int saveIndex = index;

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

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

            index = 0;

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

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

    currentFilenames.pop();
}
Esempio n. 27
0
void Widget::tcpProcessPendingDatagrams()
{
    // Find who's sending
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == nullptr)
        return;

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

    unsigned nTries = 0;

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

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

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

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

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

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

            *recvBuffer = recvBuffer->mid(dataSize);
        }
    }
}
Esempio n. 28
0
    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    void WebProxy::processQuery() {
        QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
        QByteArray requestData = socket->readAll();

        int pos = requestData.indexOf("\r\n");
        QByteArray requestLine = requestData.left(pos);
        requestData.remove(0, pos + 2);

        QList<QByteArray> entries = requestLine.split(' ');
        QByteArray method = entries.value(0);
        QByteArray address = entries.value(1);
        QByteArray version = entries.value(2);

        qDebug( )  << __FILE__ << __FUNCTION__ << "Processing " << address;

        QUrl url = QUrl::fromEncoded(address);
        if (!url.isValid()) {
            //qWarning() << "Invalid URL:" << url;
            socket->disconnectFromHost();
            return;
        }

        //Act as server is request are for local server
        if ((url.host() == "") && (QFile(address).exists())) {
            //qDebug( )  << __FILE__ << __FUNCTION__ << "Sending " << address;
            QByteArray header;
            QTextStream headerStream(&header, QIODevice::WriteOnly);
            //Construct response header
            headerStream << "HTTP/1.0 200 OK" << endl;
            headerStream << "Server: gpsbook/" << qApp->applicationVersion() << endl;
            headerStream << "Date: " << QDateTime::currentDateTime().toUTC().toString("ddd, dd MMM yyyy hh:mm:ss") << "GMT" << endl;
            headerStream << "Content-Type: text/html; charset=utf-8" << endl;
            headerStream << "Connection: close" << endl;
            headerStream << "Pragma: no-cache" << endl;
            headerStream << "Cache-Control: no-cache" << endl;
            QFile file(address);
            if (!file.open(QFile::ReadOnly | QFile::Text))
            {
                 qWarning() << "Cannot open:" << address;
                 socket->disconnectFromHost();
                 return ;
            }

            QByteArray content;
            QTextStream contentStream(&content, QIODevice::WriteOnly);

            while (!file.atEnd()) {
                contentStream << file.readLine() << endl;
            }

            headerStream << "Content-Length:" << content.size() << endl;
            headerStream << "" << endl;

            socket->write(header);
            socket->write(content);
            //qDebug( )  << __FILE__ << __FUNCTION__ << "File sent (" << content.size() << "bytes) :-)";
            socket->disconnectFromHost();
        return;
        }


#if ( QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) )
        // Some finction of QUrl have been deprecated
        // This code is require for the internet browser and should be reviewed.
#else


#ifdef Q_OS_LINUX
        //Remove advert to speedup development ;-)
        if (url.toString().contains("googlesyndication") ||
            url.toString().contains("yieldmanager.com")) {
            socket->disconnectFromHost();
            return;
        }
#endif

        qDebug( )  << __FILE__ << __FUNCTION__ << "URL: " << url.toString();

        QString host = url.host();
        int port = (url.port() < 0) ? 80 : url.port();
        QByteArray req = url.encodedPath();
        if (url.hasQuery())
            req.append('?').append(url.encodedQuery());
        requestLine = method + " " + req + " " + version + "\r\n";
        requestData.prepend(requestLine);

        QString key = host + ':' + QString::number(port);
        QTcpSocket *proxySocket = socket->findChild<QTcpSocket*>(key);
        if (proxySocket) {
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            proxySocket->write(requestData);
        } else {
            proxySocket = new QTcpSocket(socket);
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            connect(proxySocket, SIGNAL(connected()), this, SLOT(sendRequest()));
            connect(proxySocket, SIGNAL(readyRead()), this, SLOT(transferData()));
            connect(proxySocket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
            connect(proxySocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(closeConnection()));
            proxySocket->connectToHost(host, port);
        }
#endif
    } //WebProxy::processQuery
Esempio n. 29
0
	bool processHeaderData(const QByteArray &headerData)
	{
		QList<QByteArray> lines;
		int at = 0;
		while(at < headerData.size())
		{
			int end = headerData.indexOf("\n", at);
			assert(end != -1);

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

		if(lines.isEmpty())
			return false;

		QByteArray requestLine = lines[0];

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

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

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

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

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

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

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

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

			reqHeaders += HttpHeader(name, val);
		}

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

		return true;
	}
Esempio n. 30
0
AutoUpdater::VersionInfo AutoUpdater::getUpdateVersion()
{
    VersionInfo versionInfo;
    versionInfo.timestamp = 0;

    // Updates only for supported platforms
    if (platform.isEmpty())
        return versionInfo;

    if (abortFlag)
        return versionInfo;

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    manager->setProxy(Settings::getInstance().getProxy());
    QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(checkURI)));
    while (!reply->isFinished())
    {
        if (abortFlag)
            return versionInfo;
        qApp->processEvents();
    }

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "getUpdateVersion: network error: " + reply->errorString();
        reply->deleteLater();
        manager->deleteLater();
        return versionInfo;
    }

    QByteArray data = reply->readAll();
    reply->deleteLater();
    manager->deleteLater();
    if (data.size() < (int)(1+crypto_sign_BYTES))
        return versionInfo;

    // Check updater protocol version
    if ((int)data[0] != '3')
    {
        qWarning() << "getUpdateVersion: Bad version " << (uint8_t)data[0];
        return versionInfo;
    }

    // Check the signature
    QByteArray sigData = data.mid(1, crypto_sign_BYTES);
    unsigned char* sig = (unsigned char*)sigData.data();
    QByteArray msgData = data.mid(1+crypto_sign_BYTES);
    unsigned char* msg = (unsigned char*)msgData.data();

    if (crypto_sign_verify_detached(sig, msg, msgData.size(), key) != 0)
    {
        qCritical() << "getUpdateVersion: RECEIVED FORGED VERSION FILE FROM "<<updateServer;
        return versionInfo;
    }

    int sepPos = msgData.indexOf('!');
    versionInfo.timestamp = QString(msgData.left(sepPos)).toInt();
    versionInfo.versionString = msgData.mid(sepPos+1);

    qDebug() << "timestamp:"<<versionInfo.timestamp << ", str:"<<versionInfo.versionString;

    return versionInfo;
}