Esempio n. 1
0
QByteArray GameCFGWidget::getFullConfig() const
{
    QList<QByteArray> bcfg;
    int mapgen = pMapContainer->get_mapgen();
    if (Scripts->currentIndex() > 0)
    {
        bcfg << QString("escript Scripts/Multiplayer/%1.lua").arg(Scripts->itemData(Scripts->currentIndex(), GameStyleModel::ScriptRole).toString()).toUtf8();
    }

    QString currentMap = pMapContainer->getCurrentMap();
    if (currentMap.size() > 0)
    {
        bcfg << QString("emap " + currentMap).toUtf8();

// engine should figure it out on its own
//        if(pMapContainer->getCurrentIsMission())
//            bcfg << QString("escript Maps/%1/map.lua").arg(currentMap).toUtf8();
    }
    bcfg << QString("etheme " + pMapContainer->getCurrentTheme()).toUtf8();

    bcfg << QString("eseed " + pMapContainer->getCurrentSeed()).toUtf8();
    bcfg << QString("e$gmflags %1").arg(getGameFlags()).toUtf8();
    bcfg << QString("e$damagepct %1").arg(schemeData(26).toInt()).toUtf8();
    bcfg << QString("e$turntime %1").arg(schemeData(27).toInt() * 1000).toUtf8();
    bcfg << QString("e$sd_turns %1").arg(schemeData(29).toInt()).toUtf8();
    bcfg << QString("e$casefreq %1").arg(schemeData(30).toInt()).toUtf8();
    bcfg << QString("e$minestime %1").arg(schemeData(31).toInt() * 1000).toUtf8();
    bcfg << QString("e$minesnum %1").arg(schemeData(32).toInt()).toUtf8();
    bcfg << QString("e$minedudpct %1").arg(schemeData(33).toInt()).toUtf8();
    bcfg << QString("e$explosives %1").arg(schemeData(34).toInt()).toUtf8();
    bcfg << QString("e$healthprob %1").arg(schemeData(35).toInt()).toUtf8();
    bcfg << QString("e$hcaseamount %1").arg(schemeData(36).toInt()).toUtf8();
    bcfg << QString("e$waterrise %1").arg(schemeData(37).toInt()).toUtf8();
    bcfg << QString("e$healthdec %1").arg(schemeData(38).toInt()).toUtf8();
    bcfg << QString("e$ropepct %1").arg(schemeData(39).toInt()).toUtf8();
    bcfg << QString("e$getawaytime %1").arg(schemeData(40).toInt()).toUtf8();
    bcfg << QString("e$worldedge %1").arg(schemeData(41).toInt()).toUtf8();
    bcfg << QString("e$template_filter %1").arg(pMapContainer->getTemplateFilter()).toUtf8();
    bcfg << QString("e$feature_size %1").arg(pMapContainer->getFeatureSize()).toUtf8();
    bcfg << QString("e$mapgen %1").arg(mapgen).toUtf8();
    if(!schemeData(42).isNull())
        bcfg << QString("e$scriptparam %1").arg(schemeData(42).toString()).toUtf8();


    switch (mapgen)
    {
        case MAPGEN_MAZE:
        case MAPGEN_PERLIN:
            bcfg << QString("e$maze_size %1").arg(pMapContainer->getMazeSize()).toUtf8();
            break;

        case MAPGEN_DRAWN:
        {
            QByteArray data = pMapContainer->getDrawnMapData();
            while(data.size() > 0)
            {
                QByteArray tmp = data;
                tmp.truncate(200);
                tmp.prepend("edraw ");
                bcfg << tmp;
                data.remove(0, 200);
            }
            break;
        }
        default:
            ;
    }

    QByteArray result;

    foreach(QByteArray ba, bcfg)
    HWProto::addByteArrayToBuffer(result, ba);

    return result;
}
Esempio n. 2
0
//-------------------------------------------------------------------------------------------------
void RemoteMessage::slotClientRead() const
{
    Q_ASSERT(qobject_cast<QTcpSocket*>(this->sender()));
    QTcpSocket *tcpSocket = static_cast<QTcpSocket*>(sender());
    if (!tcpSocket)
        return;
    QByteArray baRequest = tcpSocket->readAll();
    if (baRequest.startsWith("POST /command "))
    {
        int iFind = baRequest.indexOf("\ncommand=", 14);        //[14 = "POST /command "]
        if (iFind >= 0)
        {
            iFind += 9;
            for (int i = iFind; i < baRequest.size(); ++i)
                if (baRequest.at(i) == '\r' || baRequest.at(i) == '\n')
                {
                    baRequest.truncate(i);
                    break;
                }
            QProcess::startDetached(baRequest.mid(iFind));
        }
    }
    else if (baRequest.startsWith("POST /"))
    {
        int iTemp = baRequest.indexOf(' ', 6);        //[6 = "POST /"]
        if (iTemp > 0)
        {
            bool bOk;
            iTemp = baRequest.mid(6, iTemp-6).toInt(&bOk);
            if (bOk && iTemp < slistEntries.size())
                QProcess::startDetached(slistEntries.at(iTemp));
        }
    }
    else if (baRequest.startsWith("GET /favicon.ico "))
    {
        tcpSocket->write(baFavicon);
        return;
    }
    else if (baRequest.startsWith("GET /screen/"))
    {
        const int iDelim = baRequest.indexOf(' ', 12);        //[12 = "GET /screen/"]
        if (iDelim > 0)
        {
            const QPixmap pixmap = qApp->primaryScreen()->grabWindow(qApp->desktop()->winId());
            Q_ASSERT(!pixmap.isNull());
            if (!pixmap.isNull())
            {
                QByteArray baImg;
                QBuffer buffer(&baImg);
                if (buffer.open(QIODevice::WriteOnly))
                {
                    const int iQuality = baRequest.mid(12, iDelim-12).toInt();        //[12 = "GET /screen/"]
                    if (iQuality > 0 && iQuality <= 100)
                    {
                        if (pixmap.save(&buffer, "JPG", iQuality))
                            tcpSocket->write("HTTP/1.1 200 OK\r\n"
                                             "Content-Type: image/jpeg\r\n"
                                             "Cache-Control: no-cache\r\n"
                                             "Content-Length: " + QByteArray::number(baImg.length()) + "\r\n\r\n" +
                                             baImg);
                    }
                    else if (pixmap.save(&buffer, "PNG", 0))
                        tcpSocket->write("HTTP/1.1 200 OK\r\n"
                                         "Content-Type: image/png\r\n"
                                         "Cache-Control: no-cache\r\n"
                                         "Content-Length: " + QByteArray::number(baImg.length()) + "\r\n\r\n" +
                                         baImg);
                    buffer.close();
                }
            }
        }
    }
    else if (baRequest.startsWith("command="))
    {
        for (int i = 8; i < baRequest.size(); ++i)
            if (baRequest.at(i) == '\r' || baRequest.at(i) == '\n')
            {
                baRequest.truncate(i);
                break;
            }
        Q_ASSERT(baRequest.indexOf('\r') < 0 && baRequest.indexOf('\n') < 0);
        QProcess::startDetached(baRequest.mid(8));
    }
    tcpSocket->write(baResponce);
}
Esempio n. 3
0
Device::Device()
{
#ifdef i386
    m_model = EMULATOR;
    return;
#endif
    QStringList list;
    QProcess *myProcess = new QProcess();

    list << "-c" << "grep erial /proc/cpuinfo|cut -c12-15";
    myProcess->start("/bin/sh", list);
    if (myProcess->waitForReadyRead(10000)) {
        QByteArray array = myProcess->readAll();
        array.truncate(array.indexOf("\n"));

        bool ok;
        int sn = QString(array).toInt(&ok, 16);

        if (ok) {
            qDebug("serial: %X", sn);
        } else {
            qDebug() << "unexpected output: " << QString(array);
            return;
        }

        switch(sn) {
        case 0xB002:
        case 0xB003:
            m_model = K2; // may not work as K2 doesn't print SN in cpuinfo
            break;
        case 0xB004:
        case 0xB005:
        case 0xB009:
            m_model = KDX;
            break;
        case 0xB006:
        case 0xB008:
        case 0xB00A:
            m_model = K3;
            break;
        case 0xB00E:
            m_model = K4NT;
            break;
        case 0xB00F:
        case 0xB010:
        case 0xB011:
        case 0xB012: // ???
            m_model = KT;
            break;
        case 0xB023:
            m_model = K4NTB;
            break;
        case 0xB01B:
        case 0xB024:
            m_model = KPW;
            break;
        default:
            qDebug("Unknown model: %X", sn);
        }
    }
}
Esempio n. 4
0
QString QHostInfo::localDomainName()
{
#if !defined(Q_OS_VXWORKS)
    resolveLibrary();
    if (local_res_ninit) {
        // using thread-safe version
        res_state_ptr state = res_state_ptr(qMalloc(sizeof(*state)));
        Q_CHECK_PTR(state);
        memset(state, 0, sizeof(*state));
        local_res_ninit(state);
        QString domainName = QUrl::fromAce(state->defdname);
        if (domainName.isEmpty())
            domainName = QUrl::fromAce(state->dnsrch[0]);
        local_res_nclose(state);
        qFree(state);

        return domainName;
    }

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

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

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

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

    // return the fallen-back-to searched domain
    return domainName;
}
Esempio n. 5
0
void Widget::tcpProcessPendingDatagrams()
{
    // Find who's sending
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == nullptr)
        return;

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

    unsigned nTries = 0;

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

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

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

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

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

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

            *recvBuffer = recvBuffer->mid(dataSize);
        }
    }
}
Esempio n. 6
0
void MocParser::loadStringData(char *&stringdata)
{
    stringdata = 0;
    QVarLengthArray<char, 1024> array;

    while (!input->atEnd()) {
        QByteArray line = readLine();
        if (line == "};\n") {
            // end of data
            stringdata = new char[array.count()];
            memcpy(stringdata, array.data(), array.count() * sizeof(*stringdata));
            return;
        }

        int start = line.indexOf('"');
        if (start == -1)
            parseError();

        int len = line.length() - 1;
        line.truncate(len);     // drop ending \n
        if (line.at(len - 1) != '"')
            parseError();

        --len;
        ++start;
        for ( ; start < len; ++start)
            if (line.at(start) == '\\') {
                // parse escaped sequence
                ++start;
                if (start == len)
                    parseError();

                QChar c(QLatin1Char(line.at(start)));
                if (!c.isDigit()) {
                    switch (c.toLatin1()) {
                    case 'a':
                        array.append('\a');
                        break;
                    case 'b':
                        array.append('\b');
                        break;
                    case 'f':
                        array.append('\f');
                        break;
                    case 'n':
                        array.append('\n');
                        break;
                    case 'r':
                        array.append('\r');
                        break;
                    case 't':
                        array.append('\t');
                        break;
                    case 'v':
                        array.append('\v');
                        break;
                    case '\\':
                    case '?':
                    case '\'':
                    case '"':
                        array.append(c.toLatin1());
                        break;

                    case 'x':
                        if (start + 2 <= len)
                            parseError();
                        array.append(char(line.mid(start + 1, 2).toInt(0, 16)));
                        break;

                    default:
                        array.append(c.toLatin1());
                        fprintf(stderr, PROGRAMNAME ": warning: invalid escape sequence '\\%c' found in input",
                                c.toLatin1());
                    }
                } else {
                    // octal
                    QRegExp octal(QLatin1String("([0-7]+)"));
                    if (octal.indexIn(QLatin1String(line), start) == -1)
                        parseError();
                    array.append(char(octal.cap(1).toInt(0, 8)));
                }
            } else {
                array.append(line.at(start));
            }
    }

    parseError();
}
Esempio n. 7
0
bool MythSocket::writeStringList(QStringList &list)
{
    if (list.size() <= 0)
    {
        VERBOSE(VB_IMPORTANT, LOC +
                "writeStringList: Error, invalid string list.");
        return false;
    }

    if (state() != Connected)
    {
        VERBOSE(VB_IMPORTANT, LOC +
                "writeStringList: Error, called with unconnected socket.");
        return false;
    }

    QString str = list.join("[]:[]");
    if (str.isEmpty())
    {
        VERBOSE(VB_IMPORTANT, LOC +
                "writeStringList: Error, joined null string.");
        return false;
    }

    QByteArray utf8 = str.toUtf8();
    int size = utf8.length();
    int written = 0;
    int written_since_timer_restart = 0;

    QByteArray payload;
    payload = payload.setNum(size);
    payload += "        ";
    payload.truncate(8);
    payload += utf8;
    size = payload.length();

    if (VERBOSE_LEVEL_CHECK(VB_NETWORK))
    {
        QString msg = QString("write -> %1 %2")
            .arg(socket(), 2).arg(payload.data());

        if (!VERBOSE_LEVEL_CHECK(VB_EXTRA) && msg.length() > 88)
        {
            msg.truncate(85);
            msg += "...";
        }
        VERBOSE(VB_NETWORK, LOC + msg);
    }

    MythTimer timer; timer.start();
    unsigned int errorcount = 0;
    while (size > 0)
    {
        if (state() != Connected)
        {
            VERBOSE(VB_IMPORTANT, LOC +
                    "writeStringList: Error, socket went unconnected." +
                    QString("\n\t\t\tWe wrote %1 of %2 bytes with %3 errors")
                    .arg(written).arg(written+size).arg(errorcount) +
                    QString("\n\t\t\tstarts with: %1").arg(toSample(payload)));
            return false;
        }

        int temp = writeBlock(payload.data() + written, size);
        if (temp > 0)
        {
            written += temp;
            written_since_timer_restart += temp;
            size -= temp;
            if ((timer.elapsed() > 500) && written_since_timer_restart != 0)
            {
                timer.restart();
                written_since_timer_restart = 0;
            }
        }
        else if (temp < 0 && error() != MSocketDevice::NoError)
        {
            VERBOSE(VB_IMPORTANT, LOC +
                    QString("writeStringList: Error, writeBlock failed. (%1)")
                    .arg(errorToString()));
            return false;
        }
        else if (temp <= 0)
        {
            errorcount++;
            if (timer.elapsed() > 1000)
            {
                VERBOSE(VB_GENERAL, LOC + "writeStringList: Error, " +
                        QString("No data written on writeBlock (%1 errors)")
                        .arg(errorcount) +
                        QString("\n\t\t\tstarts with: %1")
                        .arg(toSample(payload)));
                return false;
            }
            usleep(1000);
        }
    }

    flush();

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

    unsigned nTries = 0;

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

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

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

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

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

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

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

            *tcpReceivedDatas = tcpReceivedDatas->mid(data.size());
        }
    }
}
bool VideoPlayerBackend::initGStreamer(QString *errorMessage)
{
    static bool loaded = false;
    if (loaded)
        return true;

    GError *err;
    if (gst_init_check(0, 0, &err) == FALSE)
    {
        Q_ASSERT(err);
        qWarning() << "GStreamer initialization failed:" << err->message;
        if (errorMessage)
            *errorMessage = QString::fromLatin1("initialization failed: ") + QString::fromLatin1(err->message);
        g_error_free(err);
        return false;
    }

#ifdef Q_OS_LINUX
    if (QString::fromLatin1(GSTREAMER_PLUGINS).isEmpty())
        return true;
#endif

#ifdef Q_OS_WIN
#define EXT ".dll"
#else
#define EXT ".so"
#endif

    const char *plugins[] =
    {
        "libgsttypefindfunctions"EXT, "libgstapp"EXT, "libgstdecodebin2"EXT, "libgstmatroska"EXT,
        "libgstffmpegcolorspace"EXT, "libgstcoreelements"EXT,
#ifndef Q_OS_WIN
        "libgstffmpeg"EXT,
#endif
#ifdef Q_OS_WIN
        "libgstffmpeg-lgpl"EXT, "libgstautodetect"EXT,
#elif defined(Q_OS_MAC)
        "libgstosxaudio"EXT,
#endif
        0
    };

#undef EXT
#if defined(Q_OS_MAC)
    QString pluginPath = QApplication::applicationDirPath() + QLatin1String("/../PlugIns/gstreamer/");
#else
    QString pluginPath = QDir::toNativeSeparators(QApplication::applicationDirPath() + QDir::separator());
#endif

#if defined(GSTREAMER_PLUGINS) and not defined(Q_OS_MAC)
    QString ppx = QDir::toNativeSeparators(QString::fromLatin1(GSTREAMER_PLUGINS "/"));
    if (QDir::isAbsolutePath(ppx))
        pluginPath = ppx;
    else
        pluginPath += ppx;
#endif

    if (!QFile::exists(pluginPath))
    {
        qWarning() << "gstreamer: Plugin path" << pluginPath << "does not exist";
        if (errorMessage)
            *errorMessage = QString::fromLatin1("plugin path (%1) does not exist").arg(pluginPath);
        return false;
    }

    bool success = true;
    QByteArray path = QFile::encodeName(pluginPath);
    int pathEnd = path.size();

    if (errorMessage)
        errorMessage->clear();

    for (const char **p = plugins; *p; ++p)
    {
        path.truncate(pathEnd);
        path.append(*p);

        GError *err = 0;
        GstPlugin *plugin = gst_plugin_load_file(path.constData(), &err);
        if (!plugin)
        {
            Q_ASSERT(err);
            qWarning() << "gstreamer: Failed to load plugin" << *p << ":" << err->message;
            if (errorMessage)
                errorMessage->append(QString::fromLatin1("plugin '%1' failed: %2\n").arg(QLatin1String(*p))
                                     .arg(QLatin1String(err->message)));
            g_error_free(err);
            success = false;
        }
        else
        {
            Q_ASSERT(!err);
            gst_object_unref(plugin);
        }
    }

    if (success)
        loaded = true;
    return success;
}
Esempio n. 10
0
bool MailFolder::compact(unsigned level)
{
    // sync first so that you are sure the database is ok
    sync();

    if ( level ) {
        qDebug("Folder compressing isn't yet available.");
    }

    QCString mboxInfo;
    mboxInfo = "From - " + QDateTime::currentDateTime().toString() + "\r\n";

    QFile descriptorFile( getDescriptorFileName() );
    if ( !descriptorFile.open(IO_ReadOnly) )
        return false;

    QFile newDescriptorFile( getDescriptorFileName()+"new" );
    if ( !newDescriptorFile.open(IO_WriteOnly) )
        return false;

    QFile messageFile( getMessagesFileName() );
    if ( !messageFile.open(IO_ReadOnly) )
        return false;

    QFile newMessageFile( getMessagesFileName()+"new" );
    if ( !newMessageFile.open(IO_WriteOnly) )
        return false;

    IndexClass * index = 0L;
    QByteArray buffer;

    for (QDictIterator<IndexClass> it(indexCollection); it.current(); ++it) {
        index = it.current();

        if ( !index->getDescriptorLength() ||
                !index->getUniblockLength() ) {
            qDebug("The index file seems to be broken :(");
            indexCollection.remove( index->getID() );
            continue;
        }

        // read the descriptor
        buffer.resize( index->getDescriptorLength() );
        descriptorFile.at( index->getDescriptorOffset() );
        descriptorFile.readBlock(buffer.data(), buffer.size());

        // write the descriptor
        index->setDescriptorOffset( newDescriptorFile.at() );
        newDescriptorFile.writeBlock( buffer );

        // read the message
        buffer.resize( index->getUniblockLength() );
        messageFile.at( index->getUniblockOffset() );
        messageFile.readBlock(buffer.data(), buffer.size());

        // write the message
        // The MBOX line isn't right but the line isn't used too.
        // So, I decided to just store only the current date.
        newMessageFile.writeBlock((const char *)mboxInfo, mboxInfo.length());
        index->setUniblockOffset(newMessageFile.at(), true);

        newMessageFile.writeBlock( buffer );
        newMessageFile.writeBlock("\r\n", 2);
    }

    descriptorFile.close();
    newDescriptorFile.close();
    messageFile.close();
    newMessageFile.close();

    buffer.truncate(0);

    // replace the old files
    descriptorFile.remove();
    messageFile.remove();

    QDir folder( getStorageDevice() );
    folder.rename( newDescriptorFile.name(), getDescriptorFileName(), true );
    folder.rename( newMessageFile.name(), getMessagesFileName(), true );

    saveIndex();

    return true;
}
bool Mp3Writer::write(QByteArray &left, QByteArray &right, long samples, bool flush) {
	int ret;
	QByteArray output;
	// rough upper bound formula taken from lame.h
	long size = samples + samples / 4 + 7200;

	do {
		output.resize(size);

		if (stereo) {
			ret = lame_encode_buffer(lame, reinterpret_cast<const short *>(left.constData()),
				reinterpret_cast<const short *>(right.constData()), samples,
				reinterpret_cast<unsigned char *>(output.data()), output.size());
		} else {
			// lame.h claims to write to the buffers, even though they're declared const, be safe
			// TODO: this mixes both channels again!  can lame take only mono samples?
			ret = lame_encode_buffer(lame, reinterpret_cast<const short *>(left.data()),
				reinterpret_cast<const short *>(left.data()), samples,
				reinterpret_cast<unsigned char *>(output.data()), output.size());
		}

		if (ret == -1) {
			// there wasn't enough space in output
			size *= 2;
			continue;
		}
	} while (false);

	if (ret < 0) {
		debug(QString("Error while writing MP3 file, code = %1").arg(ret));
		return false;
	}

	samplesWritten += samples;

	if (ret > 0) {
		output.truncate(ret);
		file.write(output);
	}

	left.remove(0, samples * 2);
	if (stereo)
		right.remove(0, samples * 2);

	if (!flush)
		return true;

	// flush mp3

	output.resize(10240);
	ret = lame_encode_flush(lame, reinterpret_cast<unsigned char *>(output.data()), output.size());

	lame_close(lame);
	lame = NULL;
	hasFlushed = true;

	if (ret < 0) {
		debug(QString("Error while flushing MP3 file, code = %1").arg(ret));
		return false;
	}

	if (ret > 0) {
		output.truncate(ret);
		file.write(output);
	}

	return true;
}
Esempio n. 12
0
// iso9660 + RR use some latin1 variant. So we need to cut the desc fields
// counting 8bit chars. The GUI should take care of restricting the length
// and the charset
static void truncateTheHardWay( QString& s, int max )
{
    QByteArray cs = s.toUtf8();
    cs.truncate(max);
    s = QString::fromUtf8( cs );
}
Esempio n. 13
0
void XmlRpcServer::registerSlot( QObject * receiver, const char * slot, QString methodName, QByteArray path )
{
#ifdef DEBUG_XMLRPC
      qDebug() << this << "registerSlot():" << receiver << slot;
#endif

      // skip code first symbol 1 from SLOT macro (from qobject.cpp)
      ++slot;

      // find QMetaMethod..
      const QMetaObject * mo = receiver->metaObject();

      // we need buf in memory for const char (from qobject.cpp)
      QByteArray method = QMetaObject::normalizedSignature( slot );
      const char * normalized = method.constData();

      int slotId = mo->indexOfSlot( normalized );
      if( slotId == -1 ) {
            qCritical() << this << "registerSlot():" << receiver << normalized
                        << "can't find slot";

            qFatal("programming error");
      }
      QMetaMethod m = receiver->metaObject()->method( slotId );

      bool isDefferedResult = !qstrcmp( m.typeName(), "DeferredResult*" );
      if( qstrcmp(m.typeName(), "QVariant") && !isDefferedResult ) {
            qCritical() << this << "registerSlot():" << receiver << normalized
                        << "rpc return type should be QVariant or DeferredResult*, but" << m.typeName();

            qFatal("programming error");
      }

      foreach( QByteArray c, m.parameterTypes() )
            if( c != "QVariant" ) {
            qCritical() << this << "registerSlot():" << receiver << normalized
                        << "all parameters should be QVariant";

            qFatal("programming error");
      }

      // ok, now lets make just function name from our SLOT
      Q_ASSERT( method.indexOf('(') > 0 );
      method.truncate( method.indexOf('(') );
      if( path[0] != '/' )
            path.prepend( '/' );
      if( path[path.size()-1] != '/' )
            path.append( '/' );

      //method.prepend( path );
      methodName.prepend(path);

      // check if allready exists
      if( callbacks.contains(methodName) ) {
            qCritical() << this << "registerSlot():" << receiver << method
                        << "allready registered.";
            qFatal( "programming error" );
      }
      //callbacks[ method ] = IsMethodDeffered( receiver, isDefferedResult );
      MethodData data;
      data.receiver = receiver;
      data.method = method;
      data.isMethodDeffered = isDefferedResult;
      callbacks[ methodName ] = data;

      Methods& methods = objectMethods[ receiver ];

      if( methods.isEmpty() ) {
#ifdef DEBUG_XMLRPC
            qDebug() << this << "registerSlot(): connecting SIGNAL(destroyed()) of" << receiver;
#endif
            connect( receiver, SIGNAL(destroyed(QObject*)),
                     this, SLOT(slotReceiverDestroed(QObject*)) );
      }
Esempio n. 14
0
FreeSSM::FreeSSM(QApplication *app)
{
	_qt_translator = NULL;
	_translator = NULL;
	_iface_type = AbstractDiagInterface::interface_serialPassThrough;
	_iface_filename = "";
	_language = "en";	// default language
	_dumping = false;
	QString appsPath( QCoreApplication::applicationDirPath() );
	// SETUP GUI:
	setupUi(this);
	setWindowFlags( windowFlags() & ~Qt::WindowMaximizeButtonHint );	// only necessary for MS Windows
#ifndef SMALL_RESOLUTION
	// LOAD BACKGROUND PICTURE:
	background_label->setPixmap(appsPath + "/background.png");
	// SHOW PROGRAM TITEL + VERSION:
	QFont titlefont = this->font();
	titlefont.setPointSize(20);
	titlefont.setBold(true);
	_progtitle_label = new QLabel(this);
	_progtitle_label->setGeometry(20, 17, 315, 34);
	_progtitle_label->setFont( titlefont );
	_progtitle_label->setText("FreeSSM " + QApplication::applicationVersion());
	this->setWindowTitle("FreeSSM " + QApplication::applicationVersion());
	// PLACE WINDOW IN THE CENTER OF THE SCREEN:
	QDesktopWidget desktop;
	int x = (desktop.width() - size().width()) / 2;
	int y = (desktop.height() - size().height()) / 2 - 50;
	this->move ( x, y );
#endif
	// LOAD PREFERENCES FROM FILE:
	QString savedinterfacefilename = "";
	QString savedlanguage = "";
	QString savedGUIstyle = "";
	QString savedinterfacetype = "";
	QFile prefsfile(QDir::homePath() + "/FreeSSM.prefs");
	if (prefsfile.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		QByteArray line;
		if (!prefsfile.atEnd())
		{
			// Load interface type settings:
			line = prefsfile.readLine();
			line.truncate(line.length()-1);	// truncate newline-character
			savedinterfacefilename = static_cast<QString>(line);
		}
		if (!prefsfile.atEnd())
		{
			// Load language settings:
			line = prefsfile.readLine();
			line.truncate(line.length()-1);
			savedlanguage = static_cast<QString>(line);
		}
		if (!prefsfile.atEnd())
		{
			// Load GUI-style settings:
			line = prefsfile.readLine();
			line.truncate(line.length()-1);
			savedGUIstyle = static_cast<QString>(line);
		}
		if (!prefsfile.atEnd())
		{
			// Load interface file name settings:
			line = prefsfile.readLine();
			line.truncate(line.length()-1);
			savedinterfacetype = static_cast<QString>(line);
		}
		prefsfile.close();
	}
	// SET PREFERRED GUI-Style:
	if (savedGUIstyle.size())
	{
		QStyle *qstyle = QStyleFactory::create( savedGUIstyle );
		if (qstyle)
			QApplication::setStyle( qstyle );
	}
	// CHECK SAVED LANGUAGE:
	bool sl_valid = false;
	QLocale loc = QLocale(savedlanguage);
	if ((loc != QLocale::C) && (__supportedLocales.indexOf( loc ) > -1))
	{
		_language = savedlanguage;
		sl_valid = true;
	}
	// TRY TO SELECT SYSTEM LANGUAGE, IF SAVED LANGUAGE IS INVALID:
	if (!sl_valid)
	{
		if (__supportedLocales.indexOf( QLocale::system() ) > -1)
			_language = QLocale::system().name().section('_', 0, 0);
	}
	// SET TRANSLATOR AND RETRANSLATE:
	_translator = new QTranslator;
	bool langfileerror = false;
	langfileerror = !_translator->load("FreeSSM_" + _language + ".qm", appsPath);
	if (langfileerror && (_language != "en"))
	{
		// Fallback to English
		_language = "en";
		langfileerror = !_translator->load("FreeSSM_en.qm", appsPath);
		// Display error message about missing language file:
		QMessageBox msg( QMessageBox::Critical, tr("Error"), tr("Error:\n- Language file missing or damaged -"), QMessageBox::Ok, this);
		QFont msgfont = msg.font();
		msgfont.setPointSize(9);
		msg.setFont( msgfont );
		msg.show();
		msg.exec();
		msg.close();
	}
	if (!langfileerror)
	{
		app->installTranslator(_translator);
		retranslateUi(this);
	}
	else
	{
		delete _translator;
		_translator = NULL;
	}
	// SET Qt-TRANSLATOR (if necessary and available):
	if (_language != "en")
	{
		QString qt_ts_path = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
		if (qt_ts_path.isEmpty())
			qt_ts_path = QCoreApplication::applicationDirPath();
		_qt_translator = new QTranslator;
		if (_qt_translator->load("qt_" + _language, qt_ts_path))
			app->installTranslator(_qt_translator);
		else
		{
			delete _qt_translator;
			_qt_translator = NULL;
		}
	}
	// CHECK THE SAVED INTERFACE SETTINGS AND CORRECT IF NECESSARY:
	if (savedinterfacetype == QString::number(AbstractDiagInterface::interface_J2534))	// J2534-Pass-Through
	{
		_iface_type = AbstractDiagInterface::interface_J2534;
		const std::vector<J2534Library> J2534libs = J2534_API::getAvailableJ2534Libs();
		if (J2534libs.size())
		{
			if (!savedinterfacefilename.isEmpty())
			{
				for (const J2534Library& lib : J2534libs)
				{
					if (savedinterfacefilename == QString::fromStdString(lib.path))
					{
						_iface_filename = savedinterfacefilename;
						break;
					}
				}
			}
			if (_iface_filename.isEmpty())
				_iface_filename = QString::fromStdString(J2534libs.at(0).path);
		}
		// NOTE: otherwise _iface_filename remains empty
	}
	else	// Serial Pass-Through, AT-comand controlled (e.g. ELM, AGV, Diamex) or invalid
	{
		if (savedinterfacetype == QString::number(AbstractDiagInterface::interface_ATcommandControlled))
			_iface_type = AbstractDiagInterface::interface_ATcommandControlled;
		else
			_iface_type = AbstractDiagInterface::interface_serialPassThrough;
		std::vector<std::string> portlist;
		portlist = serialCOM::GetAvailablePorts();
		if (portlist.size())
		{
			if (!savedinterfacetype.isEmpty() && !savedinterfacefilename.isEmpty())
			{
				for (unsigned int k=0; k<portlist.size(); k++)
				{
					if (savedinterfacefilename == QString::fromStdString(portlist.at(k)))
					{
						_iface_filename = savedinterfacefilename;
						break;
					}
				}
			}
			if (_iface_filename.isEmpty())
				_iface_filename = QString::fromStdString(portlist.at(0));
		}
		// NOTE: otherwise _iface_filename remains empty
	}
	// CREATE ACTION FOR DUMPING CONTROL UNIT ID-DATA TO FILE:
	_dump_action = new QAction(this);
	_dump_action->setShortcut( QKeySequence("Ctrl+Alt+Return") );
	this->addAction(_dump_action);
	// CONNECT SIGNALS/SLOTS:
	connect( engine_pushButton, SIGNAL( released() ), this, SLOT( engine() ) );
	connect( transmission_pushButton, SIGNAL( released() ), this, SLOT( transmission() ) );
	connect( absvdc_pushButton, SIGNAL( released() ), this, SLOT( abs() ) );
	connect( cruisecontrol_pushButton, SIGNAL( released() ), this, SLOT( cruisecontrol() ) );
	connect( aircon_pushButton, SIGNAL( released() ), this, SLOT( aircon() ) );
	connect( preferences_pushButton, SIGNAL( released() ), this, SLOT( preferences() ) );
	connect( help_pushButton, SIGNAL( released() ), this, SLOT( help() ) );
	connect( about_pushButton, SIGNAL( released() ), this, SLOT( about() ) );
	connect( exit_pushButton, SIGNAL( released() ), this, SLOT( close() ) );
	// NOTE: using released() instead of pressed() as workaround for a Qt-Bug occuring under MS Windows
	connect( _dump_action, SIGNAL(triggered()), this, SLOT(dumpCUdata()) );
}
Esempio n. 15
0
bool MythSocket::readStringList(QStringList &list, uint timeoutMS)
{
    list.clear();

    if (state() != Connected)
    {
        VERBOSE(VB_IMPORTANT, LOC +
                "readStringList: Error, called with unconnected socket.");
        return false;
    }

    MythTimer timer;
    timer.start();
    int elapsed = 0;

    while (waitForMore(5) < 8)
    {
        elapsed = timer.elapsed();
        if (elapsed >= (int)timeoutMS)
        {
            VERBOSE(VB_IMPORTANT, LOC + "readStringList: " +
                    QString("Error, timed out after %1 ms.").arg(timeoutMS));
            close();
            return false;
        }

        if (state() != Connected)
        {
            VERBOSE(VB_IMPORTANT, LOC +
                    "readStringList: Connection died.");
            return false;
        }

        {
            struct timeval tv;
            int maxfd;
            fd_set rfds;

            FD_ZERO(&rfds);
            FD_SET(socket(), &rfds);
            maxfd = socket();

            tv.tv_sec = 0;
            tv.tv_usec = 0;

            int rval = select(maxfd + 1, &rfds, NULL, NULL, &tv);
            if (rval)
            {
                if (bytesAvailable() == 0)
                {
                    VERBOSE(VB_IMPORTANT, LOC +
                            "readStringList: Connection died (select).");
                    return false;
                }
            }
        }
    }

    QByteArray sizestr(8 + 1, '\0');
    if (readBlock(sizestr.data(), 8) < 0)
    {
        VERBOSE(VB_GENERAL, LOC +
                QString("readStringList: Error, readBlock return error (%1)")
                .arg(errorToString()));
        close();
        return false;
    }

    QString sizes = sizestr;
    qint64 btr = sizes.trimmed().toInt();

    if (btr < 1)
    {
        int pending = bytesAvailable();
        QByteArray dump(pending + 1, 0);
        readBlock(dump.data(), pending);
        VERBOSE(VB_IMPORTANT, LOC +
                QString("Protocol error: '%1' is not a valid size "
                        "prefix. %2 bytes pending.")
                        .arg(sizestr.data()).arg(pending));
        return false;
    }

    QByteArray utf8(btr + 1, 0);

    qint64 read = 0;
    int errmsgtime = 0;
    timer.start();

    while (btr > 0)
    {
        qint64 sret = readBlock(utf8.data() + read, btr);
        if (sret > 0)
        {
            read += sret;
            btr -= sret;
            if (btr > 0)
            {
                timer.start();
            }
        }
        else if (sret < 0 && error() != MSocketDevice::NoError)
        {
            VERBOSE(VB_GENERAL, LOC +
                    QString("readStringList: Error, readBlock %1")
                    .arg(errorToString()));
            close();
            return false;
        }
        else if (!isValid())
        {
            VERBOSE(VB_IMPORTANT, LOC +
                    "readStringList: Error, socket went unconnected");
            close();
            return false;
        }
        else
        {
            elapsed = timer.elapsed();
            if (elapsed  > 10000)
            {
                if ((elapsed - errmsgtime) > 10000)
                {
                    errmsgtime = elapsed;
                    VERBOSE(VB_GENERAL, LOC +
                            QString("readStringList: Waiting for data: %1 %2")
                            .arg(read).arg(btr));
                }
            }

            if (elapsed > 100000)
            {
                VERBOSE(VB_GENERAL, LOC +
                        "Error, readStringList timeout (readBlock)");
                return false;
            }

            usleep(500);
        }
    }

    QString str = QString::fromUtf8(utf8.data());

    QByteArray payload;
    payload = payload.setNum(str.length());
    payload += "        ";
    payload.truncate(8);
    payload += str;

    if (VERBOSE_LEVEL_CHECK(VB_NETWORK))
    {
        QString msg = QString("read  <- %1 %2").arg(socket(), 2)
            .arg(payload.data());

        if (!VERBOSE_LEVEL_CHECK(VB_EXTRA) && msg.length() > 88)
        {
            msg.truncate(85);
            msg += "...";
        }
        VERBOSE(VB_NETWORK, LOC + msg);
    }

    list = str.split("[]:[]");

    m_notifyread = false;
    s_readyread_thread->WakeReadyReadThread();
    return true;
}
Esempio n. 16
0
KVSO_CLASS_FUNCTION(xmlReader, parse)
{
	KviKvsVariant * pVariantData;

	KVSO_PARAMETERS_BEGIN(c)
	KVSO_PARAMETER("string_or_memorybuffer_object", KVS_PT_VARIANT, 0, pVariantData)
	KVSO_PARAMETERS_END(c)
#ifdef QT_NO_XML
	fatalError(__tr2qs_ctx("XML support not available in the Qt library"));
	c->returnValue()->setBoolean(false);
#else
	m_szLastError = "";
	KviXmlHandler handler(this);
	QXmlInputSource source;

	if(pVariantData->isHObject())
	{
		KviKvsObject * pObject;
		kvs_hobject_t hObject;
		pVariantData->asHObject(hObject);
		pObject = KviKvsKernel::instance()->objectController()->lookupObject(hObject);
		if(!pObject)
		{
			c->warning(__tr2qs_ctx("Data parameter is not an object", "objects"));
			return true;
		}
		if(pObject->inheritsClass("memorybuffer"))
		{
			source.setData(*((KvsObject_memoryBuffer *)pObject)->pBuffer());
		}
		else
		{
			c->warning(__tr2qs_ctx("Data parameter is not a memorybuffer object", "objects"));
			return true;
		}
	}
	else if(pVariantData->isString())
	{
		QString szString;
		pVariantData->asString(szString);
		// We have a problem here.. most kvirc functions already interpret the data
		// read from files. We should have binary data handling features to get this to work correctly.
		// The following snippet of code tries to provide a best-effort workaround.
		QByteArray utf8data = szString.toUtf8();
		QByteArray data = utf8data;
		data.truncate(utf8data.length()); // don't include the null terminator in data
		source.setData(data);
		//qDebug("PARSING(%s) LEN(%d)",szString.toUtf8().data(),szString.toUtf8().length());
	}
	else
	{
		c->warning(__tr2qs_ctx("Data is not a memorybuffer object or string", "objects"));
		return true;
	}
	QXmlSimpleReader reader;
	reader.setContentHandler(&handler);
	reader.setErrorHandler(&handler);
	c->returnValue()->setBoolean(reader.parse(source));
#endif
	return true;
}
bool MLogicalValuesPrivate::parse(const QFileInfo &fileInfo, Groups &groups)
{
    QFile file(fileInfo.filePath());
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    QByteArray group = "General";
    groups.insert("General", Values());

    while (!file.atEnd()) {
        QByteArray line = file.readLine().trimmed();
        // skip comments
        if (line.startsWith("[")) {
            // parse group header
            int index = line.indexOf("]", 1);
            if (index == -1) {
                mWarning("MLogicalValues") << "Error occurred when parsing .ini file:" << line;
                file.close();
                return false;
            }
            // this will be the currently active group
            group = line.mid(1, index - 1);
        } else {

            // key/value pair
            QByteArray key, value;
            QByteArray *target = &key;

            // stores the last 'good' character
            int truncation = 0;
            // go through whole line
            for (int i = 0; i < line.length(); i++) {
                QChar character = line.at(i);
                if (character == ';') {
                    break;
                } else if (character == '=') {
                    // remove trailing whitespaces
                    target->truncate(truncation);
                    // start to parse value
                    target = &value;
                    truncation = 0;
                } else {
                    if (target->isEmpty() && character.isSpace()) {
                        // do not add whitespaces at the beginning
                    } else {
                        (*target) += character;
                        if (!character.isSpace())
                            truncation = target->length();
                    }
                }
            }
            // remove trailing whitespaces
            target->truncate(truncation);

            // consistency check
            if (!line.startsWith(';') && line.length() > 0) {
                if (key.isEmpty() || value.isEmpty()) {
                    mWarning("MLogicalValues") << "Error occurred when parsing .ini file:" << line;
                    file.close();
                    return false;
                }
                // store
                Values &values = groups[group];

                if (!values.contains(key)) {
                    values.insert(key, value);
                }
            }
        }
    }

    saveToBinaryCache(fileInfo, groups);
    file.close();
    return true;
}
Esempio n. 18
0
QByteArray QIsciiCodec::convertFromUnicode(const QChar *uc, int len, ConverterState *state) const
{
    char replacement = '?';
    bool halant = false;
    if (state) {
        if (state->flags & ConvertInvalidToNull)
            replacement = 0;
        halant = state->state_data[0];
    }
    int invalid = 0;

    QByteArray result;
    result.resize(2*len); //worst case

    uchar *ch = reinterpret_cast<uchar *>(result.data());

    const int base = codecs[idx].base;

    for (int i =0; i < len; ++i) {
        const ushort codePoint = uc[i].unicode();

        /* The low 7 bits of ISCII is plain ASCII. However, we go all the
         * way up to 0xA0 such that we can roundtrip with convertToUnicode()'s
         * behavior. */
        if(codePoint < 0xA0) {
            *ch++ = static_cast<uchar>(codePoint);
            continue;
        }

        const int pos = codePoint - base;
        if (pos > 0 && pos < 0x80) {
            uchar iscii = uni_to_iscii_table[pos];
            if (iscii > 0x80) {
                *ch++ = iscii;
            } else if (iscii) {
                const uchar *pair = uni_to_iscii_pairs + 2*iscii;
                *ch++ = *pair++;
                *ch++ = *pair++;
            } else {
                *ch++ = replacement;
                ++invalid;
            }
        } else {
            if (uc[i].unicode() == 0x200c) { // ZWNJ
                if (halant)
                    // Consonant Halant ZWNJ -> Consonant Halant Halant
                    *ch++ = 0xe8;
            } else if (uc[i].unicode() == 0x200d) { // ZWJ
                if (halant)
                    // Consonant Halant ZWJ -> Consonant Halant Nukta
                    *ch++ = 0xe9;
            } else {
                *ch++ = replacement;
                ++invalid;
            }
        }
        halant = (pos == 0x4d);
    }
    result.truncate(ch - (uchar *)result.data());

    if (state) {
        state->invalidChars += invalid;
        state->state_data[0] = halant;
    }
    return result;
}
Esempio n. 19
0
void Widget::tcpProcessPendingDatagrams()
{
    // On détermine quel client envoie le message (recherche du QTcpSocket du client)
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0) // Si par hasard on n'a pas trouvé le client à l'origine du signal, on arrête la méthode
        return;

    unsigned nTries = 0;

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

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

                // Detect and send data files if we need to
                // TODO: Process and send all the requested data
                QByteArray data = *tcpReceivedDatas;
                int i1=0;
                do
                {
                    i1 = data.indexOf("GET");
                    if (i1 != -1)
                    {
                        int i2 = data.indexOf("HTTP")-1;
                        QString path = data.mid(i1 + 4, i2-i1-4);
                        logMessage("Received GET:"+path);
                        QFile head(QString(NETDATAPATH)+"/test.bin");
                        QFile res("gameFiles"+path);
                        head.open(QIODevice::ReadOnly);
                        res.open(QIODevice::ReadOnly);
                        socket->write(head.readAll());
                        socket->write(QString("Content-Length: "+QString().setNum(res.size())+"\n\n").toLatin1());
                        socket->write(res.readAll());
                        head.close();
                        res.close();
                        logMessage("Sent ("+QString().setNum(res.size())+" bytes)");
                        data = removeHTTPHeader(data, "POST ");
                        data = removeHTTPHeader(data, "GET ");
                    }
                } while (i1 != -1);

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

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

                    // Process data, if the buffer is not empty, keep reading
                    tcpProcessData(data, socket);
                    if (tcpReceivedDatas->isEmpty())
                        return;
                    nTries=0;
                }
            }
        }
    }
}
Esempio n. 20
0
//load dump
void bootSector::on_pushButton_clicked()
{
    //open load dialog
    QString fname = QFileDialog::getOpenFileName(this,"Load boot sector","","Binary (*.bin);;All files (*)");

    if (fname=="")
        return;


    QFile file(fname);
    if (!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this,"Error","File "+fname+" cannot be opened for reading.");
        return;
    }

    //check length
    int size=file.size();
    if (size!=this->length)
    {
        QMessageBox::critical(this,"Error","File "+fname+" has size "+QString::number(size)+"B while sector has "+QString::number(this->length)+"B. File should be the same length as sector.");
        return;
    }

    int getBlock=ui->leBIOSEnds->text().toUpper().toInt(NULL,16);
    //char blockSize=this->sectorData.at(1)-2; //size of BIOS parameter block
    QByteArray BIOSBlock;
    //check if user entered proper value
    if (ui->cbPreserveBIOS->isChecked())
    {
        if ((getBlock<11)||(this->sectorData.length()<getBlock))
        {
            QMessageBox::critical(this,"Error","Wrong byte count entered into editor. It exceeds the sector size or is smaller than starting address.");
            return;
        }
        BIOSBlock=this->sectorData.mid(11,getBlock-11);
    }

    //load the dump
    this->modified=1;
    file.seek(1);
    char newBPBSize=0;
    file.read(&newBPBSize,1);

