コード例 #1
0
ファイル: netudpserver.cpp プロジェクト: JGunning/OpenWorms2
void HWNetUdpServer::onClientRead()
{
    while (pUdpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(pUdpSocket->pendingDatagramSize());
        QHostAddress clientAddr;
        quint16 clientPort;
        pUdpSocket->readDatagram(datagram.data(), datagram.size(), &clientAddr, &clientPort);
        if(datagram.startsWith("hedgewars client"))
        {
            // send answer to client
            pUdpSocket->writeDatagram(QString("hedgewars server\n%1").arg(m_descr).toUtf8(), clientAddr, clientPort);
        }
    }
}
コード例 #2
0
ファイル: pumprotocol.cpp プロジェクト: Lewerow/PUMController
Message PUMProtocol::unpack(QByteArray packed)
{
    Message msg;

    if(packed.startsWith(START_SYMBOL) && packed.endsWith(END_SYMBOL))
    {
        msg.address = (DeviceAddress)packed.at(1);
        msg.command = (CommandType) packed.at(2);
        msg.params = QString(packed.mid(3,packed.length()-4));
    }

    else
        throw InvalidPackage;

    return msg;
}
コード例 #3
0
/*!
  Reads MIME contents from the I/O device \a dev and parses it.
*/
QByteArray TMultipartFormData::parseContent(QIODevice *dev) const
{
    if (!dev->isOpen()) {
        return QByteArray();
    }

    QByteArray content;
    while (!dev->atEnd()) {
        QByteArray line = dev->readLine();
        if (line.startsWith(dataBoundary)) {
            break;
        }
        content += line;
    }
    return content.trimmed();
}
コード例 #4
0
ファイル: QXmppSasl.cpp プロジェクト: qxmpp-project/qxmpp
bool QXmppSaslClientScram::respond(const QByteArray &challenge, QByteArray &response)
{
    Q_UNUSED(challenge);
    if (m_step == 0) {
        m_gs2Header = "n,,";
        m_clientFirstMessageBare = "n=" + username().toUtf8() + ",r=" + m_nonce;

        response = m_gs2Header + m_clientFirstMessageBare;
        m_step++;
        return true;
    } else if (m_step == 1) {
        // validate input
        const QMap<char, QByteArray> input = parseGS2(challenge);
        const QByteArray nonce = input.value('r');
        const QByteArray salt = QByteArray::fromBase64(input.value('s'));
        const int iterations = input.value('i').toInt();
        if (!nonce.startsWith(m_nonce) || salt.isEmpty() || iterations < 1) {
            return false;
        }

        // calculate proofs
        const QByteArray clientFinalMessageBare = "c=" + m_gs2Header.toBase64() + ",r=" + nonce;
        const QByteArray saltedPassword = deriveKeyPbkdf2(m_algorithm, password().toUtf8(), salt,
                                                          iterations, m_dklen);
        const QByteArray clientKey = QMessageAuthenticationCode::hash("Client Key", saltedPassword, m_algorithm);
        const QByteArray storedKey = QCryptographicHash::hash(clientKey, m_algorithm);
        const QByteArray authMessage = m_clientFirstMessageBare + "," + challenge + "," + clientFinalMessageBare;
        QByteArray clientProof = QMessageAuthenticationCode::hash(authMessage, storedKey, m_algorithm);
        std::transform(clientProof.cbegin(), clientProof.cend(), clientKey.cbegin(),
                       clientProof.begin(), std::bit_xor<char>());

        const QByteArray serverKey = QMessageAuthenticationCode::hash("Server Key", saltedPassword, m_algorithm);
        m_serverSignature = QMessageAuthenticationCode::hash(authMessage, serverKey, m_algorithm);

        response = clientFinalMessageBare + ",p=" + clientProof.toBase64();
        m_step++;
        return true;
    } else if (m_step == 2) {
        const QMap<char, QByteArray> input = parseGS2(challenge);
        response = QByteArray();
        m_step++;
        return QByteArray::fromBase64(input.value('v')) == m_serverSignature;
    } else {
        warning("QXmppSaslClientPlain : Invalid step");
        return false;
    }
}
コード例 #5
0
void DlgCustomToolbarsImp::moveDownCustomCommand(const QString& name, const QByteArray& userdata)
{
    QVariant data = workbenchBox->itemData(workbenchBox->currentIndex(), Qt::UserRole);
    Workbench* w = WorkbenchManager::instance()->active();
    if (w && w->name() == std::string((const char*)data.toByteArray())) {
        QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>(name);
        if (bars.size() != 1)
            return;

        QByteArray cmd = userdata;
        int numSep = 0, indexSep = 0;
        if (cmd.startsWith("Separator")) {
            numSep = cmd.mid(9).toInt();
            cmd = "Separator";
        }
        QList<QAction*> actions = bars.front()->actions();
        for (QList<QAction*>::ConstIterator it = actions.begin(); it != actions.end(); ++it) {
            if ((*it)->data().toByteArray() == cmd) {
                // if we move a separator then make sure to pick up the right one
                if (numSep > 0) {
                    if (++indexSep < numSep)
                        continue;
                }
                QAction* act = *it;
                if (*it == actions.back())
                    break; // we're already on the last element
                ++it;
                // second last item
                if (*it == actions.back()) {
                    QList<QAction*> group = getActionGroup(act);
                    bars.front()->removeAction(act);
                    bars.front()->addAction(act);
                    if (!group.isEmpty())
                        setActionGroup(act, group);
                    break;
                }
                ++it;
                QList<QAction*> group = getActionGroup(act);
                bars.front()->removeAction(act);
                bars.front()->insertAction(*it, act);
                if (!group.isEmpty())
                    setActionGroup(act, group);
                break;
            }
        }
    }
}
コード例 #6
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);
}
コード例 #7
0
QCA::PrivateKey EncryptioNgSimliteDecryptor::getPrivateKey(const Key &key)
{
	QByteArray keyData = key.key().toByteArray().trimmed();
	if (!keyData.startsWith(BEGIN_RSA_PRIVATE_KEY) || !keyData.endsWith(END_RSA_PRIVATE_KEY))
	{
		Valid = false;
		return QCA::PrivateKey();
	}

	keyData = keyData.mid(BEGIN_RSA_PRIVATE_KEY_LENGTH, keyData.length() - BEGIN_RSA_PRIVATE_KEY_LENGTH - END_RSA_PRIVATE_KEY_LENGTH).replace('\r', "").trimmed();

	QCA::SecureArray certificate;

	QCA::Base64 decoder;
	decoder.setLineBreaksEnabled(true);
	certificate = decoder.decode(keyData);

	// just some fake security added
	keyData.fill(' ', keyData.size());
	keyData.clear();

	if (!decoder.ok())
	{
		Valid = false;
		return QCA::PrivateKey();
	}

	PKCS1Certificate::ConversionStatus status;
	PKCS1Certificate pkcs1;

	QCA::PrivateKey privateKey = pkcs1.privateKeyFromDER(certificate, status);
	if (PKCS1Certificate::OK != status)
	{
		Valid = false;
		return QCA::PrivateKey();
	}

	if (!privateKey.canDecrypt())
	{
		Valid = false;
		return QCA::PrivateKey();
	}

	Valid = true;
	return privateKey;
}
コード例 #8
0
ファイル: networklocation.cpp プロジェクト: dmacvicar/mirall
/**
 * for now our data is just the MAC address of the default gateway
 */
