Exemple #1
2
QByteArray Dialog::digest(const QString s)
{
    QByteArray c = s.toLatin1();
    int index;

    index = 0;

    while ((index = c.indexOf("\\n", index)) != -1) {
        c.replace(index, 2, "\n");
        index += 1;
    }

    index = 0;

    while ((index = c.indexOf("\\t", index)) != -1) {
        c.replace(index, 2, "\t");
        index += 1;
    }

    index = 0;

    while ((index = c.indexOf("\r", index)) != -1) {
        c.remove(index, 1);
    }

    return c;
}
void Dispatcher::handleReceivedForwardedAnnounce(QByteArray &datagram)
{
    QByteArray tmp = datagram.mid(2, 4);
    QHostAddress announcingHost(getQuint32FromByteArray(&tmp));
    datagram.remove(2, 4);
    handleReceivedAnnounce(UnicastPacket, announcingHost, datagram);
}
/**
 *   Destroys tweet with id
 *   @param id tweet ID
 *   @param trimUser trims users info
 *   @param includeEntities true to include node entities in response
 */
void QTweetStatusDestroy::destroy(qint64 id,
                                  bool trimUser)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("https://api.twitter.com/1.1/statuses/destroy.json");

    QUrl urlQuery(url);

    urlQuery.addQueryItem("id", QString::number(id));

    if (trimUser)
        urlQuery.addQueryItem("trim_user", "true");

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(urlQuery, OAuth::POST);
    req.setRawHeader(AUTH_HEADER, oauthHeader);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QByteArray postBody = urlQuery.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority | QUrl::RemovePath);
    postBody.remove(0, 1);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, postBody);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
