コード例 #1
0
ファイル: QWsServer.cpp プロジェクト: Airisu/pokemon-online
QByteArray QWsServer::serializeInt( quint32 number, quint8 nbBytes )
{
	QByteArray ba;
	quint8 currentNbBytes = 0;
	while (number > 0 && currentNbBytes < nbBytes)
	{  
		char car = static_cast<char>(number & 0xFF);
		ba.prepend( car );
		number = number >> 8;
		currentNbBytes++;
	}
	char car = 0x00;
	while (currentNbBytes < nbBytes)
	{
		ba.prepend( car );
		currentNbBytes++;
    }
	return ba;
}
コード例 #2
0
void Exchange_BitCurex::cancelOrder(QString,QByteArray order)
{
	if(tickerOnly)return;

    QByteArray hashData="nonce="+QByteArray::number(++privateNonce)+"&offer_id="+order;
    order.prepend("{\"offer_id\":\"");
    order.append("\",\"nonce\":"+QByteArray::number(privateNonce)+"}");
	if(debugLevel)logThread->writeLog("Cancel order: "+order,2);
    sendToApi(305,"offer/del/",true,hashData,order);
}
コード例 #3
0
ファイル: ssprofile.cpp プロジェクト: sundys/shadowsocks-qt5
QByteArray SSProfile::getSsUrl()
{
    /*
     * cook a ss:// url
     */
    QString ssurl = QString("%1:%2@%3:%4").arg(method.toLower()).arg(password).arg(server).arg(server_port);
    QByteArray ba = QByteArray(ssurl.toStdString().c_str()).toBase64();
    ba.prepend("ss://");
    return ba;
}
コード例 #4
0
ファイル: qdataurl.cpp プロジェクト: jbartolozzi/CIS462_HW1
QT_BEGIN_NAMESPACE

/*!
    \internal

    Decode a data: URL into its mimetype and payload. Returns a null string if
    the URL could not be decoded.
*/
Q_CORE_EXPORT QPair<QString, QByteArray> qDecodeDataUrl(const QUrl &uri)
{
    QString mimeType;
    QByteArray payload;

    if (uri.scheme() == QLatin1String("data") && uri.host().isEmpty()) {
        mimeType = QLatin1String("text/plain;charset=US-ASCII");

        // the following would have been the correct thing, but
        // reality often differs from the specification. People have
        // data: URIs with ? and #
        //QByteArray data = QByteArray::fromPercentEncoding(uri.encodedPath());
        QByteArray data = QByteArray::fromPercentEncoding(uri.toEncoded());

        // remove the data: scheme
        data.remove(0, 5);

        // parse it:
        int pos = data.indexOf(',');
        if (pos != -1) {
            payload = data.mid(pos + 1);
            data.truncate(pos);
            data = data.trimmed();

            // find out if the payload is encoded in Base64
            if (data.endsWith(";base64")) {
                payload = QByteArray::fromBase64(payload);
                data.chop(7);
            }

            if (data.toLower().startsWith("charset")) {
                int i = 7;      // strlen("charset")
                while (data.at(i) == ' ')
                    ++i;
                if (data.at(i) == '=')
                    data.prepend("text/plain;");
            }

            if (!data.isEmpty())
                mimeType = QLatin1String(data.trimmed());

        }
    }

    return QPair<QString,QByteArray>(mimeType,payload);
}
コード例 #5
0
void PrefQuantitySpinBox::setParamGrpPath(const QByteArray& path)
{
    Q_D(PrefQuantitySpinBox);
    QByteArray groupPath = path;
    if (!groupPath.startsWith("User parameter:")) {
        groupPath.prepend("User parameter:BaseApp/Preferences/");
    }
    d->handle = App::GetApplication().GetParameterGroupByPath(groupPath);
    if (d->handle.isValid())
        d->prefGrp = path;
}
コード例 #6
0
ファイル: xor.cpp プロジェクト: pipacker10/pip3line
QByteArray Xor::applyPreviousInput(const QByteArray &data, QByteArray & key)
{
    QByteArray output;
    QByteArray temp = data;
    temp.prepend(key);

    for (int i = key.size() ; i < temp.size(); i++) {
        output.append(temp.at(i) ^ temp.at(i - key.size()));
    }

    return output;
}
コード例 #7
0
DataImageWriter TxtToPng(const QByteArray &txtData)
{
    QByteArray data = qCompress(txtData, COMPRESSION_LEVEL);

    qint32 actual_size = data.size();
    data.prepend(reinterpret_cast<const char *>(&actual_size), sizeof(qint32));

    //此处不能直接返回通过data.constData()来构建的QImage对象
    //由于QByteArray的implicit sharing(copy-on-write)特性,data在离开该函数后将会被释放掉(因为其引用计数仅为1)
    //从而导致QImage对象的数据出现随机值。为了避免data的释放,需要增加一个间接层来接受data,以便增加其引用计数
    return DataImageWriter(data);
}
コード例 #8
0
ファイル: uploader.cpp プロジェクト: QtDesktop/screengrab
/*!
 * Create boundary string
 * \param cleared -detect for str boundary line in httpRequest
 */