//    if (((unsigned char)newBPBSize>getBlock-11)&&(ui->cbPreserveBIOS->isChecked()))
//    {
//        QMessageBox::StandardButton reply;
//        reply = QMessageBox::question(this, "Wrong size",
//                                      "In loaded sector, BIOS block has length 0x"+QString::number((unsigned char)newBPBSize,16).toUpper()+
//                                      "\nAnd the image or setting is 0x"+QString::number(getBlock-11,16).toUpper()+"\n Do you want to continue?",
//                                      QMessageBox::Yes|QMessageBox::No);
//        if (reply==QMessageBox::No)
//            return;
//    }

    if (((unsigned char)newBPBSize<getBlock-11)&&(ui->cbPreserveBIOS->isChecked()))
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "Wrong size",
                                      "In loaded sector, BIOS block has length 0x"+QString::number((unsigned char)newBPBSize,16).toUpper()+
                                      "\nAnd the image or setting is 0x"+QString::number(getBlock-11,16).toUpper()+"\nThis will likely fail.\n"
                                      "Press Yes to continue and probably overwrite part of bootloader code.\n"
                                      "Press No to preserve only loaded sector's BPB (0x"+QString::number((unsigned char)newBPBSize,16).toUpper()+" Bytes). This may work.\n"
                                      "Press Cancel to abandon importing.",
                                      QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
        if (reply==QMessageBox::Cancel)
            return;
        if (reply==QMessageBox::No)
        {
            BIOSBlock.truncate(newBPBSize);
        }
    }

    file.seek(0); //After calling size() - Qt4 bug on BSD.
    this->sectorData=file.readAll();
    file.close();

    QString label=ui->leLabel->text();
    QString oem = ui->leOEMString->text();
    QString serial=ui->leSerial->text();

    this->refreshView();

    //optionally patch the dump with preserved data
    if (ui->cbPreserveBIOS->isChecked())
    {
        this->sectorData.replace(11,BIOSBlock.length(),BIOSBlock);
        this->refreshView();
    }
    if ((ui->cbPreserveLabel->isEnabled())&&(ui->cbPreserveLabel->isChecked()))
    {
        ui->leLabel->setText(label);
        this->on_leLabel_textEdited(label);
    }
    if (ui->cbPreserveOEM->isChecked())
    {
        ui->leOEMString->setText(oem);
        this->on_leOEMString_textEdited(oem);
    }
    if ((ui->cbPreserveSerial->isEnabled())&&(ui->cbPreserveSerial->isChecked()))
    {
        ui->leSerial->setText(serial);
        this->on_leSerial_textEdited(serial);
    }
}
Esempio n. 21
0
void MythSocket::WriteStringListReal(const QStringList *list, bool *ret)
{
    if (list->empty())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            "WriteStringList: Error, invalid string list.");
        *ret = false;
        return;
    }

    if (m_tcpSocket->state() != QAbstractSocket::ConnectedState)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            "WriteStringList: Error, called with unconnected socket.");
        *ret = false;
        return;
    }

    QString str = list->join("[]:[]");
    if (str.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            "WriteStringList: Error, joined null string.");
        *ret = false;
        return;
    }

    QByteArray utf8 = str.toUtf8();
    int size = utf8.length();
    int written = 0;
    int written_since_timer_restart = 0;

    QByteArray payload;
    payload = payload.setNum(size);
    payload += "        ";
    payload.truncate(8);
    payload += utf8;
    size = payload.length();

    if (VERBOSE_LEVEL_CHECK(VB_NETWORK, LOG_INFO))
    {
        QString msg = QString("write -> %1 %2")
            .arg(m_tcpSocket->socketDescriptor(), 2).arg(payload.data());

        if (logLevel < LOG_DEBUG && msg.length() > 88)
        {
            msg.truncate(85);
            msg += "...";
        }
        LOG(VB_NETWORK, LOG_INFO, LOC + msg);
    }

    MythTimer timer; timer.start();
    unsigned int errorcount = 0;
    while (size > 0)
    {
        if (m_tcpSocket->state() != QAbstractSocket::ConnectedState)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                "WriteStringList: Error, socket went unconnected." +
                QString("\n\t\t\tWe wrote %1 of %2 bytes with %3 errors")
                    .arg(written).arg(written+size).arg(errorcount) +
                    QString("\n\t\t\tstarts with: %1").arg(to_sample(payload)));
            *ret = false;
            return;
        }

        int temp = m_tcpSocket->write(payload.data() + written, size);
        if (temp > 0)
        {
            written += temp;
            written_since_timer_restart += temp;
            size -= temp;
            if ((timer.elapsed() > 500) && written_since_timer_restart != 0)
            {
                timer.restart();
                written_since_timer_restart = 0;
            }
        }
        else if (temp <= 0)
        {
            errorcount++;
            if (timer.elapsed() > 1000)
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "WriteStringList: Error, " +
                    QString("No data written on write (%1 errors)")
                        .arg(errorcount) +
                    QString("\n\t\t\tstarts with: %1")
                    .arg(to_sample(payload)));
                *ret = false;
                return;
            }
            usleep(1000);
        }
    }

    m_tcpSocket->flush();

    *ret = true;
    return;
}
void QNetworkAccessDataBackend::open()
{
    QUrl uri = request().url();

    if (operation() != QNetworkAccessManager::GetOperation &&
        operation() != QNetworkAccessManager::HeadOperation) {
        // data: doesn't support anything but GET
        QString msg = QObject::tr("Operation not supported on %1")
                      .arg(uri.toString());
        error(QNetworkReply::ContentOperationNotPermittedError, msg);
        finished();
        return;
    }

    if (uri.host().isEmpty()) {
        setHeader(QNetworkRequest::ContentTypeHeader, 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) {
            QByteArray 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())
                setHeader(QNetworkRequest::ContentTypeHeader, data.trimmed());

            setHeader(QNetworkRequest::ContentLengthHeader, payload.size());
            emit metaDataChanged();

            writeDownstreamData(payload);
            finished();
            return;
        }
    }

    // something wrong with this URI
    QString msg = QObject::tr("Invalid URI: %1").arg(uri.toString());
    error(QNetworkReply::ProtocolFailure, msg);
    finished();
}
Esempio n. 23
0
void MythSocket::ReadStringListReal(
    QStringList *list, uint timeoutMS, bool *ret)
{
    list->clear();
    *ret = false;

    MythTimer timer;
    timer.start();
    int elapsed = 0;

    while (m_tcpSocket->bytesAvailable() < 8)
    {
        elapsed = timer.elapsed();
        if (elapsed >= (int)timeoutMS)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "ReadStringList: " +
                QString("Error, timed out after %1 ms.").arg(timeoutMS));
            m_tcpSocket->close();
            m_dataAvailable.fetchAndStoreOrdered(0);
            return;
        }

        if (m_tcpSocket->state() != QAbstractSocket::ConnectedState)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "ReadStringList: Connection died.");
            m_dataAvailable.fetchAndStoreOrdered(0);
            return;
        }

        m_tcpSocket->waitForReadyRead(50);
    }

    QByteArray sizestr(8 + 1, '\0');
    if (m_tcpSocket->read(sizestr.data(), 8) < 0)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("ReadStringList: Error, read return error (%1)")
                .arg(m_tcpSocket->errorString()));
        m_tcpSocket->close();
        m_dataAvailable.fetchAndStoreOrdered(0);
        return;
    }

    QString sizes = sizestr;
    qint64 btr = sizes.trimmed().toInt();

    if (btr < 1)
    {
        int pending = m_tcpSocket->bytesAvailable();
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Protocol error: '%1' is not a valid size "
                    "prefix. %2 bytes pending.")
                .arg(sizestr.data()).arg(pending));
        ResetReal();
        return;
    }

    QByteArray utf8(btr + 1, 0);

    qint64 readoffset = 0;
    int errmsgtime = 0;
    timer.start();

    while (btr > 0)
    {
        if (m_tcpSocket->bytesAvailable() < 1)
        {
            if (m_tcpSocket->state() == QAbstractSocket::ConnectedState)
            {
                m_tcpSocket->waitForReadyRead(50);
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    "ReadStringList: Connection died.");
                m_dataAvailable.fetchAndStoreOrdered(0);
                return;
            }
        }

        qint64 sret = m_tcpSocket->read(utf8.data() + readoffset, btr);
        if (sret > 0)
        {
            readoffset += sret;
            btr -= sret;
            if (btr > 0)
            {
                timer.start();
            }
        }
        else if (sret < 0)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "ReadStringList: Error, read");
            m_tcpSocket->close();
            m_dataAvailable.fetchAndStoreOrdered(0);
            return;
        }
        else if (!m_tcpSocket->isValid())
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                "ReadStringList: Error, socket went unconnected");
            m_tcpSocket->close();
            m_dataAvailable.fetchAndStoreOrdered(0);
            return;
        }
        else
        {
            elapsed = timer.elapsed();
            if (elapsed  > 10000)
            {
                if ((elapsed - errmsgtime) > 10000)
                {
                    errmsgtime = elapsed;
                    LOG(VB_GENERAL, LOG_ERR, LOC +
                        QString("ReadStringList: Waiting for data: %1 %2")
                            .arg(readoffset).arg(btr));
                }
            }

            if (elapsed > 100000)
            {
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    "Error, ReadStringList timeout (readBlock)");
                m_dataAvailable.fetchAndStoreOrdered(0);
                return;
            }
        }
    }

    QString str = QString::fromUtf8(utf8.data());

    QByteArray payload;
    payload = payload.setNum(str.length());
    payload += "        ";
    payload.truncate(8);
    payload += str;

    if (VERBOSE_LEVEL_CHECK(VB_NETWORK, LOG_INFO))
    {
        QString msg = QString("read  <- %1 %2")
            .arg(m_tcpSocket->socketDescriptor(), 2)
            .arg(payload.data());

        if (logLevel < LOG_DEBUG && msg.length() > 88)
        {
            msg.truncate(85);
            msg += "...";
        }
        LOG(VB_NETWORK, LOG_INFO, LOC + msg);
    }

    *list = str.split("[]:[]");

    m_dataAvailable.fetchAndStoreOrdered(
        (m_tcpSocket->bytesAvailable() > 0) ? 1 : 0);

    *ret = true;
}
Esempio n. 24
0
// calculates the metatypes for the method
// the slot must have the parameters in the following form:
//  - zero or more value or const-ref parameters of any kind
//  - zero or one const ref of QDBusMessage
//  - zero or more non-const ref parameters
// No parameter may be a template.
// this function returns -1 if the parameters don't match the above form
// this function returns the number of *input* parameters, including the QDBusMessage one if any
// this function does not check the return type, so metaTypes[0] is always 0 and always present
// metaTypes.count() >= retval + 1 in all cases
//
// sig must be the normalised signature for the method
int qDBusParametersForMethod(const QMetaMethod &mm, QList<int>& metaTypes)
{
    QDBusMetaTypeId::init();

    QList<QByteArray> parameterTypes = mm.parameterTypes();
    metaTypes.clear();

    metaTypes.append(0);        // return type
    int inputCount = 0;
    bool seenMessage = false;
    QList<QByteArray>::ConstIterator it = parameterTypes.constBegin();
    QList<QByteArray>::ConstIterator end = parameterTypes.constEnd();
    for ( ; it != end; ++it) {
        const QByteArray &type = *it;
        if (type.endsWith('*')) {
            //qWarning("Could not parse the method '%s'", mm.signature());
            // pointer?
            return -1;
        }

        if (type.endsWith('&')) {
            QByteArray basictype = type;
            basictype.truncate(type.length() - 1);

            int id = qDBusNameToTypeId(basictype);
            if (id == 0) {
                //qWarning("Could not parse the method '%s'", mm.signature());
                // invalid type in method parameter list
                return -1;
            } else if (QDBusMetaType::typeToSignature(id) == 0)
                return -1;

            metaTypes.append( id );
            seenMessage = true; // it cannot appear anymore anyways
            continue;
        }

        if (seenMessage) {      // && !type.endsWith('&')
            //qWarning("Could not parse the method '%s'", mm.signature());
            // non-output parameters after message or after output params
            return -1;          // not allowed
        }

        int id = qDBusNameToTypeId(type);
        if (id == 0) {
            //qWarning("Could not parse the method '%s'", mm.signature());
            // invalid type in method parameter list
            return -1;
        }

        if (id == QDBusMetaTypeId::message)
            seenMessage = true;
        else if (QDBusMetaType::typeToSignature(id) == 0)
            return -1;

        metaTypes.append(id);
        ++inputCount;
    }

    return inputCount;
}
Esempio n. 25
0
File: main.cpp Progetto: RSATom/Qt
QT_USE_NAMESPACE

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

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

    QByteArray outname;
    QByteArray object;

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

        default:
            break;
        }
    }

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

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

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

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

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

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

    QString docu = axobject->generateDocumentation();
    out << docu;
    return 0;
}
Esempio n. 26
0
void KCodecs::quotedPrintableEncode(const QByteArray& in, QByteArray& out, bool useCRLF)
{
  out.resize (0);
  if (in.isEmpty())
    return;

  char *cursor;
  const char *data;
  unsigned int lineLength;
  unsigned int pos;

  const unsigned int length = in.size();
  const unsigned int end = length - 1;


  // Reasonable guess for output size when we're encoding
  // mostly-ASCII data. It doesn't really matter, because
  // the underlying allocation routines are quite efficient,
  // but it's nice to have 0 allocations in many cases.
  out.resize ((length*12)/10);
  cursor = out.data();
  data = in.data();
  lineLength = 0;
  pos = 0;

  for (unsigned int i = 0; i < length; i++)
  {
    unsigned char c (data[i]);

    // check if we have to enlarge the output buffer, use
    // a safety margin of 16 byte
    pos = cursor-out.data();
    if (out.size()-pos < 16) {
      out.resize(out.size()+4096);
      cursor = out.data()+pos;
    }

    // Plain ASCII chars just go straight out.

    if ((c >= 33) && (c <= 126) && ('=' != c))
    {
      *cursor++ = c;
      ++lineLength;
    }

    // Spaces need some thought. We have to encode them at eol (or eof).

    else if (' ' == c)
    {
      if
        (
         (i >= length)
         ||
         ((i < end) && ((useCRLF && ('\r' == data[i + 1]) && ('\n' == data[i + 2]))
                        ||
                        (!useCRLF && ('\n' == data[i + 1]))))
        )
      {
        *cursor++ = '=';
        *cursor++ = '2';
        *cursor++ = '0';

        lineLength += 3;
      }
      else
      {
        *cursor++ = ' ';
        ++lineLength;
      }
    }
    // If we find a line break, just let it through.
    else if ((useCRLF && ('\r' == c) && (i < end) && ('\n' == data[i + 1])) ||
             (!useCRLF && ('\n' == c)))
    {
      lineLength = 0;

      if (useCRLF) {
        *cursor++ = '\r';
        *cursor++ = '\n';
        ++i;
      } else {
        *cursor++ = '\n';
      }
    }

    // Anything else is converted to =XX.

    else
    {
      *cursor++ = '=';
      *cursor++ = hexChars[c / 16];
      *cursor++ = hexChars[c % 16];

      lineLength += 3;
    }

    // If we're approaching the maximum line length, do a soft line break.

    if ((lineLength > maxQPLineLength) && (i < end))
    {
      if (useCRLF) {
        *cursor++ = '=';
        *cursor++ = '\r';
        *cursor++ = '\n';
      } else {
        *cursor++ = '=';
        *cursor++ = '\n';
      }

      lineLength = 0;
    }
  }

  out.truncate(cursor - out.data());
}
Esempio n. 27
0
QByteArray JsonValue::parseCString(const char *&from, const char *to)
{
    QByteArray result;
    JDEBUG("parseCString: " << QByteArray(from, to - from));
    if (*from != '"') {
        qDebug() << "JSON Parse Error, double quote expected";
        ++from; // So we don't hang
        return QByteArray();
    }
    const char *ptr = from;
    ++ptr;
    while (ptr < to) {
        if (*ptr == '"') {
            ++ptr;
            result = QByteArray(from + 1, ptr - from - 2);
            break;
        }
        if (*ptr == '\\') {
            ++ptr;
            if (ptr == to) {
                qDebug() << "JSON Parse Error, unterminated backslash escape";
                from = ptr; // So we don't hang
                return QByteArray();
            }
        }
        ++ptr;
    }
    from = ptr;

    int idx = result.indexOf('\\');
    if (idx >= 0) {
        char *dst = result.data() + idx;
        const char *src = dst + 1, *end = result.data() + result.length();
        do {
            char c = *src++;
            switch (c) {
                case 'a': *dst++ = '\a'; break;
                case 'b': *dst++ = '\b'; break;
                case 'f': *dst++ = '\f'; break;
                case 'n': *dst++ = '\n'; break;
                case 'r': *dst++ = '\r'; break;
                case 't': *dst++ = '\t'; break;
                case 'v': *dst++ = '\v'; break;
                case '"': *dst++ = '"'; break;
                case '\\': *dst++ = '\\'; break;
                default:
                    {
                        int chars = 0;
                        uchar prod = 0;
                        forever {
                            if (c < '0' || c > '7') {
                                --src;
                                break;
                            }
                            prod = prod * 8 + c - '0';
                            if (++chars == 3 || src == end)
                                break;
                            c = *src++;
                        }
                        if (!chars) {
                            qDebug() << "JSON Parse Error, unrecognized backslash escape";
                            return QByteArray();
                        }
                        *dst++ = prod;
                    }
            }
            while (src != end) {
                char c = *src++;
                if (c == '\\')
                    break;
                *dst++ = c;
            }
        } while (src != end);
        *dst = 0;
        result.truncate(dst - result.data());
    }
void wrapInFunction()
{

//! [0]
QByteArray ba("Hello");
//! [0]


//! [1]
QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
//! [1]


//! [2]
for (int i = 0; i < ba.size(); ++i) {
    if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
        cout << "Found character in range [a-f]" << endl;
}
//! [2]


//! [3]
QByteArray x("and");
x.prepend("rock ");         // x == "rock and"
x.append(" roll");          // x == "rock and roll"
x.replace(5, 3, "&");       // x == "rock & roll"
//! [3]


//! [4]
QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
    cout << "Found <b> tag at index position " << j << endl;
    ++j;
}
//! [4]


//! [5]
QByteArray().isNull();          // returns true
QByteArray().isEmpty();         // returns true

QByteArray("").isNull();        // returns false
QByteArray("").isEmpty();       // returns true

QByteArray("abc").isNull();     // returns false
QByteArray("abc").isEmpty();    // returns false
//! [5]


//! [6]
QByteArray ba("Hello");
int n = ba.size();          // n == 5
ba.data()[0];               // returns 'H'
ba.data()[4];               // returns 'o'
ba.data()[5];               // returns '\0'
//! [6]


//! [7]
QByteArray().isEmpty();         // returns true
QByteArray("").isEmpty();       // returns true
QByteArray("abc").isEmpty();    // returns false
//! [7]


//! [8]
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
    cout << "[" << *data << "]" << endl;
    ++data;
}
//! [8]