// forward the CID ping to own bucket on request
void Dispatcher::handleReceivedCIDPingForwardRequest(QHostAddress &fromAddr, QByteArray &data)
{
    data.remove(0, 2);
    QByteArray tmp = data.mid(0, 4);
    QHostAddress allegedFromHost = QHostAddress(getQuint32FromByteArray(&tmp));
    if (fromAddr != allegedFromHost)
        return;

    QByteArray datagram;
    datagram.reserve(30);
    switch(networkBootstrap->getBootstrapStatus())
    {
    case NETWORK_MCAST:
        datagram.append(MulticastPacket);
        datagram.append(CIDPingForwardedPacket);
        datagram.append(data);
        sendMulticastRawDatagram(datagram);
        break;
    case NETWORK_BCAST:
        datagram.append(BroadcastPacket);
        datagram.append(CIDPingForwardedPacket);
        datagram.append(data);
        sendBroadcastRawDatagram(datagram);
        break;
    }
}
Exemple #5
0
void BabyMEG::setFiffData(QByteArray DATA)
{
    //get the first byte -- the data format
    int dformat = DATA.left(1).toInt();

    DATA.remove(0,1);
    qint32 rows = m_pFiffInfo->nchan;
    qint32 cols = (DATA.size()/dformat)/rows;

    qDebug() << "[BabyMEG] Matrix " << rows << "x" << cols << " [Data bytes:" << dformat << "]";

    MatrixXf rawData(Map<MatrixXf>( (float*)DATA.data(),rows, cols ));

    for(qint32 i = 0; i < rows*cols; ++i)
        IOUtils::swap_floatp(rawData.data()+i);


    if(m_bIsRunning)
    {
        if(!m_pRawMatrixBuffer)
            m_pRawMatrixBuffer = CircularMatrixBuffer<float>::SPtr(new CircularMatrixBuffer<float>(40, rows, cols));

        m_pRawMatrixBuffer->push(&rawData);
    }
//    else
//    {
////        std::cout << "Data coming" << std::endl; //"first ten elements \n" << rawData.block(0,0,1,10) << std::endl;

//        emit DataToSquidCtrlGUI(rawData);
//    }

    emit DataToSquidCtrlGUI(rawData);
}
Exemple #6
0
void UrlOpener::openEmail(const QByteArray &email)
{
	QString client;

	bool useDefaultEMailClient = m_configuration->deprecatedApi()->readBoolEntry("Chat", "UseDefaultEMailClient", true);
	if (!useDefaultEMailClient)
		client = m_configuration->deprecatedApi()->readEntry("Chat", "MailClient");

	QByteArray urlForDesktopServices;
	QByteArray urlForApplication;
	if (email.startsWith("mailto:"))
	{
		urlForDesktopServices = email;
		urlForApplication = email;
		urlForApplication.remove(0, 7);
	}
	else
	{
		urlForDesktopServices = "mailto:" + email;
		urlForApplication = email;
	}

	if (!openUrl(urlForDesktopServices, urlForApplication, client))
		MessageDialog::show(m_iconsManager->iconByPath(KaduIcon("dialog-error")), QCoreApplication::translate("@default", QT_TR_NOOP("Kadu")),
				QCoreApplication::translate("@default", QT_TR_NOOP("Could not spawn Mail client process. Check if the Mail client is functional")));
}
void SessionStore::resetSession(HttpServerRequest &request) const
{
    // init variables
    QList<QByteArray> headers(request.headers().values("Cookie"));
    QByteArray newValue;

    // remove old cookies
    request.headers().remove("Cookie");

    // find cookies that don't match this store's settings
    for (int i = 0;i != headers.size();++i) {
        QList<QNetworkCookie> cookies(QNetworkCookie::parseCookies(headers[i]));

        for (int i = 0;i != cookies.size();++i) {
            if (cookies[i].name() != settings.name) {
                newValue
                    += cookies[i].toRawForm(QNetworkCookie::NameAndValueOnly)
                    + "; ";
            }
        }
    }

    if (!newValue.isEmpty()) {
        // removes the final "; "
        newValue.remove(newValue.size() - 2, 2);
    }

    // update the request headers
    request.headers().insert("Cookie", newValue);
}
Exemple #8
0
void Networking::sendCoins(QString address, QString amount)
{
    QString sendRequest;
    sendRequest = QString("https://www.instawallet.org/api/v1/w/%1/payment").arg(walletId);

    updating = true;

    QByteArray data;
    QUrl parameters;

    double convertedAmount;

    long long convertedLongAmount;

    QString stringAmount;

    convertedAmount = amount.toDouble();
    convertedLongAmount = convertedAmount * 1e8 + (convertedAmount < 0.0 ? -.5 : .5);

    stringAmount = QString("%1").arg(convertedLongAmount);

    qDebug("Amount converted to Satoshis: " + stringAmount.toAscii());

    parameters.addQueryItem("address", address);
    parameters.addQueryItem("amount", stringAmount);
    data.append(parameters.toString());
    data.remove(0, 1);

    networkPaymentManager->post(QNetworkRequest(QUrl(sendRequest)), data)->ignoreSslErrors();

    connect(networkPaymentManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(walletPaymentLoaded(QNetworkReply*)));
}
Exemple #9
0
void UrlOpener::openEmail(const QByteArray &email)
{
	QString client;
	bool useDefaultEMailClient = config_file.readBoolEntry("Chat", "UseDefaultEMailClient", true);
	if (useDefaultEMailClient)
		client = config_file.readEntry("Chat", "MailClient");

	QByteArray urlForDesktopServices;
	QByteArray urlForApplication;
	if (email.startsWith("mailto:"))
	{
		urlForDesktopServices = email;
		urlForApplication = email;
		urlForApplication.remove(0, 7);
	}
	else
	{
		urlForDesktopServices = "mailto:" + email;
		urlForApplication = email;
	}

	if (!openUrl(urlForDesktopServices, urlForApplication, client))
		MessageDialog::show("dialog-error", qApp->translate("@default", QT_TR_NOOP("Kadu")),
				qApp->translate("@default", QT_TR_NOOP("Could not spawn Mail client process. Check if the Mail client is functional")));
}
void LyricWikiPlugin::onSongReplyReceived()
{
    QByteArray data = reply->readAll();
    reply->deleteLater();

    // <div class='lyricbox'>(...)<script>(...)</script>(lyrics)<!--
    int i = data.indexOf("<div class='lyricbox'>");
    if (i != -1) {
        i += 22;
        data.remove(data.indexOf("<!--", i), data.length());

        if (data.indexOf("Category:Instrumental", i) != -1) {
            emit error("According to LyricWiki this track is instrumental.");
            return;
        }

        QTextDocument lyrics; lyrics.setHtml(data.mid(data.indexOf("</script>", i) + 9));
        QString plainLyrics = lyrics.toPlainText();

        if (plainLyrics.contains("we are not licensed to display the full lyrics for this song")) {
            emit error("The lyrics for this song are incomplete on LyricWiki.");
        } else {
            emit fetched(plainLyrics);
        }
    } else {
        emit error("The lyrics for this song are missing on LyricWiki.");
    }
}
Exemple #11
0
void HWMap::SendToClientFirst()
{
    SendIPC(QString("eseed %1").arg(m_seed).toUtf8());
    SendIPC(QString("e$template_filter %1").arg(templateFilter).toUtf8());
    SendIPC(QString("e$mapgen %1").arg(m_mapgen).toUtf8());
    if (!m_script.isEmpty())
    {
        SendIPC(QString("escript Scripts/Multiplayer/%1.lua").arg(m_script).toUtf8());
    }

    switch (m_mapgen)
    {
        case MAPGEN_MAZE:
            SendIPC(QString("e$maze_size %1").arg(m_maze_size).toUtf8());
            break;

        case MAPGEN_DRAWN:
        {
            QByteArray data = m_drawMapData;
            while(data.size() > 0)
            {
                QByteArray tmp = data;
                tmp.truncate(200);
                SendIPC("edraw " + tmp);
                data.remove(0, 200);
            }
            break;
        }
        default:
            ;
    }

    SendIPC("!");
}
Exemple #12
0
void BoxitSocket::sendData(quint16 msgID, QByteArray data) {
    // Send data in multiple data packages, if data is too big...
    while (true) {
        QByteArray subData = data.mid(0, BOXIT_SOCKET_MAX_SIZE);
        data.remove(0, BOXIT_SOCKET_MAX_SIZE);

        quint16 subMsgID = msgID;
        if (!data.isEmpty())
            subMsgID = MSG_DATA_PACKAGE_MULTIPLE;

        // Send data
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_6);
        out << (quint16)0;
        out << (quint16)subMsgID;
        out << subData;
        out.device()->seek(0);
        out << (quint16)(block.size() - 2*sizeof(quint16));

        write(block);
        flush();

        waitForBytesWritten(2000);

        if (data.isEmpty())
            break;
    }
}
Exemple #13
0
QByteArray Parser::getPacket(QByteArray& ta){
    const char etx = 0x03;
    int n = ta.indexOf(etx);
    QByteArray ra = ta.left(n);
    ta = ta.remove(0,n+1);
    return ra;
}
Exemple #14
0
QByteArray shortenTemplates(const QByteArray& identifier)
{
    QByteArray ret = identifier;
    Q_ASSERT(KSharedConfig::openConfig());
    KConfigGroup conf = KSharedConfig::openConfig()->group(QLatin1String("Settings"));
    if (conf.readEntry(QLatin1String("shortenTemplates"), false)) {
        // remove template arguments between <...>
        int depth = 0;
        int open = 0;
        for (int i = 0; i < ret.length(); ++i) {
            if (ret.at(i) == '<') {
                if (!depth) {
                    open = i;
                }
                ++depth;
            } else if (ret.at(i) == '>') {
                --depth;
                if (!depth) {
                    ret.remove(open + 1, i - open - 1);
                    i = open + 1;
                    open = 0;
                }
            }
        }
    }
    return ret;
}
Exemple #15
0
ImapMailbox *ImapPrivate::parseMessages (ImapMailbox *mailbox) {
    QByteArray response;

    while (true) {
        // Read Message
        response.clear();       
        do {
            if (response.size() > 0) {
                response.remove(response.lastIndexOf('}'), 
                                response.size() - response.lastIndexOf('{'));
            }
            response.append(readLine());
        } while (isMultiline(response));

        // Break if End Response Found.
        if (isResponseEnd(response))
            break;

        // Parse and Add Message to Mailbox
        ImapMessage *message = _imapParseMessage(response.trimmed());
        if (message != NULL) mailbox->addMessage(message);
    }
    
    return(mailbox);
}
Exemple #16
0
QByteArray ImapPrivate::hmacMd5 (const QString& username,
                                 const QString& password,
                                 const QString& serverResponse)
{
    QByteArray passwordBytes = password.toLatin1();
    QByteArray ipad(64, 0);
    QByteArray opad(64, 0);
    
    for (int i = 0; i < 64; ++i) {
        if (i < passwordBytes.size()) {
            ipad[i] = (quint8)(0x36 ^ passwordBytes[i]);
            opad[i] = (quint8)(0x5c ^ passwordBytes[i]);
        } else {
            ipad[i] = 0x36;
            opad[i] = 0x5c;
        }
    }

    QByteArray serverResponseBytes = serverResponse.toLatin1();
    while (serverResponseBytes[0] == '+' || serverResponseBytes[0] == ' ')
        serverResponseBytes.remove(0, 1);
        
    QCryptographicHash md5hash(QCryptographicHash::Md5);
    md5hash.addData(ipad);
    md5hash.addData(serverResponseBytes);
    QByteArray resultIpad = md5hash.result();
    
    md5hash.reset();
    md5hash.addData(opad);
    md5hash.addData(resultIpad);
    QByteArray resultOpad = md5hash.result();
    
    QByteArray response = username.toLatin1() + ' ' + resultOpad.toHex();
    return(response.toBase64());
}
/**
 *  Creates place
 *  @param name the name a place is known as
 *  @param containedWithin placeid within which the new place can be found. Be close as possible with
                           contained place
 *  @param token token found in the response from QTweetGeoSimilarPlaces
 *  @param latLong latitude and longitude
 */