NetworkLocation NetworkLocation::currentLocation()
{
    QProcess ip;
    ip.start("/sbin/ip", QStringList() << "route");

    if (!ip.waitForStarted())
        return NetworkLocation();

    if (!ip.waitForFinished())
        return NetworkLocation();

    QByteArray gwIp;
    while (ip.canReadLine()) {
        QByteArray line = ip.readLine();
        if (line.startsWith("default")) {
            QList<QByteArray> parts = line.split(' ');
            gwIp = parts[2];
            break;
        }
    }
    if (gwIp.isEmpty())
            return NetworkLocation();

    QProcess arp;
    arp.start("/sbin/arp", QStringList() << "-a");

    if (!arp.waitForStarted())
        return NetworkLocation();

    if (!arp.waitForFinished())
        return NetworkLocation();

    QByteArray gwMAC;
    while (arp.canReadLine()) {
        QByteArray line = arp.readLine();
        if (line.contains(gwIp)) {
            QList<QByteArray> parts = line.split(' ');
            gwMAC = parts[3];
            break;
        }
    }
    if (gwMAC.isEmpty())
        return NetworkLocation();

    return NetworkLocation(gwMAC);
}
コード例 #9
0
ファイル: framefileio.cpp プロジェクト: firefeather/SavvyCAN
/*
tokens:
0 = timestamp
1 = Transmission direction
2 = Channel
3 = ID
4 = Type (s = standard, I believe x = extended)
5 = Data byte length
6-x = The data bytes

Sample chunk of a busmaster log:
***BUSMASTER Ver 2.4.0***
***PROTOCOL CAN***
***NOTE: PLEASE DO NOT EDIT THIS DOCUMENT***
***[START LOGGING SESSION]***
***START DATE AND TIME 8:8:2014 11:49:7:965***
***HEX***
***SYSTEM MODE***
***START CHANNEL BAUD RATE***
***CHANNEL 1 - Kvaser - Kvaser Leaf Light HS #0 (Channel 0), Serial Number- 0, Firmware- 0x00000037 0x00020000 - 500000 bps***
***END CHANNEL BAUD RATE***
***START DATABASE FILES (DBF/DBC)***
***END OF DATABASE FILES (DBF/DBC)***
***<Time><Tx/Rx><Channel><CAN ID><Type><DLC><DataBytes>***
11:49:12:9420 Rx 1 0x023 s 1 40
11:49:12:9440 Rx 1 0x460 s 8 03 E0 00 00 C0 00 00 00
11:49:12:9530 Rx 1 0x023 s 1 40
11:49:12:9680 Rx 1 0x408 s 8 0F 02 00 30 00 00 7F 00
11:49:12:9680 Rx 1 0x40B s 8 00 00 00 00 00 10 60 00
11:49:12:9690 Rx 1 0x045 s 8 40 00 00 00 00 00 00 00
*/
bool FrameFileIO::loadLogFile(QString filename, QVector<CANFrame>* frames)
{
    QFile *inFile = new QFile(filename);
    CANFrame thisFrame;
    QByteArray line;
    uint64_t timeStamp = Utility::GetTimeMS();
    int lineCounter = 0;

    if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        delete inFile;
        return false;
    }

    line = inFile->readLine(); //read out the header first and discard it.

    while (!inFile->atEnd()) {
        lineCounter++;
        if (lineCounter > 100)
        {
            qApp->processEvents();
            lineCounter = 0;
        }

        line = inFile->readLine();
        if (line.startsWith("***")) continue;
        if (line.length() > 1)
        {
            QList<QByteArray> tokens = line.split(' ');
            QList<QByteArray> timeToks = tokens[0].split(':');
            timeStamp = (timeToks[0].toInt() * (1000ul * 1000ul * 60ul * 60ul)) + (timeToks[1].toInt() * (1000ul * 1000ul * 60ul))
                      + (timeToks[2].toInt() * (1000ul * 1000ul)) + (timeToks[3].toInt() * 100ul);
            thisFrame.timestamp = timeStamp;
            thisFrame.ID = tokens[3].right(tokens[3].length() - 2).toInt(NULL, 16);
            if (tokens[4] == "s") thisFrame.extended = false;
            else thisFrame.extended = true;
            thisFrame.bus = tokens[2].toInt() - 1;
            thisFrame.len = tokens[5].toInt();
            for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = tokens[d + 6].toInt(NULL, 16);
        }
        frames->append(thisFrame);
    }
    inFile->close();
    delete inFile;
    return true;
}
コード例 #10
0
static bool checkCondition(const QByteArray &condition)
{
    static const QSet<QByteArray> matchedConditions = activeConditions();
    QList<QByteArray> conds = condition.split(' ');

    for (int i = 0; i < conds.size(); ++i) {
        QByteArray c = conds.at(i);
        bool result = c.startsWith('!');
        if (result)
            c = c.mid(1);

        result ^= matchedConditions.contains(c);
        if (!result)
            return false;
    }
    return true;
}
コード例 #11
0
bool QSvgIOHandler::canRead() const
{
    if (!device())
        return false;
    if (d->loaded && !d->readDone)
        return true;        // Will happen if we have been asked for the size

    QByteArray buf = device()->peek(8);
    if (buf.startsWith("\x1f\x8b")) {
        setFormat("svgz");
        return true;
    } else if (buf.contains("<?xml") || buf.contains("<svg")) {
        setFormat("svg");
        return true;
    }
    return false;
}
コード例 #12
0
bool UdevAudioInterfacePrivate::isOSSDevice(const QByteArray& lastElement, const char* lastElementAscii)
{
    m_driver = Solid::AudioInterface::UnknownAudioDriver;
    m_type = Solid::AudioInterface::UnknownAudioInterfaceType;
    m_cardnum = 0;

    m_deviceFile = m_device->property("DEVNAME").toString();

    if (lastElement.startsWith("dsp")) {
        m_driver = Solid::AudioInterface::OpenSoundSystem;
        sscanf (lastElementAscii, "dsp%d", &m_cardnum);
    }

    if (lastElement.startsWith("adsp")) {
        m_driver = Solid::AudioInterface::OpenSoundSystem;
        sscanf (lastElementAscii, "adsp%d", &m_cardnum);
    }

    if (lastElement.startsWith("midi")) {
        m_driver = Solid::AudioInterface::OpenSoundSystem;
        sscanf (lastElementAscii, "midi%d", &m_cardnum);
    }

    if (lastElement.startsWith("amidi")) {
        m_driver = Solid::AudioInterface::OpenSoundSystem;
        sscanf (lastElementAscii, "amidi%d", &m_cardnum);
    }

    if (lastElement.startsWith("audio")) {
        m_driver = Solid::AudioInterface::OpenSoundSystem;
        sscanf (lastElementAscii, "audio%d", &m_cardnum);
    }

    if (lastElement.startsWith("mixer")) {
        m_driver = Solid::AudioInterface::OpenSoundSystem;
        m_type = Solid::AudioInterface::AudioControl;
        sscanf (lastElementAscii, "mixer%d", &m_cardnum);
    }

    if (m_driver != Solid::AudioInterface::UnknownAudioDriver) {
        m_name = cardNumberToName();
        QString path;
        path.sprintf("/proc/asound/card%d/pcm0p/info", m_cardnum);
        QByteArray cardName = grepHelper(path, "name: ");
        if (!cardName.isEmpty()) {
            m_name.append(QLatin1String(" (") + cardName + ')');
        } else {
            m_name.append(QLatin1String(" (OSS Device)"));
        }
        return true;
    }
    return false;
}
コード例 #13
0
bool Napisy24DownloadEngine::lookForSubtitles(QString lang) {
  if (lang != "pl") return false;

  const QUrl url = QUrl("http://napisy24.pl/run/CheckSubAgent.php");

  auto credentials = getCredentials();

  QUrlQuery params(url);
  params.addQueryItem("postAction", "CheckSub");
  params.addQueryItem("ua", credentials.first);
  params.addQueryItem("ap", credentials.second);
  params.addQueryItem("fh", checkSum);
  params.addQueryItem("fs", QString::number(fileSize));
  params.addQueryItem("fn", QFileInfo(movie).fileName());
  // API N24 ignoruje ten parametr; jeśli nie ma napisów w żądanym języku, to i
  // tak zwraca napisy w jęz. polskim params.addQueryItem("nl", lang);
  QByteArray data = params.query().toUtf8();

  SyncHTTP http;
  QNetworkRequest req(url);
  req.setHeader(QNetworkRequest::ContentTypeHeader,
                "application/x-www-form-urlencoded");

  QNetworkReply *reply = http.syncPost(req, data);
  if (reply->error() != QNetworkReply::NoError) return false;

  QByteArray respData = reply->readAll();
  if (!respData.startsWith("OK-2")) return false;

  QString tmpPackedFile = generateTmpPath();

  QFile file(tmpPackedFile);
  if (file.exists()) file.remove();
  if (!file.open(QIODevice::WriteOnly)) return false;

  long r = file.write(respData.mid(respData.indexOf("||") + 2));
  file.close();
  if (!r) return false;

  subtitlesList << SubtitleInfo(lang, meta().name(), tmpPackedFile,
                                QFileInfo(movie).completeBaseName(), "", "txt",
                                SUBTITLE_UNKNOWN);

  return true;
}
コード例 #14
0
void brain_stroke_web::service(HttpRequest &request, HttpResponse &response){
    QLOG_ERROR() << "debug thread" << QThread::currentThread();
    QByteArray path = request.getPath();
    if(path =="/getallversion"){
        get_version_controller_ins.service(request,response);
        return;
    }
    else if (path == "/getfile") {
        download_version_controller_ins.service(request,response);
        return;
    }
    else if (path == "/rename"){
        //POST
        if(request.getMethod() != "POST"){
            netutil::write(response, 401, "wrong method");
            return;
        }
        rename_version_controller_ins.service(request,response);
        return;
    }
    else if(path == "/delete"){
        //POST
        if(request.getMethod() != "POST"){
            netutil::write(response, 401, "wrong method");
            return;
        }
        delete_version_controller_ins.service(request,response);
        return;
    }
    else if(path.startsWith("/data")){
        QString key = request.getParameter("key");
        if(key != QString(inner_data_trans_key)){
            response.setStatus(401,"key error");
            response.write("key error");
        }
        else{
            StaticFileController_ins->service(request,response);
            return;
        }
    }
    else{
        response.setStatus(401,"no matched request");
        response.write("no matched request", false);
    }
}
コード例 #15
0
ファイル: viewerwidget.cpp プロジェクト: EmmanuelOga/even
void ViewerWidget::load(const QByteArray &data)
{
    scene->clear();
    QList<QGraphicsItem *> items;
    QPixmap pixmap;
    if (pixmap.loadFromData(data)) {
        items << new QGraphicsPixmapItem(pixmap);
    }
    else if (data.startsWith("%PDF")) {
        fz_stream *stream = fz_open_memory(context, (unsigned char *)data.constData(), data.length());
        fz_document *doc = fz_open_document_with_stream(context, ".pdf", stream);
        fz_close(stream);
        int pagecount = fz_count_pages(doc);
        for (int i = 0; i < pagecount; i++) {
            fz_page *page = fz_load_page(doc, i);
            fz_rect bounds;
            fz_bound_page(doc, page, &bounds);
            fz_display_list *list = fz_new_display_list(context);
            fz_device *dev = fz_new_list_device(context, list);
            fz_run_page(doc, page, dev, &fz_identity, NULL);
            fz_free_device(dev);
            fz_free_page(doc, page);
            PageItem *item = new PageItem(context, list, bounds.x1 - bounds.x0, bounds.y1 - bounds.y0);
            item->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
            items << item;
        }
        fz_close_document(doc);
    } else {
        scene->setSceneRect(0, 0, 0, 0);
        return;
    }
    int top = 0;
    QPen outline(Qt::lightGray, 2, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
    outline.setCosmetic(true);
    foreach (QGraphicsItem *item, items) {
        QGraphicsRectItem *rim = new QGraphicsRectItem(item->boundingRect());
        item->setPos(0, top);
        rim->setPos(0, top);
        rim->setPen(outline);
        rim->setBrush(Qt::NoBrush);
        scene->addItem(rim);
        scene->addItem(item);
        top += item->boundingRect().height() + SPACING;
    }
コード例 #16
0
ファイル: udevmanager.cpp プロジェクト: Civil/cantata
bool UDevManager::Private::isOfInterest(const UdevQt::Device &device)
{
#if DETAILED_OUTPUT
    qDebug() << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";
    qDebug() << "Path:" << device.sysfsPath();
    qDebug() << "Properties:" << device.deviceProperties();
    Q_FOREACH (const QString &key, device.deviceProperties()) {
        qDebug() << "\t" << key << ":" << device.deviceProperty(key).toString();
    }
    qDebug() << "Driver:" << device.driver();
    qDebug() << "Subsystem:" << device.subsystem();
    qDebug() << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>";
#endif
    if (device.driver() == QLatin1String("processor")) {
        // Linux ACPI reports processor slots, rather than processors.
        // Empty slots will not have a system device associated with them.
        return QFile::exists(device.sysfsPath() + "/sysdev");
    }
    if (device.subsystem() == QLatin1String("sound") &&
            device.deviceProperty("SOUND_FORM_FACTOR").toString() != "internal") {
        return true;
    }

    if (device.subsystem() == QLatin1String("tty")) {
        QString path = device.deviceProperty("DEVPATH").toString();

        int lastSlash = path.length() - path.lastIndexOf(QLatin1String("/")) -1;
        #if QT_VERSION < 0x050000
        QByteArray lastElement = path.right(lastSlash).toAscii();
        #else
        QByteArray lastElement = path.right(lastSlash).toLatin1();
        #endif

        if (lastElement.startsWith("tty") && !path.startsWith("/devices/virtual")) {
            return true;
        }
    }
    return device.subsystem() == QLatin1String("dvb") ||
           device.subsystem() == QLatin1String("video4linux") ||
           device.subsystem() == QLatin1String("net") ||
           device.deviceProperty("ID_MEDIA_PLAYER").toString().isEmpty() == false || // media-player-info recognized devices
           device.deviceProperty("ID_GPHOTO2").toInt() == 1; // GPhoto2 cameras
}
コード例 #17
0
bool QMakeVfs::readFile(const QString &fn, QString *contents, QString *errStr)
{
#ifndef PROEVALUATOR_FULL
# ifdef PROEVALUATOR_THREAD_SAFE
    QMutexLocker locker(&m_mutex);
# endif
    QHash<QString, QString>::ConstIterator it = m_files.constFind(fn);
    if (it != m_files.constEnd()) {
        if (it->constData() == m_magicMissing.constData()) {
            *errStr = fL1S("No such file or directory");
            return false;
        }
        if (it->constData() != m_magicExisting.constData()) {
            *contents = *it;
            return true;
        }
    }
#endif

    QFile file(fn);
    if (!file.open(QIODevice::ReadOnly)) {
#ifndef PROEVALUATOR_FULL
        if (!IoUtils::exists(fn)) {
            m_files[fn] = m_magicMissing;
            *errStr = fL1S("No such file or directory");
        } else
#endif
            *errStr = file.errorString();
        return false;
    }
#ifndef PROEVALUATOR_FULL
    m_files[fn] = m_magicExisting;
#endif

    QByteArray bcont = file.readAll();
    if (bcont.startsWith("\xef\xbb\xbf")) {
        // UTF-8 BOM will cause subtle errors
        *errStr = fL1S("Unexpected UTF-8 BOM");
        return false;
    }
    *contents = QString::fromLocal8Bit(bcont);
    return true;
}
コード例 #18
0
ファイル: misc.cpp プロジェクト: SwarmofPeanuts/qBittorrent
/**
 * Detects the version of python by calling
 * "python --version" and parsing the output.
 */
int misc::pythonVersion() {
  static int version = -1;
  if (version < 0) {
    QProcess python_proc;
    python_proc.start("python", QStringList() << "--version", QIODevice::ReadOnly);
    if (!python_proc.waitForFinished()) return -1;
    if (python_proc.exitCode() < 0) return -1;
    QByteArray output = python_proc.readAllStandardOutput();
    if (output.isEmpty())
      output = python_proc.readAllStandardError();
    const QByteArray version_str = output.split(' ').last();
    qDebug() << "Python version is:" << version_str.trimmed();
    if (version_str.startsWith("3."))
      version = 3;
    else
      version = 2;
  }
  return version;
}
コード例 #19
0
ファイル: saslauthfeature.cpp プロジェクト: ChALkeR/vacuum-im
static QMap<QByteArray, QByteArray> parseChallenge(const QByteArray &AChallenge)
{
	int startPos = 0;
	bool quoting = false;
	QList<QByteArray> paramsList;
	for (int pos = 1; pos<AChallenge.size(); pos++)
	{
		const char c = AChallenge.at(pos);
		if (c == '\"')
		{
			if (quoting && AChallenge.at(pos-1)!='\\')
				quoting = false;
			else if (!quoting)
				quoting = true;
		}
		else if (c==',' && !quoting)
		{
			paramsList.append(AChallenge.mid(startPos,pos-startPos));
			startPos=pos+1;
		}
	}

	QMap<QByteArray, QByteArray> map;
	for (int i = 0; i<paramsList.count(); i++)
	{
		QByteArray param = paramsList.at(i).trimmed();
		int delimIndex = param.indexOf('=');
		if (delimIndex > 0)
		{
			QByteArray key = param.left(delimIndex);
			QByteArray value = param.right(param.length()-delimIndex-1);
			if (value.startsWith('"') && value.endsWith('"'))
			{
				value.remove(0,1).chop(1);
				value.replace("\\\"", "\"");
				value.replace("\\\\", "\\");
			}
			map.insert(key,value);
		}
	}

	return map;
}
コード例 #20
0
ファイル: vhttpresponse.cpp プロジェクト: AmesianX/vdream
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;
}
コード例 #21
0
QString Playlist::toRelativeUrl(const KUrl &trackUrl) const
{
	if ((trackUrl.scheme() == url.scheme()) && (trackUrl.authority() == url.authority())) {
		QByteArray playlistPath = url.encodedPath();
		int index = playlistPath.lastIndexOf('/');
		playlistPath.truncate(index + 1);
		QByteArray trackPath = trackUrl.encodedPath();

		if (trackPath.startsWith(playlistPath)) {
			trackPath.remove(0, index + 1);
			KUrl relativeUrl;
			relativeUrl.setEncodedPath(trackPath);
			relativeUrl.setEncodedQuery(trackUrl.encodedQuery());
			relativeUrl.setEncodedFragment(trackUrl.encodedFragment());
			return relativeUrl.url();
		}
	}

	return trackUrl.url();
}
コード例 #22
0
QByteArray slipDecode(const QByteArray &data)
{
    if(!data.startsWith((char)0xC0)) {
        return QByteArray();
    }

    if(!data.endsWith((char)0xC0)) {
        return QByteArray();
    }

    QByteArray decoded = data.mid(1, data.length() - 2);

    decoded.replace(QByteArray().append((char)0xDB).append((char)0xDC),
                    QByteArray().append((char)0xC0));

    decoded.replace(QByteArray().append((char)0xDB).append((char)0xDD),
                    QByteArray().append((char)0xDB));

    return decoded;
}
コード例 #23
0
/*!
  Reads MIME headers from the I/O device \a dev and parses it.
*/
TMimeHeader TMultipartFormData::parseMimeHeader(QIODevice *dev) const
{
    if (!dev->isOpen()) {
        return TMimeHeader();
    }

    TMimeHeader header;
    while (!dev->atEnd()) {
        QByteArray line = dev->readLine();
        if (line == "\r\n" || line.startsWith(dataBoundary)) {
            break;
        }
    
        int i = line.indexOf(':');
        if (i > 0) {
            header.setHeader(line.left(i).trimmed(), line.mid(i + 1).trimmed());
        }
    }
    return header;
}
コード例 #24
0
ファイル: generator.cpp プロジェクト: BGmot/Qt
QList<int> getLocations(const QSet<QString> &variables, QString source)
{
    QTextStream in(&source);

    QMap<QString, int> locations;

    foreach (QString variable, variables)
        locations[variable] = -1;

    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();

        line = line.right(line.size() - 1);

        if (line.startsWith("#var")) {
            QByteArray temp;
            QByteArray name;

            QTextStream lineStream(&line);

            lineStream >> temp >> temp >> name;

            int location = -1;

            while (!lineStream.atEnd()) {
                lineStream >> temp;

                if (temp.startsWith("c[")) {
                    location = toInt(temp.right(temp.size() - 2));
                    break;
                }

                if (temp == "texunit") {
                    lineStream >> temp;
                    location = toInt(temp);
                    break;
                }
            }

            locations[name] = location;
        }
コード例 #25
0
ファイル: imap.cpp プロジェクト: vohulg/newimapgui
//----------------------------------------------
 ImapMailbox *ImapPrivate::parseMessageHeader (ImapMailbox *mailbox)
 {
    QByteArray response;
    QByteArray fullHeaders;
    ImapMessage *message = new ImapMessage;


     int criritVal = 400;
     int controlCriticVal = 0;
     int lastHeaderField = -1; // поле которое парсилось последним
     while(true)
     {
         response.clear();
         response.append(readLine()); // читаем строчку с сокета
         // Break if End Response Found.
         if (isResponseEnd(response) || controlCriticVal > criritVal)
             break;

         if (response.startsWith('*'))
             continue;

          fullHeaders.append(response);
         // парсинг строчки
         lastHeaderField = _imapParseMessageHeaders(response.trimmed(), message, lastHeaderField);

         controlCriticVal++;
     }

   //qDebug() << fullHeaders ;

     message->setFullHeaders(fullHeaders);

     // proto здесь будет обработка адресов
     for (int i =0; i < ADDRESS_TYPE_COUNT; i++)
     {
        message->setAddresses(adressList[i], i);
     }

  if (message != NULL) mailbox->addMessage(message);
   return(mailbox);
 }
コード例 #26
0
ProjectExplorer::BuildConfiguration::BuildType CMakeBuildConfiguration::buildType() const
{
    QByteArray cmakeBuildTypeName;
    QFile cmakeCache(buildDirectory().toString() + QLatin1String("/CMakeCache.txt"));
    if (cmakeCache.open(QIODevice::ReadOnly)) {
        while (!cmakeCache.atEnd()) {
            QByteArray line = cmakeCache.readLine();
            if (line.startsWith("CMAKE_BUILD_TYPE")) {
                if (int pos = line.indexOf('='))
                    cmakeBuildTypeName = line.mid(pos + 1).trimmed();
                break;
            }
        }
        cmakeCache.close();
    }

    // Cover all common CMake build types
    const CMakeBuildConfigurationFactory::BuildType cmakeBuildType
            = CMakeBuildConfigurationFactory::buildTypeFromByteArray(cmakeBuildTypeName);
    return CMakeBuildConfigurationFactory::cmakeBuildTypeToBuildType(cmakeBuildType);
}
コード例 #27
0
void AdBlockSubscription::subscriptionDownloaded()
{
    if (m_reply != qobject_cast<FollowRedirectReply*>(sender())) {
        return;
    }

    QByteArray response = QString::fromUtf8(m_reply->readAll()).toUtf8();

    if (m_reply->error() == QNetworkReply::NoError && response.startsWith("[Adblock")) {
        // Prepend subscription info
        response.prepend(QString("Title: %1\nUrl: %2\n").arg(title(), url().toString()).toUtf8());

        saveDownloadedData(response);

        loadSubscription(AdBlockManager::instance()->disabledRules());
        emit subscriptionUpdated();
    }

    m_reply->deleteLater();
    m_reply = 0;
}
コード例 #28
0
ファイル: maildir.cpp プロジェクト: KDE/kdepim-runtime
QByteArray Maildir::readEntryHeadersFromFile(const QString &file) const
{
    QByteArray result;

    QFile f(file);
    if (!f.open(QIODevice::ReadOnly)) {
        // FIXME error handling?
        qCWarning(LIBMAILDIR_LOG) << "Maildir::readEntryHeaders unable to find: " << file;
        d->lastError = i18n("Cannot locate mail file %1.", file);
        return result;
    }
    f.map(0, qMin((qint64)8000, f.size()));
    forever {
        QByteArray line = f.readLine();
        if (line.isEmpty() || line.startsWith('\n')) {
            break;
        }
        result.append(line);
    }
    return result;
}
コード例 #29
0
bool BareMetalPlugin::initialize(const QStringList &arguments, QString *errorString)
{
    Q_UNUSED(arguments)
    Q_UNUSED(errorString)

    m_runData = new BareMetalPluginRunData;

    auto constraint = [](RunConfiguration *runConfig) {
        const QByteArray idStr = runConfig->id().name();
        const bool res = idStr.startsWith(BareMetalRunConfiguration::IdPrefix)
                || idStr == BareMetalCustomRunConfiguration::Id;
        return res;
    };

    RunControl::registerWorker<BareMetalDebugSupport>
            (ProjectExplorer::Constants::NORMAL_RUN_MODE, constraint);
    RunControl::registerWorker<BareMetalDebugSupport>
            (ProjectExplorer::Constants::DEBUG_RUN_MODE, constraint);

    return true;
}
コード例 #30
0
ファイル: youtube.cpp プロジェクト: cuiboand1/ytd-meego
void YouTube::parseLiveVideoPage(QNetworkReply *reply) {
    QNetworkAccessManager *manager = qobject_cast<QNetworkAccessManager*>(sender());

    QByteArray response = reply->readAll();
    response = QByteArray::fromPercentEncoding(response.simplified().replace(QByteArray(" "), QByteArray("")));
//    qDebug() << response;
    int pos = response.indexOf("fmt_stream_map=") + 18;
    int pos2 = response.indexOf('|', pos);
    response = response.mid(pos, pos2 - pos);
    QByteArray videoUrl = response.replace(QByteArray("\\/"), QByteArray("/")).replace(QByteArray("\\u0026"), QByteArray("&")).replace(QByteArray("%2C"), QByteArray(","));
    if (!(videoUrl.startsWith("http"))) {
        emit alert(tr("Error: Unable to retrieve video"));
        emit videoUrlError();
    }
    else {
        emit gotVideoUrl(QString(videoUrl));
    }
//        qDebug() << videoUrl;
    reply->deleteLater();
    manager->deleteLater();
}