//! [9]
QByteArray ba;
for (int i = 0; i < 10; ++i)
    ba[i] = 'A' + i;
// ba == "ABCDEFGHIJ"
//! [9]


//! [10]
QByteArray ba("Stockholm");
ba.truncate(5);             // ba == "Stock"
//! [10]


//! [11]
QByteArray ba("STARTTLS\r\n");
ba.chop(2);                 // ba == "STARTTLS"
//! [11]


//! [12]
QByteArray x("free");
QByteArray y("dom");
x += y;
// x == "freedom"
//! [12]


//! [13]
QByteArray().isNull();          // returns true
QByteArray("").isNull();        // returns false
QByteArray("abc").isNull();     // returns false
//! [13]


//! [14]
QByteArray ba("Istambul");
ba.fill('o');
// ba == "oooooooo"

ba.fill('X', 2);
// ba == "XX"
//! [14]


//! [15]
QByteArray x("ship");
QByteArray y("air");
x.prepend(y);
// x == "airship"
//! [15]


//! [16]
QByteArray x("free");
QByteArray y("dom");
x.append(y);
// x == "freedom"
//! [16]


//! [17]
QByteArray ba("Meal");
ba.insert(1, QByteArray("ontr"));
// ba == "Montreal"
//! [17]


//! [18]
QByteArray ba("Montreal");
ba.remove(1, 4);
// ba == "Meal"
//! [18]