void QTweetGeoPlaceCreate::create(const QString &name,
                                  const QString &containedWithin,
                                  const QString &token,
                                  const QTweetGeoCoord &latLong)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("http://api.twitter.com/1/geo/place.json");
    QUrl urlQuery(url);

    urlQuery.addEncodedQueryItem("name", QUrl::toPercentEncoding(name));
    urlQuery.addQueryItem("contained_within", containedWithin);
    urlQuery.addQueryItem("token", token);
    urlQuery.addQueryItem("lat", QString::number(latLong.latitude()));
    urlQuery.addQueryItem("long", QString::number(latLong.longitude()));

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(urlQuery, OAuth::POST);

    QNetworkRequest req(url);
    req.setRawHeader(AUTH_HEADER, oauthHeader);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QByteArray statusPost = urlQuery.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority | QUrl::RemovePath);
    statusPost.remove(0, 1);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, statusPost);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
void ImapMessageTest::testMailAddressFormat()
{
    QFETCH( Imap::Message::MailAddress, addr );
    QFETCH( QString, pretty );
    QFETCH( QByteArray, addrspec );
    QFETCH( bool, should2047 );

    QCOMPARE( addr.prettyName(Imap::Message::MailAddress::FORMAT_READABLE), pretty );
    QCOMPARE( addr.asSMTPMailbox(), addrspec );
    
    QByteArray full = addr.asMailHeader();
    QByteArray bracketed;
    bracketed.append(" <").append(addrspec).append(">");
    QVERIFY( full.endsWith(bracketed) );
    full.remove(full.size() - bracketed.size(), bracketed.size());
    
    if (should2047) {
        QVERIFY( full.startsWith("=?") );
        QVERIFY( full.endsWith("?=") );
        QCOMPARE( addr.name, Imap::decodeRFC2047String(full) );
    } else {
        QVERIFY( !full.contains("=?") );
        QVERIFY( !full.contains("?=") );
    }
}
void TaskPocketParameters::changeEvent(QEvent *e)
{
    TaskBox::changeEvent(e);
    if (e->type() == QEvent::LanguageChange) {
        ui->pocketLength->blockSignals(true);
        ui->lineFaceName->blockSignals(true);
        ui->changeMode->blockSignals(true);
        int index = ui->changeMode->currentIndex();
        ui->retranslateUi(proxy);
        ui->changeMode->clear();
        ui->changeMode->addItem(tr("Dimension"));
        ui->changeMode->addItem(tr("Through all"));
        ui->changeMode->addItem(tr("To first"));
        ui->changeMode->addItem(tr("Up to face"));
        ui->changeMode->setCurrentIndex(index);

        QByteArray upToFace = this->getFaceName();
        int faceId = -1;
        bool ok = false;
        if (upToFace.indexOf("Face") == 0) {
            faceId = upToFace.remove(0,4).toInt(&ok);
        }
        ui->lineFaceName->setText(ok ?
                                  tr("Face") + QString::number(faceId) :
                                  tr("No face selected"));
        ui->pocketLength->blockSignals(false);
        ui->lineFaceName->blockSignals(false);
        ui->changeMode->blockSignals(false);
    }
}
Exemple #20
0
static bool read_xpm_string(QByteArray &buf, QIODevice *d, const char * const *source, int &index,
                            QByteArray &state)
{
    if (source) {
        buf = source[index++];
        return true;
    }

    buf = "";
    bool gotQuote = false;
    int offset = 0;
    forever {
        if (offset == state.size() || state.isEmpty()) {
            char buf[2048];
            qint64 bytesRead = d->read(buf, sizeof(buf));
            if (bytesRead <= 0)
                return false;
            state = QByteArray(buf, int(bytesRead));
            offset = 0;
        }

        if (!gotQuote) {
            if (state.at(offset++) == '"')
                gotQuote = true;
        } else {
            char c = state.at(offset++);
            if (c == '"')
                break;
            buf += c;
        }
    }
    state.remove(0, offset);
    return true;
}
/**
 *   Sends direct message
 *   @param user The ID of the user who should receive the direct message.
 *   @param text The text of direct message
 *   @param includeEntities When set to true each tweet will include a node called "entities,"
 */