QByteArray Uploader::boundary(bool cleared)
{
    QByteArray retBoundary = _strBoundary;

    if (cleared == false)
    {
        retBoundary.append("\r\n");
        retBoundary.prepend("--");
    }

    return retBoundary;
}
コード例 #9
0
static QByteArray formatRegister(quint64 v, int size, RegisterFormat format)
{
    QByteArray result;
    if (format == HexadecimalFormat) {
        result = QByteArray::number(v, 16);
        result.prepend(QByteArray(2*size - result.size(), '0'));
    } else if (format == DecimalFormat) {
        result = QByteArray::number(v, 10);
        result.prepend(QByteArray(2*size - result.size(), ' '));
    } else if (format == CharacterFormat) {
        if (v >= 32 && v < 127) {
            result += '\'';
            result += char(v);
            result += '\'';
        } else {
            result += "   ";
        }
        result.prepend(QByteArray(2*size - result.size(), ' '));
    }
    return result;
}
コード例 #10
0
ファイル: moc.cpp プロジェクト: Fale/qtmoko
void Moc::generate(FILE *out)
{

    QDateTime dt = QDateTime::currentDateTime();
    QByteArray dstr = dt.toString().toLatin1();
    QByteArray fn = filename;
    int i = filename.length()-1;
    while (i>0 && filename[i-1] != '/' && filename[i-1] != '\\')
        --i;                                // skip path
    if (i >= 0)
        fn = filename.mid(i);
    fprintf(out, "/****************************************************************************\n"
            "** Meta object code from reading C++ file '%s'\n**\n" , (const char*)fn);
    fprintf(out, "** Created: %s\n"
            "**      by: The Qt Meta Object Compiler version %d (Qt %s)\n**\n" , dstr.data(), mocOutputRevision, QT_VERSION_STR);
    fprintf(out, "** WARNING! All changes made in this file will be lost!\n"
            "*****************************************************************************/\n\n");


    if (!noInclude) {
        if (includePath.size() && includePath.right(1) != "/")
            includePath += "/";
        for (int i = 0; i < includeFiles.size(); ++i) {
            QByteArray inc = includeFiles.at(i);
            if (inc[0] != '<' && inc[0] != '"') {
                if (includePath.size() && includePath != "./")
                    inc.prepend(includePath);
                inc = "\"" + inc + "\"";
            }
            fprintf(out, "#include %s\n", inc.constData());
        }
    }
    if (classList.size() && classList.first().classname == "Qt")
        fprintf(out, "#include <QtCore/qobject.h>\n");

    fprintf(out, "#if !defined(Q_MOC_OUTPUT_REVISION)\n"
            "#error \"The header file '%s' doesn't include <QObject>.\"\n", (const char *)fn);
    fprintf(out, "#elif Q_MOC_OUTPUT_REVISION != %d\n", mocOutputRevision);
    fprintf(out, "#error \"This file was generated using the moc from %s."
            " It\"\n#error \"cannot be used with the include files from"
            " this version of Qt.\"\n#error \"(The moc has changed too"
            " much.)\"\n", QT_VERSION_STR);
    fprintf(out, "#endif\n\n");

    fprintf(out, "QT_BEGIN_MOC_NAMESPACE\n");

    for (i = 0; i < classList.size(); ++i) {
        Generator generator(&classList[i], metaTypes, out);
        generator.generateCode();
    }

    fprintf(out, "QT_END_MOC_NAMESPACE\n");
}
コード例 #11
0
static QByteArray formatRegister(quint64 v, int size, RegisterFormat format, bool forEdit)
{
    QByteArray result;
    if (format == HexadecimalFormat) {
        result = QByteArray::number(v, 16);
        result.prepend(QByteArray(2*size - result.size(), '0'));
    } else if (format == DecimalFormat) {
        result = QByteArray::number(v, 10);
        result.prepend(QByteArray(2*size - result.size(), ' '));
    } else if (format == SignedDecimalFormat) {
        qint64 sv;
        if (size >= 8)
            sv = qint64(v);
        else if (size >= 4)
            sv = qint32(v);
        else if (size >= 2)
            sv = qint16(v);
        else
            sv = qint8(v);
        result = QByteArray::number(sv, 10);
        result.prepend(QByteArray(2*size - result.size(), ' '));
    } else if (format == CharacterFormat) {
        bool spacesOnly = true;
        if (v >= 32 && v < 127) {
            spacesOnly = false;
            if (!forEdit)
                result += '\'';
            result += char(v);
            if (!forEdit)
                result += '\'';
        } else {
            result += "   ";
        }
        if (spacesOnly && forEdit)
            result.clear();
        else
            result.prepend(QByteArray(2*size - result.size(), ' '));
    }
    return result;
}
コード例 #12
0
ファイル: phpqt5_zif.cpp プロジェクト: wxmaper/PQEngine
void PHPQt5::zif_R(INTERNAL_FUNCTION_PARAMETERS)
{
#ifdef PQDEBUG
    PQDBG_LVL_START(__FUNCTION__);
#endif

    const char* path;
    int path_len;

    bool addQRC = false;

    if(zend_parse_parameters(ZEND_NUM_ARGS(), "s|b", &path, &path_len, &addQRC)) {
        return;
    }

    /* old
    echo R($path);        // :/corename/some/file.txt
    echo R($path, false); // :/corename/some/file.txt
    echo R($path, true);  // qrc://corename/some/file.txt
    */
    /* new
    echo R($path);        // :/some/file.txt
    echo R($path, false); // :/some/file.txt
    echo R($path, true);  // qrc://some/file.txt
    */

    QByteArray rpath = QByteArray(path).replace("\\", "/").replace("//","/");
    if(addQRC) {
        //rpath.prepend(getCorename().prepend("qrc://").append("/"));
        rpath.prepend("qrc://");
    }
    else {
        //rpath.prepend(getCorename().prepend(":/").append("/"));
        rpath.prepend(":/");
    }

    PQDBG_LVL_DONE();
    RETURN_STRING(rpath.constData());
}
コード例 #13
0
ファイル: data.cpp プロジェクト: achorein/silenteye
 QByteArray Data::toByteArray() const
 {
     QByteArray bytes = m_data;
     switch(m_format)
     {
     case BYTES:
     case UTF8:
     case LATIN1:
     case ASCII:
         bytes.prepend((char)((int)'0' + (int)m_format));
         break;
     case FILE:
         bytes.prepend((m_name+'<').toUtf8());
         bytes.prepend((char)((int)'0' + (int)m_format));
         break;
     case UINT32:
     case F_UNDEF:
         break;
     }
     
     return bytes;
 }