//! [19]
QByteArray x("Say yes!");
QByteArray y("no");
x.replace(4, 3, y);
// x == "Say no!"
//! [19]


//! [20]
QByteArray ba("colour behaviour flavour neighbour");
ba.replace(QByteArray("ou"), QByteArray("o"));
// ba == "color behavior flavor neighbor"
//! [20]


//! [21]
QByteArray x("sticky question");
QByteArray y("sti");
x.indexOf(y);               // returns 0
x.indexOf(y, 1);            // returns 10
x.indexOf(y, 10);           // returns 10
x.indexOf(y, 11);           // returns -1
//! [21]


//! [22]
QByteArray ba("ABCBA");
ba.indexOf("B");            // returns 1
ba.indexOf("B", 1);         // returns 1
ba.indexOf("B", 2);         // returns 3
ba.indexOf("X");            // returns -1
//! [22]


//! [23]
QByteArray x("crazy azimuths");
QByteArray y("az");
x.lastIndexOf(y);           // returns 6
x.lastIndexOf(y, 6);        // returns 6
x.lastIndexOf(y, 5);        // returns 2
x.lastIndexOf(y, 1);        // returns -1
//! [23]


//! [24]
QByteArray ba("ABCBA");
ba.lastIndexOf("B");        // returns 3
ba.lastIndexOf("B", 3);     // returns 3
ba.lastIndexOf("B", 2);     // returns 1
ba.lastIndexOf("X");        // returns -1
//! [24]