void QTweetDirectMessageNew::post(const QString &screenName, const QString &text, bool includeEntities)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("https://api.twitter.com/1/direct_messages/new.json");

    QUrl urlQuery(url);

    urlQuery.addEncodedQueryItem("screen_name", QUrl::toPercentEncoding(screenName));
    urlQuery.addEncodedQueryItem("text", QUrl::toPercentEncoding(text));

    if (includeEntities)
        urlQuery.addQueryItem("include_entities", "true");

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(urlQuery, OAuth::POST);
    req.setRawHeader(AUTH_HEADER, oauthHeader);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QByteArray postBody = urlQuery.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority | QUrl::RemovePath);
    postBody.remove(0, 1);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, postBody);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
/** Creates list
 *  @param user user id
 *  @param name the name of the list
 *  @param mode true for public list, false for private list
 *  @param description the description to give the list.
 */
void QTweetListCreate::create(qint64 user,
                              const QString &name,
                              bool mode,
                              const QString &description)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url(QString("http://api.twitter.com/1/%1/lists.json").arg(user));

    QUrl urlQuery(url);

    urlQuery.addEncodedQueryItem("name", QUrl::toPercentEncoding(name));

    if (!mode)
        urlQuery.addQueryItem("mode", "private");

    if (!description.isEmpty())
        urlQuery.addEncodedQueryItem("description", QUrl::toPercentEncoding(description));

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(urlQuery, OAuth::POST);
    req.setRawHeader(AUTH_HEADER, oauthHeader);

    QByteArray postBody = urlQuery.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority | QUrl::RemovePath);
    postBody.remove(0, 1);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, postBody);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
