Esempio n. 1
0
void Updater::writeToFile()
{
    QNetworkReply *reply = ( QNetworkReply * )sender();
    QByteArray arr = reply->readAll();
    bool err = false;
    if ( firstChunk )
    {
#if defined Q_OS_WIN
        err = arr.left( 2 ) != "MZ";
#elif defined Q_OS_LINUX
        err = arr.left( 4 ) != "\x7F""ELF" && arr.left( 2 ) != "#!";
#endif
        firstChunk = false;
    }
    if ( err || updateFile.write( arr ) != arr.size() )
        reply->abort();
}
Esempio n. 2
0
void SocketHandler::SubmitQuery(int request_type, QString data)
{
    // Make a new tcp socket, and connect to the server
    socket = new QTcpSocket(this);
    socket->connectToHost(host, port);

    // Wait a few seconds for a connection
    if (socket->waitForConnected(5000))
    {
        // When connected, build a socket query based on parameters
        QString temp;
        qDebug() << "[SOCKET HANDLER] : Connected.";
        // Byte array for converting qstring to const char *
        QByteArray bytes;
        const char * query;

        switch(request_type)
        {
            case REQ_NEW_ITEM:
                qDebug() << "[SOCKET HANDLER] : Requesting new job.";
                temp = "n^" + data;
                break;
            case UPD_CUR_ITEM:
                qDebug() << "[SOCKET HANDLER] : Requesting update on job.";
                temp = "u^" + data;
                break;
            default:
                break;
        }

        // Convert data for sending
        bytes = temp.toLocal8Bit();
        query = bytes.data();

        // Send query
        socket->write(query);
        socket->waitForBytesWritten(10000);

        // Recieve a response from the server
        QByteArray arr;
        while(!arr.contains(SERVER_RECV_DELIMITER))
        {
            socket->waitForReadyRead();
            arr += socket->readAll();
        }

        int b = arr.indexOf(SERVER_RECV_DELIMITER);
        QByteArray message = arr.left(b);
        arr = arr.mid(b);
        qDebug() << "[SOCKET HANDLER] : DONE." ;
        emit dataReady(message);
        socket->close();
    }
    else
    {
        qDebug() << "[SOCKET HANDLER] : COULD NOT CONNECT.";
    }
}
Esempio n. 3
0
QList<FormData> HTTPConnection::parseFormData() const {
    // make sure we have the correct MIME type
    QList<QByteArray> elements = _requestHeaders.value("Content-Type").split(';');

    QString contentType = elements.at(0).trimmed();

    if (contentType != "multipart/form-data") {
        return QList<FormData>();
    }

    // retrieve the boundary marker
    QByteArray boundary;
    for (int ii = 1, nn = elements.size(); ii < nn; ii++) {
        QByteArray element = elements.at(ii).trimmed();
        if (element.startsWith("boundary")) {
            boundary = element.mid(element.indexOf('=') + 1).trimmed();
            break;
        }
    }
    
    QByteArray start = "--" + boundary;
    QByteArray end = "\r\n--" + boundary + "--\r\n";

    QList<FormData> data;
    QBuffer buffer(const_cast<QByteArray*>(&_requestContent));
    buffer.open(QIODevice::ReadOnly);
    while (buffer.canReadLine()) {
        QByteArray line = buffer.readLine().trimmed();
        if (line == start) {
            FormData datum;
            while (buffer.canReadLine()) {
                QByteArray line = buffer.readLine().trimmed();
                if (line.isEmpty()) {
                    // content starts after this line
                    int idx = _requestContent.indexOf(end, buffer.pos());
                    if (idx == -1) {
                        qWarning() << "Missing end boundary." << _address;
                        return data;
                    }
                    datum.second = _requestContent.mid(buffer.pos(), idx - buffer.pos());
                    data.append(datum);
                    buffer.seek(idx + end.length());

                } else {
                    // it's a header element
                    int idx = line.indexOf(':');
                    if (idx == -1) {
                        qWarning() << "Invalid header line." << _address << line;
                        continue;
                    }
                    datum.first.insert(line.left(idx).trimmed(), line.mid(idx + 1).trimmed());
                }
            }
        }
    }

    return data;
}
void encoder_tcpsocket::data_parse(QByteArray data)
{
    qDebug()<<data;
    int length = data.left(4).toInt(NULL,10);
    if(length <= 0)
        return;

    QByteArray code = data.mid(4,4); /**< 操作数 */
    qDebug()<<code;
    ///获取服务器时间
    if(code.operator ==(GET_DEVICE_TIME))
    {
        send_info_to_host(GET_DEVICE_TIME,
                          QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }
    ///获取设备地址
    else if(code.operator ==(GET_DEVICE_ADDRESS))
    {
        send_info_to_host(GET_DEVICE_ADDRESS,
                          device_setting_read.settings_addr);
    }
    ///获取设备状态,一般为解码器
    else if(code.operator ==(GET_DEVICE_STATE))
    {
        send_info_to_host(GET_DEVICE_STATE,
                          QString::number(device_setting_read.settings_state).toLatin1());
    }
    ///获取心跳
    else if(code.operator ==(GET_DEVICE_HEART))
    {
        send_info_to_host(GET_DEVICE_HEART,
                          "0000");
    }
    ///设置设备时间
    else if(code.operator ==(SET_DEVICE_TIME))
    {
        QByteArray current_time = data.mid(8,19);
        char set_time[50];
        sprintf(set_time,"time -s \" %s \"\n",current_time.data());
        system(set_time);
    }
    ///设置设备重启
    else if(code.operator ==(SET_DEVICE_EXIT))
    {
        this->close();
        system("reboot\n");
    }
    ///设置解码器IP
    else if(code.operator ==(SET_DEVICE_DECODERIP))
    {
        emit change_decoder_ip(data.mid(8,length - 8));
    }
    ///设置停止实时显示
    else if(code.operator ==(SET_DEVICE_STOP))
    {
        emit change_decoder_ip("127.0.0.1");
    }
}
Esempio n. 5
0
	virtual void main()
	{
		//init
		bool v = getFlag("v");

		//load ids and lengths
		QHash<QByteArray, int> ids;
		QSharedPointer<QFile> file = Helper::openFileForReading(getInfile("ids"));
		while (!file->atEnd())
		{
			QByteArray line = file->readLine().trimmed();
			if (line.isEmpty() || line[0]=='#') continue;
			QList<QByteArray> parts = line.split('\t');
			int length = -1;
			if (parts.count()>1)
			{
				length = Helper::toInt(parts[1], "length value");
			}
			ids.insert(parts[0], length);
		}

		//open output stream
		FastqOutfileStream outfile(getOutfile("out"), false);

		//parse input and write output
		FastqFileStream stream(getInfile("in"));
		FastqEntry entry;
		while (!stream.atEnd())
		{
			stream.readEntry(entry);

			QByteArray id = entry.header.trimmed();
			id = id.mid(1);
			int comment_start = id.indexOf(' ');
			if (comment_start!=-1) id = id.left(comment_start);
			int length = ids.value(id, -2);
			if (length==-2) //id not in list
			{
				if (!v) continue;

				outfile.write(entry);
			}
			else if (length==-1) //id is in list, but no length given
			{
				if (v) continue;

				outfile.write(entry);
			}
			else if (length>=1) //id is in list and length given
			{
				if (v) continue;

				entry.bases.resize(length);
				entry.qualities.resize(length);
				outfile.write(entry);
			}
		}
	}
Esempio n. 6
0
QString jsBridge::decrypt(QString data, QString hint)
{
    bool error = false;
    while (true) {
        PasswordDialog pwd(qApp->activeWindow(), false);
        pwd.setHint(hint);
        pwd.setError(error);
        if (pwd.exec() == QDialog::Accepted){

            RC2_KEY key;
            QByteArray b = QByteArray::fromBase64(data.toLatin1());

            QByteArray r = QCryptographicHash::hash(pwd.getPassword().toUtf8(), QCryptographicHash::Md5);
            RC2_set_key(&key, r.size(), (const unsigned char*)r.data(), 64);

            unsigned char * buf2 = new unsigned char[8];

            QByteArray result;

            while (b.size()>0) {
                QByteArray x = b.left(8);
                RC2_ecb_encrypt((const unsigned char*)x.data(),buf2,&key,RC2_DECRYPT);
                result += QByteArray((const char *)buf2, x.size());
                b.remove(0, 8);
            }

            QString crc1 = QString::fromUtf8(result.left(4));
            result.remove(0, 4);

            ulong crc = crc32(0, NULL, 0);
            crc = crc32(crc, (const Bytef *)result.data(), result.size());
            QString crc2 = QString(QByteArray::number(~(uint)crc, 16).left(4));

            if (QString::compare(crc1, crc2, Qt::CaseInsensitive) != 0){
                error = true;
                continue;
            }

            return result;
        }
        else
            return QString();
    }
    return QString();
}
static QByteArray QMetaMethod_name(const QMetaMethod &m)
{
    QByteArray sig = m.signature();
    int paren = sig.indexOf('(');
    if (paren == -1)
        return sig;
    else
        return sig.left(paren);
}
Esempio n. 8
0
qulonglong TrashSizeCache::calculateSize()
{
    // First read the directorysizes cache into memory
    QFile file( mTrashSizeCachePath );
    typedef QHash<QByteArray, CacheData> DirCacheHash;
    DirCacheHash dirCache;
    if (file.open(QIODevice::ReadOnly)) {
        while (!file.atEnd()) {
            const QByteArray line = file.readLine();
            const int firstSpace = line.indexOf(' ');
            const int secondSpace = line.indexOf(' ', firstSpace + 1);
            CacheData data;
            data.mtime = line.left(firstSpace).toLongLong();
            // "012 4567 name" -> firstSpace=3, secondSpace=8, we want mid(4,4)
            data.size = line.mid(firstSpace + 1, secondSpace - firstSpace - 1).toULongLong();
            dirCache.insert(line.mid(secondSpace + 1), data);
        }
    }
    // Iterate over the actual trashed files.
    // Orphan items (no .fileinfo) still take space.
    QDirIterator it( mTrashPath + QString::fromLatin1( "/files/" ), QDirIterator::NoIteratorFlags );

    qulonglong sum = 0;
    while ( it.hasNext() ) {
        const QFileInfo file = it.next();
        if (file.fileName() == QLatin1String(".") || file.fileName() == QLatin1String("..")) {
            continue;
        }
        if ( file.isSymLink() ) {
            // QFileInfo::size does not return the actual size of a symlink. #253776
            KDE_struct_stat buff;
            return static_cast<qulonglong>(KDE::lstat(file.absoluteFilePath(), &buff) == 0 ? buff.st_size : 0);
        } else if (file.isFile()) {
            sum += file.size();
        } else {
            bool usableCache = false;
            const QString fileId = file.fileName();
            DirCacheHash::const_iterator it = dirCache.constFind(QFile::encodeName(fileId));
            if (it != dirCache.constEnd()) {
                const CacheData &data = *it;
                const QString fileInfoPath = mTrashPath + "/info/" + fileId + ".trashinfo";
                if (QFileInfo(fileInfoPath).lastModified().toMSecsSinceEpoch() == data.mtime) {
                    sum += data.size;
                    usableCache = true;
                }
            }
            if (!usableCache) {
                const qulonglong size = DiscSpaceUtil::sizeOfPath(file.absoluteFilePath());
                sum += size;
                add(fileId, size);
            }
        }

    }

    return sum;
}
Esempio n. 9
0
/*!
 * \reimp
 */
QHttpRequestHeader QxtHttpServerConnector::parseRequest(QByteArray& buffer)
{
    int pos = buffer.indexOf("\r\n\r\n"), endpos = pos + 3;
    if (pos == -1)
    {
        pos = buffer.indexOf("\r\n"); // 0.9
        endpos = pos + 1;
    }

    QHttpRequestHeader header(QString::fromUtf8(buffer.left(endpos)));
    QByteArray firstLine = buffer.left(buffer.indexOf('\r'));
    if (firstLine.indexOf("HTTP/") == -1)
    {
        header.setRequest(header.method(), header.path(), 0, 9);
    }
    buffer.remove(0, endpos + 1);
    return header;
}
Esempio n. 10
0
bool SimulationOwner::fromByteArray(const QByteArray& data) {
    if (data.size() == NUM_BYTES_ENCODED) {
        QByteArray idBytes = data.left(NUM_BYTES_RFC4122_UUID);
        _id = QUuid::fromRfc4122(idBytes);
        _priority = data[NUM_BYTES_RFC4122_UUID];
        return true;
    }
    return false;
}
Esempio n. 11
0
QByteArray & HWProto::addByteArrayToBuffer(QByteArray & buf, const QByteArray & msg)
{
    QByteArray bmsg = msg;
    bmsg = bmsg.left(250);
    quint8 sz = bmsg.size();
    buf.append(QByteArray((char *)&sz, 1));
    buf.append(bmsg);
    return buf;
}
Esempio n. 12
0
void Cipher_T::testHmacSha1()
{
    QByteArray key = QByteArray::fromHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
    QByteArray data("Hi There");
    QByteArray digest =
            QByteArray::fromHex("b617318655057264e28bc0b6fb378c8ef146be00");
    QCOMPARE(Cipher::hmacSha1(key, data), digest.left(10));

    key = QByteArray("Jefe");
    data = QByteArray("what do ya want for nothing?");
    digest = QByteArray::fromHex("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
    QCOMPARE(Cipher::hmacSha1(key, data), digest.left(10));

    key = QByteArray::fromHex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
    data = QByteArray(50, 0xdd);
    digest = QByteArray::fromHex("125d7342b9ac11cd91a39af48aa17b4f63f175d3");
    QCOMPARE(Cipher::hmacSha1(key, data), digest.left(10));
}
Esempio n. 13
0
static bool splitHeadersAndData(const QByteArray& request, QByteArray& header, QByteArray& data)
{
    const int sep = request.indexOf("\r\n\r\n");
    if (sep <= 0)
        return false;
    header = request.left(sep);
    data = request.mid(sep + 4);
    return true;
}
Esempio n. 14
0
void Tunneld::onENetPeerPacketReceived(ENetHost *enhost, ENetPeer *enpeer, int chanid, QByteArray packet)
{
    // ToxTunChannel *chan = this->m_enpeer_chans[enpeer];
    // ToxTunChannel *chan = this->m_conid_chans[(enpeer->data)];
    // ToxTunChannel *chan = (ToxTunChannel*)enpeer->toxchan;
    ToxTunChannel *chan = peerLastChan(enpeer);

    if (packet.length() > 50) {
        // qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet.left(20)<<"..."<<packet.right(20);
    } else {
        // qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet;
    }

    if (chan == NULL) {
        qDebug()<<"error: chan null:"<<enpeer;
        if (packet.length() > 50) {
            qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet.left(20)<<"..."<<packet.right(20);
        } else {
            qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet;
        }
        qDebug()<<"drop crash packet, be careful, be true";
        return;
        // 这个断言在外网还是出现比较频繁的。
        assert(1 == 2);
    }
    
    if (chanid == 1) {
        qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet;
        if (packet == QByteArray("CLIFIN")) {
            if (chan->peer_sock_closed == false) {
                chan->peer_sock_closed = true;
                chan->peer_sock_close_time = QDateTime::currentDateTime();

                if (chan->sock_closed == false) {
                    // should close myself socket???
                    // 也就是对方不会再发送新的数据过来,也不会再接收数据了,
                    // 但有可能对方的发送缓冲区中还有未发送成功的缓冲数据。
                    // 使用计时器,如果在一定时间内再也没有收到包,则认为对方没有要发送的数据了。
                }
                
                this->promiseChannelCleanup(chan);                
            } else {
                qDebug()<<"maybe duplicate CLIFIN packet:i/o:"
                        <<enpeer->incomingPeerID<<enpeer->outgoingPeerID;
            }
        } else {
            qDebug()<<"invalid chan1 packet:";
        }
        return;
    }

    chan->last_recv_peer_pkt_time = QDateTime::currentDateTime();
    QTcpSocket *sock = chan->m_sock;

    int wrlen = sock->write(packet);
}
Esempio n. 15
0
void HTTPConnection::readHeaders() {
    while (_socket->canReadLine()) {
        QByteArray line = _socket->readLine();
        QByteArray trimmed = line.trimmed();
        if (trimmed.isEmpty()) {
            _socket->disconnect(this, SLOT(readHeaders()));

            QByteArray clength = requestHeader("Content-Length");
            if (clength.isEmpty()) {
                _parentManager->handleHTTPRequest(this, _requestUrl);

            } else {
                bool success = false;
                auto length = clength.toInt(&success);
                if (!success) {
                    qWarning() << "Invalid header." << _address << trimmed;
                    respond("400 Bad Request", "The header was malformed.");
                    return;
                }

                // Storing big requests in memory gets expensive, especially on servers
                // with limited memory. So we store big requests in a temporary file on disk
                // and map it to faster read/write access.
                static const int MAX_CONTENT_SIZE_IN_MEMORY = 10 * 1000 * 1000;
                if (length < MAX_CONTENT_SIZE_IN_MEMORY) {
                    _requestContent = MemoryStorage::make(length);
                } else {
                    _requestContent = FileStorage::make(length);
                }

                connect(_socket, SIGNAL(readyRead()), SLOT(readContent()));

                // read any content immediately available
                readContent();
            }
            return;
        }
        char first = line.at(0);
        if (first == ' ' || first == '\t') { // continuation
            _requestHeaders[_lastRequestHeader].append(trimmed);
            continue;
        }
        int idx = trimmed.indexOf(':');
        if (idx == -1) {
            qWarning() << "Invalid header." << _address << trimmed;
            respond("400 Bad Request", "The header was malformed.");
            return;
        }
        _lastRequestHeader = trimmed.left(idx).toLower();
        QByteArray& value = _requestHeaders[_lastRequestHeader];
        if (!value.isEmpty()) {
            value.append(", ");
        }
        value.append(trimmed.mid(idx + 1).trimmed());
    }
}
/*!
    \internal
 */
void QWebSocketPrivate::ping(const QByteArray &payload)
{
    QByteArray payloadTruncated = payload.left(125);
    m_pingTimer.restart();
    QByteArray pingFrame = getFrameHeader(QWebSocketProtocol::OpCodePing, payloadTruncated.size(),
                                          0 /*do not mask*/, true);
    pingFrame.append(payloadTruncated);
    qint64 ret = writeFrame(pingFrame);
    Q_UNUSED(ret);
}
Esempio n. 17
0
// kan later besluit of ons host adres uit pakkie uit wil parse of van socket af wil kry of wat.
// update: kry uit pakkie sodat forwarded searches na searcher gaan en nie na forwarder nie
//       : TODO: dink oor 'n manier om die DDoS moontlikheid wat hierin skuil aan te spreek :)
void Dispatcher::handleReceivedSearchQuestion(QHostAddress &fromHost, QByteArray &datagram)
{
    datagram.remove(0, 2);
    QHostAddress sendToHost = QHostAddress(getQuint32FromByteArray(&datagram));
    //QString q = sendToHost.toString();
    quint64 searchID = getQuint64FromByteArray(&datagram);
    QByteArray clientCID = datagram.left(24);
    datagram.remove(0, 24);
    int searchLength = getQuint16FromByteArray(&datagram);
    QByteArray searchData = datagram.left(searchLength);
    QByteArray bucket = datagram.right(datagram.length() - searchLength);

    if (searchData.length() > 0)
        emit searchQuestionReceived(sendToHost, clientCID, searchID, searchData);

    if (bucket.length() > 0)
        emit bucketContentsArrived(bucket, fromHost);

}
Esempio n. 18
0
/**
 * Decrypts data based on cipher text and cipher key
 * @param p_input Cipher text
 * @param p_key Cipher key
 * @return Decrypted data
 */
QByteArray AES::decrypt(QByteArray p_input, QByteArray p_key)
{
    if (p_input.isEmpty()) {
        qDebug() << "Error while decryption: Cannot decrypt empty input";
        return QByteArray();
    }
    QByteArray iv = p_input.left(16);
    QByteArray input = p_input.remove(0, 16);
    return decrypt(input, p_key, iv);
}
Esempio n. 19
0
size_t JavaUpload::process_header(const char* ptr, size_t size, size_t nmemb, JavaUpload* This)
{
	QByteArray line = QByteArray(ptr, size*nmemb).trimmed();
	int pos = line.indexOf(": ");
	
	if(pos != -1)
		This->m_headers[line.left(pos).toLower()] = line.mid(pos+2);
	
	return size*nmemb;
}
Esempio n. 20
0
QByteArray KGrGameIO::removeNewline (const QByteArray & line)
{
    int len = line.size();
    if ((len > 0) && (line.endsWith ('\n'))) {
        return (line.left (len -1));
    }
    else {
        return (line);
    }
}
Esempio n. 21
0
AutoUpdater::VersionInfo AutoUpdater::getUpdateVersion()
{
    VersionInfo versionInfo;
    versionInfo.timestamp = 0;

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

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(checkURI)));
    while (!reply->isFinished())
        qApp->processEvents();

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "AutoUpdater: 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] != '2')
    {
        qWarning() << "AutoUpdater: 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() << "AutoUpdater: 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;
}
Esempio n. 22
0
// time critical
bool PHPQt::qt_metacall(smokephp_object* o, Smoke::Stack args)
{
    Context::setCallType( Context::SlotCall );
    const QMetaObject* staticMetaObject = o->meta();
    const int _id = args[2].s_int;
    const int offset = staticMetaObject->methodOffset();

    const QByteArray signature( staticMetaObject->method(_id).signature() );
    const QByteArray metaMethodName = signature.left( signature.indexOf("(") );

    //! - if we have a slot overridden in php user space: call it
    //!   @see InvokeSlot
    if( PHPQt::methodExists( o->ce_ptr() , metaMethodName.constData()) ) {
        pDebug( PHPQt::Slot ) << " userspace " << signature << o->ce_ptr()->name;
        const int count = staticMetaObject->method( args[2].s_int ).parameterTypes().count() + 1;
        // zval* zmem = ALLOCA_N(zval, count);
        zval** zmem = (zval**) safe_emalloc( sizeof(zval*), count+1, 0);
        for( int i=0;i<count;i++ )
        {
            ALLOC_INIT_ZVAL( zmem[i] );
        }

        // NOTICE is memory allocation safe here?
        InvokeSlot c( o->smoke(), args, o->zval_ptr(), zmem, _id, staticMetaObject, (void**) args[3].s_voidp, metaMethodName );
        c.next();

        efree(zmem);
        return true;

    } else {
        if ( staticMetaObject->indexOfSlot( signature ) != -1 )
        {
            pDebug( PHPQt::Slot ) << " C++ " << signature;
            // return false means this will be done by smoke
            return false;
        } else {
            // TODO error case for undefined methods, see php_qt proxyMethod
            //			const int i = staticMetaObject->indexOfSignal( signature );
            //			const int offset = staticMetaObject->methodOffset(); // The offset is the summary of all methods in the class's superclasses
            pDebug( PHPQt::Signal ) << signature << staticMetaObject->className() << _id << staticMetaObject->methodOffset();

            /* C++ */	//if( _id < offset ) { qWarning() << "got an id smaller than offset"; }

            /**
            * We go through QMetaObject::activate, because it can either be connected to a C++ Slot or a user space Slot
            * cast to a QObject using smoke cast
            * */
            QObject* ptr = (QObject*) o->smoke()->cast( const_cast<void*>( o->ptr() ), o->classId(), cachedQObjectSmokeId );
            void *_b[] = { 0, ((void**) args[3].s_voidp)[1] };
            QMetaObject::activate( ptr, staticMetaObject, 0, _b );
            return true; // success
        }
    } // else method exist
    return false;
}
Esempio n. 23
0
    qint64 Request::writeData(const char* data, qint64 maxSize)
    {
        if(m_responseState == WaitingForResponseHeaders)
        {
            m_headerBuffer.append(data, maxSize);
            // We need to buffer the headers, so we can use the STATUS header appropriately
            QBuffer buffer;
            buffer.setData(m_headerBuffer);
            buffer.open(QIODevice::ReadOnly);
            buffer.seek(m_headerBufferPosition);
            while(buffer.canReadLine())
            {
                const QByteArray line = buffer.readLine().trimmed();
                if(line.isEmpty())
                {
                    Q_ASSERT(m_responseHeaders.contains("STATUS"));
                    Q_ASSERT(m_requestHeaders.contains("SERVER_PROTOCOL"));
                    m_responseState = WaitingForResponseBody;
                    const QByteArray status = m_responseHeaders.take("STATUS");
                    m_socket->write(m_requestHeaders.value("SERVER_PROTOCOL"));
                    m_socket->write(" ", 1);
                    m_socket->write(status);
                    m_socket->write("\r\n", 2);

                    //qDebug() << Q_FUNC_INFO << m_requestHeaders << m_responseHeaders;

                    for(
                        HeaderMap::ConstIterator it = m_responseHeaders.constBegin();
                        it != m_responseHeaders.constEnd();
                        ++it
                    )
                    {
                        m_socket->write(it.key());
                        m_socket->write(": ");
                        m_socket->write(it.value());
                        m_socket->write("\r\n");
                    }
                    m_socket->write("\r\n");
                    m_socket->write(buffer.readAll());
                    buffer.close();
                    m_headerBuffer.clear();
                    return maxSize;
                }
                const int lengthOfName = line.indexOf(':');
                const QByteArray name = line.left(lengthOfName);
                const QByteArray value = line.mid(lengthOfName + 2); // ": " after the name == 2 chars
                m_responseHeaders.insertMulti(name, value);
            }
            m_headerBufferPosition = buffer.pos();
            buffer.close();
            return maxSize;
        }
        Q_ASSERT(m_responseState == WaitingForResponseBody);
        return m_socket->write(data, maxSize);
    }
Esempio n. 24
0
void TestSymmetricCipher::testAes256CbcDecryption()
{
    QByteArray key = QByteArray::fromHex("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4");
    QByteArray iv = QByteArray::fromHex("000102030405060708090a0b0c0d0e0f");
    QByteArray cipherText = QByteArray::fromHex("f58c4c04d6e5f1ba779eabfb5f7bfbd6");
    cipherText.append(QByteArray::fromHex("9cfc4e967edb808d679f777bc6702c7d"));
    QByteArray plainText = QByteArray::fromHex("6bc1bee22e409f96e93d7e117393172a");
    plainText.append(QByteArray::fromHex("ae2d8a571e03ac9c9eb76fac45af8e51"));
    bool ok;

    SymmetricCipher cipher(SymmetricCipher::Aes256, SymmetricCipher::Cbc, SymmetricCipher::Decrypt);
    QVERIFY(cipher.init(key, iv));
    QCOMPARE(cipher.blockSize(), 16);

    QCOMPARE(cipher.process(cipherText, &ok),
             plainText);
    QVERIFY(ok);

    // padded with 16 0x16 bytes
    QByteArray cipherTextPadded = cipherText + QByteArray::fromHex("3a3aa5e0213db1a9901f9036cf5102d2");
    QBuffer buffer(&cipherTextPadded);
    SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc,
                                 SymmetricCipher::Decrypt);
    QVERIFY(stream.init(key, iv));
    buffer.open(QIODevice::ReadOnly);
    QVERIFY(stream.open(QIODevice::ReadOnly));

    QCOMPARE(stream.read(10),
             plainText.left(10));
    buffer.reset();
    QVERIFY(stream.reset());
    QCOMPARE(stream.read(20),
             plainText.left(20));
    buffer.reset();
    QVERIFY(stream.reset());
    QCOMPARE(stream.read(16),
             plainText.left(16));
    buffer.reset();
    QVERIFY(stream.reset());
    QCOMPARE(stream.read(100),
             plainText);
}
Esempio n. 25
0
static QList<QByteArray> splitRawData(QByteArray rawData, const QByteArray& sep)
{
  QList<QByteArray> ret;
  const int sepLength = sep.size();
  int index = 0;
  while ((index = rawData.indexOf(sep)) >= 0) {
    ret << rawData.left(index);
    rawData = rawData.mid(index + sepLength);
  }
  return ret;
}
void ThreadServeur::run()
{
    QByteArray baReception;
    while(m_etat)
    {
        baReception.clear();
             sockClient->waitForReadyRead(-1); // Attente des données pendant 0.1 sec maximum
             baReception.append(sockClient->read(sockClient->bytesAvailable())); // Lecture des donnée

             if(QString(baReception.left(4)) == QString("Env#"))
             {
                 emit(Envoie(sockClient,QString(baReception.right(baReception.length()))));
             }
             if(QString(baReception.left(4)) == QString("Fin#"))
             {
                 m_etat = false;
                emit(Fin(sockClient));
             }
    }
}
Esempio n. 27
0
BreakpointResponseId::BreakpointResponseId(const QByteArray &ba)
{
    int pos = ba.indexOf('.');
    if (pos == -1) {
        m_majorPart = ba.toInt();
        m_minorPart = 0;
    } else {
        m_majorPart = ba.left(pos).toInt();
        m_minorPart = ba.mid(pos + 1).toInt();
    }
}
Esempio n. 28
0
bool VHttpResponse::parse(QByteArray& buffer)
{
  if (!buffer.startsWith("HTTP/1")) return false;

  int pos = buffer.indexOf("\r\n\r\n");
  if (pos == -1) return false;

  QByteArray baHeader = buffer.left(pos + 2);

  int firstLinePos = baHeader.indexOf("\r\n");
  QByteArray baStatusLine = baHeader.left(firstLinePos);
  baHeader.remove(0, firstLinePos + 2);

  if (!statusLine.parse(baStatusLine)) return false;
  if (!header.parse(baHeader)) return false;

  buffer = buffer.mid(pos + 4);

  return true;
}
Esempio n. 29
0
void AccessManager::setRawCookie(const QByteArray &rawCookie, const  QUrl &url)
{
    QNetworkCookie cookie(rawCookie.left(rawCookie.indexOf('=')),
                          rawCookie.mid(rawCookie.indexOf('=')+1));
    qDebug() << Q_FUNC_INFO << cookie.name() << cookie.value();
    QList<QNetworkCookie> cookieList;
    cookieList.append(cookie);

    QNetworkCookieJar *jar = cookieJar();
    jar->setCookiesFromUrl(cookieList, url);
}
Esempio n. 30
0
void QMessage::setBody(const QString &bodyText, const QByteArray &mimeType)
{
    QByteArray mainType("text");
    QByteArray subType("plain");
    QByteArray charset;

    int index = mimeType.indexOf("/");
    if (index != -1) {
        mainType = mimeType.left(index).trimmed();

        subType = mimeType.mid(index + 1).trimmed();
        index = subType.indexOf(";");
        if (index != -1) {
            QString remainder = subType.mid(index + 1);
            subType = subType.left(index).trimmed();

            QRegExp charsetPattern("charset=(\\S+)");
            index = charsetPattern.indexIn(remainder);
            if (index != -1) {
                charset = charsetPattern.cap(1).toLatin1();
            }
        }
    }

    if (charset.isEmpty()) {
        charset = charsetFor(bodyText);
    }

    QMailMessageContentType ct;
    ct.setType(mainType);
    ct.setSubType(subType);
    ct.setCharset(charset);

    QMailMessageBody textBody(QMailMessageBody::fromData(bodyText, ct, QMailMessageBody::Base64));

    if (d_ptr->_message.multipartType() == QMailMessage::MultipartNone) {
        // Replace the body with this data
        d_ptr->_message.setBody(textBody);
    } else {
        // Replace any existing text with this part
        TextPartLocator locator;
        d_ptr->_message.foreachPart<TextPartLocator&>(locator);
        if (locator._location.isValid()) {
            // Update the existing body text part to contain the new text
            QMailMessagePart &bodyPart = d_ptr->_message.partAt(locator._location);
            bodyPart.setBody(textBody);
        } else {
            // Insert the text as the new first part
            QMailMessageContentDisposition cd(QMailMessageContentDisposition::Inline);
            QMailMessagePart part(QMailMessagePart::fromData(bodyText, ct, cd, QMailMessageBody::Base64));
            d_ptr->_message.prependPart(part);
        }
    }
}