//! [25]
QByteArray url("ftp://ftp.qt-project.org/");
if (url.startsWith("ftp:"))
    ...
//! [25]


//! [26]
QByteArray url("http://qt-project.org/doc/qt-5.0/qtdoc/index.html");
if (url.endsWith(".html"))
    ...
//! [26]


//! [27]
QByteArray x("Pineapple");
QByteArray y = x.left(4);
// y == "Pine"
//! [27]


//! [28]
QByteArray x("Pineapple");
QByteArray y = x.right(5);
// y == "apple"
//! [28]


//! [29]
QByteArray x("Five pineapples");
QByteArray y = x.mid(5, 4);     // y == "pine"
QByteArray z = x.mid(5);        // z == "pineapples"
//! [29]


//! [30]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toLower();
// y == "qt by digia"
//! [30]


//! [31]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toUpper();
// y == "QT BY DIGIA"
//! [31]


//! [32]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.simplified();
// ba == "lots of whitespace";
//! [32]


//! [33]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.trimmed();
// ba == "lots\t of\nwhitespace";
//! [33]


//! [34]
QByteArray x("apple");
QByteArray y = x.leftJustified(8, '.');   // y == "apple..."
//! [34]


//! [35]
QByteArray x("apple");
QByteArray y = x.rightJustified(8, '.');    // y == "...apple"
//! [35]