void SimulationConnectionController::SimulationDataReceived(QByteArray data)
{
    DATA_HEADER_SET header;

    if(data.length()> sizeof(DATA_HEADER_SET))
    {
        memcpy(&header,data.data(),sizeof(DATA_HEADER_SET));
        data.remove(0,sizeof(DATA_HEADER_SET));
        if(header.type == IMAGE_JPEG)
        {
            if(data.length() >= header.length)
            {
                _simulationViewImageRAW = data;

                QImage img;
                try {
                    img = QImage::fromData(_simulationViewImageRAW,"JPEG");//the second param is format name
                } catch (...) {
                    qDebug() << "SimulationDataReceived -> ImageFailed.";
                }
                emit imageReceived(img);
            }
        }
        else if(header.type == SIMULATION_OUTPUT)
        {
            emit dataReceived(data);
        }
    }
}
Exemple #24
0
bool WPUtils::removePadding(QByteArray & out) {
	char paddingLength = out[out.length() - 1];
	if (paddingLength < 1 || paddingLength > 16) {
		//toast
		qDebug() << "Invalid padding length. Were the keys good?";
		out.clear();
		return false;
	}
	if (paddingLength > out.length()) {
		//toast
		qDebug() << "Padding is claiming to be longer than the buffer!";
		out.clear();
		return false;
	}
	for (int i = 1; i < paddingLength; ++i) {
		char next = out[out.length() - 1 - i];
		if (next != paddingLength) {
			qDebug()  << "Not all padding bytes are correct!";
			out.clear();
			return false;
		}
	}
	out.remove(out.length() - paddingLength, paddingLength);
	return true;
}
/*!
    \property bool IrcPrivateMessage::request
    This property is \c true if the message is a request; otherwise \c false.

    \par Access functions:
    \li bool <b>isRequest</b>() const
 */