コード例 #14
0
QString EircomKeygen::dectoString(int mac) {
	QByteArray ret;
	while (mac > 0) {
		switch (mac % 10) {
		case 0:
			ret.prepend("Zero");
			break;
		case 1:
			ret.prepend("One");
			break;
		case 2:
			ret.prepend("Two");
			break;
		case 3:
			ret.prepend("Three");
			break;
		case 4:
			ret.prepend("Four");
			break;
		case 5:
			ret.prepend("Five");
			break;
		case 6:
			ret.prepend("Six");
			break;
		case 7:
			ret.prepend("Seven");
			break;
		case 8:
			ret.prepend("Eight");
			break;
		case 9:
			ret.prepend("Nine");
			break;
		}
		mac /= 10;
	}
	return ret;
}
コード例 #15
0
ファイル: brisawebserver.cpp プロジェクト: MIRAvzw/qt-brisa
void BrisaWebserver::removeService(QByteArray path)
{
    if (!path.startsWith('/'))
        path.prepend('/');

    mutex.lock();

    if (services.contains(path)) {
        services[path]->m_path.clear();
        services.remove(path);
    }

    mutex.unlock();
}
コード例 #16
0
ファイル: rpcadaptor.cpp プロジェクト: marchon/pokerbridge
void RpcAdaptor::spySignals(QObject *target)
{
    const QMetaObject *them = target->metaObject();
	for(int idx=0;idx<them->methodCount();idx++)
	{
		QMetaMethod mm = them->method(idx);
		if (mm.methodType() != QMetaMethod::Signal)
            continue;
		QByteArray sig = QMetaObject::normalizedSignature(mm.signature());
		sig.prepend(QSIGNAL_CODE + '0');
		QSignalIntercepter *si = new RpcSignalIntercepter(target, sig, this);
//		qLog(Debug)<<"signalspy:"<<sig;
	}
}
コード例 #17
0
ファイル: hiddmxdevice.cpp プロジェクト: PML369/qlcplus
void HIDDMXDevice::outputDMX(const QByteArray &universe, bool forceWrite)
{
    for (int i = 0; i < 16; i++)
    {
        int startOff = i * 32;
        if (startOff >= universe.size())
            return;
        QByteArray chunk = universe.mid(startOff, 32);
        if (chunk.size() < 32)
            chunk.append(QByteArray(32 - chunk.size(), (char)0x0));
        if(forceWrite == true || chunk != m_dmx_cmp.mid(startOff, 32))
        {
            /** Save different data to m_dmx_cmp */
            m_dmx_cmp.replace(startOff, 32, chunk);

            chunk.prepend((char)i);
            chunk.prepend((char)0x0);

            /** Output new data */
            hid_write(m_handle, (const unsigned char *)chunk.data(), chunk.size());
        }
    }
}
コード例 #18
0
void GdbServer::MakePacket(QByteArray &checksum,QByteArray * binary,bool ok)
{
    uint8_t check = 0;

    for (int i = 0 ; i < checksum.count(); i++)
    {
        check += (uint8_t)checksum.at(i);
    }

    GDB_SEND(checksum);
    checksum.prepend('$');
    if (ok)
        checksum.prepend('+');
    else
        checksum.prepend('-');
    if (binary)
    {
        checksum.append(*binary);
    }
    checksum.append('#');

    QString temp = QString("%1").arg(check,2,16,QChar('0'));
    checksum.append(temp);
}
コード例 #19
0
lastfm::NetworkAccessManager::NetworkAccessManager( QObject* parent )
               : QNetworkAccessManager( parent )
            #if defined WIN32 && ! defined __MINGW32__
               , m_monitor( 0 )
            #endif
{
    // can't be done in above init, as applicationName() won't be set
    if (lastfm::UserAgent.isEmpty())
    {
        QByteArray name = QCoreApplication::applicationName().toUtf8();
        QByteArray version = QCoreApplication::applicationVersion().toUtf8();
        if (version.size()) version.prepend( ' ' );
        lastfm::UserAgent = name + version + " (" + lastfm::platform() + ")";
    }
}
コード例 #20
0
ファイル: brisawebserver.cpp プロジェクト: MIRAvzw/qt-brisa
void BrisaWebserver::addService(QByteArray path, BrisaWebService *service)
{
    if (!service || path.isEmpty())
        return;

    mutex.lock();

    if (!path.startsWith('/'))
        path.prepend('/');

    services[path] = service;
    service->m_path = path;

    mutex.unlock();
}
コード例 #21
0
ファイル: cipher.cpp プロジェクト: fuzzball81/quassel
QByteArray Cipher::parseInitKeyX(QByteArray key)
{
    QCA::Initializer init;
    bool isCBC = false;

    if (key.endsWith(" CBC")) {
        isCBC = true;
        key.chop(4);
    }

    if (key.length() != 181)
        return QByteArray();

    QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
    QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
    QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH();

    if (privateKey.isNull())
        return QByteArray();

    QByteArray publicKey = privateKey.y().toArray().toByteArray();

    // remove leading 0
    if (publicKey.length() > 135 && publicKey.at(0) == '\0')
        publicKey = publicKey.mid(1);

    QCA::DHPublicKey remotePub(group, remoteKey);

    if (remotePub.isNull())
        return QByteArray();

    QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray();
    sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();

    // remove trailing = because mircryption and fish think it's a swell idea.
    while (sharedKey.endsWith('='))
        sharedKey.chop(1);

    if (isCBC)
        sharedKey.prepend("cbc:");

    bool success = setKey(sharedKey);

    if (!success)
        return QByteArray();

    return publicKey.toBase64().append('A');
}
コード例 #22
0
ファイル: recorder.cpp プロジェクト: takashiro/OnePieceBang
QImage Recorder::TXT2PNG(QByteArray txtData){
	QByteArray data = qCompress(txtData, 9);
	qint32 actual_size = data.size();
	data.prepend((const char *)&actual_size, sizeof(qint32));

	// actual data = width * height - padding
	int width = ceil(sqrt((double)data.size()));
	int height = width;
	int padding = width * height - data.size();
	QByteArray paddingData;
	paddingData.fill('\0', padding);
	data.append(paddingData);

	QImage image((const uchar *)data.constData(), width, height, QImage::Format_ARGB32);
	return image;
}
コード例 #23
0
ファイル: knmusictagm4a.cpp プロジェクト: CasparLi/Mu
inline QByteArray KNMusicTagM4a::packBox(const KNMusicTagM4a::M4ABox &box)
{
    //Generate the box data field.
    QByteArray boxData;
    //First set the name of the box.
    boxData.append(box.name);
    //Then follow up the box data.
    boxData.append(box.data, box.size);
    //The data box size is the size of the box data plus 4, prepend the size to
    //the box data.
    char dataSize[5];
    KNMusicUtil::int32ToChar(dataSize, boxData.size()+4);
    boxData.prepend(dataSize, 4);
    //Give baack the box data.
    return boxData;
}
コード例 #24
0
ファイル: webproxy.cpp プロジェクト: gagiel/X2
    void 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);

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

        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);
        }
    }