//! [36]
QByteArray str("FF");
bool ok;
int hex = str.toInt(&ok, 16);     // hex == 255, ok == true
int dec = str.toInt(&ok, 10);     // dec == 0, ok == false
//! [36]


//! [37]
QByteArray str("FF");
bool ok;
long hex = str.toLong(&ok, 16);   // hex == 255, ok == true
long dec = str.toLong(&ok, 10);   // dec == 0, ok == false
//! [37]


//! [38]
QByteArray string("1234.56");
double a = string.toDouble();   // a == 1234.56
//! [38]


//! [39]
QByteArray text("Qt is great!");
text.toBase64();        // returns "UXQgaXMgZ3JlYXQh"
//! [39]

//! [39bis]
QByteArray text("<p>Hello?</p>");
text.toBase64(QByteArray::Base64 | QByteArray::OmitTrailingEquals);      // returns "PHA+SGVsbG8/PC9wPg"
text.toBase64(QByteArray::Base64);                                       // returns "PHA+SGVsbG8/PC9wPg=="
text.toBase64(QByteArray::Base64Url);                                    // returns "PHA-SGVsbG8_PC9wPg=="
text.toBase64(QByteArray::Base64Url | QByteArray::OmitTrailingEquals);   // returns "PHA-SGVsbG8_PC9wPg"
//! [39bis]