bool IrcPrivateMessage::isRequest() const
{
    Q_D(const IrcMessage);
    QByteArray msg = d->parser.params().value(1);
    if (d->flags & (Identified | Unidentified))
        msg.remove(0, 1);
    return msg.startsWith('\1') && msg.endsWith('\1') && !isAction();
}
Exemple #26
0
void Moc::parseDeclareMetatype()
{
    next(LPAREN);
    QByteArray typeName = lexemUntil(RPAREN);
    typeName.remove(0, 1);
    typeName.chop(1);
    metaTypes.append(typeName);
}
bool RecvFileTransfer::parseHeader(QByteArray &recvBlock, struct TransferFile &transferFile)
{
    bool ok;
    int headerSize
        = recvBlock.left(TRANSFER_FILE_HEADER_SIZE_LENGTH).toInt(&ok, 16);
    if (!ok)
    {
        m_errorString = "RecvFileTransfer::parseHeader: get headerSize error";
        return false;
    }

    QByteArray header = recvBlock.left(headerSize);

    QList<QByteArray> list = header.split(':');

#define TRANSFERFILE_NAME_POS           1
#define TRANSFERFILE_SIZE_POS           2
#define TRANSFERFILE_TYPE_POS           3
#define TRANSFERFILE_ATTR_BEGIN_POS     4

    // XXX NOTE: canParseHeader() make sure we have enough items in list,
    // so we do not need to check size of list before call list.at()
//    transferFile.name = Macai::transferCodec->codec()->toUnicode(list.at(TRANSFERFILE_NAME_POS));
    QTextCodec* codec = QTextCodec::codecForName("SYSTEM");
    transferFile.name = codec->toUnicode(list.at(TRANSFERFILE_NAME_POS));

    transferFile.size = list.at(TRANSFERFILE_SIZE_POS).toLongLong(&ok, 16);
    if (!ok)
    {
        m_errorString = "RecvFileTransfer::parseHeader: get file size error";
        return false;
    }
    transferFile.type = list.at(TRANSFERFILE_TYPE_POS).toInt(&ok, 16);
    if (!ok)
    {
        m_errorString = "RecvFileTransfer::parseHeader: get file type error";
        return false;
    }

    // Extended file attribution like mtime, atime...
    for (int i = TRANSFERFILE_ATTR_BEGIN_POS; i < list.size(); ++i)
    {
        QString s = list.at(i);
        QStringList l = s.split(QChar('='));
        if (l.size() == 2)
        {
            int i = l.at(0).toInt(&ok, 16);
            if (ok)
            {
                transferFile.extendAttr.insert(i, l.at(1));
            }
        }
    }

    recvBlock.remove(0, headerSize);

    return true;
}
Exemple #28
0
void UmlClass::addContructor(bool expl)
{
    TRACE_FUNCTION;
    QLOG_INFO() << "1.1.1";
    UmlOperation * op = UmlOperation::create(this, name());
    QLOG_INFO() << "1.1.2";
    if (op == 0)
        UmlCom::trace("can't add contructor");
    else {
        QLOG_INFO() << "1.1.3";
        QByteArray s;
        int index;

        // remove the useless "${type} " mainly to remove the space

        s = op->cppDecl();
        QLOG_INFO() << s;
        QLOG_INFO() << "1.1.4";
        if (s.isEmpty())
            s = CppSettings::operationDecl();
        QLOG_INFO() << s;
        QLOG_INFO() << "1.1.5";
        if ((index = s.indexOf("${type} ")) != -1)
            s.remove(index, 8);
        QLOG_INFO() << s;
        QLOG_INFO() << "1.1.6";
        if (expl && ((index = s.indexOf("${name}")) != -1))
            s.insert(index, "explicit ");
        QLOG_INFO() << s;
        QLOG_INFO() << "1.1.7";
        op->set_CppDecl(s);
        QLOG_INFO() << s;
        QLOG_INFO() << "1.1.8";
        s = op->cppDef();
        QLOG_INFO() << s;
        QLOG_INFO() << "1.1.81";
        if (s.isEmpty())
            s = CppSettings::operationDef();
        QLOG_INFO() << "1.1.9";
        if ((index = s.indexOf("${type} ")) != -1)
            s.remove(index, 8);
        QLOG_INFO() << "1.1.10";
        op->set_CppDef(s);
    }
}
Exemple #29
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();
}
qint64 HelpNetworkReply::readData(char *buffer, qint64 maxlen)
{
    qint64 len = qMin(qint64(data.length()), maxlen);
    if (len) {
        std::memcpy(buffer, data.constData(), len);
        data.remove(0, len);
    }
    return len;
}