コード例 #25
0
ファイル: ctcpserver.cpp プロジェクト: tucher/RaspberryTV
QByteArray CTcpServer::parseHTML(QByteArray rawData, QVariantMap & postParams)
{
    //qDebug() << rawData;

    QString string = QString::fromUtf8(rawData);
    if(string.indexOf("GET") == 0)
    {
        QFile indexHTML("index.html");
        QByteArray data;
        if(indexHTML.open(QIODevice::ReadOnly))
            data = indexHTML.readAll();

        data.prepend("HTTP/1.0 200 Ok\r\nContent-Type: text/html; charset=\"utf-8\"\r\n\r\n");
        //qDebug() << data;
        return  data;
    }
    else if(string.indexOf("POST") == 0)
    {
        int i = string.indexOf("Content-Length: ") + 16;
        QString sContL = string.mid(i, string.indexOf("\n", string.indexOf("Content-Length: ")) - i - 1);
        bool ok = false;
        int contentLength = sContL.toInt(&ok);
        if(ok)
        {
            QString content = string.right(contentLength);

            QVariantMap params;
            QJsonDocument json = QJsonDocument::fromJson(content.toUtf8());
            if(!json.isNull())
            {
                postParams = json.toVariant().toMap();
            }
            else
            {
                QStringList pList = content.split("&");
                foreach(QString p, pList)
                {
                    QStringList t = p.split("=");
                    if(t.count() == 2)
                    {
                        params.insert(t[0], QUrl::fromPercentEncoding(t[1].toUtf8()));
                    }
                }
                postParams = params;
            }

        }
コード例 #26
0
ファイル: qtmain_win.cpp プロジェクト: BGmot/Qt
int APIENTRY WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR /*cmdParamarg*/, int cmdShow)
#endif
{
    QByteArray cmdParam = QString::fromWCharArray(GetCommandLine()).toLocal8Bit();

#if defined(Q_OS_WINCE)
    wchar_t appName[MAX_PATH];
    GetModuleFileName(0, appName, MAX_PATH);
    cmdParam.prepend(QString(QLatin1String("\"%1\" ")).arg(QString::fromWCharArray(appName)).toLocal8Bit());
#endif

    int argc = 0;
    QVector<char *> argv(8);
    qWinMain(instance, prevInstance, cmdParam.data(), cmdShow, argc, argv);

#if defined(Q_OS_WINCE)
    wchar_t uniqueAppID[MAX_PATH];
    GetModuleFileName(0, uniqueAppID, MAX_PATH);
    QString uid = QString::fromWCharArray(uniqueAppID).toLower().replace(QLatin1String("\\"), QLatin1String("_"));

    // If there exists an other instance of this application
    // it will be the owner of a mutex with the unique ID.
    HANDLE mutex = CreateMutex(NULL, TRUE, (LPCWSTR)uid.utf16());
    if (mutex && ERROR_ALREADY_EXISTS == GetLastError()) {
        CloseHandle(mutex);

        // The app is already running, so we use the unique
        // ID to create a unique messageNo, which is used
        // as the registered class name for the windows
        // created. Set the first instance's window to the
        // foreground, else just terminate.
        // Use bitwise 0x01 OR to reactivate window state if
        // it was hidden
        UINT msgNo = RegisterWindowMessage((LPCWSTR)uid.utf16());
        HWND aHwnd = FindWindow((LPCWSTR)QString::number(msgNo).utf16(), 0);
        if (aHwnd)
            SetForegroundWindow((HWND)(((ULONG)aHwnd) | 0x01));
        return 0;
    }
#endif // Q_OS_WINCE

    int result = main(argc, argv.data());
#if defined(Q_OS_WINCE)
    CloseHandle(mutex);
#endif
    return result;
}
コード例 #27
0
void UdpRelay::onClientUdpSocketReadyRead()
{
    QUdpSocket *sock = qobject_cast<QUdpSocket *>(sender());
    if (!sock) {
        emit info("Fatal. A false object calling onClientUdpSocketReadyRead.");
        return;
    }

    if (sock->pendingDatagramSize() > RecvSize) {
        emit info("[UDP] Datagram is too large. Discarded.");
        return;
    }

    QByteArray data;
    data.resize(sock->pendingDatagramSize());
    QHostAddress r_addr;
    quint16 r_port;
    sock->readDatagram(data.data(), RecvSize, &r_addr, &r_port);

    QByteArray response;
    if (isLocal) {
        data = encryptor->decryptAll(data);
        Address destAddr;
        int header_length = 0;
        bool _auth;

        Common::parseHeader(data, destAddr, header_length, _auth);
        if (header_length == 0) {
            emit info("[UDP] Can't parse header. "
                      "Wrong encryption method or password?");
            return;
        }
        response = QByteArray(3, static_cast<char>(0)) + data;
    } else {
        data.prepend(Common::packAddress(r_addr, r_port));
        response = encryptor->encryptAll(data);
    }

    Address clientAddress = cache.key(sock);
    if (clientAddress.getPort() != 0) {
        listenSocket.writeDatagram(response,
                                   clientAddress.getFirstIP(),
                                   clientAddress.getPort());
    } else {
        emit debug("[UDP] Drop a packet from somewhere else we know.");
    }
}
コード例 #28
0
QByteArray preprocess(QByteArray json)
{
  int commentIndex = json.indexOf('#', 0);
  while (commentIndex > -1)
  {
    int commentEnd = json.indexOf('\n', commentIndex);
    if (commentEnd == -1)
    {
      json.truncate(commentIndex);
      break;
    }
    json.remove(commentIndex, commentEnd - commentIndex);
    commentIndex = json.indexOf('#', commentIndex);
  }

  return json.prepend('{').append('}');
}
コード例 #29
0
ファイル: HttpThread.C プロジェクト: bjnano/IQmol
void HttpThread::getResponse()
{
   QHttp::ConnectionMode mode = (m_url.scheme().toLower() == "https") ?
      QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;

   m_http->setHost(m_url.host(), mode, m_url.port() == -1 ? 0 : m_url.port());
    
   QByteArray path = QUrl::toPercentEncoding(m_url.path(), "/?&=");
qDebug() << "Attempting to get" << path;
   if (path.isEmpty()) path = "/";
   if (!path.startsWith("/")) path.prepend("/");
        
qDebug() << "Attempting to get" << path;
   m_buffer = new QBuffer();
   m_buffer->open(QBuffer::ReadWrite);
   m_httpGetId = m_http->get(path, m_buffer);
}
コード例 #30
0
void QTweetUserStream::replyReadyRead()
{
    QByteArray response = m_reply->readAll();

#ifdef STREAM_LOGGER
    m_streamLog.write(response);
    m_streamLog.write("\n");
#endif

    if (m_streamTryingReconnect) {
        emit reconnected();
        m_streamTryingReconnect = false;
    }

    //set backoff timer to initial interval
    m_backofftimer->setInterval(20000);

    QByteArray responseWithPreviousCache = response.prepend(m_cachedResponse);

    int start = 0;
    int end;

    while ((end = responseWithPreviousCache.indexOf('\r', start)) != -1) {
        if (start != end) {
            QByteArray element = responseWithPreviousCache.mid(start, end - start);

            if (!element.isEmpty()) {
                emit stream(element);
                parseStream(element);
            }
        }

        int skip = (response.at(end + 1) == QLatin1Char('\n')) ? 2 : 1;
        start = end + skip;
    }

    //undelimited part just cache it
    m_cachedResponse.clear();

    if (start != responseWithPreviousCache.size()) {
        QByteArray element = responseWithPreviousCache.mid(start);
        if (!element.isEmpty())
            m_cachedResponse = element;
    }
}