//! [40]
QByteArray ba;
int n = 63;
ba.setNum(n);           // ba == "63"
ba.setNum(n, 16);       // ba == "3f"
//! [40]


//! [41]
int n = 63;
QByteArray::number(n);              // returns "63"
QByteArray::number(n, 16);          // returns "3f"
QByteArray::number(n, 16).toUpper();  // returns "3F"
//! [41]


//! [42]
QByteArray ba = QByteArray::number(12.3456, 'E', 3);
// ba == 1.235E+01
//! [42]


//! [43]
 static const char mydata[] = {
    0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
    0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
    ...
    0x6d, 0x5b
};

QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
QDataStream in(&data, QIODevice::ReadOnly);
...
//! [43]


//! [44]
QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
text.data();            // returns "Qt is great!"
//! [44]

//! [44bis]
QByteArray::fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray::Base64Encoding); // returns "<p>Hello?</p>"
QByteArray::fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray::Base64UrlEncoding); // returns "<p>Hello?</p>"
//! [44bis]


//! [45]
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data();            // returns "Qt is great!"
//! [45]

//! [46]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size()];
strcpy(data, text.data());
delete [] data;
//! [46]

//! [47]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size() + 1];
strcpy(data, text.data());
delete [] data;
//! [47]

//! [48]
QByteArray ba1("ca\0r\0t");
ba1.size();                     // Returns 2.
ba1.constData();                // Returns "ca" with terminating \0.

QByteArray ba2("ca\0r\0t", 3);
ba2.size();                     // Returns 3.
ba2.constData();                // Returns "ca\0" with terminating \0.

QByteArray ba3("ca\0r\0t", 4);
ba3.size();                     // Returns 4.
ba3.constData();                // Returns "ca\0r" with terminating \0.

const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
QByteArray ba4(QByteArray::fromRawData(cart, 6));
ba4.size();                     // Returns 6.
ba4.constData();                // Returns "ca\0r\0t" without terminating \0.
//! [48]

}
Esempio n. 29
0
	// return true if jsonp applied
	bool tryApplyJsonp(const DomainMap::JsonpConfig &config, bool *ok, QString *errorMessage)
	{
		*ok = true;

		// must be a GET
		if(requestData.method != "GET")
			return false;

		QString callbackParam = QString::fromUtf8(config.callbackParam);
		if(callbackParam.isEmpty())
			callbackParam = "callback";

		QString bodyParam;
		if(!config.bodyParam.isEmpty())
			bodyParam = QString::fromUtf8(config.bodyParam);

		QUrl uri = requestData.uri;
		QUrlQuery query(uri);

		// two ways to activate JSON-P:
		//   1) callback param present
		//   2) default callback specified in configuration and body param present
		if(!query.hasQueryItem(callbackParam) &&
			(config.defaultCallback.isEmpty() || bodyParam.isEmpty() || !query.hasQueryItem(bodyParam)))
		{
			return false;
		}

		QByteArray callback;
		if(query.hasQueryItem(callbackParam))
		{
			callback = parsePercentEncoding(query.queryItemValue(callbackParam, QUrl::FullyEncoded).toUtf8());
			if(callback.isEmpty())
			{
				log_debug("requestsession: id=%s invalid callback parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid callback parameter.";
				return false;
			}

			query.removeAllQueryItems(callbackParam);
		}
		else
			callback = config.defaultCallback;

		QString method;
		if(query.hasQueryItem("_method"))
		{
			method = QString::fromLatin1(parsePercentEncoding(query.queryItemValue("_method", QUrl::FullyEncoded).toUtf8()));
			if(!validMethod(method))
			{
				log_debug("requestsession: id=%s invalid _method parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid _method parameter.";
				return false;
			}

			query.removeAllQueryItems("_method");
		}

		HttpHeaders headers;
		if(query.hasQueryItem("_headers"))
		{
			QJsonParseError e;
			QJsonDocument doc = QJsonDocument::fromJson(parsePercentEncoding(query.queryItemValue("_headers", QUrl::FullyEncoded).toUtf8()), &e);
			if(e.error != QJsonParseError::NoError || !doc.isObject())
			{
				log_debug("requestsession: id=%s invalid _headers parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid _headers parameter.";
				return false;
			}

			QVariantMap headersMap = doc.object().toVariantMap();

			QMapIterator<QString, QVariant> vit(headersMap);
			while(vit.hasNext())
			{
				vit.next();

				if(vit.value().type() != QVariant::String)
				{
					log_debug("requestsession: id=%s invalid _headers parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid _headers parameter.";
					return false;
				}

				QByteArray key = vit.key().toUtf8();

				// ignore some headers that we explicitly set later on
				if(qstricmp(key.data(), "host") == 0)
					continue;
				if(qstricmp(key.data(), "accept") == 0)
					continue;

				headers += HttpHeader(key, vit.value().toString().toUtf8());
			}

			query.removeAllQueryItems("_headers");
		}

		QByteArray body;
		if(!bodyParam.isEmpty())
		{
			if(query.hasQueryItem(bodyParam))
			{
				body = parsePercentEncoding(query.queryItemValue(bodyParam, QUrl::FullyEncoded).toUtf8());
				if(body.isNull())
				{
					log_debug("requestsession: id=%s invalid body parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid body parameter.";
					return false;
				}

				headers.removeAll("Content-Type");
				headers += HttpHeader("Content-Type", "application/json");

				query.removeAllQueryItems(bodyParam);
			}
		}
		else
		{
			if(query.hasQueryItem("_body"))
			{
				body = parsePercentEncoding(query.queryItemValue("_body").toUtf8());
				if(body.isNull())
				{
					log_debug("requestsession: id=%s invalid _body parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid _body parameter.";
					return false;
				}

				query.removeAllQueryItems("_body");
			}
		}

		uri.setQuery(query);

		// if we have no query items anymore, strip the '?'
		if(query.isEmpty())
		{
			QByteArray tmp = uri.toEncoded();
			if(tmp.length() > 0 && tmp[tmp.length() - 1] == '?')
			{
				tmp.truncate(tmp.length() - 1);
				uri = QUrl::fromEncoded(tmp, QUrl::StrictMode);
			}
		}

		if(method.isEmpty())
			method = config.defaultMethod;

		requestData.method = method;

		requestData.uri = uri;

		headers += HttpHeader("Host", uri.host().toUtf8());
		headers += HttpHeader("Accept", "*/*");

		// carry over the rest of the headers
		foreach(const HttpHeader &h, requestData.headers)
		{
			if(qstricmp(h.first.data(), "host") == 0)
				continue;
			if(qstricmp(h.first.data(), "accept") == 0)
				continue;

			headers += h;
		}

		requestData.headers = headers;
		in += body;

		jsonpCallback = callback;
		jsonpExtendedResponse = (config.mode == DomainMap::JsonpConfig::Extended);

		return true;
	}